prompt
stringclasses
1 value
completions
listlengths
1
63.8k
labels
listlengths
1
63.8k
source
stringclasses
1 value
other_info
stringlengths
2.06k
101k
index
int64
0
6.83k
Determine whether the {function_name} code is vulnerable or not.
[ "{\n \"name\": \"node-fetch\",", " \"version\": \"3.1.0\",", " \"description\": \"A light-weight module that brings Fetch API to node.js\",\n \"main\": \"./src/index.js\",\n \"sideEffects\": false,\n \"type\": \"module\",\n \"files\": [\n \"src\",\n \"@types/index.d.ts\"\n ],\n \"types\": \"./@types/index.d.ts\",\n \"engines\": {\n \"node\": \"^12.20.0 || ^14.13.1 || >=16.0.0\"\n },\n \"scripts\": {\n \"test\": \"mocha\",\n \"coverage\": \"c8 report --reporter=text-lcov | coveralls\",\n \"test-types\": \"tsd\",\n \"lint\": \"xo\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/node-fetch/node-fetch.git\"\n },\n \"keywords\": [\n \"fetch\",\n \"http\",\n \"promise\",\n \"request\",\n \"curl\",\n \"wget\",\n \"xhr\",\n \"whatwg\"\n ],\n \"author\": \"David Frank\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/node-fetch/node-fetch/issues\"\n },\n \"homepage\": \"https://github.com/node-fetch/node-fetch\",\n \"funding\": {\n \"type\": \"opencollective\",\n \"url\": \"https://opencollective.com/node-fetch\"\n },\n \"devDependencies\": {\n \"abort-controller\": \"^3.0.0\",\n \"abortcontroller-polyfill\": \"^1.7.1\",\n \"busboy\": \"^0.3.1\",\n \"c8\": \"^7.7.2\",\n \"chai\": \"^4.3.4\",\n \"chai-as-promised\": \"^7.1.1\",\n \"chai-iterator\": \"^3.0.2\",\n \"chai-string\": \"^1.5.0\",\n \"coveralls\": \"^3.1.0\",\n \"delay\": \"^5.0.0\",\n \"form-data\": \"^4.0.0\",\n \"formdata-node\": \"^4.2.4\",\n \"mocha\": \"^9.1.3\",\n \"p-timeout\": \"^5.0.0\",\n \"stream-consumers\": \"^1.0.1\",\n \"tsd\": \"^0.14.0\",\n \"xo\": \"^0.39.1\"\n },\n \"dependencies\": {\n \"data-uri-to-buffer\": \"^4.0.0\",\n \"fetch-blob\": \"^3.1.3\",\n \"formdata-polyfill\": \"^4.0.10\"\n },\n \"tsd\": {\n \"cwd\": \"@types\",\n \"compilerOptions\": {\n \"esModuleInterop\": true\n }\n },\n \"xo\": {\n \"envs\": [\n \"node\",\n \"browser\"\n ],\n \"ignores\": [\n \"example.js\"\n ],\n \"rules\": {\n \"complexity\": 0,\n \"import/extensions\": 0,\n \"import/no-useless-path-segments\": 0,\n \"import/no-anonymous-default-export\": 0,\n \"import/no-named-as-default\": 0,\n \"unicorn/import-index\": 0,\n \"unicorn/no-array-reduce\": 0,\n \"unicorn/prefer-node-protocol\": 0,\n \"unicorn/numeric-separators-style\": 0,\n \"unicorn/explicit-length-check\": 0,\n \"capitalized-comments\": 0,\n \"node/no-unsupported-features/es-syntax\": 0,\n \"@typescript-eslint/member-ordering\": 0\n },\n \"overrides\": [\n {\n \"files\": \"test/**/*.js\",\n \"envs\": [\n \"node\",\n \"mocha\"\n ],\n \"rules\": {\n \"max-nested-callbacks\": 0,\n \"no-unused-expressions\": 0,\n \"no-warning-comments\": 0,\n \"new-cap\": 0,\n \"guard-for-in\": 0,\n \"unicorn/no-array-for-each\": 0,\n \"unicorn/prevent-abbreviations\": 0,\n \"promise/prefer-await-to-then\": 0,\n \"ava/no-import-test-files\": 0\n }\n }\n ]\n },\n \"runkitExampleFilename\": \"example.js\"\n}" ]
[ 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [10, 4], "buggy_code_start_loc": [7, 3], "filenames": ["docs/CHANGELOG.md", "package.json"], "fixing_code_end_loc": [31, 4], "fixing_code_start_loc": [7, 3], "message": "node-fetch is vulnerable to Exposure of Sensitive Information to an Unauthorized Actor", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:node-fetch_project:node-fetch:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "8BBBB24C-E889-41A5-8758-73FC1EEC04D1", "versionEndExcluding": "2.6.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:node-fetch_project:node-fetch:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "CBA8854F-A214-4FC8-BC82-C9E4CB3D653E", "versionEndExcluding": "3.1.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "3.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:siemens:sinec_ins:*:*:*:*:*:*:*:*", "matchCriteriaId": "C89891C1-DFD7-4E1F-80A9-7485D86A15B5", "versionEndExcluding": "1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:siemens:sinec_ins:1.0:-:*:*:*:*:*:*", "matchCriteriaId": "4664B195-AF14-4834-82B3-0B2C98020EB6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:siemens:sinec_ins:1.0:sp1:*:*:*:*:*:*", "matchCriteriaId": "75BC588E-CDF0-404E-AD61-02093A1DF343", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "node-fetch is vulnerable to Exposure of Sensitive Information to an Unauthorized Actor"}, {"lang": "es", "value": "node-fetch es vulnerable a una Exposici\u00f3n de Informaci\u00f3n Confidencial a un Actor no Autorizado"}], "evaluatorComment": null, "id": "CVE-2022-0235", "lastModified": "2023-02-03T19:16:07.090", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-01-16T17:15:07.870", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://cert-portal.siemens.com/productcert/pdf/ssa-637483.pdf"}, {"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/node-fetch/node-fetch/commit/36e47e8a6406185921e4985dcbeff140d73eaa10"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Third Party Advisory"], "url": "https://huntr.dev/bounties/d26ab655-38d6-48b3-be15-f9ad6b6ae6f7"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/12/msg00007.html"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-200"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-601"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/node-fetch/node-fetch/commit/36e47e8a6406185921e4985dcbeff140d73eaa10"}, "type": "CWE-200"}
170
Determine whether the {function_name} code is vulnerable or not.
[ "{\n \"name\": \"node-fetch\",", " \"version\": \"3.1.1\",", " \"description\": \"A light-weight module that brings Fetch API to node.js\",\n \"main\": \"./src/index.js\",\n \"sideEffects\": false,\n \"type\": \"module\",\n \"files\": [\n \"src\",\n \"@types/index.d.ts\"\n ],\n \"types\": \"./@types/index.d.ts\",\n \"engines\": {\n \"node\": \"^12.20.0 || ^14.13.1 || >=16.0.0\"\n },\n \"scripts\": {\n \"test\": \"mocha\",\n \"coverage\": \"c8 report --reporter=text-lcov | coveralls\",\n \"test-types\": \"tsd\",\n \"lint\": \"xo\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/node-fetch/node-fetch.git\"\n },\n \"keywords\": [\n \"fetch\",\n \"http\",\n \"promise\",\n \"request\",\n \"curl\",\n \"wget\",\n \"xhr\",\n \"whatwg\"\n ],\n \"author\": \"David Frank\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/node-fetch/node-fetch/issues\"\n },\n \"homepage\": \"https://github.com/node-fetch/node-fetch\",\n \"funding\": {\n \"type\": \"opencollective\",\n \"url\": \"https://opencollective.com/node-fetch\"\n },\n \"devDependencies\": {\n \"abort-controller\": \"^3.0.0\",\n \"abortcontroller-polyfill\": \"^1.7.1\",\n \"busboy\": \"^0.3.1\",\n \"c8\": \"^7.7.2\",\n \"chai\": \"^4.3.4\",\n \"chai-as-promised\": \"^7.1.1\",\n \"chai-iterator\": \"^3.0.2\",\n \"chai-string\": \"^1.5.0\",\n \"coveralls\": \"^3.1.0\",\n \"delay\": \"^5.0.0\",\n \"form-data\": \"^4.0.0\",\n \"formdata-node\": \"^4.2.4\",\n \"mocha\": \"^9.1.3\",\n \"p-timeout\": \"^5.0.0\",\n \"stream-consumers\": \"^1.0.1\",\n \"tsd\": \"^0.14.0\",\n \"xo\": \"^0.39.1\"\n },\n \"dependencies\": {\n \"data-uri-to-buffer\": \"^4.0.0\",\n \"fetch-blob\": \"^3.1.3\",\n \"formdata-polyfill\": \"^4.0.10\"\n },\n \"tsd\": {\n \"cwd\": \"@types\",\n \"compilerOptions\": {\n \"esModuleInterop\": true\n }\n },\n \"xo\": {\n \"envs\": [\n \"node\",\n \"browser\"\n ],\n \"ignores\": [\n \"example.js\"\n ],\n \"rules\": {\n \"complexity\": 0,\n \"import/extensions\": 0,\n \"import/no-useless-path-segments\": 0,\n \"import/no-anonymous-default-export\": 0,\n \"import/no-named-as-default\": 0,\n \"unicorn/import-index\": 0,\n \"unicorn/no-array-reduce\": 0,\n \"unicorn/prefer-node-protocol\": 0,\n \"unicorn/numeric-separators-style\": 0,\n \"unicorn/explicit-length-check\": 0,\n \"capitalized-comments\": 0,\n \"node/no-unsupported-features/es-syntax\": 0,\n \"@typescript-eslint/member-ordering\": 0\n },\n \"overrides\": [\n {\n \"files\": \"test/**/*.js\",\n \"envs\": [\n \"node\",\n \"mocha\"\n ],\n \"rules\": {\n \"max-nested-callbacks\": 0,\n \"no-unused-expressions\": 0,\n \"no-warning-comments\": 0,\n \"new-cap\": 0,\n \"guard-for-in\": 0,\n \"unicorn/no-array-for-each\": 0,\n \"unicorn/prevent-abbreviations\": 0,\n \"promise/prefer-await-to-then\": 0,\n \"ava/no-import-test-files\": 0\n }\n }\n ]\n },\n \"runkitExampleFilename\": \"example.js\"\n}" ]
[ 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [10, 4], "buggy_code_start_loc": [7, 3], "filenames": ["docs/CHANGELOG.md", "package.json"], "fixing_code_end_loc": [31, 4], "fixing_code_start_loc": [7, 3], "message": "node-fetch is vulnerable to Exposure of Sensitive Information to an Unauthorized Actor", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:node-fetch_project:node-fetch:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "8BBBB24C-E889-41A5-8758-73FC1EEC04D1", "versionEndExcluding": "2.6.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:node-fetch_project:node-fetch:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "CBA8854F-A214-4FC8-BC82-C9E4CB3D653E", "versionEndExcluding": "3.1.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "3.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:siemens:sinec_ins:*:*:*:*:*:*:*:*", "matchCriteriaId": "C89891C1-DFD7-4E1F-80A9-7485D86A15B5", "versionEndExcluding": "1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:siemens:sinec_ins:1.0:-:*:*:*:*:*:*", "matchCriteriaId": "4664B195-AF14-4834-82B3-0B2C98020EB6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:siemens:sinec_ins:1.0:sp1:*:*:*:*:*:*", "matchCriteriaId": "75BC588E-CDF0-404E-AD61-02093A1DF343", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "node-fetch is vulnerable to Exposure of Sensitive Information to an Unauthorized Actor"}, {"lang": "es", "value": "node-fetch es vulnerable a una Exposici\u00f3n de Informaci\u00f3n Confidencial a un Actor no Autorizado"}], "evaluatorComment": null, "id": "CVE-2022-0235", "lastModified": "2023-02-03T19:16:07.090", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-01-16T17:15:07.870", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://cert-portal.siemens.com/productcert/pdf/ssa-637483.pdf"}, {"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/node-fetch/node-fetch/commit/36e47e8a6406185921e4985dcbeff140d73eaa10"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Third Party Advisory"], "url": "https://huntr.dev/bounties/d26ab655-38d6-48b3-be15-f9ad6b6ae6f7"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/12/msg00007.html"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-200"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-601"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/node-fetch/node-fetch/commit/36e47e8a6406185921e4985dcbeff140d73eaa10"}, "type": "CWE-200"}
170
Determine whether the {function_name} code is vulnerable or not.
[ "/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.", "Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou 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\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/", "// See docs in ../ops/image_ops.cc", "#include <cstdint>\n#include <memory>", "#define EIGEN_USE_THREADS", "#include \"absl/strings/escaping.h\"\n#include \"tensorflow/core/framework/bounds_check.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/register_types.h\"\n#include \"tensorflow/core/framework/tensor.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n#include \"tensorflow/core/framework/types.h\"\n#include \"tensorflow/core/lib/core/status.h\"\n#include \"tensorflow/core/lib/gif/gif_io.h\"\n#include \"tensorflow/core/lib/jpeg/jpeg_mem.h\"\n#include \"tensorflow/core/lib/png/png_io.h\"\n#include \"tensorflow/core/lib/strings/str_util.h\"\n#include \"tensorflow/core/platform/byte_order.h\"\n#include \"tensorflow/core/platform/logging.h\"\n#include \"tensorflow/core/util/tensor_bundle/byte_swap.h\"", "namespace tensorflow {\nnamespace {", "// Magic bytes (hex) for each image format.\n// https://en.wikipedia.org/wiki/List_of_file_signatures\n// WARNING: Changing `static const` to `constexpr` requires first checking that\n// it works with supported MSVC version.\n// https://docs.microsoft.com/en-us/cpp/cpp/constexpr-cpp?redirectedfrom=MSDN&view=vs-2019\nstatic const char kPngMagicBytes[] = \"\\x89\\x50\\x4E\\x47\\x0D\\x0A\\x1A\\x0A\";\nstatic const char kGifMagicBytes[] = \"\\x47\\x49\\x46\\x38\";\nstatic const char kBmpMagicBytes[] = \"\\x42\\x4d\";\n// The 4th byte of JPEG is '\\xe0' or '\\xe1', so check just the first three.\nstatic const char kJpegMagicBytes[] = \"\\xff\\xd8\\xff\";", "enum FileFormat {\n kUnknownFormat = 0,\n kPngFormat = 1,\n kJpgFormat = 2,\n kGifFormat = 3,\n kBmpFormat = 4,\n};", "// Classify the contents of a file based on starting bytes (the magic number).\nFileFormat ClassifyFileFormat(StringPiece data) {\n if (absl::StartsWith(data, kJpegMagicBytes)) return kJpgFormat;\n if (absl::StartsWith(data, kPngMagicBytes)) return kPngFormat;\n if (absl::StartsWith(data, kGifMagicBytes)) return kGifFormat;\n if (absl::StartsWith(data, kBmpMagicBytes)) return kBmpFormat;\n return kUnknownFormat;\n}", "// Decode an image. Supported image formats are JPEG, PNG, GIF and BMP. This is\n// a newer version of `DecodeImageOp` for enabling image data parsing to take\n// place in kernels only, reducing security vulnerabilities and redundancy.\nclass DecodeImageV2Op : public OpKernel {\n public:\n explicit DecodeImageV2Op(OpKernelConstruction* context) : OpKernel(context) {\n // Keep track of op string information because:\n // [1] Currently by the API, PNG, JPEG and GIF can decode each other and\n // depending on the op type, we need to return either 3-D or 4-D shapes.\n // [2] Different ops have different attributes. e.g. `DecodeImage` op has\n // `expand_animations` attribute that other ops don't.\n // `DecodeAndDropJpeg` also has additional attributes.\n op_type_ = type_string();", " // Validate op type.\n OP_REQUIRES(context,\n op_type_ == \"DecodeJpeg\" || op_type_ == \"DecodeAndCropJpeg\" ||\n op_type_ == \"DecodePng\" || op_type_ == \"DecodeGif\" ||\n op_type_ == \"DecodeBmp\" || op_type_ == \"DecodeImage\",\n errors::InvalidArgument(\"Bad op type \", op_type_));", " // Get attributes from `DecodeJpeg` and `DecodeAndCropJpeg` op\n // invocations. For `DecodeImage` op, set JPEG decoding setting to TF\n // default.\n if (op_type_ == \"DecodeJpeg\" || op_type_ == \"DecodeAndCropJpeg\") {\n OP_REQUIRES_OK(context, context->GetAttr(\"ratio\", &flags_.ratio));\n OP_REQUIRES(context,\n flags_.ratio == 1 || flags_.ratio == 2 || flags_.ratio == 4 ||\n flags_.ratio == 8,\n errors::InvalidArgument(\"ratio must be 1, 2, 4, or 8, got \",\n flags_.ratio));\n OP_REQUIRES_OK(context, context->GetAttr(\"fancy_upscaling\",\n &flags_.fancy_upscaling));\n OP_REQUIRES_OK(context,\n context->GetAttr(\"try_recover_truncated\",\n &flags_.try_recover_truncated_jpeg));\n OP_REQUIRES_OK(context,\n context->GetAttr(\"acceptable_fraction\",\n &flags_.min_acceptable_fraction));\n string dct_method;\n OP_REQUIRES_OK(context, context->GetAttr(\"dct_method\", &dct_method));\n OP_REQUIRES(\n context,\n (dct_method.empty() || dct_method == \"INTEGER_FAST\" ||\n dct_method == \"INTEGER_ACCURATE\"),\n errors::InvalidArgument(\"dct_method must be one of \"\n \"{'', 'INTEGER_FAST', 'INTEGER_ACCURATE'}\"));\n // The TensorFlow-chosen default for JPEG decoding is IFAST, sacrificing\n // image quality for speed.\n if (dct_method.empty() || dct_method == \"INTEGER_FAST\") {\n flags_.dct_method = JDCT_IFAST;\n } else if (dct_method == \"INTEGER_ACCURATE\") {\n flags_.dct_method = JDCT_ISLOW;\n }\n } else {\n flags_ = jpeg::UncompressFlags();\n flags_.dct_method = JDCT_IFAST;\n }", " // Get `dtype` attribute from `DecodePng` or `DecodeImage` op invocations.\n if (op_type_ == \"DecodePng\" || op_type_ == \"DecodeImage\") {\n OP_REQUIRES_OK(context, context->GetAttr(\"dtype\", &data_type_));\n if (op_type_ == \"DecodePng\") {\n OP_REQUIRES(\n context,\n data_type_ == DataType::DT_UINT8 ||\n data_type_ == DataType::DT_UINT16,\n errors::InvalidArgument(\n \"`dtype` for `DecodePng` must be unit8, unit16 but got: \",\n data_type_));\n } else {\n OP_REQUIRES(context,\n data_type_ == DataType::DT_UINT8 ||\n data_type_ == DataType::DT_UINT16 ||\n data_type_ == DataType::DT_FLOAT,\n errors::InvalidArgument(\"`dtype` for `DecodeImage` must be \"\n \"unit8, unit16, float but got: \",\n data_type_));\n OP_REQUIRES_OK(context, context->GetAttr(\"expand_animations\",\n &expand_animations_));\n }\n }", " // Get `channels` attribute for all ops except `DecodeGif` op.\n // `DecodeGif` doesn't have `channels` attribute but it supports 3\n // channels by default.\n if (op_type_ != \"DecodeGif\") {\n OP_REQUIRES_OK(context, context->GetAttr(\"channels\", &channels_));\n OP_REQUIRES(\n context,\n channels_ == 0 || channels_ == 1 || channels_ == 3 || channels_ == 4,\n errors::InvalidArgument(\"`channels` must be 0, 1, 3 or 4 but got \",\n channels_));\n } else {\n channels_ = 3;\n }\n }", " // Helper for decoding BMP.\n inline int32 ByteSwapInt32ForBigEndian(int32_t x) {\n if (!port::kLittleEndian) {\n return BYTE_SWAP_32(x);\n } else {\n return x;\n }\n }", " // Helper for decoding BMP.\n inline int16 ByteSwapInt16ForBigEndian(int16_t x) {\n if (!port::kLittleEndian) {\n return BYTE_SWAP_16(x);\n } else {\n return x;\n }\n }", " void Compute(OpKernelContext* context) override {\n const Tensor& contents = context->input(0);\n OP_REQUIRES(\n context, TensorShapeUtils::IsScalar(contents.shape()),\n errors::InvalidArgument(\"`contents` must be scalar but got shape\",\n contents.shape().DebugString()));\n const StringPiece input = contents.scalar<tstring>()();\n OP_REQUIRES(context, !input.empty(),\n errors::InvalidArgument(\"Input is empty.\"));\n OP_REQUIRES(context, input.size() <= std::numeric_limits<int>::max(),\n errors::InvalidArgument(\n \"Input contents are too large for int: \", input.size()));", " // Parse magic bytes to determine file format.\n switch (ClassifyFileFormat(input)) {\n case kJpgFormat:\n DecodeJpegV2(context, input);\n break;\n case kPngFormat:\n DecodePngV2(context, input);\n break;\n case kGifFormat:\n DecodeGifV2(context, input);\n break;\n case kBmpFormat:\n DecodeBmpV2(context, input);\n break;\n case kUnknownFormat:\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\"Unknown image file format. One of \"\n \"JPEG, PNG, GIF, BMP required.\"));\n break;\n }\n }", " void DecodeJpegV2(OpKernelContext* context, StringPiece input) {\n OP_REQUIRES(context, channels_ == 0 || channels_ == 1 || channels_ == 3,\n errors::InvalidArgument(\"JPEG does not support 4 channels\"));", " // Use local copy of flags to avoid race condition as the class member is\n // shared among different invocations.\n jpeg::UncompressFlags flags = flags_;\n flags.components = channels_;", " if (op_type_ == \"DecodeAndCropJpeg\") {\n flags.crop = true;\n // Update flags to include crop window.\n const Tensor& crop_window = context->input(1);\n OP_REQUIRES(context, crop_window.dims() == 1,\n errors::InvalidArgument(\"crop_window must be 1-D, got shape \",\n crop_window.shape().DebugString()));\n OP_REQUIRES(context, crop_window.dim_size(0) == 4,\n errors::InvalidArgument(\"crop_size must have four elements \",\n crop_window.shape().DebugString()));\n auto crop_window_vec = crop_window.vec<int32>();\n flags.crop_y = crop_window_vec(0);\n flags.crop_x = crop_window_vec(1);\n flags.crop_height = crop_window_vec(2);\n flags.crop_width = crop_window_vec(3);\n } else if (op_type_ == \"DecodeBmp\") {\n // TODO(b/171060723): Only DecodeBmp as op_type_ is not acceptable here\n // because currently `decode_(jpeg|png|gif)` ops can decode any one of\n // jpeg, png or gif but not bmp. Similarly, `decode_bmp` cannot decode\n // anything but bmp formats. This behavior needs to be revisited. For more\n // details, please refer to the bug.\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"Trying to decode JPEG format using DecodeBmp op. Use \"\n \"`decode_jpeg` or `decode_image` instead.\"));\n }", " // Output tensor and the image buffer size.\n Tensor* output = nullptr;\n int buffer_size = 0;", " // Decode JPEG. Directly allocate to the output buffer if data type is\n // uint8 (to save extra copying). Otherwise, allocate a new uint8 buffer\n // with buffer size. `jpeg::Uncompress` supports unit8 only.\n uint8* buffer = jpeg::Uncompress(\n input.data(), input.size(), flags, nullptr /* nwarn */,\n [&](int width, int height, int channels) -> uint8* {\n buffer_size = height * width * channels;\n Status status;\n // By the existing API, we support decoding JPEG with `DecodeGif`\n // op. We need to make sure to return 4-D shapes when using\n // `DecodeGif`.\n if (op_type_ == \"DecodeGif\") {\n status = context->allocate_output(\n 0, TensorShape({1, height, width, channels}), &output);\n } else {\n status = context->allocate_output(\n 0, TensorShape({height, width, channels}), &output);\n }\n if (!status.ok()) {\n VLOG(1) << status;\n context->SetStatus(status);\n return nullptr;\n }", " if (data_type_ == DataType::DT_UINT8) {\n return output->flat<uint8>().data();\n } else {\n return new uint8[buffer_size];\n }\n });", " OP_REQUIRES(\n context, buffer,\n errors::InvalidArgument(\n \"jpeg::Uncompress failed. Invalid JPEG data or crop window.\"));", " // For when desired data type if unit8, the output buffer is already\n // allocated during the `jpeg::Uncompress` call above; return.\n if (data_type_ == DataType::DT_UINT8) {\n return;\n }\n // Make sure we don't forget to deallocate `buffer`.\n std::unique_ptr<uint8[]> buffer_unique_ptr(buffer);", " // Convert uint8 image data to desired data type.\n // Use eigen threadpooling to speed up the copy operation.\n const auto& device = context->eigen_device<Eigen::ThreadPoolDevice>();\n TTypes<uint8>::UnalignedConstFlat buffer_view(buffer, buffer_size);\n if (data_type_ == DataType::DT_UINT16) {\n uint16 scale = floor((std::numeric_limits<uint16>::max() + 1) /\n (std::numeric_limits<uint8>::max() + 1));\n // Fill output tensor with desired dtype.\n output->flat<uint16>().device(device) =\n buffer_view.cast<uint16>() * scale;\n } else if (data_type_ == DataType::DT_FLOAT) {\n float scale = 1. / std::numeric_limits<uint8>::max();\n // Fill output tensor with desired dtype.\n output->flat<float>().device(device) = buffer_view.cast<float>() * scale;\n }\n }", " void DecodePngV2(OpKernelContext* context, StringPiece input) {\n int channel_bits = (data_type_ == DataType::DT_UINT8) ? 8 : 16;\n png::DecodeContext decode;\n OP_REQUIRES(\n context, png::CommonInitDecode(input, channels_, channel_bits, &decode),\n errors::InvalidArgument(\"Invalid PNG. Failed to initialize decoder.\"));", " // Verify that width and height are not too large:\n // - verify width and height don't overflow int.\n // - width can later be multiplied by channels_ and sizeof(uint16), so\n // verify single dimension is not too large.\n // - verify when width and height are multiplied together, there are a few\n // bits to spare as well.\n const int width = static_cast<int>(decode.width);\n const int height = static_cast<int>(decode.height);\n const int64_t total_size =\n static_cast<int64_t>(width) * static_cast<int64_t>(height);\n if (width != static_cast<int64_t>(decode.width) || width <= 0 ||\n width >= (1LL << 27) || height != static_cast<int64_t>(decode.height) ||\n height <= 0 || height >= (1LL << 27) || total_size >= (1LL << 29)) {", " png::CommonFreeDecode(&decode);", " OP_REQUIRES(context, false,\n errors::InvalidArgument(\"PNG size too large for int: \",\n decode.width, \" by \", decode.height));\n }", " Tensor* output = nullptr;\n Status status;\n // By the existing API, we support decoding PNG with `DecodeGif` op.\n // We need to make sure to return 4-D shapes when using `DecodeGif`.\n if (op_type_ == \"DecodeGif\") {\n status = context->allocate_output(\n 0, TensorShape({1, height, width, decode.channels}), &output);\n } else {\n status = context->allocate_output(\n 0, TensorShape({height, width, decode.channels}), &output);\n }", " if (op_type_ == \"DecodeBmp\") {\n // TODO(b/171060723): Only DecodeBmp as op_type_ is not acceptable here\n // because currently `decode_(jpeg|png|gif)` ops can decode any one of\n // jpeg, png or gif but not bmp. Similarly, `decode_bmp` cannot decode\n // anything but bmp formats. This behavior needs to be revisited. For more\n // details, please refer to the bug.\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"Trying to decode PNG format using DecodeBmp op. Use \"\n \"`decode_png` or `decode_image` instead.\"));\n } else if (op_type_ == \"DecodeAndCropJpeg\") {\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"DecodeAndCropJpeg operation can run on JPEG only, but \"\n \"detected PNG.\"));\n }", " if (!status.ok()) png::CommonFreeDecode(&decode);\n OP_REQUIRES_OK(context, status);", " if (data_type_ == DataType::DT_UINT8) {\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(\n reinterpret_cast<png_bytep>(output->flat<uint8>().data()),\n decode.channels * width * sizeof(uint8), &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));\n } else if (data_type_ == DataType::DT_UINT16) {\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(\n reinterpret_cast<png_bytep>(output->flat<uint16>().data()),\n decode.channels * width * sizeof(uint16), &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));\n } else if (data_type_ == DataType::DT_FLOAT) {\n // `png::CommonFinishDecode` does not support `float`. First allocate\n // uint16 buffer for the image and decode in uint16 (lossless). Wrap the\n // buffer in `unique_ptr` so that we don't forget to delete the buffer.\n std::unique_ptr<uint16[]> buffer(\n new uint16[height * width * decode.channels]);\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(reinterpret_cast<png_bytep>(buffer.get()),\n decode.channels * width * sizeof(uint16),\n &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));", " // Convert uint16 image data to desired data type.\n // Use eigen threadpooling to speed up the copy operation.\n const auto& device = context->eigen_device<Eigen::ThreadPoolDevice>();\n TTypes<uint16, 3>::UnalignedConstTensor buf(buffer.get(), height, width,\n decode.channels);\n float scale = 1. / std::numeric_limits<uint16>::max();\n // Fill output tensor with desired dtype.\n output->tensor<float, 3>().device(device) = buf.cast<float>() * scale;\n }\n }", " void DecodeGifV2(OpKernelContext* context, StringPiece input) {\n // GIF has 3 channels.\n OP_REQUIRES(context, channels_ == 0 || channels_ == 3,\n errors::InvalidArgument(\"channels must be 0 or 3 for GIF, got \",\n channels_));", " if (op_type_ == \"DecodeBmp\") {\n // TODO(b/171060723): Only DecodeBmp as op_type_ is not acceptable here\n // because currently `decode_(jpeg|png|gif)` ops can decode any one of\n // jpeg, png or gif but not bmp. Similarly, `decode_bmp` cannot decode\n // anything but bmp formats. This behavior needs to be revisited. For more\n // details, please refer to the bug.\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"Trying to decode GIF format using DecodeBmp op. Use \"\n \"`decode_gif` or `decode_image` instead.\"));\n } else if (op_type_ == \"DecodeAndCropJpeg\") {\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"DecodeAndCropJpeg operation can run on JPEG only, but \"\n \"detected GIF.\"));\n }", " // Decode GIF, allocating tensor if dtype is uint8, otherwise defer tensor\n // allocation til after dtype conversion is done. `gif`::Decode` supports\n // uint8 only.\n Tensor* output = nullptr;\n int buffer_size = 0;\n string error_string;\n uint8* buffer = gif::Decode(\n input.data(), input.size(),\n [&](int num_frames, int width, int height, int channels) -> uint8* {\n buffer_size = num_frames * height * width * channels;", " Status status;\n // By the existing API, we support decoding GIF with `decode_jpeg` or\n // with `decode_png` if the GIF is a single-frame GIF (non-animated).\n // We need to make sure to return 3-D shapes when using in this case.\n if (op_type_ == \"DecodePng\" || op_type_ == \"DecodeJpeg\") {\n if (num_frames == 1) {\n status = context->allocate_output(\n 0, TensorShape({height, width, channels}), &output);\n } else {\n status = errors::InvalidArgument(\n \"Got \", num_frames, \" frames, but animated gifs \",\n \"can only be decoded by tf.io.decode_gif or \",\n \"tf.io.decode_image\");\n }\n } else if (op_type_ == \"DecodeGif\" ||\n (op_type_ == \"DecodeImage\" && expand_animations_)) {\n status = context->allocate_output(\n 0, TensorShape({num_frames, height, width, channels}), &output);\n } else if (op_type_ == \"DecodeImage\" && !expand_animations_) {\n status = context->allocate_output(\n 0, TensorShape({height, width, channels}), &output);\n } else {\n status = errors::InvalidArgument(\"Bad op type \", op_type_);\n }\n if (!status.ok()) {\n VLOG(1) << status;\n context->SetStatus(status);\n return nullptr;\n }", " if (data_type_ == DataType::DT_UINT8) {\n return output->flat<uint8>().data();\n } else {\n return new uint8[buffer_size];\n }\n },\n &error_string, expand_animations_);", " OP_REQUIRES(context, buffer,\n errors::InvalidArgument(\"Invalid GIF data (size \", input.size(),\n \"), \", error_string));", " // For when desired data type is uint8, the output buffer is already\n // allocated during the `gif::Decode` call above; return.\n if (data_type_ == DataType::DT_UINT8) {\n return;\n }\n // Make sure we don't forget to deallocate `buffer`.\n std::unique_ptr<uint8[]> buffer_unique_ptr(buffer);", " // Convert the raw uint8 buffer to desired dtype.\n // Use eigen threadpooling to speed up the copy operation.\n TTypes<uint8>::UnalignedConstFlat buffer_view(buffer, buffer_size);\n const auto& device = context->eigen_device<Eigen::ThreadPoolDevice>();\n if (data_type_ == DataType::DT_UINT16) {\n uint16 scale = floor((std::numeric_limits<uint16>::max() + 1) /\n (std::numeric_limits<uint8>::max() + 1));\n // Fill output tensor with desired dtype.\n output->flat<uint16>().device(device) =\n buffer_view.cast<uint16>() * scale;\n } else if (data_type_ == DataType::DT_FLOAT) {\n float scale = 1. / std::numeric_limits<uint8>::max();\n // Fill output tensor with desired dtype.\n output->flat<float>().device(device) = buffer_view.cast<float>() * scale;\n }\n }", " void DecodeBmpV2(OpKernelContext* context, StringPiece input) {\n OP_REQUIRES(\n context, channels_ != 1,\n errors::InvalidArgument(\n \"`channels` must be 0, 3 or 4 for BMP, but got \", channels_));", " if (op_type_ != \"DecodeBmp\" && op_type_ != \"DecodeImage\") {\n if (op_type_ == \"DecodeAndCropJpeg\") {\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"DecodeAndCropJpeg operation can run on JPEG only, but \"\n \"detected BMP.\"));\n } else {\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"Trying to decode BMP format using a wrong op. Use \"\n \"`decode_bmp` or `decode_image` instead. Op used: \",\n op_type_));\n }\n }", " OP_REQUIRES(context, (32 <= input.size()),\n errors::InvalidArgument(\"Incomplete bmp content, requires at \"\n \"least 32 bytes to find the header \"\n \"size, width, height, and bpp, got \",\n input.size(), \" bytes\"));", " const uint8* img_bytes = reinterpret_cast<const uint8*>(input.data());\n int32_t header_size_ = internal::SubtleMustCopy(\n *(reinterpret_cast<const int32*>(img_bytes + 10)));\n const int32_t header_size = ByteSwapInt32ForBigEndian(header_size_);\n int32_t width_ = internal::SubtleMustCopy(\n *(reinterpret_cast<const int32*>(img_bytes + 18)));\n const int32_t width = ByteSwapInt32ForBigEndian(width_);\n int32_t height_ = internal::SubtleMustCopy(\n *(reinterpret_cast<const int32*>(img_bytes + 22)));\n const int32_t height = ByteSwapInt32ForBigEndian(height_);\n int16_t bpp_ = internal::SubtleMustCopy(\n *(reinterpret_cast<const int16*>(img_bytes + 28)));\n const int16_t bpp = ByteSwapInt16ForBigEndian(bpp_);", " // `channels_` is desired number of channels. `img_channels` is number of\n // channels inherent in the image.\n int img_channels = bpp / 8;\n OP_REQUIRES(\n context, (img_channels == 1 || img_channels == 3 || img_channels == 4),\n errors::InvalidArgument(\n \"Number of channels inherent in the image must be 1, 3 or 4, was \",\n img_channels));\n const int requested_channels = channels_ ? channels_ : img_channels;", " OP_REQUIRES(context, width > 0,\n errors::InvalidArgument(\"Width must be positive\"));\n OP_REQUIRES(context, height != 0,\n errors::InvalidArgument(\"Height must be nonzero\"));\n OP_REQUIRES(context, header_size >= 0,\n errors::InvalidArgument(\"header size must be nonnegative\"));", " // The real requirement is < 2^31 minus some headers and channel data,\n // so rounding down to something that's still ridiculously big.\n OP_REQUIRES(\n context,\n (static_cast<int64_t>(width) * std::abs(static_cast<int64_t>(height))) <\n static_cast<int64_t>(std::numeric_limits<int32_t>::max() / 8),\n errors::InvalidArgument(\n \"Total possible pixel bytes must be less than 2^30\"));", " const int32_t abs_height = abs(height);", " // there may be padding bytes when the width is not a multiple of 4 bytes\n const int row_size = (img_channels * width + 3) / 4 * 4;", " // Make sure the size of input data matches up with the total size of\n // headers plus height * row_size.\n int size_diff = input.size() - header_size - (row_size * abs_height);\n OP_REQUIRES(\n context, size_diff == 0,\n errors::InvalidArgument(\n \"Input size should match (header_size + row_size * abs_height) but \"\n \"they differ by \",\n size_diff));", " const int64_t last_pixel_offset = static_cast<int64_t>(header_size) +\n (abs_height - 1) * row_size +\n (width - 1) * img_channels;", " // [expected file size] = [last pixel offset] + [last pixel size=channels]\n const int64_t expected_file_size = last_pixel_offset + img_channels;", " OP_REQUIRES(\n context, (expected_file_size <= input.size()),\n errors::InvalidArgument(\"Incomplete bmp content, requires at least \",\n expected_file_size, \" bytes, got \",\n input.size(), \" bytes\"));", " // if height is negative, data layout is top down\n // otherwise, it's bottom up.\n bool top_down = (height < 0);", " // Decode image, allocating tensor once the image size is known.\n Tensor* output = nullptr;\n OP_REQUIRES_OK(\n context,\n context->allocate_output(\n 0, TensorShape({abs_height, width, requested_channels}), &output));", " const uint8* bmp_pixels = &img_bytes[header_size];", " if (data_type_ == DataType::DT_UINT8) {\n DecodeBMP(bmp_pixels, row_size, output->flat<uint8>().data(), width,\n abs_height, requested_channels, img_channels, top_down);\n } else {\n std::unique_ptr<uint8[]> buffer(\n new uint8[height * width * requested_channels]);\n DecodeBMP(bmp_pixels, row_size, buffer.get(), width, abs_height,\n requested_channels, img_channels, top_down);\n TTypes<uint8, 3>::UnalignedConstTensor buf(buffer.get(), height, width,\n requested_channels);\n // Convert the raw uint8 buffer to desired dtype.\n // Use eigen threadpooling to speed up the copy operation.\n const auto& device = context->eigen_device<Eigen::ThreadPoolDevice>();\n if (data_type_ == DataType::DT_UINT16) {\n uint16 scale = floor((std::numeric_limits<uint16>::max() + 1) /\n (std::numeric_limits<uint8>::max() + 1));\n // Fill output tensor with desired dtype.\n output->tensor<uint16, 3>().device(device) = buf.cast<uint16>() * scale;\n } else if (data_type_ == DataType::DT_FLOAT) {\n float scale = 1. / std::numeric_limits<uint8>::max();\n // Fill output tensor with desired dtype.\n output->tensor<float, 3>().device(device) = buf.cast<float>() * scale;\n }\n }\n }", " private:\n void DecodeBMP(const uint8* input, const int row_size, uint8* const output,\n const int width, const int height, const int output_channels,\n const int input_channels, bool top_down);", " int channels_ = 0;\n DataType data_type_ = DataType::DT_UINT8;\n bool expand_animations_ = true;\n jpeg::UncompressFlags flags_;\n string op_type_;\n};", "REGISTER_KERNEL_BUILDER(Name(\"DecodeJpeg\").Device(DEVICE_CPU), DecodeImageV2Op);\nREGISTER_KERNEL_BUILDER(Name(\"DecodePng\").Device(DEVICE_CPU), DecodeImageV2Op);\nREGISTER_KERNEL_BUILDER(Name(\"DecodeGif\").Device(DEVICE_CPU), DecodeImageV2Op);\nREGISTER_KERNEL_BUILDER(Name(\"DecodeAndCropJpeg\").Device(DEVICE_CPU),\n DecodeImageV2Op);\nREGISTER_KERNEL_BUILDER(Name(\"DecodeImage\").Device(DEVICE_CPU),\n DecodeImageV2Op);\nREGISTER_KERNEL_BUILDER(Name(\"DecodeBmp\").Device(DEVICE_CPU), DecodeImageV2Op);", "void DecodeImageV2Op::DecodeBMP(const uint8* input, const int row_size,\n uint8* const output, const int width,\n const int height, const int output_channels,\n const int input_channels, bool top_down) {\n for (int i = 0; i < height; i++) {\n int src_pos;\n int dst_pos;", " for (int j = 0; j < width; j++) {\n if (!top_down) {\n src_pos = ((height - 1 - i) * row_size) + j * input_channels;\n } else {\n src_pos = i * row_size + j * input_channels;\n }", " dst_pos = (i * width + j) * output_channels;", " switch (input_channels) {\n case 1:\n output[dst_pos] = input[src_pos];\n // Set 2nd and 3rd channels if user requested for 3 or 4 channels.\n // Repeat 1st channel's value.\n if (output_channels == 3 || output_channels == 4) {\n output[dst_pos + 1] = input[src_pos];\n output[dst_pos + 2] = input[src_pos];\n }\n // Set 4th channel (alpha) to maximum value if user requested for\n // 4 channels.\n if (output_channels == 4) {\n output[dst_pos + 3] = UINT8_MAX;\n }\n break;\n case 3:\n // BGR -> RGB\n output[dst_pos] = input[src_pos + 2];\n output[dst_pos + 1] = input[src_pos + 1];\n output[dst_pos + 2] = input[src_pos];\n // Set 4th channel (alpha) to maximum value if the user requested for\n // 4 channels and the input image has 3 channels only.\n if (output_channels == 4) {\n output[dst_pos + 3] = UINT8_MAX;\n }\n break;\n case 4:\n // BGRA -> RGBA\n output[dst_pos] = input[src_pos + 2];\n output[dst_pos + 1] = input[src_pos + 1];\n output[dst_pos + 2] = input[src_pos];\n // Set 4th channel only if the user requested for 4 channels. If not,\n // then user requested 3 channels; skip this step.\n if (output_channels == 4) {\n output[dst_pos + 3] = input[src_pos + 3];\n }\n break;\n default:\n LOG(FATAL) << \"Unexpected number of channels: \" << input_channels;\n break;\n }\n }\n }\n}", "} // namespace\n} // namespace tensorflow" ]
[ 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [343], "buggy_code_start_loc": [342], "filenames": ["tensorflow/core/kernels/image/decode_image_op.cc"], "fixing_code_end_loc": [341], "fixing_code_start_loc": [341], "message": "Tensorflow is an Open Source Machine Learning Framework. A malicious user can cause a use after free behavior when decoding PNG images. After `png::CommonFreeDecode(&decode)` gets called, the values of `decode.width` and `decode.height` are in an unspecified state. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "688150BF-477C-48FC-9AEF-A79AC57A6DDC", "versionEndExcluding": null, "versionEndIncluding": "2.5.2", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "C9E69B60-8C97-47E2-9027-9598B8392E5D", "versionEndExcluding": null, "versionEndIncluding": "2.6.2", "versionStartExcluding": null, "versionStartIncluding": "2.6.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.7.0:*:*:*:*:*:*:*", "matchCriteriaId": "2EDFAAB8-799C-4259-9102-944D4760DA2C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Tensorflow is an Open Source Machine Learning Framework. A malicious user can cause a use after free behavior when decoding PNG images. After `png::CommonFreeDecode(&decode)` gets called, the values of `decode.width` and `decode.height` are in an unspecified state. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range."}, {"lang": "es", "value": "Tensorflow es un Marco de Aprendizaje Autom\u00e1tico de C\u00f3digo Abierto. Un usuario malicioso puede causar un comportamiento de uso de memoria previamente liberada cuando decodifica im\u00e1genes PNG. Despu\u00e9s de llamar a \"png::CommonFreeDecode(&amp;decode)\", los valores de \"decode.width\" y \"decode.height\" est\u00e1n en un estado no especificado. La correcci\u00f3n ser\u00e1 incluida en TensorFlow versi\u00f3n 2.8.0. Tambi\u00e9n seleccionaremos este commit en TensorFlow versi\u00f3n 2.7.1, TensorFlow versi\u00f3n 2.6.3, y TensorFlow versi\u00f3n 2.5.3, ya que estos tambi\u00e9n est\u00e1n afectados y a\u00fan est\u00e1n en el rango admitido"}], "evaluatorComment": null, "id": "CVE-2022-23584", "lastModified": "2022-02-10T17:23:58.667", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-02-04T23:15:14.873", "references": [{"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/blob/a1320ec1eac186da1d03f033109191f715b2b130/tensorflow/core/kernels/image/decode_image_op.cc#L339-L346"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/commit/e746adbfcfee15e9cfdb391ff746c765b99bdf9b"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-24x4-6qmh-88qg"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-416"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/e746adbfcfee15e9cfdb391ff746c765b99bdf9b"}, "type": "CWE-416"}
171
Determine whether the {function_name} code is vulnerable or not.
[ "/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.", "Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou 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\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/", "// See docs in ../ops/image_ops.cc", "#include <cstdint>\n#include <memory>", "#define EIGEN_USE_THREADS", "#include \"absl/strings/escaping.h\"\n#include \"tensorflow/core/framework/bounds_check.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/register_types.h\"\n#include \"tensorflow/core/framework/tensor.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n#include \"tensorflow/core/framework/types.h\"\n#include \"tensorflow/core/lib/core/status.h\"\n#include \"tensorflow/core/lib/gif/gif_io.h\"\n#include \"tensorflow/core/lib/jpeg/jpeg_mem.h\"\n#include \"tensorflow/core/lib/png/png_io.h\"\n#include \"tensorflow/core/lib/strings/str_util.h\"\n#include \"tensorflow/core/platform/byte_order.h\"\n#include \"tensorflow/core/platform/logging.h\"\n#include \"tensorflow/core/util/tensor_bundle/byte_swap.h\"", "namespace tensorflow {\nnamespace {", "// Magic bytes (hex) for each image format.\n// https://en.wikipedia.org/wiki/List_of_file_signatures\n// WARNING: Changing `static const` to `constexpr` requires first checking that\n// it works with supported MSVC version.\n// https://docs.microsoft.com/en-us/cpp/cpp/constexpr-cpp?redirectedfrom=MSDN&view=vs-2019\nstatic const char kPngMagicBytes[] = \"\\x89\\x50\\x4E\\x47\\x0D\\x0A\\x1A\\x0A\";\nstatic const char kGifMagicBytes[] = \"\\x47\\x49\\x46\\x38\";\nstatic const char kBmpMagicBytes[] = \"\\x42\\x4d\";\n// The 4th byte of JPEG is '\\xe0' or '\\xe1', so check just the first three.\nstatic const char kJpegMagicBytes[] = \"\\xff\\xd8\\xff\";", "enum FileFormat {\n kUnknownFormat = 0,\n kPngFormat = 1,\n kJpgFormat = 2,\n kGifFormat = 3,\n kBmpFormat = 4,\n};", "// Classify the contents of a file based on starting bytes (the magic number).\nFileFormat ClassifyFileFormat(StringPiece data) {\n if (absl::StartsWith(data, kJpegMagicBytes)) return kJpgFormat;\n if (absl::StartsWith(data, kPngMagicBytes)) return kPngFormat;\n if (absl::StartsWith(data, kGifMagicBytes)) return kGifFormat;\n if (absl::StartsWith(data, kBmpMagicBytes)) return kBmpFormat;\n return kUnknownFormat;\n}", "// Decode an image. Supported image formats are JPEG, PNG, GIF and BMP. This is\n// a newer version of `DecodeImageOp` for enabling image data parsing to take\n// place in kernels only, reducing security vulnerabilities and redundancy.\nclass DecodeImageV2Op : public OpKernel {\n public:\n explicit DecodeImageV2Op(OpKernelConstruction* context) : OpKernel(context) {\n // Keep track of op string information because:\n // [1] Currently by the API, PNG, JPEG and GIF can decode each other and\n // depending on the op type, we need to return either 3-D or 4-D shapes.\n // [2] Different ops have different attributes. e.g. `DecodeImage` op has\n // `expand_animations` attribute that other ops don't.\n // `DecodeAndDropJpeg` also has additional attributes.\n op_type_ = type_string();", " // Validate op type.\n OP_REQUIRES(context,\n op_type_ == \"DecodeJpeg\" || op_type_ == \"DecodeAndCropJpeg\" ||\n op_type_ == \"DecodePng\" || op_type_ == \"DecodeGif\" ||\n op_type_ == \"DecodeBmp\" || op_type_ == \"DecodeImage\",\n errors::InvalidArgument(\"Bad op type \", op_type_));", " // Get attributes from `DecodeJpeg` and `DecodeAndCropJpeg` op\n // invocations. For `DecodeImage` op, set JPEG decoding setting to TF\n // default.\n if (op_type_ == \"DecodeJpeg\" || op_type_ == \"DecodeAndCropJpeg\") {\n OP_REQUIRES_OK(context, context->GetAttr(\"ratio\", &flags_.ratio));\n OP_REQUIRES(context,\n flags_.ratio == 1 || flags_.ratio == 2 || flags_.ratio == 4 ||\n flags_.ratio == 8,\n errors::InvalidArgument(\"ratio must be 1, 2, 4, or 8, got \",\n flags_.ratio));\n OP_REQUIRES_OK(context, context->GetAttr(\"fancy_upscaling\",\n &flags_.fancy_upscaling));\n OP_REQUIRES_OK(context,\n context->GetAttr(\"try_recover_truncated\",\n &flags_.try_recover_truncated_jpeg));\n OP_REQUIRES_OK(context,\n context->GetAttr(\"acceptable_fraction\",\n &flags_.min_acceptable_fraction));\n string dct_method;\n OP_REQUIRES_OK(context, context->GetAttr(\"dct_method\", &dct_method));\n OP_REQUIRES(\n context,\n (dct_method.empty() || dct_method == \"INTEGER_FAST\" ||\n dct_method == \"INTEGER_ACCURATE\"),\n errors::InvalidArgument(\"dct_method must be one of \"\n \"{'', 'INTEGER_FAST', 'INTEGER_ACCURATE'}\"));\n // The TensorFlow-chosen default for JPEG decoding is IFAST, sacrificing\n // image quality for speed.\n if (dct_method.empty() || dct_method == \"INTEGER_FAST\") {\n flags_.dct_method = JDCT_IFAST;\n } else if (dct_method == \"INTEGER_ACCURATE\") {\n flags_.dct_method = JDCT_ISLOW;\n }\n } else {\n flags_ = jpeg::UncompressFlags();\n flags_.dct_method = JDCT_IFAST;\n }", " // Get `dtype` attribute from `DecodePng` or `DecodeImage` op invocations.\n if (op_type_ == \"DecodePng\" || op_type_ == \"DecodeImage\") {\n OP_REQUIRES_OK(context, context->GetAttr(\"dtype\", &data_type_));\n if (op_type_ == \"DecodePng\") {\n OP_REQUIRES(\n context,\n data_type_ == DataType::DT_UINT8 ||\n data_type_ == DataType::DT_UINT16,\n errors::InvalidArgument(\n \"`dtype` for `DecodePng` must be unit8, unit16 but got: \",\n data_type_));\n } else {\n OP_REQUIRES(context,\n data_type_ == DataType::DT_UINT8 ||\n data_type_ == DataType::DT_UINT16 ||\n data_type_ == DataType::DT_FLOAT,\n errors::InvalidArgument(\"`dtype` for `DecodeImage` must be \"\n \"unit8, unit16, float but got: \",\n data_type_));\n OP_REQUIRES_OK(context, context->GetAttr(\"expand_animations\",\n &expand_animations_));\n }\n }", " // Get `channels` attribute for all ops except `DecodeGif` op.\n // `DecodeGif` doesn't have `channels` attribute but it supports 3\n // channels by default.\n if (op_type_ != \"DecodeGif\") {\n OP_REQUIRES_OK(context, context->GetAttr(\"channels\", &channels_));\n OP_REQUIRES(\n context,\n channels_ == 0 || channels_ == 1 || channels_ == 3 || channels_ == 4,\n errors::InvalidArgument(\"`channels` must be 0, 1, 3 or 4 but got \",\n channels_));\n } else {\n channels_ = 3;\n }\n }", " // Helper for decoding BMP.\n inline int32 ByteSwapInt32ForBigEndian(int32_t x) {\n if (!port::kLittleEndian) {\n return BYTE_SWAP_32(x);\n } else {\n return x;\n }\n }", " // Helper for decoding BMP.\n inline int16 ByteSwapInt16ForBigEndian(int16_t x) {\n if (!port::kLittleEndian) {\n return BYTE_SWAP_16(x);\n } else {\n return x;\n }\n }", " void Compute(OpKernelContext* context) override {\n const Tensor& contents = context->input(0);\n OP_REQUIRES(\n context, TensorShapeUtils::IsScalar(contents.shape()),\n errors::InvalidArgument(\"`contents` must be scalar but got shape\",\n contents.shape().DebugString()));\n const StringPiece input = contents.scalar<tstring>()();\n OP_REQUIRES(context, !input.empty(),\n errors::InvalidArgument(\"Input is empty.\"));\n OP_REQUIRES(context, input.size() <= std::numeric_limits<int>::max(),\n errors::InvalidArgument(\n \"Input contents are too large for int: \", input.size()));", " // Parse magic bytes to determine file format.\n switch (ClassifyFileFormat(input)) {\n case kJpgFormat:\n DecodeJpegV2(context, input);\n break;\n case kPngFormat:\n DecodePngV2(context, input);\n break;\n case kGifFormat:\n DecodeGifV2(context, input);\n break;\n case kBmpFormat:\n DecodeBmpV2(context, input);\n break;\n case kUnknownFormat:\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\"Unknown image file format. One of \"\n \"JPEG, PNG, GIF, BMP required.\"));\n break;\n }\n }", " void DecodeJpegV2(OpKernelContext* context, StringPiece input) {\n OP_REQUIRES(context, channels_ == 0 || channels_ == 1 || channels_ == 3,\n errors::InvalidArgument(\"JPEG does not support 4 channels\"));", " // Use local copy of flags to avoid race condition as the class member is\n // shared among different invocations.\n jpeg::UncompressFlags flags = flags_;\n flags.components = channels_;", " if (op_type_ == \"DecodeAndCropJpeg\") {\n flags.crop = true;\n // Update flags to include crop window.\n const Tensor& crop_window = context->input(1);\n OP_REQUIRES(context, crop_window.dims() == 1,\n errors::InvalidArgument(\"crop_window must be 1-D, got shape \",\n crop_window.shape().DebugString()));\n OP_REQUIRES(context, crop_window.dim_size(0) == 4,\n errors::InvalidArgument(\"crop_size must have four elements \",\n crop_window.shape().DebugString()));\n auto crop_window_vec = crop_window.vec<int32>();\n flags.crop_y = crop_window_vec(0);\n flags.crop_x = crop_window_vec(1);\n flags.crop_height = crop_window_vec(2);\n flags.crop_width = crop_window_vec(3);\n } else if (op_type_ == \"DecodeBmp\") {\n // TODO(b/171060723): Only DecodeBmp as op_type_ is not acceptable here\n // because currently `decode_(jpeg|png|gif)` ops can decode any one of\n // jpeg, png or gif but not bmp. Similarly, `decode_bmp` cannot decode\n // anything but bmp formats. This behavior needs to be revisited. For more\n // details, please refer to the bug.\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"Trying to decode JPEG format using DecodeBmp op. Use \"\n \"`decode_jpeg` or `decode_image` instead.\"));\n }", " // Output tensor and the image buffer size.\n Tensor* output = nullptr;\n int buffer_size = 0;", " // Decode JPEG. Directly allocate to the output buffer if data type is\n // uint8 (to save extra copying). Otherwise, allocate a new uint8 buffer\n // with buffer size. `jpeg::Uncompress` supports unit8 only.\n uint8* buffer = jpeg::Uncompress(\n input.data(), input.size(), flags, nullptr /* nwarn */,\n [&](int width, int height, int channels) -> uint8* {\n buffer_size = height * width * channels;\n Status status;\n // By the existing API, we support decoding JPEG with `DecodeGif`\n // op. We need to make sure to return 4-D shapes when using\n // `DecodeGif`.\n if (op_type_ == \"DecodeGif\") {\n status = context->allocate_output(\n 0, TensorShape({1, height, width, channels}), &output);\n } else {\n status = context->allocate_output(\n 0, TensorShape({height, width, channels}), &output);\n }\n if (!status.ok()) {\n VLOG(1) << status;\n context->SetStatus(status);\n return nullptr;\n }", " if (data_type_ == DataType::DT_UINT8) {\n return output->flat<uint8>().data();\n } else {\n return new uint8[buffer_size];\n }\n });", " OP_REQUIRES(\n context, buffer,\n errors::InvalidArgument(\n \"jpeg::Uncompress failed. Invalid JPEG data or crop window.\"));", " // For when desired data type if unit8, the output buffer is already\n // allocated during the `jpeg::Uncompress` call above; return.\n if (data_type_ == DataType::DT_UINT8) {\n return;\n }\n // Make sure we don't forget to deallocate `buffer`.\n std::unique_ptr<uint8[]> buffer_unique_ptr(buffer);", " // Convert uint8 image data to desired data type.\n // Use eigen threadpooling to speed up the copy operation.\n const auto& device = context->eigen_device<Eigen::ThreadPoolDevice>();\n TTypes<uint8>::UnalignedConstFlat buffer_view(buffer, buffer_size);\n if (data_type_ == DataType::DT_UINT16) {\n uint16 scale = floor((std::numeric_limits<uint16>::max() + 1) /\n (std::numeric_limits<uint8>::max() + 1));\n // Fill output tensor with desired dtype.\n output->flat<uint16>().device(device) =\n buffer_view.cast<uint16>() * scale;\n } else if (data_type_ == DataType::DT_FLOAT) {\n float scale = 1. / std::numeric_limits<uint8>::max();\n // Fill output tensor with desired dtype.\n output->flat<float>().device(device) = buffer_view.cast<float>() * scale;\n }\n }", " void DecodePngV2(OpKernelContext* context, StringPiece input) {\n int channel_bits = (data_type_ == DataType::DT_UINT8) ? 8 : 16;\n png::DecodeContext decode;\n OP_REQUIRES(\n context, png::CommonInitDecode(input, channels_, channel_bits, &decode),\n errors::InvalidArgument(\"Invalid PNG. Failed to initialize decoder.\"));", " // Verify that width and height are not too large:\n // - verify width and height don't overflow int.\n // - width can later be multiplied by channels_ and sizeof(uint16), so\n // verify single dimension is not too large.\n // - verify when width and height are multiplied together, there are a few\n // bits to spare as well.\n const int width = static_cast<int>(decode.width);\n const int height = static_cast<int>(decode.height);\n const int64_t total_size =\n static_cast<int64_t>(width) * static_cast<int64_t>(height);\n if (width != static_cast<int64_t>(decode.width) || width <= 0 ||\n width >= (1LL << 27) || height != static_cast<int64_t>(decode.height) ||\n height <= 0 || height >= (1LL << 27) || total_size >= (1LL << 29)) {", "", " OP_REQUIRES(context, false,\n errors::InvalidArgument(\"PNG size too large for int: \",\n decode.width, \" by \", decode.height));\n }", " Tensor* output = nullptr;\n Status status;\n // By the existing API, we support decoding PNG with `DecodeGif` op.\n // We need to make sure to return 4-D shapes when using `DecodeGif`.\n if (op_type_ == \"DecodeGif\") {\n status = context->allocate_output(\n 0, TensorShape({1, height, width, decode.channels}), &output);\n } else {\n status = context->allocate_output(\n 0, TensorShape({height, width, decode.channels}), &output);\n }", " if (op_type_ == \"DecodeBmp\") {\n // TODO(b/171060723): Only DecodeBmp as op_type_ is not acceptable here\n // because currently `decode_(jpeg|png|gif)` ops can decode any one of\n // jpeg, png or gif but not bmp. Similarly, `decode_bmp` cannot decode\n // anything but bmp formats. This behavior needs to be revisited. For more\n // details, please refer to the bug.\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"Trying to decode PNG format using DecodeBmp op. Use \"\n \"`decode_png` or `decode_image` instead.\"));\n } else if (op_type_ == \"DecodeAndCropJpeg\") {\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"DecodeAndCropJpeg operation can run on JPEG only, but \"\n \"detected PNG.\"));\n }", " if (!status.ok()) png::CommonFreeDecode(&decode);\n OP_REQUIRES_OK(context, status);", " if (data_type_ == DataType::DT_UINT8) {\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(\n reinterpret_cast<png_bytep>(output->flat<uint8>().data()),\n decode.channels * width * sizeof(uint8), &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));\n } else if (data_type_ == DataType::DT_UINT16) {\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(\n reinterpret_cast<png_bytep>(output->flat<uint16>().data()),\n decode.channels * width * sizeof(uint16), &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));\n } else if (data_type_ == DataType::DT_FLOAT) {\n // `png::CommonFinishDecode` does not support `float`. First allocate\n // uint16 buffer for the image and decode in uint16 (lossless). Wrap the\n // buffer in `unique_ptr` so that we don't forget to delete the buffer.\n std::unique_ptr<uint16[]> buffer(\n new uint16[height * width * decode.channels]);\n OP_REQUIRES(\n context,\n png::CommonFinishDecode(reinterpret_cast<png_bytep>(buffer.get()),\n decode.channels * width * sizeof(uint16),\n &decode),\n errors::InvalidArgument(\"Invalid PNG data, size \", input.size()));", " // Convert uint16 image data to desired data type.\n // Use eigen threadpooling to speed up the copy operation.\n const auto& device = context->eigen_device<Eigen::ThreadPoolDevice>();\n TTypes<uint16, 3>::UnalignedConstTensor buf(buffer.get(), height, width,\n decode.channels);\n float scale = 1. / std::numeric_limits<uint16>::max();\n // Fill output tensor with desired dtype.\n output->tensor<float, 3>().device(device) = buf.cast<float>() * scale;\n }\n }", " void DecodeGifV2(OpKernelContext* context, StringPiece input) {\n // GIF has 3 channels.\n OP_REQUIRES(context, channels_ == 0 || channels_ == 3,\n errors::InvalidArgument(\"channels must be 0 or 3 for GIF, got \",\n channels_));", " if (op_type_ == \"DecodeBmp\") {\n // TODO(b/171060723): Only DecodeBmp as op_type_ is not acceptable here\n // because currently `decode_(jpeg|png|gif)` ops can decode any one of\n // jpeg, png or gif but not bmp. Similarly, `decode_bmp` cannot decode\n // anything but bmp formats. This behavior needs to be revisited. For more\n // details, please refer to the bug.\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"Trying to decode GIF format using DecodeBmp op. Use \"\n \"`decode_gif` or `decode_image` instead.\"));\n } else if (op_type_ == \"DecodeAndCropJpeg\") {\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"DecodeAndCropJpeg operation can run on JPEG only, but \"\n \"detected GIF.\"));\n }", " // Decode GIF, allocating tensor if dtype is uint8, otherwise defer tensor\n // allocation til after dtype conversion is done. `gif`::Decode` supports\n // uint8 only.\n Tensor* output = nullptr;\n int buffer_size = 0;\n string error_string;\n uint8* buffer = gif::Decode(\n input.data(), input.size(),\n [&](int num_frames, int width, int height, int channels) -> uint8* {\n buffer_size = num_frames * height * width * channels;", " Status status;\n // By the existing API, we support decoding GIF with `decode_jpeg` or\n // with `decode_png` if the GIF is a single-frame GIF (non-animated).\n // We need to make sure to return 3-D shapes when using in this case.\n if (op_type_ == \"DecodePng\" || op_type_ == \"DecodeJpeg\") {\n if (num_frames == 1) {\n status = context->allocate_output(\n 0, TensorShape({height, width, channels}), &output);\n } else {\n status = errors::InvalidArgument(\n \"Got \", num_frames, \" frames, but animated gifs \",\n \"can only be decoded by tf.io.decode_gif or \",\n \"tf.io.decode_image\");\n }\n } else if (op_type_ == \"DecodeGif\" ||\n (op_type_ == \"DecodeImage\" && expand_animations_)) {\n status = context->allocate_output(\n 0, TensorShape({num_frames, height, width, channels}), &output);\n } else if (op_type_ == \"DecodeImage\" && !expand_animations_) {\n status = context->allocate_output(\n 0, TensorShape({height, width, channels}), &output);\n } else {\n status = errors::InvalidArgument(\"Bad op type \", op_type_);\n }\n if (!status.ok()) {\n VLOG(1) << status;\n context->SetStatus(status);\n return nullptr;\n }", " if (data_type_ == DataType::DT_UINT8) {\n return output->flat<uint8>().data();\n } else {\n return new uint8[buffer_size];\n }\n },\n &error_string, expand_animations_);", " OP_REQUIRES(context, buffer,\n errors::InvalidArgument(\"Invalid GIF data (size \", input.size(),\n \"), \", error_string));", " // For when desired data type is uint8, the output buffer is already\n // allocated during the `gif::Decode` call above; return.\n if (data_type_ == DataType::DT_UINT8) {\n return;\n }\n // Make sure we don't forget to deallocate `buffer`.\n std::unique_ptr<uint8[]> buffer_unique_ptr(buffer);", " // Convert the raw uint8 buffer to desired dtype.\n // Use eigen threadpooling to speed up the copy operation.\n TTypes<uint8>::UnalignedConstFlat buffer_view(buffer, buffer_size);\n const auto& device = context->eigen_device<Eigen::ThreadPoolDevice>();\n if (data_type_ == DataType::DT_UINT16) {\n uint16 scale = floor((std::numeric_limits<uint16>::max() + 1) /\n (std::numeric_limits<uint8>::max() + 1));\n // Fill output tensor with desired dtype.\n output->flat<uint16>().device(device) =\n buffer_view.cast<uint16>() * scale;\n } else if (data_type_ == DataType::DT_FLOAT) {\n float scale = 1. / std::numeric_limits<uint8>::max();\n // Fill output tensor with desired dtype.\n output->flat<float>().device(device) = buffer_view.cast<float>() * scale;\n }\n }", " void DecodeBmpV2(OpKernelContext* context, StringPiece input) {\n OP_REQUIRES(\n context, channels_ != 1,\n errors::InvalidArgument(\n \"`channels` must be 0, 3 or 4 for BMP, but got \", channels_));", " if (op_type_ != \"DecodeBmp\" && op_type_ != \"DecodeImage\") {\n if (op_type_ == \"DecodeAndCropJpeg\") {\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"DecodeAndCropJpeg operation can run on JPEG only, but \"\n \"detected BMP.\"));\n } else {\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"Trying to decode BMP format using a wrong op. Use \"\n \"`decode_bmp` or `decode_image` instead. Op used: \",\n op_type_));\n }\n }", " OP_REQUIRES(context, (32 <= input.size()),\n errors::InvalidArgument(\"Incomplete bmp content, requires at \"\n \"least 32 bytes to find the header \"\n \"size, width, height, and bpp, got \",\n input.size(), \" bytes\"));", " const uint8* img_bytes = reinterpret_cast<const uint8*>(input.data());\n int32_t header_size_ = internal::SubtleMustCopy(\n *(reinterpret_cast<const int32*>(img_bytes + 10)));\n const int32_t header_size = ByteSwapInt32ForBigEndian(header_size_);\n int32_t width_ = internal::SubtleMustCopy(\n *(reinterpret_cast<const int32*>(img_bytes + 18)));\n const int32_t width = ByteSwapInt32ForBigEndian(width_);\n int32_t height_ = internal::SubtleMustCopy(\n *(reinterpret_cast<const int32*>(img_bytes + 22)));\n const int32_t height = ByteSwapInt32ForBigEndian(height_);\n int16_t bpp_ = internal::SubtleMustCopy(\n *(reinterpret_cast<const int16*>(img_bytes + 28)));\n const int16_t bpp = ByteSwapInt16ForBigEndian(bpp_);", " // `channels_` is desired number of channels. `img_channels` is number of\n // channels inherent in the image.\n int img_channels = bpp / 8;\n OP_REQUIRES(\n context, (img_channels == 1 || img_channels == 3 || img_channels == 4),\n errors::InvalidArgument(\n \"Number of channels inherent in the image must be 1, 3 or 4, was \",\n img_channels));\n const int requested_channels = channels_ ? channels_ : img_channels;", " OP_REQUIRES(context, width > 0,\n errors::InvalidArgument(\"Width must be positive\"));\n OP_REQUIRES(context, height != 0,\n errors::InvalidArgument(\"Height must be nonzero\"));\n OP_REQUIRES(context, header_size >= 0,\n errors::InvalidArgument(\"header size must be nonnegative\"));", " // The real requirement is < 2^31 minus some headers and channel data,\n // so rounding down to something that's still ridiculously big.\n OP_REQUIRES(\n context,\n (static_cast<int64_t>(width) * std::abs(static_cast<int64_t>(height))) <\n static_cast<int64_t>(std::numeric_limits<int32_t>::max() / 8),\n errors::InvalidArgument(\n \"Total possible pixel bytes must be less than 2^30\"));", " const int32_t abs_height = abs(height);", " // there may be padding bytes when the width is not a multiple of 4 bytes\n const int row_size = (img_channels * width + 3) / 4 * 4;", " // Make sure the size of input data matches up with the total size of\n // headers plus height * row_size.\n int size_diff = input.size() - header_size - (row_size * abs_height);\n OP_REQUIRES(\n context, size_diff == 0,\n errors::InvalidArgument(\n \"Input size should match (header_size + row_size * abs_height) but \"\n \"they differ by \",\n size_diff));", " const int64_t last_pixel_offset = static_cast<int64_t>(header_size) +\n (abs_height - 1) * row_size +\n (width - 1) * img_channels;", " // [expected file size] = [last pixel offset] + [last pixel size=channels]\n const int64_t expected_file_size = last_pixel_offset + img_channels;", " OP_REQUIRES(\n context, (expected_file_size <= input.size()),\n errors::InvalidArgument(\"Incomplete bmp content, requires at least \",\n expected_file_size, \" bytes, got \",\n input.size(), \" bytes\"));", " // if height is negative, data layout is top down\n // otherwise, it's bottom up.\n bool top_down = (height < 0);", " // Decode image, allocating tensor once the image size is known.\n Tensor* output = nullptr;\n OP_REQUIRES_OK(\n context,\n context->allocate_output(\n 0, TensorShape({abs_height, width, requested_channels}), &output));", " const uint8* bmp_pixels = &img_bytes[header_size];", " if (data_type_ == DataType::DT_UINT8) {\n DecodeBMP(bmp_pixels, row_size, output->flat<uint8>().data(), width,\n abs_height, requested_channels, img_channels, top_down);\n } else {\n std::unique_ptr<uint8[]> buffer(\n new uint8[height * width * requested_channels]);\n DecodeBMP(bmp_pixels, row_size, buffer.get(), width, abs_height,\n requested_channels, img_channels, top_down);\n TTypes<uint8, 3>::UnalignedConstTensor buf(buffer.get(), height, width,\n requested_channels);\n // Convert the raw uint8 buffer to desired dtype.\n // Use eigen threadpooling to speed up the copy operation.\n const auto& device = context->eigen_device<Eigen::ThreadPoolDevice>();\n if (data_type_ == DataType::DT_UINT16) {\n uint16 scale = floor((std::numeric_limits<uint16>::max() + 1) /\n (std::numeric_limits<uint8>::max() + 1));\n // Fill output tensor with desired dtype.\n output->tensor<uint16, 3>().device(device) = buf.cast<uint16>() * scale;\n } else if (data_type_ == DataType::DT_FLOAT) {\n float scale = 1. / std::numeric_limits<uint8>::max();\n // Fill output tensor with desired dtype.\n output->tensor<float, 3>().device(device) = buf.cast<float>() * scale;\n }\n }\n }", " private:\n void DecodeBMP(const uint8* input, const int row_size, uint8* const output,\n const int width, const int height, const int output_channels,\n const int input_channels, bool top_down);", " int channels_ = 0;\n DataType data_type_ = DataType::DT_UINT8;\n bool expand_animations_ = true;\n jpeg::UncompressFlags flags_;\n string op_type_;\n};", "REGISTER_KERNEL_BUILDER(Name(\"DecodeJpeg\").Device(DEVICE_CPU), DecodeImageV2Op);\nREGISTER_KERNEL_BUILDER(Name(\"DecodePng\").Device(DEVICE_CPU), DecodeImageV2Op);\nREGISTER_KERNEL_BUILDER(Name(\"DecodeGif\").Device(DEVICE_CPU), DecodeImageV2Op);\nREGISTER_KERNEL_BUILDER(Name(\"DecodeAndCropJpeg\").Device(DEVICE_CPU),\n DecodeImageV2Op);\nREGISTER_KERNEL_BUILDER(Name(\"DecodeImage\").Device(DEVICE_CPU),\n DecodeImageV2Op);\nREGISTER_KERNEL_BUILDER(Name(\"DecodeBmp\").Device(DEVICE_CPU), DecodeImageV2Op);", "void DecodeImageV2Op::DecodeBMP(const uint8* input, const int row_size,\n uint8* const output, const int width,\n const int height, const int output_channels,\n const int input_channels, bool top_down) {\n for (int i = 0; i < height; i++) {\n int src_pos;\n int dst_pos;", " for (int j = 0; j < width; j++) {\n if (!top_down) {\n src_pos = ((height - 1 - i) * row_size) + j * input_channels;\n } else {\n src_pos = i * row_size + j * input_channels;\n }", " dst_pos = (i * width + j) * output_channels;", " switch (input_channels) {\n case 1:\n output[dst_pos] = input[src_pos];\n // Set 2nd and 3rd channels if user requested for 3 or 4 channels.\n // Repeat 1st channel's value.\n if (output_channels == 3 || output_channels == 4) {\n output[dst_pos + 1] = input[src_pos];\n output[dst_pos + 2] = input[src_pos];\n }\n // Set 4th channel (alpha) to maximum value if user requested for\n // 4 channels.\n if (output_channels == 4) {\n output[dst_pos + 3] = UINT8_MAX;\n }\n break;\n case 3:\n // BGR -> RGB\n output[dst_pos] = input[src_pos + 2];\n output[dst_pos + 1] = input[src_pos + 1];\n output[dst_pos + 2] = input[src_pos];\n // Set 4th channel (alpha) to maximum value if the user requested for\n // 4 channels and the input image has 3 channels only.\n if (output_channels == 4) {\n output[dst_pos + 3] = UINT8_MAX;\n }\n break;\n case 4:\n // BGRA -> RGBA\n output[dst_pos] = input[src_pos + 2];\n output[dst_pos + 1] = input[src_pos + 1];\n output[dst_pos + 2] = input[src_pos];\n // Set 4th channel only if the user requested for 4 channels. If not,\n // then user requested 3 channels; skip this step.\n if (output_channels == 4) {\n output[dst_pos + 3] = input[src_pos + 3];\n }\n break;\n default:\n LOG(FATAL) << \"Unexpected number of channels: \" << input_channels;\n break;\n }\n }\n }\n}", "} // namespace\n} // namespace tensorflow" ]
[ 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [343], "buggy_code_start_loc": [342], "filenames": ["tensorflow/core/kernels/image/decode_image_op.cc"], "fixing_code_end_loc": [341], "fixing_code_start_loc": [341], "message": "Tensorflow is an Open Source Machine Learning Framework. A malicious user can cause a use after free behavior when decoding PNG images. After `png::CommonFreeDecode(&decode)` gets called, the values of `decode.width` and `decode.height` are in an unspecified state. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "688150BF-477C-48FC-9AEF-A79AC57A6DDC", "versionEndExcluding": null, "versionEndIncluding": "2.5.2", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "C9E69B60-8C97-47E2-9027-9598B8392E5D", "versionEndExcluding": null, "versionEndIncluding": "2.6.2", "versionStartExcluding": null, "versionStartIncluding": "2.6.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.7.0:*:*:*:*:*:*:*", "matchCriteriaId": "2EDFAAB8-799C-4259-9102-944D4760DA2C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Tensorflow is an Open Source Machine Learning Framework. A malicious user can cause a use after free behavior when decoding PNG images. After `png::CommonFreeDecode(&decode)` gets called, the values of `decode.width` and `decode.height` are in an unspecified state. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range."}, {"lang": "es", "value": "Tensorflow es un Marco de Aprendizaje Autom\u00e1tico de C\u00f3digo Abierto. Un usuario malicioso puede causar un comportamiento de uso de memoria previamente liberada cuando decodifica im\u00e1genes PNG. Despu\u00e9s de llamar a \"png::CommonFreeDecode(&amp;decode)\", los valores de \"decode.width\" y \"decode.height\" est\u00e1n en un estado no especificado. La correcci\u00f3n ser\u00e1 incluida en TensorFlow versi\u00f3n 2.8.0. Tambi\u00e9n seleccionaremos este commit en TensorFlow versi\u00f3n 2.7.1, TensorFlow versi\u00f3n 2.6.3, y TensorFlow versi\u00f3n 2.5.3, ya que estos tambi\u00e9n est\u00e1n afectados y a\u00fan est\u00e1n en el rango admitido"}], "evaluatorComment": null, "id": "CVE-2022-23584", "lastModified": "2022-02-10T17:23:58.667", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-02-04T23:15:14.873", "references": [{"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/blob/a1320ec1eac186da1d03f033109191f715b2b130/tensorflow/core/kernels/image/decode_image_op.cc#L339-L346"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/commit/e746adbfcfee15e9cfdb391ff746c765b99bdf9b"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-24x4-6qmh-88qg"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-416"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/e746adbfcfee15e9cfdb391ff746c765b99bdf9b"}, "type": "CWE-416"}
171
Determine whether the {function_name} code is vulnerable or not.
[ "/* vi:set ts=8 sts=4 sw=4 noet:\n *\n * VIM - Vi IMproved\tby Bram Moolenaar\n *\n * Do \":help uganda\" in Vim to read copying and usage conditions.\n * Do \":help credits\" in Vim to see a list of people who contributed.\n * See README.txt for an overview of the Vim source code.\n */", "/*\n * insexpand.c: functions for Insert mode completion\n */", "#include \"vim.h\"", "/*\n * Definitions used for CTRL-X submode.\n * Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[] and\n * ctrl_x_mode_names[] below.\n */\n# define CTRL_X_WANT_IDENT\t0x100", "# define CTRL_X_NORMAL\t\t0 // CTRL-N CTRL-P completion, default\n# define CTRL_X_NOT_DEFINED_YET\t1\n# define CTRL_X_SCROLL\t\t2\n# define CTRL_X_WHOLE_LINE\t3\n# define CTRL_X_FILES\t\t4\n# define CTRL_X_TAGS\t\t(5 + CTRL_X_WANT_IDENT)\n# define CTRL_X_PATH_PATTERNS\t(6 + CTRL_X_WANT_IDENT)\n# define CTRL_X_PATH_DEFINES\t(7 + CTRL_X_WANT_IDENT)\n# define CTRL_X_FINISHED\t\t8\n# define CTRL_X_DICTIONARY\t(9 + CTRL_X_WANT_IDENT)\n# define CTRL_X_THESAURUS\t(10 + CTRL_X_WANT_IDENT)\n# define CTRL_X_CMDLINE\t\t11\n# define CTRL_X_FUNCTION\t12\n# define CTRL_X_OMNI\t\t13\n# define CTRL_X_SPELL\t\t14\n# define CTRL_X_LOCAL_MSG\t15\t// only used in \"ctrl_x_msgs\"\n# define CTRL_X_EVAL\t\t16\t// for builtin function complete()\n# define CTRL_X_CMDLINE_CTRL_X\t17\t// CTRL-X typed in CTRL_X_CMDLINE", "# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]", "// Message for CTRL-X mode, index is ctrl_x_mode.\nstatic char *ctrl_x_msgs[] =\n{\n N_(\" Keyword completion (^N^P)\"), // CTRL_X_NORMAL, ^P/^N compl.\n N_(\" ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)\"),\n NULL, // CTRL_X_SCROLL: depends on state\n N_(\" Whole line completion (^L^N^P)\"),\n N_(\" File name completion (^F^N^P)\"),\n N_(\" Tag completion (^]^N^P)\"),\n N_(\" Path pattern completion (^N^P)\"),\n N_(\" Definition completion (^D^N^P)\"),\n NULL, // CTRL_X_FINISHED\n N_(\" Dictionary completion (^K^N^P)\"),\n N_(\" Thesaurus completion (^T^N^P)\"),\n N_(\" Command-line completion (^V^N^P)\"),\n N_(\" User defined completion (^U^N^P)\"),\n N_(\" Omni completion (^O^N^P)\"),\n N_(\" Spelling suggestion (s^N^P)\"),\n N_(\" Keyword Local completion (^N^P)\"),\n NULL, // CTRL_X_EVAL doesn't use msg.\n N_(\" Command-line completion (^V^N^P)\"),\n};", "#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)\nstatic char *ctrl_x_mode_names[] = {\n\t\"keyword\",\n\t\"ctrl_x\",\n\t\"scroll\",\n\t\"whole_line\",\n\t\"files\",\n\t\"tags\",\n\t\"path_patterns\",\n\t\"path_defines\",\n\t\"unknown\",\t // CTRL_X_FINISHED\n\t\"dictionary\",\n\t\"thesaurus\",\n\t\"cmdline\",\n\t\"function\",\n\t\"omni\",\n\t\"spell\",\n\tNULL,\t\t // CTRL_X_LOCAL_MSG only used in \"ctrl_x_msgs\"\n\t\"eval\",\n\t\"cmdline\",\n};\n#endif", "/*\n * Array indexes used for cp_text[].\n */\n#define CPT_ABBR\t0\t// \"abbr\"\n#define CPT_MENU\t1\t// \"menu\"\n#define CPT_KIND\t2\t// \"kind\"\n#define CPT_INFO\t3\t// \"info\"\n#define CPT_COUNT\t4\t// Number of entries", "/*\n * Structure used to store one match for insert completion.\n */\ntypedef struct compl_S compl_T;\nstruct compl_S\n{\n compl_T\t*cp_next;\n compl_T\t*cp_prev;\n char_u\t*cp_str;\t// matched text\n char_u\t*(cp_text[CPT_COUNT]);\t// text for the menu\n#ifdef FEAT_EVAL\n typval_T\tcp_user_data;\n#endif\n char_u\t*cp_fname;\t// file containing the match, allocated when\n\t\t\t\t// cp_flags has CP_FREE_FNAME\n int\t\tcp_flags;\t// CP_ values\n int\t\tcp_number;\t// sequence number\n};", "// values for cp_flags\n# define CP_ORIGINAL_TEXT 1\t// the original text when the expansion begun\n# define CP_FREE_FNAME\t 2\t// cp_fname is allocated\n# define CP_CONT_S_IPOS\t 4\t// use CONT_S_IPOS for compl_cont_status\n# define CP_EQUAL\t 8\t// ins_compl_equal() always returns TRUE\n# define CP_ICASE\t 16\t// ins_compl_equal() ignores case\n# define CP_FAST\t 32\t// use fast_breakcheck instead of ui_breakcheck", "static char e_hitend[] = N_(\"Hit end of paragraph\");", "/*\n * All the current matches are stored in a list.\n * \"compl_first_match\" points to the start of the list.\n * \"compl_curr_match\" points to the currently selected entry.\n * \"compl_shown_match\" is different from compl_curr_match during\n * ins_compl_get_exp().\n * \"compl_old_match\" points to previous \"compl_curr_match\".\n */\nstatic compl_T *compl_first_match = NULL;\nstatic compl_T *compl_curr_match = NULL;\nstatic compl_T *compl_shown_match = NULL;\nstatic compl_T *compl_old_match = NULL;", "// After using a cursor key <Enter> selects a match in the popup menu,\n// otherwise it inserts a line break.\nstatic int\t compl_enter_selects = FALSE;", "// When \"compl_leader\" is not NULL only matches that start with this string\n// are used.\nstatic char_u\t *compl_leader = NULL;", "static int\t compl_get_longest = FALSE;\t// put longest common string\n\t\t\t\t\t\t// in compl_leader", "static int\t compl_no_insert = FALSE;\t// FALSE: select & insert\n\t\t\t\t\t\t// TRUE: noinsert\nstatic int\t compl_no_select = FALSE;\t// FALSE: select & insert\n\t\t\t\t\t\t// TRUE: noselect", "// Selected one of the matches. When FALSE the match was edited or using the\n// longest common string.\nstatic int\t compl_used_match;", "// didn't finish finding completions.\nstatic int\t compl_was_interrupted = FALSE;", "// Set when character typed while looking for matches and it means we should\n// stop looking for matches.\nstatic int\t compl_interrupted = FALSE;", "static int\t compl_restarting = FALSE;\t// don't insert match", "// When the first completion is done \"compl_started\" is set. When it's\n// FALSE the word to be completed must be located.\nstatic int\t compl_started = FALSE;", "// Which Ctrl-X mode are we in?\nstatic int\t ctrl_x_mode = CTRL_X_NORMAL;", "static int\t compl_matches = 0;\t // number of completion matches\nstatic char_u\t *compl_pattern = NULL;\nstatic int\t compl_direction = FORWARD;\nstatic int\t compl_shows_dir = FORWARD;\nstatic int\t compl_pending = 0;\t // > 1 for postponed CTRL-N\nstatic pos_T\t compl_startpos;\n// Length in bytes of the text being completed (this is deleted to be replaced\n// by the match.)\nstatic int\t compl_length = 0;\nstatic colnr_T\t compl_col = 0;\t // column where the text starts\n\t\t\t\t\t // that is being completed\nstatic char_u\t *compl_orig_text = NULL; // text as it was before\n\t\t\t\t\t // completion started\nstatic int\t compl_cont_mode = 0;\nstatic expand_T\t compl_xp;", "// List of flags for method of completion.\nstatic int\t compl_cont_status = 0;\n# define CONT_ADDING\t1\t// \"normal\" or \"adding\" expansion\n# define CONT_INTRPT\t(2 + 4)\t// a ^X interrupted the current expansion\n\t\t\t\t// it's set only iff N_ADDS is set\n# define CONT_N_ADDS\t4\t// next ^X<> will add-new or expand-current\n# define CONT_S_IPOS\t8\t// next ^X<> will set initial_pos?\n\t\t\t\t// if so, word-wise-expansion will set SOL\n# define CONT_SOL\t16\t// pattern includes start of line, just for\n\t\t\t\t// word-wise expansion, not set for ^X^L\n# define CONT_LOCAL\t32\t// for ctrl_x_mode 0, ^X^P/^X^N do a local\n\t\t\t\t// expansion, (eg use complete=.)", "static int\t compl_opt_refresh_always = FALSE;\nstatic int\t compl_opt_suppress_empty = FALSE;", "static int ins_compl_add(char_u *str, int len, char_u *fname, char_u **cptext, typval_T *user_data, int cdir, int flags, int adup);\nstatic void ins_compl_longest_match(compl_T *match);\nstatic void ins_compl_del_pum(void);\nstatic void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);\nstatic char_u *find_line_end(char_u *ptr);\nstatic void ins_compl_free(void);\nstatic int ins_compl_need_restart(void);\nstatic void ins_compl_new_leader(void);\nstatic int get_compl_len(void);\nstatic void ins_compl_restart(void);\nstatic void ins_compl_set_original_text(char_u *str);\nstatic void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);\n# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)\nstatic void ins_compl_add_list(list_T *list);\nstatic void ins_compl_add_dict(dict_T *dict);\n# endif\nstatic int ins_compl_key2dir(int c);\nstatic int ins_compl_pum_key(int c);\nstatic int ins_compl_key2count(int c);\nstatic void show_pum(int prev_w_wrow, int prev_w_leftcol);\nstatic unsigned quote_meta(char_u *dest, char_u *str, int len);", "#ifdef FEAT_SPELL\nstatic void spell_back_to_badword(void);\nstatic int spell_bad_len = 0;\t// length of located bad word\n#endif", "/*\n * CTRL-X pressed in Insert mode.\n */\n void\nins_ctrl_x(void)\n{\n if (!ctrl_x_mode_cmdline())\n {\n\t// if the next ^X<> won't ADD nothing, then reset compl_cont_status\n\tif (compl_cont_status & CONT_N_ADDS)\n\t compl_cont_status |= CONT_INTRPT;\n\telse\n\t compl_cont_status = 0;\n\t// We're not sure which CTRL-X mode it will be yet\n\tctrl_x_mode = CTRL_X_NOT_DEFINED_YET;\n\tedit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));\n\tedit_submode_pre = NULL;\n\tshowmode();\n }\n else\n\t// CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X\n\t// CTRL-V look like CTRL-N\n\tctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;", " may_trigger_modechanged();\n}", "/*\n * Functions to check the current CTRL-X mode.\n */\nint ctrl_x_mode_none(void) { return ctrl_x_mode == 0; }\nint ctrl_x_mode_normal(void) { return ctrl_x_mode == CTRL_X_NORMAL; }\nint ctrl_x_mode_scroll(void) { return ctrl_x_mode == CTRL_X_SCROLL; }\nint ctrl_x_mode_whole_line(void) { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }\nint ctrl_x_mode_files(void) { return ctrl_x_mode == CTRL_X_FILES; }\nint ctrl_x_mode_tags(void) { return ctrl_x_mode == CTRL_X_TAGS; }\nint ctrl_x_mode_path_patterns(void) {\n\t\t\t\t return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }\nint ctrl_x_mode_path_defines(void) {\n\t\t\t\t return ctrl_x_mode == CTRL_X_PATH_DEFINES; }\nint ctrl_x_mode_dictionary(void) { return ctrl_x_mode == CTRL_X_DICTIONARY; }\nint ctrl_x_mode_thesaurus(void) { return ctrl_x_mode == CTRL_X_THESAURUS; }\nint ctrl_x_mode_cmdline(void) {\n\treturn ctrl_x_mode == CTRL_X_CMDLINE\n\t\t|| ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }\nint ctrl_x_mode_function(void) { return ctrl_x_mode == CTRL_X_FUNCTION; }\nint ctrl_x_mode_omni(void) { return ctrl_x_mode == CTRL_X_OMNI; }\nint ctrl_x_mode_spell(void) { return ctrl_x_mode == CTRL_X_SPELL; }\nstatic int ctrl_x_mode_eval(void) { return ctrl_x_mode == CTRL_X_EVAL; }\nint ctrl_x_mode_line_or_eval(void) {\n return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }", "/*\n * Whether other than default completion has been selected.\n */\n int\nctrl_x_mode_not_default(void)\n{\n return ctrl_x_mode != CTRL_X_NORMAL;\n}", "/*\n * Whether CTRL-X was typed without a following character,\n * not including when in CTRL-X CTRL-V mode.\n */\n int\nctrl_x_mode_not_defined_yet(void)\n{\n return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;\n}", "/*\n * Return TRUE if currently in \"normal\" or \"adding\" insert completion matches\n * state\n */\n int\ncompl_status_adding(void)\n{\n return compl_cont_status & CONT_ADDING;\n}", "/*\n * Return TRUE if the completion pattern includes start of line, just for\n * word-wise expansion.\n */\n int\ncompl_status_sol(void)\n{\n return compl_cont_status & CONT_SOL;\n}", "/*\n * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)\n */\n int\ncompl_status_local(void)\n{\n return compl_cont_status & CONT_LOCAL;\n}", "/*\n * Clear the completion status flags\n */\n void\ncompl_status_clear(void)\n{\n compl_cont_status = 0;\n}", "/*\n * Return TRUE if completion is using the forward direction matches\n */\n static int\ncompl_dir_forward(void)\n{\n return compl_direction == FORWARD;\n}", "/*\n * Return TRUE if currently showing forward completion matches\n */\n static int\ncompl_shows_dir_forward(void)\n{\n return compl_shows_dir == FORWARD;\n}", "/*\n * Return TRUE if currently showing backward completion matches\n */\n static int\ncompl_shows_dir_backward(void)\n{\n return compl_shows_dir == BACKWARD;\n}", "/*\n * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.\n */\n int\nhas_compl_option(int dict_opt)\n{\n if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL\n#ifdef FEAT_SPELL\n\t\t\t\t\t\t\t&& !curwin->w_p_spell\n#endif\n\t\t\t\t\t\t\t)\n\t\t : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL\n#ifdef FEAT_COMPL_FUNC\n\t\t && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL\n#endif\n\t\t ))\n {\n\tctrl_x_mode = CTRL_X_NORMAL;\n\tedit_submode = NULL;\n\tmsg_attr(dict_opt ? _(\"'dictionary' option is empty\")\n\t\t\t : _(\"'thesaurus' option is empty\"),\n\t\t\t\t\t\t\t HL_ATTR(HLF_E));\n\tif (emsg_silent == 0 && !in_assert_fails)\n\t{\n\t vim_beep(BO_COMPL);\n\t setcursor();\n\t out_flush();\n#ifdef FEAT_EVAL\n\t if (!get_vim_var_nr(VV_TESTING))\n#endif\n\t\tui_delay(2004L, FALSE);\n\t}\n\treturn FALSE;\n }\n return TRUE;\n}", "/*\n * Is the character \"c\" a valid key to go to or keep us in CTRL-X mode?\n * This depends on the current mode.\n */\n int\nvim_is_ctrl_x_key(int c)\n{\n // Always allow ^R - let its results then be checked\n if (c == Ctrl_R)\n\treturn TRUE;", " // Accept <PageUp> and <PageDown> if the popup menu is visible.\n if (ins_compl_pum_key(c))\n\treturn TRUE;", " switch (ctrl_x_mode)\n {\n\tcase 0:\t\t // Not in any CTRL-X mode\n\t return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);\n\tcase CTRL_X_NOT_DEFINED_YET:\n\tcase CTRL_X_CMDLINE_CTRL_X:\n\t return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E\n\t\t || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB\n\t\t || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P\n\t\t || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V\n\t\t || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O\n\t\t || c == Ctrl_S || c == Ctrl_K || c == 's'\n\t\t || c == Ctrl_Z);\n\tcase CTRL_X_SCROLL:\n\t return (c == Ctrl_Y || c == Ctrl_E);\n\tcase CTRL_X_WHOLE_LINE:\n\t return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);\n\tcase CTRL_X_FILES:\n\t return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);\n\tcase CTRL_X_DICTIONARY:\n\t return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);\n\tcase CTRL_X_THESAURUS:\n\t return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);\n\tcase CTRL_X_TAGS:\n\t return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);\n#ifdef FEAT_FIND_ID\n\tcase CTRL_X_PATH_PATTERNS:\n\t return (c == Ctrl_P || c == Ctrl_N);\n\tcase CTRL_X_PATH_DEFINES:\n\t return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);\n#endif\n\tcase CTRL_X_CMDLINE:\n\t return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N\n\t\t || c == Ctrl_X);\n#ifdef FEAT_COMPL_FUNC\n\tcase CTRL_X_FUNCTION:\n\t return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);\n\tcase CTRL_X_OMNI:\n\t return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);\n#endif\n\tcase CTRL_X_SPELL:\n\t return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);\n\tcase CTRL_X_EVAL:\n\t return (c == Ctrl_P || c == Ctrl_N);\n }\n internal_error(\"vim_is_ctrl_x_key()\");\n return FALSE;\n}", "/*\n * Return TRUE if \"match\" is the original text when the completion began.\n */\n static int\nmatch_at_original_text(compl_T *match)\n{\n return match->cp_flags & CP_ORIGINAL_TEXT;\n}", "/*\n * Returns TRUE if \"match\" is the first match in the completion list.\n */\n static int\nis_first_match(compl_T *match)\n{\n return match == compl_first_match;\n}", "/*\n * Return TRUE when character \"c\" is part of the item currently being\n * completed. Used to decide whether to abandon complete mode when the menu\n * is visible.\n */\n int\nins_compl_accept_char(int c)\n{\n if (ctrl_x_mode & CTRL_X_WANT_IDENT)\n\t// When expanding an identifier only accept identifier chars.\n\treturn vim_isIDc(c);", " switch (ctrl_x_mode)\n {\n\tcase CTRL_X_FILES:\n\t // When expanding file name only accept file name chars. But not\n\t // path separators, so that \"proto/<Tab>\" expands files in\n\t // \"proto\", not \"proto/\" as a whole\n\t return vim_isfilec(c) && !vim_ispathsep(c);", "\tcase CTRL_X_CMDLINE:\n\tcase CTRL_X_CMDLINE_CTRL_X:\n\tcase CTRL_X_OMNI:\n\t // Command line and Omni completion can work with just about any\n\t // printable character, but do stop at white space.\n\t return vim_isprintc(c) && !VIM_ISWHITE(c);", "\tcase CTRL_X_WHOLE_LINE:\n\t // For while line completion a space can be part of the line.\n\t return vim_isprintc(c);\n }\n return vim_iswordc(c);\n}", "/*\n * Get the completed text by inferring the case of the originally typed text.", "", " */\n static char_u *\nins_compl_infercase_gettext(\n\tchar_u\t*str,", "\tint\tactual_len,\n\tint\tactual_compl_length,\n\tint\tmin_len)", "{\n int\t\t*wca;\t\t\t// Wide character array.\n char_u\t*p;\n int\t\ti, c;\n int\t\thas_lower = FALSE;\n int\t\twas_letter = FALSE;", "", "\n IObuff[0] = NUL;", " // Allocate wide character array for the completion and fill it.", " wca = ALLOC_MULT(int, actual_len);", " if (wca == NULL)\n\treturn IObuff;", " p = str;", " for (i = 0; i < actual_len; ++i)", "\tif (has_mbyte)\n\t wca[i] = mb_ptr2char_adv(&p);\n\telse\n\t wca[i] = *(p++);", " // Rule 1: Were any chars converted to lower?\n p = compl_orig_text;\n for (i = 0; i < min_len; ++i)\n {\n\tif (has_mbyte)\n\t c = mb_ptr2char_adv(&p);\n\telse\n\t c = *(p++);\n\tif (MB_ISLOWER(c))\n\t{\n\t has_lower = TRUE;\n\t if (MB_ISUPPER(wca[i]))\n\t {\n\t\t// Rule 1 is satisfied.", "\t\tfor (i = actual_compl_length; i < actual_len; ++i)", "\t\t wca[i] = MB_TOLOWER(wca[i]);\n\t\tbreak;\n\t }\n\t}\n }", " // Rule 2: No lower case, 2nd consecutive letter converted to\n // upper case.\n if (!has_lower)\n {\n\tp = compl_orig_text;\n\tfor (i = 0; i < min_len; ++i)\n\t{\n\t if (has_mbyte)\n\t\tc = mb_ptr2char_adv(&p);\n\t else\n\t\tc = *(p++);\n\t if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))\n\t {\n\t\t// Rule 2 is satisfied.", "\t\tfor (i = actual_compl_length; i < actual_len; ++i)", "\t\t wca[i] = MB_TOUPPER(wca[i]);\n\t\tbreak;\n\t }\n\t was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);\n\t}\n }", " // Copy the original case of the part we typed.\n p = compl_orig_text;\n for (i = 0; i < min_len; ++i)\n {\n\tif (has_mbyte)\n\t c = mb_ptr2char_adv(&p);\n\telse\n\t c = *(p++);\n\tif (MB_ISLOWER(c))\n\t wca[i] = MB_TOLOWER(wca[i]);\n\telse if (MB_ISUPPER(c))\n\t wca[i] = MB_TOUPPER(wca[i]);\n }", " // Generate encoding specific output from wide character array.", " // Multi-byte characters can occupy up to five bytes more than\n // ASCII characters, and we also need one byte for NUL, so stay\n // six bytes away from the edge of IObuff.", " p = IObuff;\n i = 0;", " while (i < actual_len && (p - IObuff + 6) < IOSIZE)\n\tif (has_mbyte)", "\t p += (*mb_char2bytes)(wca[i++], p);\n\telse\n\t *(p++) = wca[i++];", "", " *p = NUL;", "\n vim_free(wca);\n", " return IObuff;\n}", "/*\n * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the\n * case of the originally typed text is used, and the case of the completed\n * text is inferred, ie this tries to work out what case you probably wanted\n * the rest of the word to be in -- webb\n */\n int\nins_compl_add_infercase(\n char_u\t*str_arg,\n int\t\tlen,\n int\t\ticase,\n char_u\t*fname,\n int\t\tdir,\n int\t\tcont_s_ipos) // next ^X<> will set initial_pos\n{\n char_u\t*str = str_arg;\n char_u\t*p;", " int\t\tactual_len;\t\t// Take multi-byte characters\n int\t\tactual_compl_length;\t// into account.", " int\t\tmin_len;\n int\t\tflags = 0;", "", "\n if (p_ic && curbuf->b_p_inf && len > 0)\n {\n\t// Infer case of completed part.", "\t// Find actual length of completion.\n\tif (has_mbyte)\n\t{\n\t p = str;", "\t actual_len = 0;", "\t while (*p != NUL)\n\t {\n\t\tMB_PTR_ADV(p);", "\t\t++actual_len;", "\t }\n\t}\n\telse", "\t actual_len = len;", "\n\t// Find actual length of original text.\n\tif (has_mbyte)\n\t{\n\t p = compl_orig_text;", "\t actual_compl_length = 0;", "\t while (*p != NUL)\n\t {\n\t\tMB_PTR_ADV(p);", "\t\t++actual_compl_length;", "\t }\n\t}\n\telse", "\t actual_compl_length = compl_length;", "\t// \"actual_len\" may be smaller than \"actual_compl_length\" when using", "\t// thesaurus, only use the minimum when comparing.", "\tmin_len = actual_len < actual_compl_length\n\t\t\t\t\t ? actual_len : actual_compl_length;", "\tstr = ins_compl_infercase_gettext(str, actual_len, actual_compl_length,\n\t\t\t\t\t\t\t\tmin_len);", " }\n if (cont_s_ipos)\n\tflags |= CP_CONT_S_IPOS;\n if (icase)\n\tflags |= CP_ICASE;\n", " return ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE);", "}", "/*\n * Add a match to the list of matches. The arguments are:\n * str - text of the match to add\n * len - length of \"str\". If -1, then the length of \"str\" is\n *\t\t computed.\n * fname - file name to associate with this match.\n * cptext - list of strings to use with this match (for abbr, menu, info\n *\t\t and kind)\n * user_data - user supplied data (any vim type) for this match\n * cdir\t - match direction. If 0, use \"compl_direction\".\n * flags_arg - match flags (cp_flags)\n * adup\t - accept this match even if it is already present.\n * If \"cdir\" is FORWARD, then the match is added after the current match.\n * Otherwise, it is added before the current match.\n *\n * If the given string is already in the list of completions, then return\n * NOTDONE, otherwise add it to the list and return OK. If there is an error,\n * maybe because alloc() returns NULL, then FAIL is returned.\n */\n static int\nins_compl_add(\n char_u\t*str,\n int\t\tlen,\n char_u\t*fname,\n char_u\t**cptext,\t // extra text for popup menu or NULL\n typval_T\t*user_data UNUSED, // \"user_data\" entry or NULL\n int\t\tcdir,\n int\t\tflags_arg,\n int\t\tadup)\t\t// accept duplicate match\n{\n compl_T\t*match;\n int\t\tdir = (cdir == 0 ? compl_direction : cdir);\n int\t\tflags = flags_arg;", " if (flags & CP_FAST)\n\tfast_breakcheck();\n else\n\tui_breakcheck();\n if (got_int)\n\treturn FAIL;\n if (len < 0)\n\tlen = (int)STRLEN(str);", " // If the same match is already present, don't add it.\n if (compl_first_match != NULL && !adup)\n {\n\tmatch = compl_first_match;\n\tdo\n\t{\n\t if (!match_at_original_text(match)\n\t\t && STRNCMP(match->cp_str, str, len) == 0\n\t\t && match->cp_str[len] == NUL)\n\t\treturn NOTDONE;\n\t match = match->cp_next;\n\t} while (match != NULL && !is_first_match(match));\n }", " // Remove any popup menu before changing the list of matches.\n ins_compl_del_pum();", " // Allocate a new match structure.\n // Copy the values to the new match structure.\n match = ALLOC_CLEAR_ONE(compl_T);\n if (match == NULL)\n\treturn FAIL;\n match->cp_number = -1;\n if (flags & CP_ORIGINAL_TEXT)\n\tmatch->cp_number = 0;\n if ((match->cp_str = vim_strnsave(str, len)) == NULL)\n {\n\tvim_free(match);\n\treturn FAIL;\n }", " // match-fname is:\n // - compl_curr_match->cp_fname if it is a string equal to fname.\n // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.\n // - NULL otherwise.\t--Acevedo\n if (fname != NULL\n\t && compl_curr_match != NULL\n\t && compl_curr_match->cp_fname != NULL\n\t && STRCMP(fname, compl_curr_match->cp_fname) == 0)\n\tmatch->cp_fname = compl_curr_match->cp_fname;\n else if (fname != NULL)\n {\n\tmatch->cp_fname = vim_strsave(fname);\n\tflags |= CP_FREE_FNAME;\n }\n else\n\tmatch->cp_fname = NULL;\n match->cp_flags = flags;", " if (cptext != NULL)\n {\n\tint i;", "\tfor (i = 0; i < CPT_COUNT; ++i)\n\t if (cptext[i] != NULL && *cptext[i] != NUL)\n\t\tmatch->cp_text[i] = vim_strsave(cptext[i]);\n }\n#ifdef FEAT_EVAL\n if (user_data != NULL)\n\tmatch->cp_user_data = *user_data;\n#endif", " // Link the new match structure after (FORWARD) or before (BACKWARD) the\n // current match in the list of matches .\n if (compl_first_match == NULL)\n\tmatch->cp_next = match->cp_prev = NULL;\n else if (dir == FORWARD)\n {\n\tmatch->cp_next = compl_curr_match->cp_next;\n\tmatch->cp_prev = compl_curr_match;\n }\n else\t// BACKWARD\n {\n\tmatch->cp_next = compl_curr_match;\n\tmatch->cp_prev = compl_curr_match->cp_prev;\n }\n if (match->cp_next)\n\tmatch->cp_next->cp_prev = match;\n if (match->cp_prev)\n\tmatch->cp_prev->cp_next = match;\n else\t// if there's nothing before, it is the first match\n\tcompl_first_match = match;\n compl_curr_match = match;", " // Find the longest common string if still doing that.\n if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)\n\tins_compl_longest_match(match);", " return OK;\n}", "/*\n * Return TRUE if \"str[len]\" matches with match->cp_str, considering\n * match->cp_flags.\n */\n static int\nins_compl_equal(compl_T *match, char_u *str, int len)\n{\n if (match->cp_flags & CP_EQUAL)\n\treturn TRUE;\n if (match->cp_flags & CP_ICASE)\n\treturn STRNICMP(match->cp_str, str, (size_t)len) == 0;\n return STRNCMP(match->cp_str, str, (size_t)len) == 0;\n}", "/*\n * Reduce the longest common string for match \"match\".\n */\n static void\nins_compl_longest_match(compl_T *match)\n{\n char_u\t*p, *s;\n int\t\tc1, c2;\n int\t\thad_match;", " if (compl_leader == NULL)\n {\n\t// First match, use it as a whole.\n\tcompl_leader = vim_strsave(match->cp_str);\n\tif (compl_leader == NULL)\n\t return;", "\thad_match = (curwin->w_cursor.col > compl_col);\n\tins_compl_delete();\n\tins_bytes(compl_leader + get_compl_len());\n\tins_redraw(FALSE);", "\t// When the match isn't there (to avoid matching itself) remove it\n\t// again after redrawing.\n\tif (!had_match)\n\t ins_compl_delete();\n\tcompl_used_match = FALSE;", "\treturn;\n }", " // Reduce the text if this match differs from compl_leader.\n p = compl_leader;\n s = match->cp_str;\n while (*p != NUL)\n {\n\tif (has_mbyte)\n\t{\n\t c1 = mb_ptr2char(p);\n\t c2 = mb_ptr2char(s);\n\t}\n\telse\n\t{\n\t c1 = *p;\n\t c2 = *s;\n\t}\n\tif ((match->cp_flags & CP_ICASE)\n\t\t? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))\n\t break;\n\tif (has_mbyte)\n\t{\n\t MB_PTR_ADV(p);\n\t MB_PTR_ADV(s);\n\t}\n\telse\n\t{\n\t ++p;\n\t ++s;\n\t}\n }", " if (*p != NUL)\n {\n\t// Leader was shortened, need to change the inserted text.\n\t*p = NUL;\n\thad_match = (curwin->w_cursor.col > compl_col);\n\tins_compl_delete();\n\tins_bytes(compl_leader + get_compl_len());\n\tins_redraw(FALSE);", "\t// When the match isn't there (to avoid matching itself) remove it\n\t// again after redrawing.\n\tif (!had_match)\n\t ins_compl_delete();\n }", " compl_used_match = FALSE;\n}", "/*\n * Add an array of matches to the list of matches.\n * Frees matches[].\n */\n static void\nins_compl_add_matches(\n int\t\tnum_matches,\n char_u\t**matches,\n int\t\ticase)\n{\n int\t\ti;\n int\t\tadd_r = OK;\n int\t\tdir = compl_direction;", " for (i = 0; i < num_matches && add_r != FAIL; i++)\n\tif ((add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,\n\t\t\t CP_FAST | (icase ? CP_ICASE : 0), FALSE)) == OK)\n\t // if dir was BACKWARD then honor it just once\n\t dir = FORWARD;\n FreeWild(num_matches, matches);\n}", "/*\n * Make the completion list cyclic.\n * Return the number of matches (excluding the original).\n */\n static int\nins_compl_make_cyclic(void)\n{\n compl_T *match;\n int\t count = 0;", " if (compl_first_match == NULL)\n\treturn 0;", " // Find the end of the list.\n match = compl_first_match;\n // there's always an entry for the compl_orig_text, it doesn't count.\n while (match->cp_next != NULL && !is_first_match(match->cp_next))\n {\n\tmatch = match->cp_next;\n\t++count;\n }\n match->cp_next = compl_first_match;\n compl_first_match->cp_prev = match;", " return count;\n}", "/*\n * Return whether there currently is a shown match.\n */\n int\nins_compl_has_shown_match(void)\n{\n return compl_shown_match == NULL\n\t|| compl_shown_match != compl_shown_match->cp_next;\n}", "/*\n * Return whether the shown match is long enough.\n */\n int\nins_compl_long_shown_match(void)\n{\n return (int)STRLEN(compl_shown_match->cp_str)\n\t\t\t\t\t > curwin->w_cursor.col - compl_col;\n}", "/*\n * Set variables that store noselect and noinsert behavior from the\n * 'completeopt' value.\n */\n void\ncompleteopt_was_set(void)\n{\n compl_no_insert = FALSE;\n compl_no_select = FALSE;\n if (strstr((char *)p_cot, \"noselect\") != NULL)\n\tcompl_no_select = TRUE;\n if (strstr((char *)p_cot, \"noinsert\") != NULL)\n\tcompl_no_insert = TRUE;\n}", "\n// \"compl_match_array\" points the currently displayed list of entries in the\n// popup menu. It is NULL when there is no popup menu.\nstatic pumitem_T *compl_match_array = NULL;\nstatic int compl_match_arraysize;", "/*\n * Update the screen and when there is any scrolling remove the popup menu.\n */\n static void\nins_compl_upd_pum(void)\n{\n int\t\th;", " if (compl_match_array == NULL)\n\treturn;", " h = curwin->w_cline_height;\n // Update the screen later, before drawing the popup menu over it.\n pum_call_update_screen();\n if (h != curwin->w_cline_height)\n\tins_compl_del_pum();\n}", "/*\n * Remove any popup menu.\n */\n static void\nins_compl_del_pum(void)\n{\n if (compl_match_array == NULL)\n\treturn;", " pum_undisplay();\n VIM_CLEAR(compl_match_array);\n}", "/*\n * Return TRUE if the popup menu should be displayed.\n */\n int\npum_wanted(void)\n{\n // 'completeopt' must contain \"menu\" or \"menuone\"\n if (vim_strchr(p_cot, 'm') == NULL)\n\treturn FALSE;", " // The display looks bad on a B&W display.\n if (t_colors < 8\n#ifdef FEAT_GUI\n\t && !gui.in_use\n#endif\n\t )\n\treturn FALSE;\n return TRUE;\n}", "/*\n * Return TRUE if there are two or more matches to be shown in the popup menu.\n * One if 'completopt' contains \"menuone\".\n */\n static int\npum_enough_matches(void)\n{\n compl_T *compl;\n int\t\ti;", " // Don't display the popup menu if there are no matches or there is only\n // one (ignoring the original text).\n compl = compl_first_match;\n i = 0;\n do\n {\n\tif (compl == NULL || (!match_at_original_text(compl) && ++i == 2))\n\t break;\n\tcompl = compl->cp_next;\n } while (!is_first_match(compl));", " if (strstr((char *)p_cot, \"menuone\") != NULL)\n\treturn (i >= 1);\n return (i >= 2);\n}", "#if defined(FEAT_EVAL) || defined(PROTO)\n/*\n * Allocate Dict for the completed item.\n * { word, abbr, menu, kind, info }\n */\n static dict_T *\nins_compl_dict_alloc(compl_T *match)\n{\n dict_T *dict = dict_alloc_lock(VAR_FIXED);", " if (dict == NULL)\n\treturn NULL;", " dict_add_string(dict, \"word\", match->cp_str);\n dict_add_string(dict, \"abbr\", match->cp_text[CPT_ABBR]);\n dict_add_string(dict, \"menu\", match->cp_text[CPT_MENU]);\n dict_add_string(dict, \"kind\", match->cp_text[CPT_KIND]);\n dict_add_string(dict, \"info\", match->cp_text[CPT_INFO]);\n if (match->cp_user_data.v_type == VAR_UNKNOWN)\n\tdict_add_string(dict, \"user_data\", (char_u *)\"\");\n else\n\tdict_add_tv(dict, \"user_data\", &match->cp_user_data);", " return dict;\n}", "/*\n * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode\n * completion menu is changed.\n */\n static void\ntrigger_complete_changed_event(int cur)\n{\n dict_T\t *v_event;\n dict_T\t *item;\n static int\t recursive = FALSE;\n save_v_event_T save_v_event;", " if (recursive)\n\treturn;", " if (cur < 0)\n\titem = dict_alloc();\n else\n\titem = ins_compl_dict_alloc(compl_curr_match);\n if (item == NULL)\n\treturn;\n v_event = get_v_event(&save_v_event);\n dict_add_dict(v_event, \"completed_item\", item);\n pum_set_event_info(v_event);\n dict_set_items_ro(v_event);", " recursive = TRUE;\n textlock++;\n apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);\n textlock--;\n recursive = FALSE;", " restore_v_event(v_event, &save_v_event);\n}\n#endif", "/*\n * Build a popup menu to show the completion matches.\n * Returns the popup menu entry that should be selected. Returns -1 if nothing\n * should be selected.\n */\n static int\nins_compl_build_pum(void)\n{\n compl_T *compl;\n compl_T *shown_compl = NULL;\n int\t\tdid_find_shown_match = FALSE;\n int\t\tshown_match_ok = FALSE;\n int\t\ti;\n int\t\tcur = -1;\n int\t\tlead_len = 0;", " // Need to build the popup menu list.\n compl_match_arraysize = 0;\n compl = compl_first_match;\n if (compl_leader != NULL)\n\tlead_len = (int)STRLEN(compl_leader);", " do\n {\n\tif (!match_at_original_text(compl)\n\t\t&& (compl_leader == NULL\n\t\t || ins_compl_equal(compl, compl_leader, lead_len)))\n\t ++compl_match_arraysize;\n\tcompl = compl->cp_next;\n } while (compl != NULL && !is_first_match(compl));", " if (compl_match_arraysize == 0)\n\treturn -1;", " compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);\n if (compl_match_array == NULL)\n\treturn -1;", " // If the current match is the original text don't find the first\n // match after it, don't highlight anything.\n if (match_at_original_text(compl_shown_match))\n\tshown_match_ok = TRUE;", " i = 0;\n compl = compl_first_match;\n do\n {\n\tif (!match_at_original_text(compl)\n\t\t&& (compl_leader == NULL\n\t\t || ins_compl_equal(compl, compl_leader, lead_len)))\n\t{\n\t if (!shown_match_ok)\n\t {\n\t\tif (compl == compl_shown_match || did_find_shown_match)\n\t\t{\n\t\t // This item is the shown match or this is the\n\t\t // first displayed item after the shown match.\n\t\t compl_shown_match = compl;\n\t\t did_find_shown_match = TRUE;\n\t\t shown_match_ok = TRUE;\n\t\t}\n\t\telse\n\t\t // Remember this displayed match for when the\n\t\t // shown match is just below it.\n\t\t shown_compl = compl;\n\t\tcur = i;\n\t }", "\t if (compl->cp_text[CPT_ABBR] != NULL)\n\t\tcompl_match_array[i].pum_text =\n\t\t compl->cp_text[CPT_ABBR];\n\t else\n\t\tcompl_match_array[i].pum_text = compl->cp_str;\n\t compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];\n\t compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];\n\t if (compl->cp_text[CPT_MENU] != NULL)\n\t\tcompl_match_array[i++].pum_extra =\n\t\t compl->cp_text[CPT_MENU];\n\t else\n\t\tcompl_match_array[i++].pum_extra = compl->cp_fname;\n\t}", "\tif (compl == compl_shown_match)\n\t{\n\t did_find_shown_match = TRUE;", "\t // When the original text is the shown match don't set\n\t // compl_shown_match.\n\t if (match_at_original_text(compl))\n\t\tshown_match_ok = TRUE;", "\t if (!shown_match_ok && shown_compl != NULL)\n\t {\n\t\t// The shown match isn't displayed, set it to the\n\t\t// previously displayed match.\n\t\tcompl_shown_match = shown_compl;\n\t\tshown_match_ok = TRUE;\n\t }\n\t}\n\tcompl = compl->cp_next;\n } while (compl != NULL && !is_first_match(compl));", " if (!shown_match_ok) // no displayed match at all\n\tcur = -1;", " return cur;\n}", "/*\n * Show the popup menu for the list of matches.\n * Also adjusts \"compl_shown_match\" to an entry that is actually displayed.\n */\n void\nins_compl_show_pum(void)\n{\n int\t\ti;\n int\t\tcur = -1;\n colnr_T\tcol;", " if (!pum_wanted() || !pum_enough_matches())\n\treturn;", "#if defined(FEAT_EVAL)\n // Dirty hard-coded hack: remove any matchparen highlighting.\n do_cmdline_cmd((char_u *)\"if exists('g:loaded_matchparen')|:3match none|endif\");\n#endif", " // Update the screen later, before drawing the popup menu over it.\n pum_call_update_screen();", " if (compl_match_array == NULL)\n\t// Need to build the popup menu list.\n\tcur = ins_compl_build_pum();\n else\n {\n\t// popup menu already exists, only need to find the current item.\n\tfor (i = 0; i < compl_match_arraysize; ++i)\n\t if (compl_match_array[i].pum_text == compl_shown_match->cp_str\n\t\t || compl_match_array[i].pum_text\n\t\t\t\t == compl_shown_match->cp_text[CPT_ABBR])\n\t {\n\t\tcur = i;\n\t\tbreak;\n\t }\n }", " if (compl_match_array == NULL)\n\treturn;", " // In Replace mode when a $ is displayed at the end of the line only\n // part of the screen would be updated. We do need to redraw here.\n dollar_vcol = -1;", " // Compute the screen column of the start of the completed text.\n // Use the cursor to get all wrapping and other settings right.\n col = curwin->w_cursor.col;\n curwin->w_cursor.col = compl_col;\n pum_display(compl_match_array, compl_match_arraysize, cur);\n curwin->w_cursor.col = col;", "#ifdef FEAT_EVAL\n if (has_completechanged())\n\ttrigger_complete_changed_event(cur);\n#endif\n}", "#define DICT_FIRST\t(1)\t// use just first element in \"dict\"\n#define DICT_EXACT\t(2)\t// \"dict\" is the exact name of a file", "/*\n * Add any identifiers that match the given pattern \"pat\" in the list of\n * dictionary files \"dict_start\" to the list of completions.\n */\n static void\nins_compl_dictionaries(\n char_u\t*dict_start,\n char_u\t*pat,\n int\t\tflags,\t\t// DICT_FIRST and/or DICT_EXACT\n int\t\tthesaurus)\t// Thesaurus completion\n{\n char_u\t*dict = dict_start;\n char_u\t*ptr;\n char_u\t*buf;\n regmatch_T\tregmatch;\n char_u\t**files;\n int\t\tcount;\n int\t\tsave_p_scs;\n int\t\tdir = compl_direction;", " if (*dict == NUL)\n {\n#ifdef FEAT_SPELL\n\t// When 'dictionary' is empty and spell checking is enabled use\n\t// \"spell\".\n\tif (!thesaurus && curwin->w_p_spell)\n\t dict = (char_u *)\"spell\";\n\telse\n#endif\n\t return;\n }", " buf = alloc(LSIZE);\n if (buf == NULL)\n\treturn;\n regmatch.regprog = NULL;\t// so that we can goto theend", " // If 'infercase' is set, don't use 'smartcase' here\n save_p_scs = p_scs;\n if (curbuf->b_p_inf)\n\tp_scs = FALSE;", " // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern\n // to only match at the start of a line. Otherwise just match the\n // pattern. Also need to double backslashes.\n if (ctrl_x_mode_line_or_eval())\n {\n\tchar_u *pat_esc = vim_strsave_escaped(pat, (char_u *)\"\\\\\");\n\tsize_t len;", "\tif (pat_esc == NULL)\n\t goto theend;\n\tlen = STRLEN(pat_esc) + 10;\n\tptr = alloc(len);\n\tif (ptr == NULL)\n\t{\n\t vim_free(pat_esc);\n\t goto theend;\n\t}\n\tvim_snprintf((char *)ptr, len, \"^\\\\s*\\\\zs\\\\V%s\", pat_esc);\n\tregmatch.regprog = vim_regcomp(ptr, RE_MAGIC);\n\tvim_free(pat_esc);\n\tvim_free(ptr);\n }\n else\n {\n\tregmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);\n\tif (regmatch.regprog == NULL)\n\t goto theend;\n }", " // ignore case depends on 'ignorecase', 'smartcase' and \"pat\"\n regmatch.rm_ic = ignorecase(pat);\n while (*dict != NUL && !got_int && !compl_interrupted)\n {\n\t// copy one dictionary file name into buf\n\tif (flags == DICT_EXACT)\n\t{\n\t count = 1;\n\t files = &dict;\n\t}\n\telse\n\t{\n\t // Expand wildcards in the dictionary name, but do not allow\n\t // backticks (for security, the 'dict' option may have been set in\n\t // a modeline).\n\t copy_option_part(&dict, buf, LSIZE, \",\");\n# ifdef FEAT_SPELL\n\t if (!thesaurus && STRCMP(buf, \"spell\") == 0)\n\t\tcount = -1;\n\t else\n# endif\n\t\tif (vim_strchr(buf, '`') != NULL\n\t\t || expand_wildcards(1, &buf, &count, &files,\n\t\t\t\t\t\t EW_FILE|EW_SILENT) != OK)\n\t\tcount = 0;\n\t}", "# ifdef FEAT_SPELL\n\tif (count == -1)\n\t{\n\t // Complete from active spelling. Skip \"\\<\" in the pattern, we\n\t // don't use it as a RE.\n\t if (pat[0] == '\\\\' && pat[1] == '<')\n\t\tptr = pat + 2;\n\t else\n\t\tptr = pat;\n\t spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);\n\t}\n\telse\n# endif\n\t if (count > 0)\t// avoid warning for using \"files\" uninit\n\t{\n\t ins_compl_files(count, files, thesaurus, flags,\n\t\t\t\t\t\t\t&regmatch, buf, &dir);\n\t if (flags != DICT_EXACT)\n\t\tFreeWild(count, files);\n\t}\n\tif (flags != 0)\n\t break;\n }", "theend:\n p_scs = save_p_scs;\n vim_regfree(regmatch.regprog);\n vim_free(buf);\n}", "/*\n * Add all the words in the line \"*buf_arg\" from the thesaurus file \"fname\"\n * skipping the word at 'skip_word'. Returns OK on success.\n */\n static int\nthesarurs_add_words_in_line(\n\tchar_u\t*fname,\n\tchar_u\t**buf_arg,\n\tint\tdir,\n\tchar_u\t*skip_word)\n{\n int\t\tstatus = OK;\n char_u\t*ptr;\n char_u\t*wstart;", " // Add the other matches on the line\n ptr = *buf_arg;\n while (!got_int)\n {\n\t// Find start of the next word. Skip white\n\t// space and punctuation.\n\tptr = find_word_start(ptr);\n\tif (*ptr == NUL || *ptr == NL)\n\t break;\n\twstart = ptr;", "\t// Find end of the word.\n\tif (has_mbyte)\n\t // Japanese words may have characters in\n\t // different classes, only separate words\n\t // with single-byte non-word characters.\n\t while (*ptr != NUL)\n\t {\n\t\tint l = (*mb_ptr2len)(ptr);", "\t\tif (l < 2 && !vim_iswordc(*ptr))\n\t\t break;\n\t\tptr += l;\n\t }\n\telse\n\t ptr = find_word_end(ptr);", "\t// Add the word. Skip the regexp match.\n\tif (wstart != skip_word)\n\t{\n\t status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,\n\t\t\t\t\t\t\tfname, dir, FALSE);\n\t if (status == FAIL)\n\t\tbreak;\n\t}\n }", " *buf_arg = ptr;\n return status;\n}", "/*\n * Process \"count\" dictionary/thesaurus \"files\" and add the text matching\n * \"regmatch\".\n */\n static void\nins_compl_files(\n int\t\tcount,\n char_u\t**files,\n int\t\tthesaurus,\n int\t\tflags,\n regmatch_T\t*regmatch,\n char_u\t*buf,\n int\t\t*dir)\n{\n char_u\t*ptr;\n int\t\ti;\n FILE\t*fp;\n int\t\tadd_r;", " for (i = 0; i < count && !got_int && !compl_interrupted; i++)\n {\n\tfp = mch_fopen((char *)files[i], \"r\"); // open dictionary file\n\tif (flags != DICT_EXACT)\n\t{\n\t msg_hist_off = TRUE;\t// reset in msg_trunc_attr()\n\t vim_snprintf((char *)IObuff, IOSIZE,\n\t\t\t _(\"Scanning dictionary: %s\"), (char *)files[i]);\n\t (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));\n\t}", "\tif (fp == NULL)\n\t continue;", "\t// Read dictionary file line by line.\n\t// Check each line for a match.\n\twhile (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))\n\t{\n\t ptr = buf;\n\t while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))\n\t {\n\t\tptr = regmatch->startp[0];\n\t\tif (ctrl_x_mode_line_or_eval())\n\t\t ptr = find_line_end(ptr);\n\t\telse\n\t\t ptr = find_word_end(ptr);\n\t\tadd_r = ins_compl_add_infercase(regmatch->startp[0],\n\t\t\t(int)(ptr - regmatch->startp[0]),\n\t\t\tp_ic, files[i], *dir, FALSE);\n\t\tif (thesaurus)\n\t\t{\n\t\t // For a thesaurus, add all the words in the line\n\t\t ptr = buf;\n\t\t add_r = thesarurs_add_words_in_line(files[i], &ptr, *dir,\n\t\t\t\t\t\t\tregmatch->startp[0]);\n\t\t}\n\t\tif (add_r == OK)\n\t\t // if dir was BACKWARD then honor it just once\n\t\t *dir = FORWARD;\n\t\telse if (add_r == FAIL)\n\t\t break;\n\t\t// avoid expensive call to vim_regexec() when at end\n\t\t// of line\n\t\tif (*ptr == '\\n' || got_int)\n\t\t break;\n\t }\n\t line_breakcheck();\n\t ins_compl_check_keys(50, FALSE);\n\t}\n\tfclose(fp);\n }\n}", "/*\n * Find the start of the next word.\n * Returns a pointer to the first char of the word. Also stops at a NUL.\n */\n char_u *\nfind_word_start(char_u *ptr)\n{\n if (has_mbyte)\n\twhile (*ptr != NUL && *ptr != '\\n' && mb_get_class(ptr) <= 1)\n\t ptr += (*mb_ptr2len)(ptr);\n else\n\twhile (*ptr != NUL && *ptr != '\\n' && !vim_iswordc(*ptr))\n\t ++ptr;\n return ptr;\n}", "/*\n * Find the end of the word. Assumes it starts inside a word.\n * Returns a pointer to just after the word.\n */\n char_u *\nfind_word_end(char_u *ptr)\n{\n int\t\tstart_class;", " if (has_mbyte)\n {\n\tstart_class = mb_get_class(ptr);\n\tif (start_class > 1)\n\t while (*ptr != NUL)\n\t {\n\t\tptr += (*mb_ptr2len)(ptr);\n\t\tif (mb_get_class(ptr) != start_class)\n\t\t break;\n\t }\n }\n else\n\twhile (vim_iswordc(*ptr))\n\t ++ptr;\n return ptr;\n}", "/*\n * Find the end of the line, omitting CR and NL at the end.\n * Returns a pointer to just after the line.\n */\n static char_u *\nfind_line_end(char_u *ptr)\n{\n char_u\t*s;", " s = ptr + STRLEN(ptr);\n while (s > ptr && (s[-1] == CAR || s[-1] == NL))\n\t--s;\n return s;\n}", "/*\n * Free the list of completions\n */\n static void\nins_compl_free(void)\n{\n compl_T *match;\n int\t i;", " VIM_CLEAR(compl_pattern);\n VIM_CLEAR(compl_leader);", " if (compl_first_match == NULL)\n\treturn;", " ins_compl_del_pum();\n pum_clear();", " compl_curr_match = compl_first_match;\n do\n {\n\tmatch = compl_curr_match;\n\tcompl_curr_match = compl_curr_match->cp_next;\n\tvim_free(match->cp_str);\n\t// several entries may use the same fname, free it just once.\n\tif (match->cp_flags & CP_FREE_FNAME)\n\t vim_free(match->cp_fname);\n\tfor (i = 0; i < CPT_COUNT; ++i)\n\t vim_free(match->cp_text[i]);\n#ifdef FEAT_EVAL\n\tclear_tv(&match->cp_user_data);\n#endif\n\tvim_free(match);\n } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));\n compl_first_match = compl_curr_match = NULL;\n compl_shown_match = NULL;\n compl_old_match = NULL;\n}", "/*\n * Reset/clear the completion state.\n */\n void\nins_compl_clear(void)\n{\n compl_cont_status = 0;\n compl_started = FALSE;\n compl_matches = 0;\n VIM_CLEAR(compl_pattern);\n VIM_CLEAR(compl_leader);\n edit_submode_extra = NULL;\n VIM_CLEAR(compl_orig_text);\n compl_enter_selects = FALSE;\n#ifdef FEAT_EVAL\n // clear v:completed_item\n set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));\n#endif\n}", "/*\n * Return TRUE when Insert completion is active.\n */\n int\nins_compl_active(void)\n{\n return compl_started;\n}", "/*\n * Selected one of the matches. When FALSE the match was edited or using the\n * longest common string.\n */\n int\nins_compl_used_match(void)\n{\n return compl_used_match;\n}", "/*\n * Initialize get longest common string.\n */\n void\nins_compl_init_get_longest(void)\n{\n compl_get_longest = FALSE;\n}", "/*\n * Returns TRUE when insert completion is interrupted.\n */\n int\nins_compl_interrupted(void)\n{\n return compl_interrupted;\n}", "/*\n * Returns TRUE if the <Enter> key selects a match in the completion popup\n * menu.\n */\n int\nins_compl_enter_selects(void)\n{\n return compl_enter_selects;\n}", "/*\n * Return the column where the text starts that is being completed\n */\n colnr_T\nins_compl_col(void)\n{\n return compl_col;\n}", "/*\n * Return the length in bytes of the text being completed\n */\n int\nins_compl_len(void)\n{\n return compl_length;\n}", "/*\n * Delete one character before the cursor and show the subset of the matches\n * that match the word that is now before the cursor.\n * Returns the character to be used, NUL if the work is done and another char\n * to be got from the user.\n */\n int\nins_compl_bs(void)\n{\n char_u\t*line;\n char_u\t*p;", " line = ml_get_curline();\n p = line + curwin->w_cursor.col;\n MB_PTR_BACK(line, p);", " // Stop completion when the whole word was deleted. For Omni completion\n // allow the word to be deleted, we won't match everything.\n // Respect the 'backspace' option.\n if ((int)(p - line) - (int)compl_col < 0\n\t || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())\n\t || ctrl_x_mode_eval()\n\t || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col\n\t\t\t\t\t\t\t- compl_length < 0))\n\treturn K_BS;", " // Deleted more than what was used to find matches or didn't finish\n // finding all matches: need to look for matches all over again.\n if (curwin->w_cursor.col <= compl_col + compl_length\n\t\t\t\t\t\t || ins_compl_need_restart())\n\tins_compl_restart();", " vim_free(compl_leader);\n compl_leader = vim_strnsave(line + compl_col, (p - line) - compl_col);\n if (compl_leader == NULL)\n\treturn K_BS;", " ins_compl_new_leader();\n if (compl_shown_match != NULL)\n\t// Make sure current match is not a hidden item.\n\tcompl_curr_match = compl_shown_match;\n return NUL;\n}", "/*\n * Return TRUE when we need to find matches again, ins_compl_restart() is to\n * be called.\n */\n static int\nins_compl_need_restart(void)\n{\n // Return TRUE if we didn't complete finding matches or when the\n // 'completefunc' returned \"always\" in the \"refresh\" dictionary item.\n return compl_was_interrupted\n\t|| ((ctrl_x_mode_function() || ctrl_x_mode_omni())\n\t\t\t\t\t\t && compl_opt_refresh_always);\n}", "/*\n * Called after changing \"compl_leader\".\n * Show the popup menu with a different set of matches.\n * May also search for matches again if the previous search was interrupted.\n */\n static void\nins_compl_new_leader(void)\n{\n ins_compl_del_pum();\n ins_compl_delete();\n ins_bytes(compl_leader + get_compl_len());\n compl_used_match = FALSE;", " if (compl_started)\n\tins_compl_set_original_text(compl_leader);\n else\n {\n#ifdef FEAT_SPELL\n\tspell_bad_len = 0;\t// need to redetect bad word\n#endif\n\t// Matches were cleared, need to search for them now. Before drawing\n\t// the popup menu display the changed text before the cursor. Set\n\t// \"compl_restarting\" to avoid that the first match is inserted.\n\tpum_call_update_screen();\n#ifdef FEAT_GUI\n\tif (gui.in_use)\n\t{\n\t // Show the cursor after the match, not after the redrawn text.\n\t setcursor();\n\t out_flush_cursor(FALSE, FALSE);\n\t}\n#endif\n\tcompl_restarting = TRUE;\n\tif (ins_complete(Ctrl_N, TRUE) == FAIL)\n\t compl_cont_status = 0;\n\tcompl_restarting = FALSE;\n }", " compl_enter_selects = !compl_used_match;", " // Show the popup menu with a different set of matches.\n ins_compl_show_pum();", " // Don't let Enter select the original text when there is no popup menu.\n if (compl_match_array == NULL)\n\tcompl_enter_selects = FALSE;\n}", "/*\n * Return the length of the completion, from the completion start column to\n * the cursor column. Making sure it never goes below zero.\n */\n static int\nget_compl_len(void)\n{\n int off = (int)curwin->w_cursor.col - (int)compl_col;", " if (off < 0)\n\treturn 0;\n return off;\n}", "/*\n * Append one character to the match leader. May reduce the number of\n * matches.\n */\n void\nins_compl_addleader(int c)\n{\n int\t\tcc;", " if (stop_arrow() == FAIL)\n\treturn;\n if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)\n {\n\tchar_u\tbuf[MB_MAXBYTES + 1];", "\t(*mb_char2bytes)(c, buf);\n\tbuf[cc] = NUL;\n\tins_char_bytes(buf, cc);\n\tif (compl_opt_refresh_always)\n\t AppendToRedobuff(buf);\n }\n else\n {\n\tins_char(c);\n\tif (compl_opt_refresh_always)\n\t AppendCharToRedobuff(c);\n }", " // If we didn't complete finding matches we must search again.\n if (ins_compl_need_restart())\n\tins_compl_restart();", " // When 'always' is set, don't reset compl_leader. While completing,\n // cursor doesn't point original position, changing compl_leader would\n // break redo.\n if (!compl_opt_refresh_always)\n {\n\tvim_free(compl_leader);\n\tcompl_leader = vim_strnsave(ml_get_curline() + compl_col,\n\t\t\t\t\t curwin->w_cursor.col - compl_col);\n\tif (compl_leader != NULL)\n\t ins_compl_new_leader();\n }\n}", "/*\n * Setup for finding completions again without leaving CTRL-X mode. Used when\n * BS or a key was typed while still searching for matches.\n */\n static void\nins_compl_restart(void)\n{\n ins_compl_free();\n compl_started = FALSE;\n compl_matches = 0;\n compl_cont_status = 0;\n compl_cont_mode = 0;\n}", "/*\n * Set the first match, the original text.\n */\n static void\nins_compl_set_original_text(char_u *str)\n{\n char_u\t*p;", " // Replace the original text entry.\n // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly\n // be at the last item for backward completion\n if (match_at_original_text(compl_first_match))\t// safety check\n {\n\tp = vim_strsave(str);\n\tif (p != NULL)\n\t{\n\t vim_free(compl_first_match->cp_str);\n\t compl_first_match->cp_str = p;\n\t}\n }\n else if (compl_first_match->cp_prev != NULL\n\t && match_at_original_text(compl_first_match->cp_prev))\n {\n p = vim_strsave(str);\n if (p != NULL)\n {\n\t vim_free(compl_first_match->cp_prev->cp_str);\n\t compl_first_match->cp_prev->cp_str = p;\n }\n }\n}", "/*\n * Append one character to the match leader. May reduce the number of\n * matches.\n */\n void\nins_compl_addfrommatch(void)\n{\n char_u\t*p;\n int\t\tlen = (int)curwin->w_cursor.col - (int)compl_col;\n int\t\tc;\n compl_T\t*cp;", " p = compl_shown_match->cp_str;\n if ((int)STRLEN(p) <= len) // the match is too short\n {\n\t// When still at the original match use the first entry that matches\n\t// the leader.\n\tif (!match_at_original_text(compl_shown_match))\n\t return;", "\tp = NULL;\n\tfor (cp = compl_shown_match->cp_next; cp != NULL\n\t\t&& !is_first_match(cp); cp = cp->cp_next)\n\t{\n\t if (compl_leader == NULL\n\t\t || ins_compl_equal(cp, compl_leader,\n\t\t\t(int)STRLEN(compl_leader)))\n\t {\n\t\tp = cp->cp_str;\n\t\tbreak;\n\t }\n\t}\n\tif (p == NULL || (int)STRLEN(p) <= len)\n\t return;\n }\n p += len;\n c = PTR2CHAR(p);\n ins_compl_addleader(c);\n}", "/*\n * Set the CTRL-X completion mode based on the key \"c\" typed after a CTRL-X.\n * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,\n * compl_cont_mode and compl_cont_status.\n * Returns TRUE when the character is not to be inserted.\n */\n static int\nset_ctrl_x_mode(int c)\n{\n int retval = FALSE;", " switch (c)\n {\n\tcase Ctrl_E:\n\tcase Ctrl_Y:\n\t // scroll the window one line up or down\n\t ctrl_x_mode = CTRL_X_SCROLL;\n\t if (!(State & REPLACE_FLAG))\n\t\tedit_submode = (char_u *)_(\" (insert) Scroll (^E/^Y)\");\n\t else\n\t\tedit_submode = (char_u *)_(\" (replace) Scroll (^E/^Y)\");\n\t edit_submode_pre = NULL;\n\t showmode();\n\t break;\n\tcase Ctrl_L:\n\t // complete whole line\n\t ctrl_x_mode = CTRL_X_WHOLE_LINE;\n\t break;\n\tcase Ctrl_F:\n\t // complete filenames\n\t ctrl_x_mode = CTRL_X_FILES;\n\t break;\n\tcase Ctrl_K:\n\t // complete words from a dictinoary\n\t ctrl_x_mode = CTRL_X_DICTIONARY;\n\t break;\n\tcase Ctrl_R:\n\t // Register insertion without exiting CTRL-X mode\n\t // Simply allow ^R to happen without affecting ^X mode\n\t break;\n\tcase Ctrl_T:\n\t // complete words from a thesaurus\n\t ctrl_x_mode = CTRL_X_THESAURUS;\n\t break;\n#ifdef FEAT_COMPL_FUNC\n\tcase Ctrl_U:\n\t // user defined completion\n\t ctrl_x_mode = CTRL_X_FUNCTION;\n\t break;\n\tcase Ctrl_O:\n\t // omni completion\n\t ctrl_x_mode = CTRL_X_OMNI;\n\t break;\n#endif\n\tcase 's':\n\tcase Ctrl_S:\n\t // complete spelling suggestions\n\t ctrl_x_mode = CTRL_X_SPELL;\n#ifdef FEAT_SPELL\n\t ++emsg_off;\t// Avoid getting the E756 error twice.\n\t spell_back_to_badword();\n\t --emsg_off;\n#endif\n\t break;\n\tcase Ctrl_RSB:\n\t // complete tag names\n\t ctrl_x_mode = CTRL_X_TAGS;\n\t break;\n#ifdef FEAT_FIND_ID\n\tcase Ctrl_I:\n\tcase K_S_TAB:\n\t // complete keywords from included files\n\t ctrl_x_mode = CTRL_X_PATH_PATTERNS;\n\t break;\n\tcase Ctrl_D:\n\t // complete definitions from included files\n\t ctrl_x_mode = CTRL_X_PATH_DEFINES;\n\t break;\n#endif\n\tcase Ctrl_V:\n\tcase Ctrl_Q:\n\t // complete vim commands\n\t ctrl_x_mode = CTRL_X_CMDLINE;\n\t break;\n\tcase Ctrl_Z:\n\t // stop completion\n\t ctrl_x_mode = CTRL_X_NORMAL;\n\t edit_submode = NULL;\n\t showmode();\n\t retval = TRUE;\n\t break;\n\tcase Ctrl_P:\n\tcase Ctrl_N:\n\t // ^X^P means LOCAL expansion if nothing interrupted (eg we\n\t // just started ^X mode, or there were enough ^X's to cancel\n\t // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)\n\t // do normal expansion when interrupting a different mode (say\n\t // ^X^F^X^P or ^P^X^X^P, see below)\n\t // nothing changes if interrupting mode 0, (eg, the flag\n\t // doesn't change when going to ADDING mode -- Acevedo\n\t if (!(compl_cont_status & CONT_INTRPT))\n\t\tcompl_cont_status |= CONT_LOCAL;\n\t else if (compl_cont_mode != 0)\n\t\tcompl_cont_status &= ~CONT_LOCAL;\n\t // FALLTHROUGH\n\tdefault:\n\t // If we have typed at least 2 ^X's... for modes != 0, we set\n\t // compl_cont_status = 0 (eg, as if we had just started ^X\n\t // mode).\n\t // For mode 0, we set \"compl_cont_mode\" to an impossible\n\t // value, in both cases ^X^X can be used to restart the same\n\t // mode (avoiding ADDING mode).\n\t // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start\n\t // 'complete' and local ^P expansions respectively.\n\t // In mode 0 an extra ^X is needed since ^X^P goes to ADDING\n\t // mode -- Acevedo\n\t if (c == Ctrl_X)\n\t {\n\t\tif (compl_cont_mode != 0)\n\t\t compl_cont_status = 0;\n\t\telse\n\t\t compl_cont_mode = CTRL_X_NOT_DEFINED_YET;\n\t }\n\t ctrl_x_mode = CTRL_X_NORMAL;\n\t edit_submode = NULL;\n\t showmode();\n\t break;\n }", " return retval;\n}", "/*\n * Stop insert completion mode\n */\n static int\nins_compl_stop(int c, int prev_mode, int retval)\n{\n char_u\t*ptr;\n int\t\twant_cindent;", " // Get here when we have finished typing a sequence of ^N and\n // ^P or other completion characters in CTRL-X mode. Free up\n // memory that was used, and make sure we can redo the insert.\n if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)\n {\n\t// If any of the original typed text has been changed, eg when\n\t// ignorecase is set, we must add back-spaces to the redo\n\t// buffer. We add as few as necessary to delete just the part\n\t// of the original text that has changed.\n\t// When using the longest match, edited the match or used\n\t// CTRL-E then don't use the current match.\n\tif (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)\n\t ptr = compl_curr_match->cp_str;\n\telse\n\t ptr = NULL;\n\tins_compl_fixRedoBufForLeader(ptr);\n }", " want_cindent = (get_can_cindent() && cindent_on());", " // When completing whole lines: fix indent for 'cindent'.\n // Otherwise, break line if it's too long.\n if (compl_cont_mode == CTRL_X_WHOLE_LINE)\n {\n\t// re-indent the current line\n\tif (want_cindent)\n\t{\n\t do_c_expr_indent();\n\t want_cindent = FALSE;\t// don't do it again\n\t}\n }\n else\n {\n\tint prev_col = curwin->w_cursor.col;", "\t// put the cursor on the last char, for 'tw' formatting\n\tif (prev_col > 0)\n\t dec_cursor();\n\t// only format when something was inserted\n\tif (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)\n\t insertchar(NUL, 0, -1);\n\tif (prev_col > 0\n\t\t&& ml_get_curline()[curwin->w_cursor.col] != NUL)\n\t inc_cursor();\n }", " // If the popup menu is displayed pressing CTRL-Y means accepting\n // the selection without inserting anything. When\n // compl_enter_selects is set the Enter key does the same.\n if ((c == Ctrl_Y || (compl_enter_selects\n\t\t && (c == CAR || c == K_KENTER || c == NL)))\n\t && pum_visible())\n\tretval = TRUE;", " // CTRL-E means completion is Ended, go back to the typed text.\n // but only do this, if the Popup is still visible\n if (c == Ctrl_E)\n {\n\tchar_u *p = NULL;", "\tins_compl_delete();\n\tif (compl_leader != NULL)\n\t p = compl_leader;\n\telse if (compl_first_match != NULL)\n\t p = compl_orig_text;\n\tif (p != NULL)\n\t{\n\t int\t compl_len = get_compl_len();\n\t int\t len = (int)STRLEN(p);", "\t if (len > compl_len)\n\t\tins_bytes_len(p + compl_len, len - compl_len);\n\t}\n\tretval = TRUE;\n }", " auto_format(FALSE, TRUE);", " // Trigger the CompleteDonePre event to give scripts a chance to\n // act upon the completion before clearing the info, and restore\n // ctrl_x_mode, so that complete_info() can be used.\n ctrl_x_mode = prev_mode;\n ins_apply_autocmds(EVENT_COMPLETEDONEPRE);", " ins_compl_free();\n compl_started = FALSE;\n compl_matches = 0;\n if (!shortmess(SHM_COMPLETIONMENU))\n\tmsg_clr_cmdline();\t// necessary for \"noshowmode\"\n ctrl_x_mode = CTRL_X_NORMAL;\n compl_enter_selects = FALSE;\n if (edit_submode != NULL)\n {\n\tedit_submode = NULL;\n\tshowmode();\n }", "#ifdef FEAT_CMDWIN\n if (c == Ctrl_C && cmdwin_type != 0)\n\t// Avoid the popup menu remains displayed when leaving the\n\t// command line window.\n\tupdate_screen(0);\n#endif\n // Indent now if a key was typed that is in 'cinkeys'.\n if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))\n\tdo_c_expr_indent();\n // Trigger the CompleteDone event to give scripts a chance to act\n // upon the end of completion.\n ins_apply_autocmds(EVENT_COMPLETEDONE);", " return retval;\n}", "/*\n * Prepare for Insert mode completion, or stop it.\n * Called just after typing a character in Insert mode.\n * Returns TRUE when the character is not to be inserted;\n */\n int\nins_compl_prep(int c)\n{\n int\t\tretval = FALSE;\n int\t\tprev_mode = ctrl_x_mode;", " // Forget any previous 'special' messages if this is actually\n // a ^X mode key - bar ^R, in which case we wait to see what it gives us.\n if (c != Ctrl_R && vim_is_ctrl_x_key(c))\n\tedit_submode_extra = NULL;", " // Ignore end of Select mode mapping and mouse scroll buttons.\n if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP\n\t || c == K_MOUSELEFT || c == K_MOUSERIGHT\n\t || c == K_COMMAND || c == K_SCRIPT_COMMAND)\n\treturn retval;", "#ifdef FEAT_PROP_POPUP\n // Ignore mouse events in a popup window\n if (is_mouse_key(c))\n {\n\t// Ignore drag and release events, the position does not need to be in\n\t// the popup and it may have just closed.\n\tif (c == K_LEFTRELEASE\n\t\t|| c == K_LEFTRELEASE_NM\n\t\t|| c == K_MIDDLERELEASE\n\t\t|| c == K_RIGHTRELEASE\n\t\t|| c == K_X1RELEASE\n\t\t|| c == K_X2RELEASE\n\t\t|| c == K_LEFTDRAG\n\t\t|| c == K_MIDDLEDRAG\n\t\t|| c == K_RIGHTDRAG\n\t\t|| c == K_X1DRAG\n\t\t|| c == K_X2DRAG)\n\t return retval;\n\tif (popup_visible)\n\t{\n\t int\t row = mouse_row;\n\t int\t col = mouse_col;\n\t win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);", "\t if (wp != NULL && WIN_IS_POPUP(wp))\n\t\treturn retval;\n\t}\n }\n#endif", " if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)\n {\n\tif (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)\n\t\t|| !vim_is_ctrl_x_key(c))\n\t{\n\t // Not starting another completion mode.\n\t ctrl_x_mode = CTRL_X_CMDLINE;", "\t // CTRL-X CTRL-Z should stop completion without inserting anything\n\t if (c == Ctrl_Z)\n\t\tretval = TRUE;\n\t}\n\telse\n\t{\n\t ctrl_x_mode = CTRL_X_CMDLINE;", "\t // Other CTRL-X keys first stop completion, then start another\n\t // completion mode.\n\t ins_compl_prep(' ');\n\t ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;\n\t}\n }", " // Set \"compl_get_longest\" when finding the first matches.\n if (ctrl_x_mode_not_defined_yet()\n\t\t\t || (ctrl_x_mode_normal() && !compl_started))\n {\n\tcompl_get_longest = (strstr((char *)p_cot, \"longest\") != NULL);\n\tcompl_used_match = TRUE;", " }", " if (ctrl_x_mode_not_defined_yet())\n\t// We have just typed CTRL-X and aren't quite sure which CTRL-X mode\n\t// it will be yet. Now we decide.\n\tretval = set_ctrl_x_mode(c);\n else if (ctrl_x_mode_not_default())\n {\n\t// We're already in CTRL-X mode, do we stay in it?\n\tif (!vim_is_ctrl_x_key(c))\n\t{\n\t if (ctrl_x_mode_scroll())\n\t\tctrl_x_mode = CTRL_X_NORMAL;\n\t else\n\t\tctrl_x_mode = CTRL_X_FINISHED;\n\t edit_submode = NULL;\n\t}\n\tshowmode();\n }", " if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)\n {\n\t// Show error message from attempted keyword completion (probably\n\t// 'Pattern not found') until another key is hit, then go back to\n\t// showing what mode we are in.\n\tshowmode();\n\tif ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P\n\t\t\t\t && c != Ctrl_R && !ins_compl_pum_key(c))\n\t\t|| ctrl_x_mode == CTRL_X_FINISHED)\n\t retval = ins_compl_stop(c, prev_mode, retval);\n }\n else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)\n\t// Trigger the CompleteDone event to give scripts a chance to act\n\t// upon the (possibly failed) completion.\n\tins_apply_autocmds(EVENT_COMPLETEDONE);", " may_trigger_modechanged();", " // reset continue_* if we left expansion-mode, if we stay they'll be\n // (re)set properly in ins_complete()\n if (!vim_is_ctrl_x_key(c))\n {\n\tcompl_cont_status = 0;\n\tcompl_cont_mode = 0;\n }", " return retval;\n}", "/*\n * Fix the redo buffer for the completion leader replacing some of the typed\n * text. This inserts backspaces and appends the changed text.\n * \"ptr\" is the known leader text or NUL.\n */\n static void\nins_compl_fixRedoBufForLeader(char_u *ptr_arg)\n{\n int\t len;\n char_u *p;\n char_u *ptr = ptr_arg;", " if (ptr == NULL)\n {\n\tif (compl_leader != NULL)\n\t ptr = compl_leader;\n\telse\n\t return; // nothing to do\n }\n if (compl_orig_text != NULL)\n {\n\tp = compl_orig_text;\n\tfor (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)\n\t ;\n\tif (len > 0)\n\t len -= (*mb_head_off)(p, p + len);\n\tfor (p += len; *p != NUL; MB_PTR_ADV(p))\n\t AppendCharToRedobuff(K_BS);\n }\n else\n\tlen = 0;\n if (ptr != NULL)\n\tAppendToRedobuffLit(ptr + len, -1);\n}", "/*\n * Loops through the list of windows, loaded-buffers or non-loaded-buffers\n * (depending on flag) starting from buf and looking for a non-scanned\n * buffer (other than curbuf).\tcurbuf is special, if it is called with\n * buf=curbuf then it has to be the first call for a given flag/expansion.\n *\n * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo\n */\n static buf_T *\nins_compl_next_buf(buf_T *buf, int flag)\n{\n static win_T *wp = NULL;", " if (flag == 'w')\t\t// just windows\n {\n\tif (buf == curbuf || wp == NULL) // first call for this flag/expansion\n\t wp = curwin;\n\twhile ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin\n\t\t&& wp->w_buffer->b_scanned)\n\t ;\n\tbuf = wp->w_buffer;\n }\n else\n\t// 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'\n\t// (unlisted buffers)\n\t// When completing whole lines skip unloaded buffers.\n\twhile ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf\n\t\t&& ((flag == 'U'\n\t\t\t? buf->b_p_bl\n\t\t\t: (!buf->b_p_bl\n\t\t\t || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))\n\t\t || buf->b_scanned))\n\t ;\n return buf;\n}", "#ifdef FEAT_COMPL_FUNC", "# ifdef FEAT_EVAL\nstatic callback_T cfu_cb;\t // 'completefunc' callback function\nstatic callback_T ofu_cb;\t // 'omnifunc' callback function\nstatic callback_T tsrfu_cb;\t // 'thesaurusfunc' callback function\n# endif", "/*\n * Copy a global callback function to a buffer local callback.\n */\n static void\ncopy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)\n{\n free_callback(bufcb);\n if (globcb->cb_name != NULL && *globcb->cb_name != NUL)\n\tcopy_callback(bufcb, globcb);\n}", "/*\n * Parse the 'completefunc' option value and set the callback function.\n * Invoked when the 'completefunc' option is set. The option value can be a\n * name of a function (string), or function(<name>) or funcref(<name>) or a\n * lambda expression.\n */\n int\nset_completefunc_option(void)\n{\n int\tretval;", " retval = option_set_callback_func(curbuf->b_p_cfu, &cfu_cb);\n if (retval == OK)\n\tset_buflocal_cfu_callback(curbuf);", " return retval;\n}", "/*\n * Copy the global 'completefunc' callback function to the buffer-local\n * 'completefunc' callback for \"buf\".\n */\n void\nset_buflocal_cfu_callback(buf_T *buf UNUSED)\n{\n# ifdef FEAT_EVAL\n copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);\n# endif\n}", "/*\n * Parse the 'omnifunc' option value and set the callback function.\n * Invoked when the 'omnifunc' option is set. The option value can be a\n * name of a function (string), or function(<name>) or funcref(<name>) or a\n * lambda expression.\n */\n int\nset_omnifunc_option(void)\n{\n int\tretval;", " retval = option_set_callback_func(curbuf->b_p_ofu, &ofu_cb);\n if (retval == OK)\n\tset_buflocal_ofu_callback(curbuf);", " return retval;\n}", "/*\n * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'\n * callback for \"buf\".\n */\n void\nset_buflocal_ofu_callback(buf_T *buf UNUSED)\n{\n# ifdef FEAT_EVAL\n copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);\n# endif\n}", "/*\n * Parse the 'thesaurusfunc' option value and set the callback function.\n * Invoked when the 'thesaurusfunc' option is set. The option value can be a\n * name of a function (string), or function(<name>) or funcref(<name>) or a\n * lambda expression.\n */\n int\nset_thesaurusfunc_option(void)\n{\n int\tretval;", " if (*curbuf->b_p_tsrfu != NUL)\n {\n\t// buffer-local option set\n\tretval = option_set_callback_func(curbuf->b_p_tsrfu,\n\t\t\t\t\t\t\t&curbuf->b_tsrfu_cb);\n }\n else\n {\n\t// global option set\n\tretval = option_set_callback_func(p_tsrfu, &tsrfu_cb);\n }", " return retval;\n}", "/*\n * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with\n * \"copyID\" so that they are not garbage collected.\n */\n int\nset_ref_in_insexpand_funcs(int copyID)\n{\n int abort = FALSE;", " abort = set_ref_in_callback(&cfu_cb, copyID);\n abort = abort || set_ref_in_callback(&ofu_cb, copyID);\n abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);", " return abort;\n}", "/*\n * Get the user-defined completion function name for completion \"type\"\n */\n static char_u *\nget_complete_funcname(int type)\n{\n switch (type)\n {\n\tcase CTRL_X_FUNCTION:\n\t return curbuf->b_p_cfu;\n\tcase CTRL_X_OMNI:\n\t return curbuf->b_p_ofu;\n\tcase CTRL_X_THESAURUS:\n\t return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;\n\tdefault:\n\t return (char_u *)\"\";\n }\n}", "/*\n * Get the callback to use for insert mode completion.\n */\n static callback_T *\nget_insert_callback(int type)\n{\n if (type == CTRL_X_FUNCTION)\n\treturn &curbuf->b_cfu_cb;\n if (type == CTRL_X_OMNI)\n\treturn &curbuf->b_ofu_cb;\n // CTRL_X_THESAURUS\n return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;\n}", "/*\n * Execute user defined complete function 'completefunc', 'omnifunc' or\n * 'thesaurusfunc', and get matches in \"matches\".\n * \"type\" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.\n */\n static void\nexpand_by_function(int type, char_u *base)\n{\n list_T *matchlist = NULL;\n dict_T\t*matchdict = NULL;\n typval_T\targs[3];\n char_u\t*funcname;\n pos_T\tpos;\n callback_T\t*cb;\n typval_T\trettv;\n int\t\tsave_State = State;\n int\t\tretval;", " funcname = get_complete_funcname(type);\n if (*funcname == NUL)\n\treturn;", " // Call 'completefunc' to obtain the list of matches.\n args[0].v_type = VAR_NUMBER;\n args[0].vval.v_number = 0;\n args[1].v_type = VAR_STRING;\n args[1].vval.v_string = base != NULL ? base : (char_u *)\"\";\n args[2].v_type = VAR_UNKNOWN;", " pos = curwin->w_cursor;\n // Lock the text to avoid weird things from happening. Also disallow\n // switching to another window, it should not be needed and may end up in\n // Insert mode in another buffer.\n ++textlock;", " cb = get_insert_callback(type);\n retval = call_callback(cb, 0, &rettv, 2, args);", " // Call a function, which returns a list or dict.\n if (retval == OK)\n {\n\tswitch (rettv.v_type)\n\t{\n\t case VAR_LIST:\n\t\tmatchlist = rettv.vval.v_list;\n\t\tbreak;\n\t case VAR_DICT:\n\t\tmatchdict = rettv.vval.v_dict;\n\t\tbreak;\n\t case VAR_SPECIAL:\n\t\tif (rettv.vval.v_number == VVAL_NONE)\n\t\t compl_opt_suppress_empty = TRUE;\n\t\t// FALLTHROUGH\n\t default:\n\t\t// TODO: Give error message?\n\t\tclear_tv(&rettv);\n\t\tbreak;\n\t}\n }\n --textlock;", " curwin->w_cursor = pos;\t// restore the cursor position\n validate_cursor();\n if (!EQUAL_POS(curwin->w_cursor, pos))\n {\n\temsg(_(e_complete_function_deleted_text));\n\tgoto theend;\n }", " if (matchlist != NULL)\n\tins_compl_add_list(matchlist);\n else if (matchdict != NULL)\n\tins_compl_add_dict(matchdict);", "theend:\n // Restore State, it might have been changed.\n State = save_State;", " if (matchdict != NULL)\n\tdict_unref(matchdict);\n if (matchlist != NULL)\n\tlist_unref(matchlist);\n}\n#endif // FEAT_COMPL_FUNC", "#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)\n/*\n * Add a match to the list of matches from a typeval_T.\n * If the given string is already in the list of completions, then return\n * NOTDONE, otherwise add it to the list and return OK. If there is an error,\n * maybe because alloc() returns NULL, then FAIL is returned.\n * When \"fast\" is TRUE use fast_breakcheck() instead of ui_breakcheck().\n */\n static int\nins_compl_add_tv(typval_T *tv, int dir, int fast)\n{\n char_u\t*word;\n int\t\tdup = FALSE;\n int\t\tempty = FALSE;\n int\t\tflags = fast ? CP_FAST : 0;\n char_u\t*(cptext[CPT_COUNT]);\n typval_T\tuser_data;\n int\t\tstatus;", " user_data.v_type = VAR_UNKNOWN;\n if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)\n {\n\tword = dict_get_string(tv->vval.v_dict, (char_u *)\"word\", FALSE);\n\tcptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict,\n\t\t\t\t\t\t (char_u *)\"abbr\", FALSE);\n\tcptext[CPT_MENU] = dict_get_string(tv->vval.v_dict,\n\t\t\t\t\t\t (char_u *)\"menu\", FALSE);\n\tcptext[CPT_KIND] = dict_get_string(tv->vval.v_dict,\n\t\t\t\t\t\t (char_u *)\"kind\", FALSE);\n\tcptext[CPT_INFO] = dict_get_string(tv->vval.v_dict,\n\t\t\t\t\t\t (char_u *)\"info\", FALSE);\n\tdict_get_tv(tv->vval.v_dict, (char_u *)\"user_data\", &user_data);\n\tif (dict_get_string(tv->vval.v_dict, (char_u *)\"icase\", FALSE) != NULL\n\t\t\t&& dict_get_number(tv->vval.v_dict, (char_u *)\"icase\"))\n\t flags |= CP_ICASE;\n\tif (dict_get_string(tv->vval.v_dict, (char_u *)\"dup\", FALSE) != NULL)\n\t dup = dict_get_number(tv->vval.v_dict, (char_u *)\"dup\");\n\tif (dict_get_string(tv->vval.v_dict, (char_u *)\"empty\", FALSE) != NULL)\n\t empty = dict_get_number(tv->vval.v_dict, (char_u *)\"empty\");\n\tif (dict_get_string(tv->vval.v_dict, (char_u *)\"equal\", FALSE) != NULL\n\t\t\t&& dict_get_number(tv->vval.v_dict, (char_u *)\"equal\"))\n\t flags |= CP_EQUAL;\n }\n else\n {\n\tword = tv_get_string_chk(tv);\n\tCLEAR_FIELD(cptext);\n }\n if (word == NULL || (!empty && *word == NUL))\n {\n\tclear_tv(&user_data);\n\treturn FAIL;\n }\n status = ins_compl_add(word, -1, NULL, cptext, &user_data, dir, flags, dup);\n if (status != OK)\n\tclear_tv(&user_data);\n return status;\n}", "/*\n * Add completions from a list.\n */\n static void\nins_compl_add_list(list_T *list)\n{\n listitem_T\t*li;\n int\t\tdir = compl_direction;", " // Go through the List with matches and add each of them.\n CHECK_LIST_MATERIALIZE(list);\n FOR_ALL_LIST_ITEMS(list, li)\n {\n\tif (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)\n\t // if dir was BACKWARD then honor it just once\n\t dir = FORWARD;\n\telse if (did_emsg)\n\t break;\n }\n}", "/*\n * Add completions from a dict.\n */\n static void\nins_compl_add_dict(dict_T *dict)\n{\n dictitem_T\t*di_refresh;\n dictitem_T\t*di_words;", " // Check for optional \"refresh\" item.\n compl_opt_refresh_always = FALSE;\n di_refresh = dict_find(dict, (char_u *)\"refresh\", 7);\n if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)\n {\n\tchar_u\t*v = di_refresh->di_tv.vval.v_string;", "\tif (v != NULL && STRCMP(v, (char_u *)\"always\") == 0)\n\t compl_opt_refresh_always = TRUE;\n }", " // Add completions from a \"words\" list.\n di_words = dict_find(dict, (char_u *)\"words\", 5);\n if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)\n\tins_compl_add_list(di_words->di_tv.vval.v_list);\n}", "/*\n * Start completion for the complete() function.\n * \"startcol\" is where the matched text starts (1 is first column).\n * \"list\" is the list of matches.\n */\n static void\nset_completion(colnr_T startcol, list_T *list)\n{\n int save_w_wrow = curwin->w_wrow;\n int save_w_leftcol = curwin->w_leftcol;\n int flags = CP_ORIGINAL_TEXT;", " // If already doing completions stop it.\n if (ctrl_x_mode_not_default())\n\tins_compl_prep(' ');\n ins_compl_clear();\n ins_compl_free();", " compl_direction = FORWARD;\n if (startcol > curwin->w_cursor.col)\n\tstartcol = curwin->w_cursor.col;\n compl_col = startcol;\n compl_length = (int)curwin->w_cursor.col - (int)startcol;\n // compl_pattern doesn't need to be set\n compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);\n if (p_ic)\n\tflags |= CP_ICASE;\n if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,\n\t\t\t\t\t -1, NULL, NULL, NULL, 0,\n\t\t\t\t\t flags | CP_FAST, FALSE) != OK)\n\treturn;", " ctrl_x_mode = CTRL_X_EVAL;", " ins_compl_add_list(list);\n compl_matches = ins_compl_make_cyclic();\n compl_started = TRUE;\n compl_used_match = TRUE;\n compl_cont_status = 0;", " compl_curr_match = compl_first_match;\n if (compl_no_insert || compl_no_select)\n {\n\tins_complete(K_DOWN, FALSE);\n\tif (compl_no_select)\n\t // Down/Up has no real effect.\n\t ins_complete(K_UP, FALSE);\n }\n else\n\tins_complete(Ctrl_N, FALSE);\n compl_enter_selects = compl_no_insert;", " // Lazily show the popup menu, unless we got interrupted.\n if (!compl_interrupted)\n\tshow_pum(save_w_wrow, save_w_leftcol);\n may_trigger_modechanged();\n out_flush();\n}", "/*\n * \"complete()\" function\n */\n void\nf_complete(typval_T *argvars, typval_T *rettv UNUSED)\n{\n int\t startcol;", " if (in_vim9script()\n\t && (check_for_number_arg(argvars, 0) == FAIL\n\t\t|| check_for_list_arg(argvars, 1) == FAIL))\n\treturn;", " if ((State & MODE_INSERT) == 0)\n {\n\temsg(_(e_complete_can_only_be_used_in_insert_mode));\n\treturn;\n }", " // Check for undo allowed here, because if something was already inserted\n // the line was already saved for undo and this check isn't done.\n if (!undo_allowed())\n\treturn;", " if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)\n\temsg(_(e_invalid_argument));\n else\n {\n\tstartcol = (int)tv_get_number_chk(&argvars[0], NULL);\n\tif (startcol > 0)\n\t set_completion(startcol - 1, argvars[1].vval.v_list);\n }\n}", "/*\n * \"complete_add()\" function\n */\n void\nf_complete_add(typval_T *argvars, typval_T *rettv)\n{\n if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)\n\treturn;", " rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);\n}", "/*\n * \"complete_check()\" function\n */\n void\nf_complete_check(typval_T *argvars UNUSED, typval_T *rettv)\n{\n int\t\tsaved = RedrawingDisabled;", " RedrawingDisabled = 0;\n ins_compl_check_keys(0, TRUE);\n rettv->vval.v_number = ins_compl_interrupted();\n RedrawingDisabled = saved;\n}", "/*\n * Return Insert completion mode name string\n */\n static char_u *\nins_compl_mode(void)\n{\n if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)\n\treturn (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];", " return (char_u *)\"\";\n}", "/*\n * Assign the sequence number to all the completion matches which don't have\n * one assigned yet.\n */\n static void\nins_compl_update_sequence_numbers()\n{\n int\t\tnumber = 0;\n compl_T\t*match;", " if (compl_dir_forward())\n {\n\t// search backwards for the first valid (!= -1) number.\n\t// This should normally succeed already at the first loop\n\t// cycle, so it's fast!\n\tfor (match = compl_curr_match->cp_prev; match != NULL\n\t\t&& !is_first_match(match); match = match->cp_prev)\n\t if (match->cp_number != -1)\n\t {\n\t\tnumber = match->cp_number;\n\t\tbreak;\n\t }\n\tif (match != NULL)\n\t // go up and assign all numbers which are not assigned\n\t // yet\n\t for (match = match->cp_next;\n\t\t match != NULL && match->cp_number == -1;\n\t\t\t\t\t match = match->cp_next)\n\t\tmatch->cp_number = ++number;\n }\n else // BACKWARD\n {\n\t// search forwards (upwards) for the first valid (!= -1)\n\t// number. This should normally succeed already at the\n\t// first loop cycle, so it's fast!\n\tfor (match = compl_curr_match->cp_next; match != NULL\n\t\t&& !is_first_match(match); match = match->cp_next)\n\t if (match->cp_number != -1)\n\t {\n\t\tnumber = match->cp_number;\n\t\tbreak;\n\t }\n\tif (match != NULL)\n\t // go down and assign all numbers which are not\n\t // assigned yet\n\t for (match = match->cp_prev; match\n\t\t && match->cp_number == -1;\n\t\t\t\t\t match = match->cp_prev)\n\t\tmatch->cp_number = ++number;\n }\n}", "/*\n * Get complete information\n */\n static void\nget_complete_info(list_T *what_list, dict_T *retdict)\n{\n int\t\tret = OK;\n listitem_T\t*item;\n#define CI_WHAT_MODE\t\t0x01\n#define CI_WHAT_PUM_VISIBLE\t0x02\n#define CI_WHAT_ITEMS\t\t0x04\n#define CI_WHAT_SELECTED\t0x08\n#define CI_WHAT_INSERTED\t0x10\n#define CI_WHAT_ALL\t\t0xff\n int\t\twhat_flag;", " if (what_list == NULL)\n\twhat_flag = CI_WHAT_ALL;\n else\n {\n\twhat_flag = 0;\n\tCHECK_LIST_MATERIALIZE(what_list);\n\tFOR_ALL_LIST_ITEMS(what_list, item)\n\t{\n\t char_u *what = tv_get_string(&item->li_tv);", "\t if (STRCMP(what, \"mode\") == 0)\n\t\twhat_flag |= CI_WHAT_MODE;\n\t else if (STRCMP(what, \"pum_visible\") == 0)\n\t\twhat_flag |= CI_WHAT_PUM_VISIBLE;\n\t else if (STRCMP(what, \"items\") == 0)\n\t\twhat_flag |= CI_WHAT_ITEMS;\n\t else if (STRCMP(what, \"selected\") == 0)\n\t\twhat_flag |= CI_WHAT_SELECTED;\n\t else if (STRCMP(what, \"inserted\") == 0)\n\t\twhat_flag |= CI_WHAT_INSERTED;\n\t}\n }", " if (ret == OK && (what_flag & CI_WHAT_MODE))\n\tret = dict_add_string(retdict, \"mode\", ins_compl_mode());", " if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))\n\tret = dict_add_number(retdict, \"pum_visible\", pum_visible());", " if (ret == OK && (what_flag & CI_WHAT_ITEMS))\n {\n\tlist_T\t *li;\n\tdict_T\t *di;\n\tcompl_T *match;", "\tli = list_alloc();\n\tif (li == NULL)\n\t return;\n\tret = dict_add_list(retdict, \"items\", li);\n\tif (ret == OK && compl_first_match != NULL)\n\t{\n\t match = compl_first_match;\n\t do\n\t {\n\t\tif (!match_at_original_text(match))\n\t\t{\n\t\t di = dict_alloc();\n\t\t if (di == NULL)\n\t\t\treturn;\n\t\t ret = list_append_dict(li, di);\n\t\t if (ret != OK)\n\t\t\treturn;\n\t\t dict_add_string(di, \"word\", match->cp_str);\n\t\t dict_add_string(di, \"abbr\", match->cp_text[CPT_ABBR]);\n\t\t dict_add_string(di, \"menu\", match->cp_text[CPT_MENU]);\n\t\t dict_add_string(di, \"kind\", match->cp_text[CPT_KIND]);\n\t\t dict_add_string(di, \"info\", match->cp_text[CPT_INFO]);\n\t\t if (match->cp_user_data.v_type == VAR_UNKNOWN)\n\t\t\t// Add an empty string for backwards compatibility\n\t\t\tdict_add_string(di, \"user_data\", (char_u *)\"\");\n\t\t else\n\t\t\tdict_add_tv(di, \"user_data\", &match->cp_user_data);\n\t\t}\n\t\tmatch = match->cp_next;\n\t }\n\t while (match != NULL && !is_first_match(match));\n\t}\n }", " if (ret == OK && (what_flag & CI_WHAT_SELECTED))\n {\n\tif (compl_curr_match != NULL && compl_curr_match->cp_number == -1)\n\t ins_compl_update_sequence_numbers();\n\tret = dict_add_number(retdict, \"selected\", compl_curr_match != NULL\n\t\t\t\t ? compl_curr_match->cp_number - 1 : -1);\n }", " // TODO\n // if (ret == OK && (what_flag & CI_WHAT_INSERTED))\n}", "/*\n * \"complete_info()\" function\n */\n void\nf_complete_info(typval_T *argvars, typval_T *rettv)\n{\n list_T\t*what_list = NULL;", " if (rettv_dict_alloc(rettv) == FAIL)\n\treturn;", " if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)\n\treturn;", " if (argvars[0].v_type != VAR_UNKNOWN)\n {\n\tif (argvars[0].v_type != VAR_LIST)\n\t{\n\t emsg(_(e_list_required));\n\t return;\n\t}\n\twhat_list = argvars[0].vval.v_list;\n }\n get_complete_info(what_list, rettv->vval.v_dict);\n}\n#endif", "/*\n * Returns TRUE when using a user-defined function for thesaurus completion.\n */\n static int\nthesaurus_func_complete(int type UNUSED)\n{\n#ifdef FEAT_COMPL_FUNC\n return type == CTRL_X_THESAURUS\n\t\t&& (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);\n#else\n return FALSE;\n#endif\n}", "/*\n * Return value of process_next_cpt_value()\n */\nenum\n{\n INS_COMPL_CPT_OK = 1,\n INS_COMPL_CPT_CONT,\n INS_COMPL_CPT_END\n};", "/*\n * state information used for getting the next set of insert completion\n * matches.\n */\ntypedef struct\n{\n char_u\t*e_cpt;\t\t\t// current entry in 'complete'\n buf_T\t*ins_buf;\t\t// buffer being scanned\n pos_T\t*cur_match_pos;\t\t\t// current match position\n pos_T\tprev_match_pos;\t\t// previous match position\n int\t\tset_match_pos;\t\t// save first_match_pos/last_match_pos\n pos_T\tfirst_match_pos;\t// first match position\n pos_T\tlast_match_pos;\t\t// last match position\n int\t\tfound_all;\t\t// found all matches of a certain type.\n char_u\t*dict;\t\t\t// dictionary file to search\n int\t\tdict_f;\t\t\t// \"dict\" is an exact file name or not\n} ins_compl_next_state_T;", "/*\n * Process the next 'complete' option value in st->e_cpt.\n *\n * If successful, the arguments are set as below:\n * st->cpt - pointer to the next option value in \"st->cpt\"\n * compl_type_arg - type of insert mode completion to use\n * st->found_all - all matches of this type are found\n * st->ins_buf - search for completions in this buffer\n * st->first_match_pos - position of the first completion match\n * st->last_match_pos - position of the last completion match\n * st->set_match_pos - TRUE if the first match position should be saved to\n *\t\t\t avoid loops after the search wraps around.\n * st->dict - name of the dictionary or thesaurus file to search\n * st->dict_f - flag specifying whether \"dict\" is an exact file name or not\n *\n * Returns INS_COMPL_CPT_OK if the next value is processed successfully.\n * Returns INS_COMPL_CPT_CONT to skip the current completion source matching\n * the \"st->e_cpt\" option value and process the next matching source.\n * Returns INS_COMPL_CPT_END if all the values in \"st->e_cpt\" are processed.\n */\n static int\nprocess_next_cpt_value(\n\tins_compl_next_state_T *st,\n\tint\t\t*compl_type_arg,\n\tpos_T\t\t*start_match_pos)\n{\n int\t compl_type = -1;\n int\t status = INS_COMPL_CPT_OK;", " st->found_all = FALSE;", " while (*st->e_cpt == ',' || *st->e_cpt == ' ')\n\tst->e_cpt++;", " if (*st->e_cpt == '.' && !curbuf->b_scanned)\n {\n\tst->ins_buf = curbuf;\n\tst->first_match_pos = *start_match_pos;\n\t// Move the cursor back one character so that ^N can match the\n\t// word immediately after the cursor.\n\tif (ctrl_x_mode_normal() && dec(&st->first_match_pos) < 0)\n\t{\n\t // Move the cursor to after the last character in the\n\t // buffer, so that word at start of buffer is found\n\t // correctly.\n\t st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;\n\t st->first_match_pos.col =\n\t\t(colnr_T)STRLEN(ml_get(st->first_match_pos.lnum));\n\t}\n\tst->last_match_pos = st->first_match_pos;\n\tcompl_type = 0;", "\t// Remember the first match so that the loop stops when we\n\t// wrap and come back there a second time.\n\tst->set_match_pos = TRUE;\n }\n else if (vim_strchr((char_u *)\"buwU\", *st->e_cpt) != NULL\n\t && (st->ins_buf = ins_compl_next_buf(st->ins_buf, *st->e_cpt)) != curbuf)\n {\n\t// Scan a buffer, but not the current one.\n\tif (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer\n\t{\n\t compl_started = TRUE;\n\t st->first_match_pos.col = st->last_match_pos.col = 0;\n\t st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;\n\t st->last_match_pos.lnum = 0;\n\t compl_type = 0;\n\t}\n\telse\t// unloaded buffer, scan like dictionary\n\t{\n\t st->found_all = TRUE;\n\t if (st->ins_buf->b_fname == NULL)\n\t {\n\t\tstatus = INS_COMPL_CPT_CONT;\n\t\tgoto done;\n\t }\n\t compl_type = CTRL_X_DICTIONARY;\n\t st->dict = st->ins_buf->b_fname;\n\t st->dict_f = DICT_EXACT;\n\t}\n\tmsg_hist_off = TRUE;\t// reset in msg_trunc_attr()\n\tvim_snprintf((char *)IObuff, IOSIZE, _(\"Scanning: %s\"),\n\t\tst->ins_buf->b_fname == NULL\n\t\t ? buf_spname(st->ins_buf)\n\t\t : st->ins_buf->b_sfname == NULL\n\t\t\t? st->ins_buf->b_fname\n\t\t\t: st->ins_buf->b_sfname);\n\t(void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));\n }\n else if (*st->e_cpt == NUL)\n\tstatus = INS_COMPL_CPT_END;\n else\n {\n\tif (ctrl_x_mode_line_or_eval())\n\t compl_type = -1;\n\telse if (*st->e_cpt == 'k' || *st->e_cpt == 's')\n\t{\n\t if (*st->e_cpt == 'k')\n\t\tcompl_type = CTRL_X_DICTIONARY;\n\t else\n\t\tcompl_type = CTRL_X_THESAURUS;\n\t if (*++st->e_cpt != ',' && *st->e_cpt != NUL)\n\t {\n\t\tst->dict = st->e_cpt;\n\t\tst->dict_f = DICT_FIRST;\n\t }\n\t}\n#ifdef FEAT_FIND_ID\n\telse if (*st->e_cpt == 'i')\n\t compl_type = CTRL_X_PATH_PATTERNS;\n\telse if (*st->e_cpt == 'd')\n\t compl_type = CTRL_X_PATH_DEFINES;\n#endif\n\telse if (*st->e_cpt == ']' || *st->e_cpt == 't')\n\t{\n\t msg_hist_off = TRUE;\t// reset in msg_trunc_attr()\n\t compl_type = CTRL_X_TAGS;\n\t vim_snprintf((char *)IObuff, IOSIZE, _(\"Scanning tags.\"));\n\t (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));\n\t}\n\telse\n\t compl_type = -1;", "\t// in any case e_cpt is advanced to the next entry\n\t(void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, \",\");", "\tst->found_all = TRUE;\n\tif (compl_type == -1)\n\t status = INS_COMPL_CPT_CONT;\n }", "done:\n *compl_type_arg = compl_type;\n return status;\n}", "#ifdef FEAT_FIND_ID\n/*\n * Get the next set of identifiers or defines matching \"compl_pattern\" in\n * included files.\n */\n static void\nget_next_include_file_completion(int compl_type)\n{\n find_pattern_in_path(compl_pattern, compl_direction,\n\t (int)STRLEN(compl_pattern), FALSE, FALSE,\n\t (compl_type == CTRL_X_PATH_DEFINES\n\t && !(compl_cont_status & CONT_SOL))\n\t ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,\n\t (linenr_T)1, (linenr_T)MAXLNUM);\n}\n#endif", "/*\n * Get the next set of words matching \"compl_pattern\" in dictionary or\n * thesaurus files.\n */\n static void\nget_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)\n{\n#ifdef FEAT_COMPL_FUNC\n if (thesaurus_func_complete(compl_type))\n\texpand_by_function(compl_type, compl_pattern);\n else\n#endif\n\tins_compl_dictionaries(\n\t\tdict != NULL ? dict\n\t\t: (compl_type == CTRL_X_THESAURUS\n\t\t ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)\n\t\t : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),\n\t\tcompl_pattern,\n\t\tdict != NULL ? dict_f : 0,\n\t\tcompl_type == CTRL_X_THESAURUS);\n}", "/*\n * Get the next set of tag names matching \"compl_pattern\".\n */\n static void\nget_next_tag_completion(void)\n{\n int\t\tsave_p_ic;\n char_u\t**matches;\n int\t\tnum_matches;", " // set p_ic according to p_ic, p_scs and pat for find_tags().\n save_p_ic = p_ic;\n p_ic = ignorecase(compl_pattern);", " // Find up to TAG_MANY matches. Avoids that an enormous number\n // of matches is found when compl_pattern is empty\n g_tag_at_cursor = TRUE;\n if (find_tags(compl_pattern, &num_matches, &matches,\n\t\tTAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP\n\t\t| (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),\n\t\tTAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)\n\tins_compl_add_matches(num_matches, matches, p_ic);\n g_tag_at_cursor = FALSE;\n p_ic = save_p_ic;\n}", "/*\n * Get the next set of filename matching \"compl_pattern\".\n */\n static void\nget_next_filename_completion(void)\n{\n char_u\t**matches;\n int\t\tnum_matches;", " if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,\n\t\tEW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)\n\treturn;", " // May change home directory back to \"~\".\n tilde_replace(compl_pattern, num_matches, matches);\n#ifdef BACKSLASH_IN_FILENAME\n if (curbuf->b_p_csl[0] != NUL)\n {\n\tint\t i;", "\tfor (i = 0; i < num_matches; ++i)\n\t{\n\t char_u\t*ptr = matches[i];", "\t while (*ptr != NUL)\n\t {\n\t\tif (curbuf->b_p_csl[0] == 's' && *ptr == '\\\\')\n\t\t *ptr = '/';\n\t\telse if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')\n\t\t *ptr = '\\\\';\n\t\tptr += (*mb_ptr2len)(ptr);\n\t }\n\t}\n }\n#endif\n ins_compl_add_matches(num_matches, matches, p_fic || p_wic);\n}", "/*\n * Get the next set of command-line completions matching \"compl_pattern\".\n */\n static void\nget_next_cmdline_completion()\n{\n char_u\t**matches;\n int\t\tnum_matches;", " if (expand_cmdline(&compl_xp, compl_pattern,\n\t\t(int)STRLEN(compl_pattern),\n\t\t&num_matches, &matches) == EXPAND_OK)\n\tins_compl_add_matches(num_matches, matches, FALSE);\n}", "/*\n * Get the next set of spell suggestions matching \"compl_pattern\".\n */\n static void\nget_next_spell_completion(linenr_T lnum UNUSED)\n{\n#ifdef FEAT_SPELL\n char_u\t**matches;\n int\t\tnum_matches;", " num_matches = expand_spelling(lnum, compl_pattern, &matches);\n if (num_matches > 0)\n\tins_compl_add_matches(num_matches, matches, p_ic);\n else\n\tvim_free(matches);\n#endif\n}", "/*\n * Return the next word or line from buffer \"ins_buf\" at position\n * \"cur_match_pos\" for completion. The length of the match is set in \"len\".\n */\n static char_u *\nins_comp_get_next_word_or_line(\n\tbuf_T\t*ins_buf,\t\t// buffer being scanned\n\tpos_T\t*cur_match_pos,\t\t// current match position\n\tint\t*match_len,\n\tint\t*cont_s_ipos)\t\t// next ^X<> will set initial_pos\n{\n char_u\t*ptr;\n int\t\tlen;", " *match_len = 0;\n ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +\n\tcur_match_pos->col;\n if (ctrl_x_mode_line_or_eval())\n {\n\tif (compl_status_adding())\n\t{\n\t if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)\n\t\treturn NULL;\n\t ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);\n\t if (!p_paste)\n\t\tptr = skipwhite(ptr);\n\t}\n\tlen = (int)STRLEN(ptr);\n }\n else\n {\n\tchar_u\t*tmp_ptr = ptr;", "\tif (compl_status_adding())\n\t{\n\t tmp_ptr += compl_length;\n\t // Skip if already inside a word.\n\t if (vim_iswordp(tmp_ptr))\n\t\treturn NULL;\n\t // Find start of next word.\n\t tmp_ptr = find_word_start(tmp_ptr);\n\t}\n\t// Find end of this word.\n\ttmp_ptr = find_word_end(tmp_ptr);\n\tlen = (int)(tmp_ptr - ptr);", "\tif (compl_status_adding() && len == compl_length)\n\t{\n\t if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)\n\t {\n\t\t// Try next line, if any. the new word will be\n\t\t// \"join\" as if the normal command \"J\" was used.\n\t\t// IOSIZE is always greater than\n\t\t// compl_length, so the next STRNCPY always\n\t\t// works -- Acevedo\n\t\tSTRNCPY(IObuff, ptr, len);\n\t\tptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);\n\t\ttmp_ptr = ptr = skipwhite(ptr);\n\t\t// Find start of next word.\n\t\ttmp_ptr = find_word_start(tmp_ptr);\n\t\t// Find end of next word.\n\t\ttmp_ptr = find_word_end(tmp_ptr);\n\t\tif (tmp_ptr > ptr)\n\t\t{\n\t\t if (*ptr != ')' && IObuff[len - 1] != TAB)\n\t\t {\n\t\t\tif (IObuff[len - 1] != ' ')\n\t\t\t IObuff[len++] = ' ';\n\t\t\t// IObuf =~ \"\\k.* \", thus len >= 2\n\t\t\tif (p_js\n\t\t\t\t&& (IObuff[len - 2] == '.'\n\t\t\t\t || (vim_strchr(p_cpo, CPO_JOINSP)\n\t\t\t\t\t== NULL\n\t\t\t\t\t&& (IObuff[len - 2] == '?'\n\t\t\t\t\t || IObuff[len - 2] == '!'))))\n\t\t\t IObuff[len++] = ' ';\n\t\t }\n\t\t // copy as much as possible of the new word\n\t\t if (tmp_ptr - ptr >= IOSIZE - len)\n\t\t\ttmp_ptr = ptr + IOSIZE - len - 1;\n\t\t STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);\n\t\t len += (int)(tmp_ptr - ptr);\n\t\t *cont_s_ipos = TRUE;\n\t\t}\n\t\tIObuff[len] = NUL;\n\t\tptr = IObuff;\n\t }\n\t if (len == compl_length)\n\t\treturn NULL;\n\t}\n }", " *match_len = len;\n return ptr;\n}", "/*\n * Get the next set of words matching \"compl_pattern\" for default completion(s)\n * (normal ^P/^N and ^X^L).\n * Search for \"compl_pattern\" in the buffer \"st->ins_buf\" starting from the\n * position \"st->start_pos\" in the \"compl_direction\" direction. If\n * \"st->set_match_pos\" is TRUE, then set the \"st->first_match_pos\" and\n * \"st->last_match_pos\".\n * Returns OK if a new next match is found, otherwise returns FAIL.\n */\n static int\nget_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)\n{\n int\t\tfound_new_match = FAIL;\n int\t\tsave_p_scs;\n int\t\tsave_p_ws;\n int\t\tlooped_around = FALSE;\n char_u\t*ptr;\n int\t\tlen;", " // If 'infercase' is set, don't use 'smartcase' here\n save_p_scs = p_scs;\n if (st->ins_buf->b_p_inf)\n\tp_scs = FALSE;", " //\tBuffers other than curbuf are scanned from the beginning or the\n //\tend but never from the middle, thus setting nowrapscan in this\n //\tbuffer is a good idea, on the other hand, we always set\n //\twrapscan for curbuf to avoid missing matches -- Acevedo,Webb\n save_p_ws = p_ws;\n if (st->ins_buf != curbuf)\n\tp_ws = FALSE;\n else if (*st->e_cpt == '.')\n\tp_ws = TRUE;\n looped_around = FALSE;\n for (;;)\n {\n\tint\tcont_s_ipos = FALSE;", "\t++msg_silent; // Don't want messages for wrapscan.", "\t// ctrl_x_mode_line_or_eval() || word-wise search that\n\t// has added a word that was at the beginning of the line\n\tif (ctrl_x_mode_line_or_eval() || (compl_cont_status & CONT_SOL))\n\t found_new_match = search_for_exact_line(st->ins_buf,\n\t\t\t st->cur_match_pos, compl_direction, compl_pattern);\n\telse\n\t found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,\n\t\t\t\tNULL, compl_direction, compl_pattern, 1L,\n\t\t\t\tSEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);\n\t--msg_silent;\n\tif (!compl_started || st->set_match_pos)\n\t{\n\t // set \"compl_started\" even on fail\n\t compl_started = TRUE;\n\t st->first_match_pos = *st->cur_match_pos;\n\t st->last_match_pos = *st->cur_match_pos;\n\t st->set_match_pos = FALSE;\n\t}\n\telse if (st->first_match_pos.lnum == st->last_match_pos.lnum\n\t\t&& st->first_match_pos.col == st->last_match_pos.col)\n\t{\n\t found_new_match = FAIL;\n\t}\n\telse if (compl_dir_forward()\n\t\t&& (st->prev_match_pos.lnum > st->cur_match_pos->lnum\n\t\t || (st->prev_match_pos.lnum == st->cur_match_pos->lnum\n\t\t\t&& st->prev_match_pos.col >= st->cur_match_pos->col)))\n\t{\n\t if (looped_around)\n\t\tfound_new_match = FAIL;\n\t else\n\t\tlooped_around = TRUE;\n\t}\n\telse if (!compl_dir_forward()\n\t\t&& (st->prev_match_pos.lnum < st->cur_match_pos->lnum\n\t\t || (st->prev_match_pos.lnum == st->cur_match_pos->lnum\n\t\t\t&& st->prev_match_pos.col <= st->cur_match_pos->col)))\n\t{\n\t if (looped_around)\n\t\tfound_new_match = FAIL;\n\t else\n\t\tlooped_around = TRUE;\n\t}\n\tst->prev_match_pos = *st->cur_match_pos;\n\tif (found_new_match == FAIL)\n\t break;", "\t// when ADDING, the text before the cursor matches, skip it\n\tif (compl_status_adding() && st->ins_buf == curbuf\n\t\t&& start_pos->lnum == st->cur_match_pos->lnum\n\t\t&& start_pos->col == st->cur_match_pos->col)\n\t continue;", "\tptr = ins_comp_get_next_word_or_line(st->ins_buf, st->cur_match_pos,\n\t\t\t\t\t\t\t&len, &cont_s_ipos);\n\tif (ptr == NULL)\n\t continue;", "\tif (ins_compl_add_infercase(ptr, len, p_ic,\n\t\t st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,\n\t\t 0, cont_s_ipos) != NOTDONE)\n\t{\n\t found_new_match = OK;\n\t break;\n\t}\n }\n p_scs = save_p_scs;\n p_ws = save_p_ws;", " return found_new_match;\n}", "/*\n * get the next set of completion matches for \"type\".\n * Returns TRUE if a new match is found. Otherwise returns FALSE.\n */\n static int\nget_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)\n{\n int\tfound_new_match = FALSE;", " switch (type)\n {\n\tcase -1:\n\t break;\n#ifdef FEAT_FIND_ID\n\tcase CTRL_X_PATH_PATTERNS:\n\tcase CTRL_X_PATH_DEFINES:\n\t get_next_include_file_completion(type);\n\t break;\n#endif", "\tcase CTRL_X_DICTIONARY:\n\tcase CTRL_X_THESAURUS:\n\t get_next_dict_tsr_completion(type, st->dict, st->dict_f);\n\t st->dict = NULL;\n\t break;", "\tcase CTRL_X_TAGS:\n\t get_next_tag_completion();\n\t break;", "\tcase CTRL_X_FILES:\n\t get_next_filename_completion();\n\t break;", "\tcase CTRL_X_CMDLINE:\n\tcase CTRL_X_CMDLINE_CTRL_X:\n\t get_next_cmdline_completion();\n\t break;", "#ifdef FEAT_COMPL_FUNC\n\tcase CTRL_X_FUNCTION:\n\tcase CTRL_X_OMNI:\n\t expand_by_function(type, compl_pattern);\n\t break;\n#endif", "\tcase CTRL_X_SPELL:\n\t get_next_spell_completion(st->first_match_pos.lnum);\n\t break;", "\tdefault:\t// normal ^P/^N and ^X^L\n\t found_new_match = get_next_default_completion(st, ini);\n\t if (found_new_match == FAIL && st->ins_buf == curbuf)\n\t\tst->found_all = TRUE;\n }", " // check if compl_curr_match has changed, (e.g. other type of\n // expansion added something)\n if (type != 0 && compl_curr_match != compl_old_match)\n\tfound_new_match = OK;", " return found_new_match;\n}", "/*\n * Get the next expansion(s), using \"compl_pattern\".\n * The search starts at position \"ini\" in curbuf and in the direction\n * compl_direction.\n * When \"compl_started\" is FALSE start at that position, otherwise continue\n * where we stopped searching before.\n * This may return before finding all the matches.\n * Return the total number of matches or -1 if still unknown -- Acevedo\n */\n static int\nins_compl_get_exp(pos_T *ini)\n{\n static ins_compl_next_state_T st;\n int\t\ti;\n int\t\tfound_new_match;\n int\t\ttype = ctrl_x_mode;", " if (!compl_started)\n {\n\tFOR_ALL_BUFFERS(st.ins_buf)\n\t st.ins_buf->b_scanned = 0;\n\tst.found_all = FALSE;\n\tst.ins_buf = curbuf;\n\tst.e_cpt = (compl_cont_status & CONT_LOCAL)\n\t\t\t\t\t ? (char_u *)\".\" : curbuf->b_p_cpt;\n\tst.last_match_pos = st.first_match_pos = *ini;\n }\n else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))\n\tst.ins_buf = curbuf; // In case the buffer was wiped out.", " compl_old_match = compl_curr_match;\t// remember the last current match\n st.cur_match_pos = (compl_dir_forward())\n\t\t\t\t? &st.last_match_pos : &st.first_match_pos;", " // For ^N/^P loop over all the flags/windows/buffers in 'complete'.\n for (;;)\n {\n\tfound_new_match = FAIL;\n\tst.set_match_pos = FALSE;", "\t// For ^N/^P pick a new entry from e_cpt if compl_started is off,\n\t// or if found_all says this entry is done. For ^X^L only use the\n\t// entries from 'complete' that look in loaded buffers.\n\tif ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())\n\t\t\t\t\t&& (!compl_started || st.found_all))\n\t{\n\t int status = process_next_cpt_value(&st, &type, ini);", "\t if (status == INS_COMPL_CPT_END)\n\t\tbreak;\n\t if (status == INS_COMPL_CPT_CONT)\n\t\tcontinue;\n\t}", "\t// If complete() was called then compl_pattern has been reset. The\n\t// following won't work then, bail out.\n\tif (compl_pattern == NULL)\n\t break;", "\t// get the next set of completion matches\n\tfound_new_match = get_next_completion_match(type, &st, ini);", "\t// break the loop for specialized modes (use 'complete' just for the\n\t// generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new\n\t// match\n\tif ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())\n\t\t\t\t\t\t|| found_new_match != FAIL)\n\t{\n\t if (got_int)\n\t\tbreak;\n\t // Fill the popup menu as soon as possible.\n\t if (type != -1)\n\t\tins_compl_check_keys(0, FALSE);", "\t if ((ctrl_x_mode_not_default()\n\t\t\t&& !ctrl_x_mode_line_or_eval()) || compl_interrupted)\n\t\tbreak;\n\t compl_started = TRUE;\n\t}\n\telse\n\t{\n\t // Mark a buffer scanned when it has been scanned completely\n\t if (type == 0 || type == CTRL_X_PATH_PATTERNS)\n\t\tst.ins_buf->b_scanned = TRUE;", "\t compl_started = FALSE;\n\t}\n }\n compl_started = TRUE;", " if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())\n\t && *st.e_cpt == NUL)\t\t// Got to end of 'complete'\n\tfound_new_match = FAIL;", " i = -1;\t\t// total of matches, unknown\n if (found_new_match == FAIL || (ctrl_x_mode_not_default()\n\t\t\t\t\t && !ctrl_x_mode_line_or_eval()))\n\ti = ins_compl_make_cyclic();", " if (compl_old_match != NULL)\n {\n\t// If several matches were added (FORWARD) or the search failed and has\n\t// just been made cyclic then we have to move compl_curr_match to the\n\t// next or previous entry (if any) -- Acevedo\n\tcompl_curr_match = compl_dir_forward() ? compl_old_match->cp_next\n\t\t\t\t\t\t : compl_old_match->cp_prev;\n\tif (compl_curr_match == NULL)\n\t compl_curr_match = compl_old_match;\n }\n may_trigger_modechanged();", " return i;\n}", "/*\n * Update \"compl_shown_match\" to the actually shown match, it may differ when\n * \"compl_leader\" is used to omit some of the matches.\n */\n static void\nins_compl_update_shown_match(void)\n{\n while (!ins_compl_equal(compl_shown_match,\n\t\tcompl_leader, (int)STRLEN(compl_leader))\n\t && compl_shown_match->cp_next != NULL\n\t && !is_first_match(compl_shown_match->cp_next))\n\tcompl_shown_match = compl_shown_match->cp_next;", " // If we didn't find it searching forward, and compl_shows_dir is\n // backward, find the last match.\n if (compl_shows_dir_backward()\n\t && !ins_compl_equal(compl_shown_match,\n\t\tcompl_leader, (int)STRLEN(compl_leader))\n\t && (compl_shown_match->cp_next == NULL\n\t\t|| is_first_match(compl_shown_match->cp_next)))\n {\n\twhile (!ins_compl_equal(compl_shown_match,\n\t\t compl_leader, (int)STRLEN(compl_leader))\n\t\t&& compl_shown_match->cp_prev != NULL\n\t\t&& !is_first_match(compl_shown_match->cp_prev))\n\t compl_shown_match = compl_shown_match->cp_prev;\n }\n}", "/*\n * Delete the old text being completed.\n */\n void\nins_compl_delete(void)\n{\n int\t col;", " // In insert mode: Delete the typed part.\n // In replace mode: Put the old characters back, if any.\n col = compl_col + (compl_status_adding() ? compl_length : 0);\n if ((int)curwin->w_cursor.col > col)\n {\n\tif (stop_arrow() == FAIL)\n\t return;\n\tbackspace_until_column(col);\n }", " // TODO: is this sufficient for redrawing? Redrawing everything causes\n // flicker, thus we can't do that.\n changed_cline_bef_curs();\n#ifdef FEAT_EVAL\n // clear v:completed_item\n set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));\n#endif\n}", "/*\n * Insert the new text being completed.\n * \"in_compl_func\" is TRUE when called from complete_check().\n */\n void\nins_compl_insert(int in_compl_func)\n{\n int compl_len = get_compl_len();", " // Make sure we don't go over the end of the string, this can happen with\n // illegal bytes.\n if (compl_len < (int)STRLEN(compl_shown_match->cp_str))\n\tins_bytes(compl_shown_match->cp_str + compl_len);\n if (match_at_original_text(compl_shown_match))\n\tcompl_used_match = FALSE;\n else\n\tcompl_used_match = TRUE;\n#ifdef FEAT_EVAL\n {\n\tdict_T *dict = ins_compl_dict_alloc(compl_shown_match);", "\tset_vim_var_dict(VV_COMPLETED_ITEM, dict);\n }\n#endif\n if (!in_compl_func)\n\tcompl_curr_match = compl_shown_match;\n}", "/*\n * show the file name for the completion match (if any). Truncate the file\n * name to avoid a wait for return.\n */\n static void\nins_compl_show_filename(void)\n{\n char\t*lead = _(\"match in file\");\n int\t\tspace = sc_col - vim_strsize((char_u *)lead) - 2;\n char_u\t*s;\n char_u\t*e;", " if (space <= 0)\n\treturn;", " // We need the tail that fits. With double-byte encoding going\n // back from the end is very slow, thus go from the start and keep\n // the text that fits in \"space\" between \"s\" and \"e\".\n for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))\n {\n\tspace -= ptr2cells(e);\n\twhile (space < 0)\n\t{\n\t space += ptr2cells(s);\n\t MB_PTR_ADV(s);\n\t}\n }\n msg_hist_off = TRUE;\n vim_snprintf((char *)IObuff, IOSIZE, \"%s %s%s\", lead,\n\t s > compl_shown_match->cp_fname ? \"<\" : \"\", s);\n msg((char *)IObuff);\n msg_hist_off = FALSE;\n redraw_cmdline = FALSE;\t // don't overwrite!\n}", "/*\n * Find the next set of matches for completion. Repeat the completion \"todo\"\n * times. The number of matches found is returned in 'num_matches'.\n *\n * If \"allow_get_expansion\" is TRUE, then ins_compl_get_exp() may be called to\n * get more completions. If it is FALSE, then do nothing when there are no more\n * completions in the given direction.\n *\n * If \"advance\" is TRUE, then completion will move to the first match.\n * Otherwise, the original text will be shown.\n *\n * Returns OK on success and -1 if the number of matches are unknown.\n */\n static int\nfind_next_completion_match(\n\tint\tallow_get_expansion,\n\tint\ttodo,\t\t// repeat completion this many times\n\tint\tadvance,\n\tint\t*num_matches)\n{\n int\t found_end = FALSE;\n compl_T *found_compl = NULL;", " while (--todo >= 0)\n {\n\tif (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)\n\t{\n\t compl_shown_match = compl_shown_match->cp_next;\n\t found_end = (compl_first_match != NULL\n\t\t && (is_first_match(compl_shown_match->cp_next)\n\t\t\t|| is_first_match(compl_shown_match)));\n\t}\n\telse if (compl_shows_dir_backward()\n\t\t&& compl_shown_match->cp_prev != NULL)\n\t{\n\t found_end = is_first_match(compl_shown_match);\n\t compl_shown_match = compl_shown_match->cp_prev;\n\t found_end |= is_first_match(compl_shown_match);\n\t}\n\telse\n\t{\n\t if (!allow_get_expansion)\n\t {\n\t\tif (advance)\n\t\t{\n\t\t if (compl_shows_dir_backward())\n\t\t\tcompl_pending -= todo + 1;\n\t\t else\n\t\t\tcompl_pending += todo + 1;\n\t\t}\n\t\treturn -1;\n\t }", "\t if (!compl_no_select && advance)\n\t {\n\t\tif (compl_shows_dir_backward())\n\t\t --compl_pending;\n\t\telse\n\t\t ++compl_pending;\n\t }", "\t // Find matches.\n\t *num_matches = ins_compl_get_exp(&compl_startpos);", "\t // handle any pending completions\n\t while (compl_pending != 0 && compl_direction == compl_shows_dir\n\t\t && advance)\n\t {\n\t\tif (compl_pending > 0 && compl_shown_match->cp_next != NULL)\n\t\t{\n\t\t compl_shown_match = compl_shown_match->cp_next;\n\t\t --compl_pending;\n\t\t}\n\t\tif (compl_pending < 0 && compl_shown_match->cp_prev != NULL)\n\t\t{\n\t\t compl_shown_match = compl_shown_match->cp_prev;\n\t\t ++compl_pending;\n\t\t}\n\t\telse\n\t\t break;\n\t }\n\t found_end = FALSE;\n\t}\n\tif (!match_at_original_text(compl_shown_match)\n\t\t&& compl_leader != NULL\n\t\t&& !ins_compl_equal(compl_shown_match,\n\t\t compl_leader, (int)STRLEN(compl_leader)))\n\t ++todo;\n\telse\n\t // Remember a matching item.\n\t found_compl = compl_shown_match;", "\t// Stop at the end of the list when we found a usable match.\n\tif (found_end)\n\t{\n\t if (found_compl != NULL)\n\t {\n\t\tcompl_shown_match = found_compl;\n\t\tbreak;\n\t }\n\t todo = 1;\t // use first usable match after wrapping around\n\t}\n }", " return OK;\n}", "/*\n * Fill in the next completion in the current direction.\n * If \"allow_get_expansion\" is TRUE, then we may call ins_compl_get_exp() to\n * get more completions. If it is FALSE, then we just do nothing when there\n * are no more completions in a given direction. The latter case is used when\n * we are still in the middle of finding completions, to allow browsing\n * through the ones found so far.\n * Return the total number of matches, or -1 if still unknown -- webb.\n *\n * compl_curr_match is currently being used by ins_compl_get_exp(), so we use\n * compl_shown_match here.\n *\n * Note that this function may be called recursively once only. First with\n * \"allow_get_expansion\" TRUE, which calls ins_compl_get_exp(), which in turn\n * calls this function with \"allow_get_expansion\" FALSE.\n */\n static int\nins_compl_next(\n int\t allow_get_expansion,\n int\t count,\t\t// repeat completion this many times; should\n\t\t\t\t// be at least 1\n int\t insert_match,\t// Insert the newly selected match\n int\t in_compl_func)\t// called from complete_check()\n{\n int\t num_matches = -1;\n int\t todo = count;\n int\t advance;\n int\t started = compl_started;", " // When user complete function return -1 for findstart which is next\n // time of 'always', compl_shown_match become NULL.\n if (compl_shown_match == NULL)\n\treturn -1;", " if (compl_leader != NULL && !match_at_original_text(compl_shown_match))\n\t// Update \"compl_shown_match\" to the actually shown match\n\tins_compl_update_shown_match();", " if (allow_get_expansion && insert_match\n\t && (!(compl_get_longest || compl_restarting) || compl_used_match))\n\t// Delete old text to be replaced\n\tins_compl_delete();", " // When finding the longest common text we stick at the original text,\n // don't let CTRL-N or CTRL-P move to the first match.\n advance = count != 1 || !allow_get_expansion || !compl_get_longest;", " // When restarting the search don't insert the first match either.\n if (compl_restarting)\n {\n\tadvance = FALSE;\n\tcompl_restarting = FALSE;\n }", " // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap\n // around.\n if (find_next_completion_match(allow_get_expansion, todo, advance,\n\t\t\t\t\t\t\t&num_matches) == -1)\n\treturn -1;", " // Insert the text of the new completion, or the compl_leader.\n if (compl_no_insert && !started)\n {\n\tins_bytes(compl_orig_text + get_compl_len());\n\tcompl_used_match = FALSE;\n }\n else if (insert_match)\n {\n\tif (!compl_get_longest || compl_used_match)\n\t ins_compl_insert(in_compl_func);\n\telse\n\t ins_bytes(compl_leader + get_compl_len());\n }\n else\n\tcompl_used_match = FALSE;", " if (!allow_get_expansion)\n {\n\t// may undisplay the popup menu first\n\tins_compl_upd_pum();", "\tif (pum_enough_matches())\n\t // Will display the popup menu, don't redraw yet to avoid flicker.\n\t pum_call_update_screen();\n\telse\n\t // Not showing the popup menu yet, redraw to show the user what was\n\t // inserted.\n\t update_screen(0);", "\t// display the updated popup menu\n\tins_compl_show_pum();\n#ifdef FEAT_GUI\n\tif (gui.in_use)\n\t{\n\t // Show the cursor after the match, not after the redrawn text.\n\t setcursor();\n\t out_flush_cursor(FALSE, FALSE);\n\t}\n#endif", "\t// Delete old text to be replaced, since we're still searching and\n\t// don't want to match ourselves!\n\tins_compl_delete();\n }", " // Enter will select a match when the match wasn't inserted and the popup\n // menu is visible.\n if (compl_no_insert && !started)\n\tcompl_enter_selects = TRUE;\n else\n\tcompl_enter_selects = !insert_match && compl_match_array != NULL;", " // Show the file name for the match (if any)\n if (compl_shown_match->cp_fname != NULL)\n\tins_compl_show_filename();", " return num_matches;\n}", "/*\n * Call this while finding completions, to check whether the user has hit a key\n * that should change the currently displayed completion, or exit completion\n * mode. Also, when compl_pending is not zero, show a completion as soon as\n * possible. -- webb\n * \"frequency\" specifies out of how many calls we actually check.\n * \"in_compl_func\" is TRUE when called from complete_check(), don't set\n * compl_curr_match.\n */\n void\nins_compl_check_keys(int frequency, int in_compl_func)\n{\n static int\tcount = 0;\n int\t\tc;", " // Don't check when reading keys from a script, :normal or feedkeys().\n // That would break the test scripts. But do check for keys when called\n // from complete_check().\n if (!in_compl_func && (using_script() || ex_normal_busy))\n\treturn;", " // Only do this at regular intervals\n if (++count < frequency)\n\treturn;\n count = 0;", " // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()\n // can't do its work correctly.\n c = vpeekc_any();\n if (c != NUL)\n {\n\tif (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)\n\t{\n\t c = safe_vgetc();\t// Eat the character\n\t compl_shows_dir = ins_compl_key2dir(c);\n\t (void)ins_compl_next(FALSE, ins_compl_key2count(c),\n\t\t\t\t c != K_UP && c != K_DOWN, in_compl_func);\n\t}\n\telse\n\t{\n\t // Need to get the character to have KeyTyped set. We'll put it\n\t // back with vungetc() below. But skip K_IGNORE.\n\t c = safe_vgetc();\n\t if (c != K_IGNORE)\n\t {\n\t\t// Don't interrupt completion when the character wasn't typed,\n\t\t// e.g., when doing @q to replay keys.\n\t\tif (c != Ctrl_R && KeyTyped)\n\t\t compl_interrupted = TRUE;", "\t\tvungetc(c);\n\t }\n\t}\n }\n if (compl_pending != 0 && !got_int && !compl_no_insert)\n {\n\tint todo = compl_pending > 0 ? compl_pending : -compl_pending;", "\tcompl_pending = 0;\n\t(void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);\n }\n}", "/*\n * Decide the direction of Insert mode complete from the key typed.\n * Returns BACKWARD or FORWARD.\n */\n static int\nins_compl_key2dir(int c)\n{\n if (c == Ctrl_P || c == Ctrl_L\n\t || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)\n\treturn BACKWARD;\n return FORWARD;\n}", "/*\n * Return TRUE for keys that are used for completion only when the popup menu\n * is visible.\n */\n static int\nins_compl_pum_key(int c)\n{\n return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP\n\t\t || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN\n\t\t || c == K_UP || c == K_DOWN);\n}", "/*\n * Decide the number of completions to move forward.\n * Returns 1 for most keys, height of the popup menu for page-up/down keys.\n */\n static int\nins_compl_key2count(int c)\n{\n int\t\th;", " if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)\n {\n\th = pum_get_height();\n\tif (h > 3)\n\t h -= 2; // keep some context\n\treturn h;\n }\n return 1;\n}", "/*\n * Return TRUE if completion with \"c\" should insert the match, FALSE if only\n * to change the currently selected completion.\n */\n static int\nins_compl_use_match(int c)\n{\n switch (c)\n {\n\tcase K_UP:\n\tcase K_DOWN:\n\tcase K_PAGEDOWN:\n\tcase K_KPAGEDOWN:\n\tcase K_S_DOWN:\n\tcase K_PAGEUP:\n\tcase K_KPAGEUP:\n\tcase K_S_UP:\n\t return FALSE;\n }\n return TRUE;\n}", "/*\n * Get the pattern, column and length for normal completion (CTRL-N CTRL-P\n * completion)\n * Sets the global variables: compl_col, compl_length and compl_pattern.\n * Uses the global variables: compl_cont_status and ctrl_x_mode\n */\n static int\nget_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)\n{\n if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())\n {\n\tif (!compl_status_adding())\n\t{\n\t while (--startcol >= 0 && vim_isIDc(line[startcol]))\n\t\t;\n\t compl_col += ++startcol;\n\t compl_length = curs_col - startcol;\n\t}\n\tif (p_ic)\n\t compl_pattern = str_foldcase(line + compl_col,\n\t\t compl_length, NULL, 0);\n\telse\n\t compl_pattern = vim_strnsave(line + compl_col, compl_length);\n\tif (compl_pattern == NULL)\n\t return FAIL;\n }\n else if (compl_status_adding())\n {\n\tchar_u\t *prefix = (char_u *)\"\\\\<\";", "\t// we need up to 2 extra chars for the prefix\n\tcompl_pattern = alloc(quote_meta(NULL, line + compl_col,\n\t\t compl_length) + 2);\n\tif (compl_pattern == NULL)\n\t return FAIL;\n\tif (!vim_iswordp(line + compl_col)\n\t\t|| (compl_col > 0\n\t\t && (vim_iswordp(mb_prevptr(line, line + compl_col)))))\n\t prefix = (char_u *)\"\";\n\tSTRCPY((char *)compl_pattern, prefix);\n\t(void)quote_meta(compl_pattern + STRLEN(prefix),\n\t\tline + compl_col, compl_length);\n }\n else if (--startcol < 0\n\t || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))\n {\n\t// Match any word of at least two chars\n\tcompl_pattern = vim_strsave((char_u *)\"\\\\<\\\\k\\\\k\");\n\tif (compl_pattern == NULL)\n\t return FAIL;\n\tcompl_col += curs_col;\n\tcompl_length = 0;\n }\n else\n {\n\t// Search the point of change class of multibyte character\n\t// or not a word single byte character backward.\n\tif (has_mbyte)\n\t{\n\t int base_class;\n\t int head_off;", "\t startcol -= (*mb_head_off)(line, line + startcol);\n\t base_class = mb_get_class(line + startcol);\n\t while (--startcol >= 0)\n\t {\n\t\thead_off = (*mb_head_off)(line, line + startcol);\n\t\tif (base_class != mb_get_class(line + startcol\n\t\t\t - head_off))\n\t\t break;\n\t\tstartcol -= head_off;\n\t }\n\t}\n\telse\n\t while (--startcol >= 0 && vim_iswordc(line[startcol]))\n\t\t;\n\tcompl_col += ++startcol;\n\tcompl_length = (int)curs_col - startcol;\n\tif (compl_length == 1)\n\t{\n\t // Only match word with at least two chars -- webb\n\t // there's no need to call quote_meta,\n\t // alloc(7) is enough -- Acevedo\n\t compl_pattern = alloc(7);\n\t if (compl_pattern == NULL)\n\t\treturn FAIL;\n\t STRCPY((char *)compl_pattern, \"\\\\<\");\n\t (void)quote_meta(compl_pattern + 2, line + compl_col, 1);\n\t STRCAT((char *)compl_pattern, \"\\\\k\");\n\t}\n\telse\n\t{\n\t compl_pattern = alloc(quote_meta(NULL, line + compl_col,\n\t\t\tcompl_length) + 2);\n\t if (compl_pattern == NULL)\n\t\treturn FAIL;\n\t STRCPY((char *)compl_pattern, \"\\\\<\");\n\t (void)quote_meta(compl_pattern + 2, line + compl_col,\n\t\t compl_length);\n\t}\n }", " return OK;\n}", "/*\n * Get the pattern, column and length for whole line completion or for the\n * complete() function.\n * Sets the global variables: compl_col, compl_length and compl_pattern.\n */\n static int\nget_wholeline_compl_info(char_u *line, colnr_T curs_col)\n{\n compl_col = (colnr_T)getwhitecols(line);\n compl_length = (int)curs_col - (int)compl_col;\n if (compl_length < 0)\t// cursor in indent: empty pattern\n\tcompl_length = 0;\n if (p_ic)\n\tcompl_pattern = str_foldcase(line + compl_col, compl_length,\n\t\tNULL, 0);\n else\n\tcompl_pattern = vim_strnsave(line + compl_col, compl_length);\n if (compl_pattern == NULL)\n\treturn FAIL;", " return OK;\n}", "/*\n * Get the pattern, column and length for filename completion.\n * Sets the global variables: compl_col, compl_length and compl_pattern.\n */\n static int\nget_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)\n{\n // Go back to just before the first filename character.\n if (startcol > 0)\n {\n\tchar_u\t*p = line + startcol;", "\tMB_PTR_BACK(line, p);\n\twhile (p > line && vim_isfilec(PTR2CHAR(p)))\n\t MB_PTR_BACK(line, p);\n\tif (p == line && vim_isfilec(PTR2CHAR(p)))\n\t startcol = 0;\n\telse\n\t startcol = (int)(p - line) + 1;\n }", " compl_col += startcol;\n compl_length = (int)curs_col - startcol;\n compl_pattern = addstar(line + compl_col, compl_length, EXPAND_FILES);\n if (compl_pattern == NULL)\n\treturn FAIL;", " return OK;\n}", "/*\n * Get the pattern, column and length for command-line completion.\n * Sets the global variables: compl_col, compl_length and compl_pattern.\n */\n static int\nget_cmdline_compl_info(char_u *line, colnr_T curs_col)\n{\n compl_pattern = vim_strnsave(line, curs_col);\n if (compl_pattern == NULL)\n\treturn FAIL;\n set_cmd_context(&compl_xp, compl_pattern,\n\t (int)STRLEN(compl_pattern), curs_col, FALSE);\n if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL\n\t || compl_xp.xp_context == EXPAND_NOTHING)\n\t// No completion possible, use an empty pattern to get a\n\t// \"pattern not found\" message.\n\tcompl_col = curs_col;\n else\n\tcompl_col = (int)(compl_xp.xp_pattern - compl_pattern);\n compl_length = curs_col - compl_col;", " return OK;\n}", "/*\n * Get the pattern, column and length for user defined completion ('omnifunc',\n * 'completefunc' and 'thesaurusfunc')\n * Sets the global variables: compl_col, compl_length and compl_pattern.\n * Uses the global variable: spell_bad_len\n */\n static int\nget_userdefined_compl_info(colnr_T curs_col UNUSED)\n{\n int\t\tret = FAIL;", "#ifdef FEAT_COMPL_FUNC\n // Call user defined function 'completefunc' with \"a:findstart\"\n // set to 1 to obtain the length of text to use for completion.\n char_u\t*line;\n typval_T\targs[3];\n int\t\tcol;\n char_u\t*funcname;\n pos_T\tpos;\n int\t\tsave_State = State;\n callback_T\t*cb;", " // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern\n // length as a string\n funcname = get_complete_funcname(ctrl_x_mode);\n if (*funcname == NUL)\n {\n\tsemsg(_(e_option_str_is_not_set), ctrl_x_mode_function()\n\t\t? \"completefunc\" : \"omnifunc\");\n\treturn FAIL;\n }", " args[0].v_type = VAR_NUMBER;\n args[0].vval.v_number = 1;\n args[1].v_type = VAR_STRING;\n args[1].vval.v_string = (char_u *)\"\";\n args[2].v_type = VAR_UNKNOWN;\n pos = curwin->w_cursor;\n ++textlock;\n cb = get_insert_callback(ctrl_x_mode);\n col = call_callback_retnr(cb, 2, args);\n --textlock;", " State = save_State;\n curwin->w_cursor = pos;\t// restore the cursor position\n validate_cursor();\n if (!EQUAL_POS(curwin->w_cursor, pos))\n {\n\temsg(_(e_complete_function_deleted_text));\n\treturn FAIL;\n }", " // Return value -2 means the user complete function wants to cancel the\n // complete without an error, do the same if the function did not execute\n // successfully.\n if (col == -2 || aborting())\n\treturn FAIL;\n // Return value -3 does the same as -2 and leaves CTRL-X mode.\n if (col == -3)\n {\n\tctrl_x_mode = CTRL_X_NORMAL;\n\tedit_submode = NULL;\n\tif (!shortmess(SHM_COMPLETIONMENU))\n\t msg_clr_cmdline();\n\treturn FAIL;\n }", " // Reset extended parameters of completion, when starting new\n // completion.\n compl_opt_refresh_always = FALSE;\n compl_opt_suppress_empty = FALSE;", " if (col < 0)\n\tcol = curs_col;\n compl_col = col;\n if (compl_col > curs_col)\n\tcompl_col = curs_col;", " // Setup variables for completion. Need to obtain \"line\" again,\n // it may have become invalid.\n line = ml_get(curwin->w_cursor.lnum);\n compl_length = curs_col - compl_col;\n compl_pattern = vim_strnsave(line + compl_col, compl_length);\n if (compl_pattern == NULL)\n\treturn FAIL;", " ret = OK;\n#endif", " return ret;\n}", "/*\n * Get the pattern, column and length for spell completion.\n * Sets the global variables: compl_col, compl_length and compl_pattern.\n * Uses the global variable: spell_bad_len\n */\n static int\nget_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)\n{\n int\t\tret = FAIL;\n#ifdef FEAT_SPELL\n char_u\t*line;", " if (spell_bad_len > 0)\n\tcompl_col = curs_col - spell_bad_len;\n else\n\tcompl_col = spell_word_start(startcol);\n if (compl_col >= (colnr_T)startcol)\n {\n\tcompl_length = 0;\n\tcompl_col = curs_col;\n }\n else\n {\n\tspell_expand_check_cap(compl_col);\n\tcompl_length = (int)curs_col - compl_col;\n }\n // Need to obtain \"line\" again, it may have become invalid.\n line = ml_get(curwin->w_cursor.lnum);\n compl_pattern = vim_strnsave(line + compl_col, compl_length);\n if (compl_pattern == NULL)\n\treturn FAIL;", " ret = OK;\n#endif", " return ret;\n}", "/*\n * Get the completion pattern, column and length.\n * \"startcol\" - start column number of the completion pattern/text\n * \"cur_col\" - current cursor column\n * On return, \"line_invalid\" is set to TRUE, if the current line may have\n * become invalid and needs to be fetched again.\n * Returns OK on success.\n */\n static int\ncompl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)\n{\n if (ctrl_x_mode_normal()\n\t || (ctrl_x_mode & CTRL_X_WANT_IDENT\n\t\t&& !thesaurus_func_complete(ctrl_x_mode)))\n {\n\treturn get_normal_compl_info(line, startcol, curs_col);\n }\n else if (ctrl_x_mode_line_or_eval())\n {\n\treturn get_wholeline_compl_info(line, curs_col);\n }\n else if (ctrl_x_mode_files())\n {\n\treturn get_filename_compl_info(line, startcol, curs_col);\n }\n else if (ctrl_x_mode == CTRL_X_CMDLINE)\n {\n\treturn get_cmdline_compl_info(line, curs_col);\n }\n else if (ctrl_x_mode_function() || ctrl_x_mode_omni()\n\t || thesaurus_func_complete(ctrl_x_mode))\n {\n\tif (get_userdefined_compl_info(curs_col) == FAIL)\n\t return FAIL;\n\t*line_invalid = TRUE;\t// \"line\" may have become invalid\n }\n else if (ctrl_x_mode_spell())\n {\n\tif (get_spell_compl_info(startcol, curs_col) == FAIL)\n\t return FAIL;\n\t*line_invalid = TRUE;\t// \"line\" may have become invalid\n }\n else\n {\n\tinternal_error(\"ins_complete()\");\n\treturn FAIL;\n }", " return OK;\n}", "/*\n * Continue an interrupted completion mode search in \"line\".\n *\n * If this same ctrl_x_mode has been interrupted use the text from\n * \"compl_startpos\" to the cursor as a pattern to add a new word instead of\n * expand the one before the cursor, in word-wise if \"compl_startpos\" is not in\n * the same line as the cursor then fix it (the line has been split because it\n * was longer than 'tw'). if SOL is set then skip the previous pattern, a word\n * at the beginning of the line has been inserted, we'll look for that.\n */\n static void\nins_compl_continue_search(char_u *line)\n{\n // it is a continued search\n compl_cont_status &= ~CONT_INTRPT;\t// remove INTRPT\n if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()\n\t\t\t\t\t\t|| ctrl_x_mode_path_defines())\n {\n\tif (compl_startpos.lnum != curwin->w_cursor.lnum)\n\t{\n\t // line (probably) wrapped, set compl_startpos to the\n\t // first non_blank in the line, if it is not a wordchar\n\t // include it to get a better pattern, but then we don't\n\t // want the \"\\\\<\" prefix, check it below\n\t compl_col = (colnr_T)getwhitecols(line);\n\t compl_startpos.col = compl_col;\n\t compl_startpos.lnum = curwin->w_cursor.lnum;\n\t compl_cont_status &= ~CONT_SOL; // clear SOL if present\n\t}\n\telse\n\t{\n\t // S_IPOS was set when we inserted a word that was at the\n\t // beginning of the line, which means that we'll go to SOL\n\t // mode but first we need to redefine compl_startpos\n\t if (compl_cont_status & CONT_S_IPOS)\n\t {\n\t\tcompl_cont_status |= CONT_SOL;\n\t\tcompl_startpos.col = (colnr_T)(skipwhite(\n\t\t\t line + compl_length\n\t\t\t + compl_startpos.col) - line);\n\t }\n\t compl_col = compl_startpos.col;\n\t}\n\tcompl_length = curwin->w_cursor.col - (int)compl_col;\n\t// IObuff is used to add a \"word from the next line\" would we\n\t// have enough space? just being paranoid\n#define\tMIN_SPACE 75\n\tif (compl_length > (IOSIZE - MIN_SPACE))\n\t{\n\t compl_cont_status &= ~CONT_SOL;\n\t compl_length = (IOSIZE - MIN_SPACE);\n\t compl_col = curwin->w_cursor.col - compl_length;\n\t}\n\tcompl_cont_status |= CONT_ADDING | CONT_N_ADDS;\n\tif (compl_length < 1)\n\t compl_cont_status &= CONT_LOCAL;\n }\n else if (ctrl_x_mode_line_or_eval())\n\tcompl_cont_status = CONT_ADDING | CONT_N_ADDS;\n else\n\tcompl_cont_status = 0;\n}", "/*\n * start insert mode completion\n */\n static int\nins_compl_start(void)\n{\n char_u\t*line;\n int\t\tstartcol = 0;\t // column where searched text starts\n colnr_T\tcurs_col;\t // cursor column\n int\t\tline_invalid = FALSE;\n int\t\tsave_did_ai = did_ai;\n int\t\tflags = CP_ORIGINAL_TEXT;", " // First time we hit ^N or ^P (in a row, I mean)", " did_ai = FALSE;\n did_si = FALSE;\n can_si = FALSE;\n can_si_back = FALSE;\n if (stop_arrow() == FAIL)\n\treturn FAIL;", " line = ml_get(curwin->w_cursor.lnum);\n curs_col = curwin->w_cursor.col;\n compl_pending = 0;", " if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT\n\t && compl_cont_mode == ctrl_x_mode)\n\t// this same ctrl-x_mode was interrupted previously. Continue the\n\t// completion.\n\tins_compl_continue_search(line);\n else\n\tcompl_cont_status &= CONT_LOCAL;", " if (!compl_status_adding())\t// normal expansion\n {\n\tcompl_cont_mode = ctrl_x_mode;\n\tif (ctrl_x_mode_not_default())\n\t // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL\n\t compl_cont_status = 0;\n\tcompl_cont_status |= CONT_N_ADDS;\n\tcompl_startpos = curwin->w_cursor;\n\tstartcol = (int)curs_col;\n\tcompl_col = 0;\n }", " // Work out completion pattern and original text -- webb\n if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)\n {\n\tif (ctrl_x_mode_function() || ctrl_x_mode_omni()\n\t\t\t\t|| thesaurus_func_complete(ctrl_x_mode))\n\t // restore did_ai, so that adding comment leader works\n\t did_ai = save_did_ai;\n\treturn FAIL;\n }\n // If \"line\" was changed while getting completion info get it again.\n if (line_invalid)\n\tline = ml_get(curwin->w_cursor.lnum);", " if (compl_status_adding())\n {\n\tedit_submode_pre = (char_u *)_(\" Adding\");\n\tif (ctrl_x_mode_line_or_eval())\n\t{\n\t // Insert a new line, keep indentation but ignore 'comments'.\n\t char_u *old = curbuf->b_p_com;", "\t curbuf->b_p_com = (char_u *)\"\";\n\t compl_startpos.lnum = curwin->w_cursor.lnum;\n\t compl_startpos.col = compl_col;\n\t ins_eol('\\r');\n\t curbuf->b_p_com = old;\n\t compl_length = 0;\n\t compl_col = curwin->w_cursor.col;\n\t}\n }\n else\n {\n\tedit_submode_pre = NULL;\n\tcompl_startpos.col = compl_col;\n }", " if (compl_cont_status & CONT_LOCAL)\n\tedit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);\n else\n\tedit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));", " // If any of the original typed text has been changed we need to fix\n // the redo buffer.\n ins_compl_fixRedoBufForLeader(NULL);", " // Always add completion for the original text.\n vim_free(compl_orig_text);\n compl_orig_text = vim_strnsave(line + compl_col, compl_length);\n if (p_ic)\n\tflags |= CP_ICASE;\n if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,\n\t\t-1, NULL, NULL, NULL, 0, flags, FALSE) != OK)\n {\n\tVIM_CLEAR(compl_pattern);\n\tVIM_CLEAR(compl_orig_text);\n\treturn FAIL;\n }", " // showmode might reset the internal line pointers, so it must\n // be called before line = ml_get(), or when this address is no\n // longer needed. -- Acevedo.\n edit_submode_extra = (char_u *)_(\"-- Searching...\");\n edit_submode_highl = HLF_COUNT;\n showmode();\n edit_submode_extra = NULL;\n out_flush();", " return OK;\n}", "/*\n * display the completion status message\n */\n static void\nins_compl_show_statusmsg(void)\n{\n // we found no match if the list has only the \"compl_orig_text\"-entry\n if (is_first_match(compl_first_match->cp_next))\n {\n\tedit_submode_extra = compl_status_adding() && compl_length > 1\n\t\t\t\t? (char_u *)_(e_hitend)\n\t\t\t\t: (char_u *)_(e_pattern_not_found);\n\tedit_submode_highl = HLF_E;\n }", " if (edit_submode_extra == NULL)\n {\n\tif (match_at_original_text(compl_curr_match))\n\t{\n\t edit_submode_extra = (char_u *)_(\"Back at original\");\n\t edit_submode_highl = HLF_W;\n\t}\n\telse if (compl_cont_status & CONT_S_IPOS)\n\t{\n\t edit_submode_extra = (char_u *)_(\"Word from other line\");\n\t edit_submode_highl = HLF_COUNT;\n\t}\n\telse if (compl_curr_match->cp_next == compl_curr_match->cp_prev)\n\t{\n\t edit_submode_extra = (char_u *)_(\"The only match\");\n\t edit_submode_highl = HLF_COUNT;\n\t compl_curr_match->cp_number = 1;\n\t}\n\telse\n\t{\n#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)\n\t // Update completion sequence number when needed.\n\t if (compl_curr_match->cp_number == -1)\n\t\tins_compl_update_sequence_numbers();\n#endif\n\t // The match should always have a sequence number now, this is\n\t // just a safety check.\n\t if (compl_curr_match->cp_number != -1)\n\t {\n\t\t// Space for 10 text chars. + 2x10-digit no.s = 31.\n\t\t// Translations may need more than twice that.\n\t\tstatic char_u match_ref[81];", "\t\tif (compl_matches > 0)\n\t\t vim_snprintf((char *)match_ref, sizeof(match_ref),\n\t\t\t _(\"match %d of %d\"),\n\t\t\t compl_curr_match->cp_number, compl_matches);\n\t\telse\n\t\t vim_snprintf((char *)match_ref, sizeof(match_ref),\n\t\t\t _(\"match %d\"),\n\t\t\t compl_curr_match->cp_number);\n\t\tedit_submode_extra = match_ref;\n\t\tedit_submode_highl = HLF_R;\n\t\tif (dollar_vcol >= 0)\n\t\t curs_columns(FALSE);\n\t }\n\t}\n }", " // Show a message about what (completion) mode we're in.\n if (!compl_opt_suppress_empty)\n {\n\tshowmode();\n\tif (!shortmess(SHM_COMPLETIONMENU))\n\t{\n\t if (edit_submode_extra != NULL)\n\t {\n\t\tif (!p_smd)\n\t\t{\n\t\t msg_hist_off = TRUE;\n\t\t msg_attr((char *)edit_submode_extra,\n\t\t\t edit_submode_highl < HLF_COUNT\n\t\t\t ? HL_ATTR(edit_submode_highl) : 0);\n\t\t msg_hist_off = FALSE;\n\t\t}\n\t }\n\t else\n\t\tmsg_clr_cmdline();\t// necessary for \"noshowmode\"\n\t}\n }\n}", "/*\n * Do Insert mode completion.\n * Called when character \"c\" was typed, which has a meaning for completion.\n * Returns OK if completion was done, FAIL if something failed (out of mem).\n */\n int\nins_complete(int c, int enable_pum)\n{\n int\t\tn;\n int\t\tsave_w_wrow;\n int\t\tsave_w_leftcol;\n int\t\tinsert_match;", " compl_direction = ins_compl_key2dir(c);\n insert_match = ins_compl_use_match(c);", " if (!compl_started)\n {\n\tif (ins_compl_start() == FAIL)\n\t return FAIL;\n }\n else if (insert_match && stop_arrow() == FAIL)\n\treturn FAIL;", " compl_shown_match = compl_curr_match;\n compl_shows_dir = compl_direction;", " // Find next match (and following matches).\n save_w_wrow = curwin->w_wrow;\n save_w_leftcol = curwin->w_leftcol;\n n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);", " // may undisplay the popup menu\n ins_compl_upd_pum();", " if (n > 1)\t\t// all matches have been found\n\tcompl_matches = n;\n compl_curr_match = compl_shown_match;\n compl_direction = compl_shows_dir;", " // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert\n // mode.\n if (got_int && !global_busy)\n {\n\t(void)vgetc();\n\tgot_int = FALSE;\n }", " // we found no match if the list has only the \"compl_orig_text\"-entry\n if (is_first_match(compl_first_match->cp_next))\n {\n\t// remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,\n\t// because we couldn't expand anything at first place, but if we used\n\t// ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word\n\t// (such as M in M'exico) if not tried already. -- Acevedo\n\tif (compl_length > 1\n\t\t|| compl_status_adding()\n\t\t|| (ctrl_x_mode_not_default()\n\t\t && !ctrl_x_mode_path_patterns()\n\t\t && !ctrl_x_mode_path_defines()))\n\t compl_cont_status &= ~CONT_N_ADDS;\n }", " if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)\n\tcompl_cont_status |= CONT_S_IPOS;\n else\n\tcompl_cont_status &= ~CONT_S_IPOS;", " ins_compl_show_statusmsg();", " // Show the popup menu, unless we got interrupted.\n if (enable_pum && !compl_interrupted)\n\tshow_pum(save_w_wrow, save_w_leftcol);", " compl_was_interrupted = compl_interrupted;\n compl_interrupted = FALSE;", " return OK;\n}", "/*\n * Remove (if needed) and show the popup menu\n */\n static void\nshow_pum(int prev_w_wrow, int prev_w_leftcol)\n{\n // RedrawingDisabled may be set when invoked through complete().\n int n = RedrawingDisabled;", " RedrawingDisabled = 0;", " // If the cursor moved or the display scrolled we need to remove the pum\n // first.\n setcursor();\n if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)\n\tins_compl_del_pum();", " ins_compl_show_pum();\n setcursor();\n RedrawingDisabled = n;\n}", "/*\n * Looks in the first \"len\" chars. of \"src\" for search-metachars.\n * If dest is not NULL the chars. are copied there quoting (with\n * a backslash) the metachars, and dest would be NUL terminated.\n * Returns the length (needed) of dest\n */\n static unsigned\nquote_meta(char_u *dest, char_u *src, int len)\n{\n unsigned\tm = (unsigned)len + 1; // one extra for the NUL", " for ( ; --len >= 0; src++)\n {\n\tswitch (*src)\n\t{\n\t case '.':\n\t case '*':\n\t case '[':\n\t\tif (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())\n\t\t break;\n\t\t// FALLTHROUGH\n\t case '~':\n\t\tif (!magic_isset())\t// quote these only if magic is set\n\t\t break;\n\t\t// FALLTHROUGH\n\t case '\\\\':\n\t\tif (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())\n\t\t break;\n\t\t// FALLTHROUGH\n\t case '^':\t\t// currently it's not needed.\n\t case '$':\n\t\tm++;\n\t\tif (dest != NULL)\n\t\t *dest++ = '\\\\';\n\t\tbreak;\n\t}\n\tif (dest != NULL)\n\t *dest++ = *src;\n\t// Copy remaining bytes of a multibyte character.\n\tif (has_mbyte)\n\t{\n\t int i, mb_len;", "\t mb_len = (*mb_ptr2len)(src) - 1;\n\t if (mb_len > 0 && len >= mb_len)\n\t\tfor (i = 0; i < mb_len; ++i)\n\t\t{\n\t\t --len;\n\t\t ++src;\n\t\t if (dest != NULL)\n\t\t\t*dest++ = *src;\n\t\t}\n\t}\n }\n if (dest != NULL)\n\t*dest = NUL;", " return m;\n}", "#if defined(EXITFREE) || defined(PROTO)\n void\nfree_insexpand_stuff(void)\n{\n VIM_CLEAR(compl_orig_text);\n# ifdef FEAT_EVAL\n free_callback(&cfu_cb);\n free_callback(&ofu_cb);\n free_callback(&tsrfu_cb);\n# endif\n}\n#endif", "#ifdef FEAT_SPELL\n/*\n * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly\n * spelled word, if there is one.\n */\n static void\nspell_back_to_badword(void)\n{\n pos_T\ttpos = curwin->w_cursor;", " spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL);\n if (curwin->w_cursor.col != tpos.col)\n\tstart_arrow(&tpos);\n}\n#endif" ]
[ 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, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 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, 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, 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, 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, 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, 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, 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, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [698, 2100, 737], "buggy_code_start_loc": [526, 2100, 737], "filenames": ["src/insexpand.c", "src/testdir/test_ins_complete.vim", "src/version.c"], "fixing_code_end_loc": [736, 2117, 740], "fixing_code_start_loc": [527, 2101, 738], "message": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0044.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "0069C36F-19A3-4647-B84F-84CE62E8A554", "versionEndExcluding": "9.0.0044", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:35:*:*:*:*:*:*:*", "matchCriteriaId": "80E516C0-98A4-4ADE-B69F-66A772E2BAAA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0044."}, {"lang": "es", "value": "Un Desbordamiento de B\u00fafer en la Regi\u00f3n Heap de la Memoria en el repositorio de GitHub vim/vim versiones anteriores a 9.0.0044"}], "evaluatorComment": null, "id": "CVE-2022-2343", "lastModified": "2023-05-03T12:15:58.413", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-07-08T18:15:09.820", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/caea66442d86e7bbba3bf3dc202c3c0d549b9853"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2ecb4345-2fc7-4e7f-adb0-83a20bb458f5"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/43Y3VJPOTTY3NTREDIFUPITM2POG4ZLP/"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/202208-32"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-122"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/caea66442d86e7bbba3bf3dc202c3c0d549b9853"}, "type": "CWE-122"}
172
Determine whether the {function_name} code is vulnerable or not.
[ "/* vi:set ts=8 sts=4 sw=4 noet:\n *\n * VIM - Vi IMproved\tby Bram Moolenaar\n *\n * Do \":help uganda\" in Vim to read copying and usage conditions.\n * Do \":help credits\" in Vim to see a list of people who contributed.\n * See README.txt for an overview of the Vim source code.\n */", "/*\n * insexpand.c: functions for Insert mode completion\n */", "#include \"vim.h\"", "/*\n * Definitions used for CTRL-X submode.\n * Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[] and\n * ctrl_x_mode_names[] below.\n */\n# define CTRL_X_WANT_IDENT\t0x100", "# define CTRL_X_NORMAL\t\t0 // CTRL-N CTRL-P completion, default\n# define CTRL_X_NOT_DEFINED_YET\t1\n# define CTRL_X_SCROLL\t\t2\n# define CTRL_X_WHOLE_LINE\t3\n# define CTRL_X_FILES\t\t4\n# define CTRL_X_TAGS\t\t(5 + CTRL_X_WANT_IDENT)\n# define CTRL_X_PATH_PATTERNS\t(6 + CTRL_X_WANT_IDENT)\n# define CTRL_X_PATH_DEFINES\t(7 + CTRL_X_WANT_IDENT)\n# define CTRL_X_FINISHED\t\t8\n# define CTRL_X_DICTIONARY\t(9 + CTRL_X_WANT_IDENT)\n# define CTRL_X_THESAURUS\t(10 + CTRL_X_WANT_IDENT)\n# define CTRL_X_CMDLINE\t\t11\n# define CTRL_X_FUNCTION\t12\n# define CTRL_X_OMNI\t\t13\n# define CTRL_X_SPELL\t\t14\n# define CTRL_X_LOCAL_MSG\t15\t// only used in \"ctrl_x_msgs\"\n# define CTRL_X_EVAL\t\t16\t// for builtin function complete()\n# define CTRL_X_CMDLINE_CTRL_X\t17\t// CTRL-X typed in CTRL_X_CMDLINE", "# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]", "// Message for CTRL-X mode, index is ctrl_x_mode.\nstatic char *ctrl_x_msgs[] =\n{\n N_(\" Keyword completion (^N^P)\"), // CTRL_X_NORMAL, ^P/^N compl.\n N_(\" ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)\"),\n NULL, // CTRL_X_SCROLL: depends on state\n N_(\" Whole line completion (^L^N^P)\"),\n N_(\" File name completion (^F^N^P)\"),\n N_(\" Tag completion (^]^N^P)\"),\n N_(\" Path pattern completion (^N^P)\"),\n N_(\" Definition completion (^D^N^P)\"),\n NULL, // CTRL_X_FINISHED\n N_(\" Dictionary completion (^K^N^P)\"),\n N_(\" Thesaurus completion (^T^N^P)\"),\n N_(\" Command-line completion (^V^N^P)\"),\n N_(\" User defined completion (^U^N^P)\"),\n N_(\" Omni completion (^O^N^P)\"),\n N_(\" Spelling suggestion (s^N^P)\"),\n N_(\" Keyword Local completion (^N^P)\"),\n NULL, // CTRL_X_EVAL doesn't use msg.\n N_(\" Command-line completion (^V^N^P)\"),\n};", "#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)\nstatic char *ctrl_x_mode_names[] = {\n\t\"keyword\",\n\t\"ctrl_x\",\n\t\"scroll\",\n\t\"whole_line\",\n\t\"files\",\n\t\"tags\",\n\t\"path_patterns\",\n\t\"path_defines\",\n\t\"unknown\",\t // CTRL_X_FINISHED\n\t\"dictionary\",\n\t\"thesaurus\",\n\t\"cmdline\",\n\t\"function\",\n\t\"omni\",\n\t\"spell\",\n\tNULL,\t\t // CTRL_X_LOCAL_MSG only used in \"ctrl_x_msgs\"\n\t\"eval\",\n\t\"cmdline\",\n};\n#endif", "/*\n * Array indexes used for cp_text[].\n */\n#define CPT_ABBR\t0\t// \"abbr\"\n#define CPT_MENU\t1\t// \"menu\"\n#define CPT_KIND\t2\t// \"kind\"\n#define CPT_INFO\t3\t// \"info\"\n#define CPT_COUNT\t4\t// Number of entries", "/*\n * Structure used to store one match for insert completion.\n */\ntypedef struct compl_S compl_T;\nstruct compl_S\n{\n compl_T\t*cp_next;\n compl_T\t*cp_prev;\n char_u\t*cp_str;\t// matched text\n char_u\t*(cp_text[CPT_COUNT]);\t// text for the menu\n#ifdef FEAT_EVAL\n typval_T\tcp_user_data;\n#endif\n char_u\t*cp_fname;\t// file containing the match, allocated when\n\t\t\t\t// cp_flags has CP_FREE_FNAME\n int\t\tcp_flags;\t// CP_ values\n int\t\tcp_number;\t// sequence number\n};", "// values for cp_flags\n# define CP_ORIGINAL_TEXT 1\t// the original text when the expansion begun\n# define CP_FREE_FNAME\t 2\t// cp_fname is allocated\n# define CP_CONT_S_IPOS\t 4\t// use CONT_S_IPOS for compl_cont_status\n# define CP_EQUAL\t 8\t// ins_compl_equal() always returns TRUE\n# define CP_ICASE\t 16\t// ins_compl_equal() ignores case\n# define CP_FAST\t 32\t// use fast_breakcheck instead of ui_breakcheck", "static char e_hitend[] = N_(\"Hit end of paragraph\");", "/*\n * All the current matches are stored in a list.\n * \"compl_first_match\" points to the start of the list.\n * \"compl_curr_match\" points to the currently selected entry.\n * \"compl_shown_match\" is different from compl_curr_match during\n * ins_compl_get_exp().\n * \"compl_old_match\" points to previous \"compl_curr_match\".\n */\nstatic compl_T *compl_first_match = NULL;\nstatic compl_T *compl_curr_match = NULL;\nstatic compl_T *compl_shown_match = NULL;\nstatic compl_T *compl_old_match = NULL;", "// After using a cursor key <Enter> selects a match in the popup menu,\n// otherwise it inserts a line break.\nstatic int\t compl_enter_selects = FALSE;", "// When \"compl_leader\" is not NULL only matches that start with this string\n// are used.\nstatic char_u\t *compl_leader = NULL;", "static int\t compl_get_longest = FALSE;\t// put longest common string\n\t\t\t\t\t\t// in compl_leader", "static int\t compl_no_insert = FALSE;\t// FALSE: select & insert\n\t\t\t\t\t\t// TRUE: noinsert\nstatic int\t compl_no_select = FALSE;\t// FALSE: select & insert\n\t\t\t\t\t\t// TRUE: noselect", "// Selected one of the matches. When FALSE the match was edited or using the\n// longest common string.\nstatic int\t compl_used_match;", "// didn't finish finding completions.\nstatic int\t compl_was_interrupted = FALSE;", "// Set when character typed while looking for matches and it means we should\n// stop looking for matches.\nstatic int\t compl_interrupted = FALSE;", "static int\t compl_restarting = FALSE;\t// don't insert match", "// When the first completion is done \"compl_started\" is set. When it's\n// FALSE the word to be completed must be located.\nstatic int\t compl_started = FALSE;", "// Which Ctrl-X mode are we in?\nstatic int\t ctrl_x_mode = CTRL_X_NORMAL;", "static int\t compl_matches = 0;\t // number of completion matches\nstatic char_u\t *compl_pattern = NULL;\nstatic int\t compl_direction = FORWARD;\nstatic int\t compl_shows_dir = FORWARD;\nstatic int\t compl_pending = 0;\t // > 1 for postponed CTRL-N\nstatic pos_T\t compl_startpos;\n// Length in bytes of the text being completed (this is deleted to be replaced\n// by the match.)\nstatic int\t compl_length = 0;\nstatic colnr_T\t compl_col = 0;\t // column where the text starts\n\t\t\t\t\t // that is being completed\nstatic char_u\t *compl_orig_text = NULL; // text as it was before\n\t\t\t\t\t // completion started\nstatic int\t compl_cont_mode = 0;\nstatic expand_T\t compl_xp;", "// List of flags for method of completion.\nstatic int\t compl_cont_status = 0;\n# define CONT_ADDING\t1\t// \"normal\" or \"adding\" expansion\n# define CONT_INTRPT\t(2 + 4)\t// a ^X interrupted the current expansion\n\t\t\t\t// it's set only iff N_ADDS is set\n# define CONT_N_ADDS\t4\t// next ^X<> will add-new or expand-current\n# define CONT_S_IPOS\t8\t// next ^X<> will set initial_pos?\n\t\t\t\t// if so, word-wise-expansion will set SOL\n# define CONT_SOL\t16\t// pattern includes start of line, just for\n\t\t\t\t// word-wise expansion, not set for ^X^L\n# define CONT_LOCAL\t32\t// for ctrl_x_mode 0, ^X^P/^X^N do a local\n\t\t\t\t// expansion, (eg use complete=.)", "static int\t compl_opt_refresh_always = FALSE;\nstatic int\t compl_opt_suppress_empty = FALSE;", "static int ins_compl_add(char_u *str, int len, char_u *fname, char_u **cptext, typval_T *user_data, int cdir, int flags, int adup);\nstatic void ins_compl_longest_match(compl_T *match);\nstatic void ins_compl_del_pum(void);\nstatic void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);\nstatic char_u *find_line_end(char_u *ptr);\nstatic void ins_compl_free(void);\nstatic int ins_compl_need_restart(void);\nstatic void ins_compl_new_leader(void);\nstatic int get_compl_len(void);\nstatic void ins_compl_restart(void);\nstatic void ins_compl_set_original_text(char_u *str);\nstatic void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);\n# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)\nstatic void ins_compl_add_list(list_T *list);\nstatic void ins_compl_add_dict(dict_T *dict);\n# endif\nstatic int ins_compl_key2dir(int c);\nstatic int ins_compl_pum_key(int c);\nstatic int ins_compl_key2count(int c);\nstatic void show_pum(int prev_w_wrow, int prev_w_leftcol);\nstatic unsigned quote_meta(char_u *dest, char_u *str, int len);", "#ifdef FEAT_SPELL\nstatic void spell_back_to_badword(void);\nstatic int spell_bad_len = 0;\t// length of located bad word\n#endif", "/*\n * CTRL-X pressed in Insert mode.\n */\n void\nins_ctrl_x(void)\n{\n if (!ctrl_x_mode_cmdline())\n {\n\t// if the next ^X<> won't ADD nothing, then reset compl_cont_status\n\tif (compl_cont_status & CONT_N_ADDS)\n\t compl_cont_status |= CONT_INTRPT;\n\telse\n\t compl_cont_status = 0;\n\t// We're not sure which CTRL-X mode it will be yet\n\tctrl_x_mode = CTRL_X_NOT_DEFINED_YET;\n\tedit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));\n\tedit_submode_pre = NULL;\n\tshowmode();\n }\n else\n\t// CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X\n\t// CTRL-V look like CTRL-N\n\tctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;", " may_trigger_modechanged();\n}", "/*\n * Functions to check the current CTRL-X mode.\n */\nint ctrl_x_mode_none(void) { return ctrl_x_mode == 0; }\nint ctrl_x_mode_normal(void) { return ctrl_x_mode == CTRL_X_NORMAL; }\nint ctrl_x_mode_scroll(void) { return ctrl_x_mode == CTRL_X_SCROLL; }\nint ctrl_x_mode_whole_line(void) { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }\nint ctrl_x_mode_files(void) { return ctrl_x_mode == CTRL_X_FILES; }\nint ctrl_x_mode_tags(void) { return ctrl_x_mode == CTRL_X_TAGS; }\nint ctrl_x_mode_path_patterns(void) {\n\t\t\t\t return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }\nint ctrl_x_mode_path_defines(void) {\n\t\t\t\t return ctrl_x_mode == CTRL_X_PATH_DEFINES; }\nint ctrl_x_mode_dictionary(void) { return ctrl_x_mode == CTRL_X_DICTIONARY; }\nint ctrl_x_mode_thesaurus(void) { return ctrl_x_mode == CTRL_X_THESAURUS; }\nint ctrl_x_mode_cmdline(void) {\n\treturn ctrl_x_mode == CTRL_X_CMDLINE\n\t\t|| ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }\nint ctrl_x_mode_function(void) { return ctrl_x_mode == CTRL_X_FUNCTION; }\nint ctrl_x_mode_omni(void) { return ctrl_x_mode == CTRL_X_OMNI; }\nint ctrl_x_mode_spell(void) { return ctrl_x_mode == CTRL_X_SPELL; }\nstatic int ctrl_x_mode_eval(void) { return ctrl_x_mode == CTRL_X_EVAL; }\nint ctrl_x_mode_line_or_eval(void) {\n return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }", "/*\n * Whether other than default completion has been selected.\n */\n int\nctrl_x_mode_not_default(void)\n{\n return ctrl_x_mode != CTRL_X_NORMAL;\n}", "/*\n * Whether CTRL-X was typed without a following character,\n * not including when in CTRL-X CTRL-V mode.\n */\n int\nctrl_x_mode_not_defined_yet(void)\n{\n return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;\n}", "/*\n * Return TRUE if currently in \"normal\" or \"adding\" insert completion matches\n * state\n */\n int\ncompl_status_adding(void)\n{\n return compl_cont_status & CONT_ADDING;\n}", "/*\n * Return TRUE if the completion pattern includes start of line, just for\n * word-wise expansion.\n */\n int\ncompl_status_sol(void)\n{\n return compl_cont_status & CONT_SOL;\n}", "/*\n * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)\n */\n int\ncompl_status_local(void)\n{\n return compl_cont_status & CONT_LOCAL;\n}", "/*\n * Clear the completion status flags\n */\n void\ncompl_status_clear(void)\n{\n compl_cont_status = 0;\n}", "/*\n * Return TRUE if completion is using the forward direction matches\n */\n static int\ncompl_dir_forward(void)\n{\n return compl_direction == FORWARD;\n}", "/*\n * Return TRUE if currently showing forward completion matches\n */\n static int\ncompl_shows_dir_forward(void)\n{\n return compl_shows_dir == FORWARD;\n}", "/*\n * Return TRUE if currently showing backward completion matches\n */\n static int\ncompl_shows_dir_backward(void)\n{\n return compl_shows_dir == BACKWARD;\n}", "/*\n * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.\n */\n int\nhas_compl_option(int dict_opt)\n{\n if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL\n#ifdef FEAT_SPELL\n\t\t\t\t\t\t\t&& !curwin->w_p_spell\n#endif\n\t\t\t\t\t\t\t)\n\t\t : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL\n#ifdef FEAT_COMPL_FUNC\n\t\t && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL\n#endif\n\t\t ))\n {\n\tctrl_x_mode = CTRL_X_NORMAL;\n\tedit_submode = NULL;\n\tmsg_attr(dict_opt ? _(\"'dictionary' option is empty\")\n\t\t\t : _(\"'thesaurus' option is empty\"),\n\t\t\t\t\t\t\t HL_ATTR(HLF_E));\n\tif (emsg_silent == 0 && !in_assert_fails)\n\t{\n\t vim_beep(BO_COMPL);\n\t setcursor();\n\t out_flush();\n#ifdef FEAT_EVAL\n\t if (!get_vim_var_nr(VV_TESTING))\n#endif\n\t\tui_delay(2004L, FALSE);\n\t}\n\treturn FALSE;\n }\n return TRUE;\n}", "/*\n * Is the character \"c\" a valid key to go to or keep us in CTRL-X mode?\n * This depends on the current mode.\n */\n int\nvim_is_ctrl_x_key(int c)\n{\n // Always allow ^R - let its results then be checked\n if (c == Ctrl_R)\n\treturn TRUE;", " // Accept <PageUp> and <PageDown> if the popup menu is visible.\n if (ins_compl_pum_key(c))\n\treturn TRUE;", " switch (ctrl_x_mode)\n {\n\tcase 0:\t\t // Not in any CTRL-X mode\n\t return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);\n\tcase CTRL_X_NOT_DEFINED_YET:\n\tcase CTRL_X_CMDLINE_CTRL_X:\n\t return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E\n\t\t || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB\n\t\t || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P\n\t\t || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V\n\t\t || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O\n\t\t || c == Ctrl_S || c == Ctrl_K || c == 's'\n\t\t || c == Ctrl_Z);\n\tcase CTRL_X_SCROLL:\n\t return (c == Ctrl_Y || c == Ctrl_E);\n\tcase CTRL_X_WHOLE_LINE:\n\t return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);\n\tcase CTRL_X_FILES:\n\t return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);\n\tcase CTRL_X_DICTIONARY:\n\t return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);\n\tcase CTRL_X_THESAURUS:\n\t return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);\n\tcase CTRL_X_TAGS:\n\t return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);\n#ifdef FEAT_FIND_ID\n\tcase CTRL_X_PATH_PATTERNS:\n\t return (c == Ctrl_P || c == Ctrl_N);\n\tcase CTRL_X_PATH_DEFINES:\n\t return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);\n#endif\n\tcase CTRL_X_CMDLINE:\n\t return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N\n\t\t || c == Ctrl_X);\n#ifdef FEAT_COMPL_FUNC\n\tcase CTRL_X_FUNCTION:\n\t return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);\n\tcase CTRL_X_OMNI:\n\t return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);\n#endif\n\tcase CTRL_X_SPELL:\n\t return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);\n\tcase CTRL_X_EVAL:\n\t return (c == Ctrl_P || c == Ctrl_N);\n }\n internal_error(\"vim_is_ctrl_x_key()\");\n return FALSE;\n}", "/*\n * Return TRUE if \"match\" is the original text when the completion began.\n */\n static int\nmatch_at_original_text(compl_T *match)\n{\n return match->cp_flags & CP_ORIGINAL_TEXT;\n}", "/*\n * Returns TRUE if \"match\" is the first match in the completion list.\n */\n static int\nis_first_match(compl_T *match)\n{\n return match == compl_first_match;\n}", "/*\n * Return TRUE when character \"c\" is part of the item currently being\n * completed. Used to decide whether to abandon complete mode when the menu\n * is visible.\n */\n int\nins_compl_accept_char(int c)\n{\n if (ctrl_x_mode & CTRL_X_WANT_IDENT)\n\t// When expanding an identifier only accept identifier chars.\n\treturn vim_isIDc(c);", " switch (ctrl_x_mode)\n {\n\tcase CTRL_X_FILES:\n\t // When expanding file name only accept file name chars. But not\n\t // path separators, so that \"proto/<Tab>\" expands files in\n\t // \"proto\", not \"proto/\" as a whole\n\t return vim_isfilec(c) && !vim_ispathsep(c);", "\tcase CTRL_X_CMDLINE:\n\tcase CTRL_X_CMDLINE_CTRL_X:\n\tcase CTRL_X_OMNI:\n\t // Command line and Omni completion can work with just about any\n\t // printable character, but do stop at white space.\n\t return vim_isprintc(c) && !VIM_ISWHITE(c);", "\tcase CTRL_X_WHOLE_LINE:\n\t // For while line completion a space can be part of the line.\n\t return vim_isprintc(c);\n }\n return vim_iswordc(c);\n}", "/*\n * Get the completed text by inferring the case of the originally typed text.", " * If the result is in allocated memory \"tofree\" is set to it.", " */\n static char_u *\nins_compl_infercase_gettext(\n\tchar_u\t*str,", "\tint\tchar_len,\n\tint\tcompl_char_len,\n\tint\tmin_len,\n\tchar_u **tofree)", "{\n int\t\t*wca;\t\t\t// Wide character array.\n char_u\t*p;\n int\t\ti, c;\n int\t\thas_lower = FALSE;\n int\t\twas_letter = FALSE;", " garray_T\tgap;", "\n IObuff[0] = NUL;", " // Allocate wide character array for the completion and fill it.", " wca = ALLOC_MULT(int, char_len);", " if (wca == NULL)\n\treturn IObuff;", " p = str;", " for (i = 0; i < char_len; ++i)", "\tif (has_mbyte)\n\t wca[i] = mb_ptr2char_adv(&p);\n\telse\n\t wca[i] = *(p++);", " // Rule 1: Were any chars converted to lower?\n p = compl_orig_text;\n for (i = 0; i < min_len; ++i)\n {\n\tif (has_mbyte)\n\t c = mb_ptr2char_adv(&p);\n\telse\n\t c = *(p++);\n\tif (MB_ISLOWER(c))\n\t{\n\t has_lower = TRUE;\n\t if (MB_ISUPPER(wca[i]))\n\t {\n\t\t// Rule 1 is satisfied.", "\t\tfor (i = compl_char_len; i < char_len; ++i)", "\t\t wca[i] = MB_TOLOWER(wca[i]);\n\t\tbreak;\n\t }\n\t}\n }", " // Rule 2: No lower case, 2nd consecutive letter converted to\n // upper case.\n if (!has_lower)\n {\n\tp = compl_orig_text;\n\tfor (i = 0; i < min_len; ++i)\n\t{\n\t if (has_mbyte)\n\t\tc = mb_ptr2char_adv(&p);\n\t else\n\t\tc = *(p++);\n\t if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))\n\t {\n\t\t// Rule 2 is satisfied.", "\t\tfor (i = compl_char_len; i < char_len; ++i)", "\t\t wca[i] = MB_TOUPPER(wca[i]);\n\t\tbreak;\n\t }\n\t was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);\n\t}\n }", " // Copy the original case of the part we typed.\n p = compl_orig_text;\n for (i = 0; i < min_len; ++i)\n {\n\tif (has_mbyte)\n\t c = mb_ptr2char_adv(&p);\n\telse\n\t c = *(p++);\n\tif (MB_ISLOWER(c))\n\t wca[i] = MB_TOLOWER(wca[i]);\n\telse if (MB_ISUPPER(c))\n\t wca[i] = MB_TOUPPER(wca[i]);\n }", " // Generate encoding specific output from wide character array.", "", " p = IObuff;\n i = 0;", " ga_init2(&gap, 1, 500);\n while (i < char_len)\n {\n\tif (gap.ga_data != NULL)\n\t{\n\t if (ga_grow(&gap, 10) == FAIL)\n\t {\n\t\tga_clear(&gap);\n\t\treturn (char_u *)\"[failed]\";\n\t }\n\t p = (char_u *)gap.ga_data + gap.ga_len;\n\t if (has_mbyte)\n\t\tgap.ga_len += (*mb_char2bytes)(wca[i++], p);\n\t else\n\t {\n\t\t*p = wca[i++];\n\t\t++gap.ga_len;\n\t }\n\t}\n\telse if ((p - IObuff) + 6 >= IOSIZE)\n\t{\n\t // Multi-byte characters can occupy up to five bytes more than\n\t // ASCII characters, and we also need one byte for NUL, so when\n\t // getting to six bytes from the edge of IObuff switch to using a\n\t // growarray. Add the character in the next round.\n\t if (ga_grow(&gap, IOSIZE) == FAIL)\n\t\treturn (char_u *)\"[failed]\";\n\t STRCPY(gap.ga_data, IObuff);\n\t gap.ga_len = STRLEN(IObuff);\n\t}\n\telse if (has_mbyte)", "\t p += (*mb_char2bytes)(wca[i++], p);\n\telse\n\t *(p++) = wca[i++];", " }\n vim_free(wca);", " if (gap.ga_data != NULL)\n {\n\t*tofree = gap.ga_data;\n\treturn gap.ga_data;\n }\n", " *p = NUL;", "", " return IObuff;\n}", "/*\n * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the\n * case of the originally typed text is used, and the case of the completed\n * text is inferred, ie this tries to work out what case you probably wanted\n * the rest of the word to be in -- webb\n */\n int\nins_compl_add_infercase(\n char_u\t*str_arg,\n int\t\tlen,\n int\t\ticase,\n char_u\t*fname,\n int\t\tdir,\n int\t\tcont_s_ipos) // next ^X<> will set initial_pos\n{\n char_u\t*str = str_arg;\n char_u\t*p;", " int\t\tchar_len;\t\t// count multi-byte characters\n int\t\tcompl_char_len;", " int\t\tmin_len;\n int\t\tflags = 0;", " int\t\tres;\n char_u\t*tofree = NULL;", "\n if (p_ic && curbuf->b_p_inf && len > 0)\n {\n\t// Infer case of completed part.", "\t// Find actual length of completion.\n\tif (has_mbyte)\n\t{\n\t p = str;", "\t char_len = 0;", "\t while (*p != NUL)\n\t {\n\t\tMB_PTR_ADV(p);", "\t\t++char_len;", "\t }\n\t}\n\telse", "\t char_len = len;", "\n\t// Find actual length of original text.\n\tif (has_mbyte)\n\t{\n\t p = compl_orig_text;", "\t compl_char_len = 0;", "\t while (*p != NUL)\n\t {\n\t\tMB_PTR_ADV(p);", "\t\t++compl_char_len;", "\t }\n\t}\n\telse", "\t compl_char_len = compl_length;", "\t// \"char_len\" may be smaller than \"compl_char_len\" when using", "\t// thesaurus, only use the minimum when comparing.", "\tmin_len = char_len < compl_char_len ? char_len : compl_char_len;", "\tstr = ins_compl_infercase_gettext(str, char_len,\n\t\t\t\t\t compl_char_len, min_len, &tofree);", " }\n if (cont_s_ipos)\n\tflags |= CP_CONT_S_IPOS;\n if (icase)\n\tflags |= CP_ICASE;\n", " res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE);\n vim_free(tofree);\n return res;", "}", "/*\n * Add a match to the list of matches. The arguments are:\n * str - text of the match to add\n * len - length of \"str\". If -1, then the length of \"str\" is\n *\t\t computed.\n * fname - file name to associate with this match.\n * cptext - list of strings to use with this match (for abbr, menu, info\n *\t\t and kind)\n * user_data - user supplied data (any vim type) for this match\n * cdir\t - match direction. If 0, use \"compl_direction\".\n * flags_arg - match flags (cp_flags)\n * adup\t - accept this match even if it is already present.\n * If \"cdir\" is FORWARD, then the match is added after the current match.\n * Otherwise, it is added before the current match.\n *\n * If the given string is already in the list of completions, then return\n * NOTDONE, otherwise add it to the list and return OK. If there is an error,\n * maybe because alloc() returns NULL, then FAIL is returned.\n */\n static int\nins_compl_add(\n char_u\t*str,\n int\t\tlen,\n char_u\t*fname,\n char_u\t**cptext,\t // extra text for popup menu or NULL\n typval_T\t*user_data UNUSED, // \"user_data\" entry or NULL\n int\t\tcdir,\n int\t\tflags_arg,\n int\t\tadup)\t\t// accept duplicate match\n{\n compl_T\t*match;\n int\t\tdir = (cdir == 0 ? compl_direction : cdir);\n int\t\tflags = flags_arg;", " if (flags & CP_FAST)\n\tfast_breakcheck();\n else\n\tui_breakcheck();\n if (got_int)\n\treturn FAIL;\n if (len < 0)\n\tlen = (int)STRLEN(str);", " // If the same match is already present, don't add it.\n if (compl_first_match != NULL && !adup)\n {\n\tmatch = compl_first_match;\n\tdo\n\t{\n\t if (!match_at_original_text(match)\n\t\t && STRNCMP(match->cp_str, str, len) == 0\n\t\t && match->cp_str[len] == NUL)\n\t\treturn NOTDONE;\n\t match = match->cp_next;\n\t} while (match != NULL && !is_first_match(match));\n }", " // Remove any popup menu before changing the list of matches.\n ins_compl_del_pum();", " // Allocate a new match structure.\n // Copy the values to the new match structure.\n match = ALLOC_CLEAR_ONE(compl_T);\n if (match == NULL)\n\treturn FAIL;\n match->cp_number = -1;\n if (flags & CP_ORIGINAL_TEXT)\n\tmatch->cp_number = 0;\n if ((match->cp_str = vim_strnsave(str, len)) == NULL)\n {\n\tvim_free(match);\n\treturn FAIL;\n }", " // match-fname is:\n // - compl_curr_match->cp_fname if it is a string equal to fname.\n // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.\n // - NULL otherwise.\t--Acevedo\n if (fname != NULL\n\t && compl_curr_match != NULL\n\t && compl_curr_match->cp_fname != NULL\n\t && STRCMP(fname, compl_curr_match->cp_fname) == 0)\n\tmatch->cp_fname = compl_curr_match->cp_fname;\n else if (fname != NULL)\n {\n\tmatch->cp_fname = vim_strsave(fname);\n\tflags |= CP_FREE_FNAME;\n }\n else\n\tmatch->cp_fname = NULL;\n match->cp_flags = flags;", " if (cptext != NULL)\n {\n\tint i;", "\tfor (i = 0; i < CPT_COUNT; ++i)\n\t if (cptext[i] != NULL && *cptext[i] != NUL)\n\t\tmatch->cp_text[i] = vim_strsave(cptext[i]);\n }\n#ifdef FEAT_EVAL\n if (user_data != NULL)\n\tmatch->cp_user_data = *user_data;\n#endif", " // Link the new match structure after (FORWARD) or before (BACKWARD) the\n // current match in the list of matches .\n if (compl_first_match == NULL)\n\tmatch->cp_next = match->cp_prev = NULL;\n else if (dir == FORWARD)\n {\n\tmatch->cp_next = compl_curr_match->cp_next;\n\tmatch->cp_prev = compl_curr_match;\n }\n else\t// BACKWARD\n {\n\tmatch->cp_next = compl_curr_match;\n\tmatch->cp_prev = compl_curr_match->cp_prev;\n }\n if (match->cp_next)\n\tmatch->cp_next->cp_prev = match;\n if (match->cp_prev)\n\tmatch->cp_prev->cp_next = match;\n else\t// if there's nothing before, it is the first match\n\tcompl_first_match = match;\n compl_curr_match = match;", " // Find the longest common string if still doing that.\n if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)\n\tins_compl_longest_match(match);", " return OK;\n}", "/*\n * Return TRUE if \"str[len]\" matches with match->cp_str, considering\n * match->cp_flags.\n */\n static int\nins_compl_equal(compl_T *match, char_u *str, int len)\n{\n if (match->cp_flags & CP_EQUAL)\n\treturn TRUE;\n if (match->cp_flags & CP_ICASE)\n\treturn STRNICMP(match->cp_str, str, (size_t)len) == 0;\n return STRNCMP(match->cp_str, str, (size_t)len) == 0;\n}", "/*\n * Reduce the longest common string for match \"match\".\n */\n static void\nins_compl_longest_match(compl_T *match)\n{\n char_u\t*p, *s;\n int\t\tc1, c2;\n int\t\thad_match;", " if (compl_leader == NULL)\n {\n\t// First match, use it as a whole.\n\tcompl_leader = vim_strsave(match->cp_str);\n\tif (compl_leader == NULL)\n\t return;", "\thad_match = (curwin->w_cursor.col > compl_col);\n\tins_compl_delete();\n\tins_bytes(compl_leader + get_compl_len());\n\tins_redraw(FALSE);", "\t// When the match isn't there (to avoid matching itself) remove it\n\t// again after redrawing.\n\tif (!had_match)\n\t ins_compl_delete();\n\tcompl_used_match = FALSE;", "\treturn;\n }", " // Reduce the text if this match differs from compl_leader.\n p = compl_leader;\n s = match->cp_str;\n while (*p != NUL)\n {\n\tif (has_mbyte)\n\t{\n\t c1 = mb_ptr2char(p);\n\t c2 = mb_ptr2char(s);\n\t}\n\telse\n\t{\n\t c1 = *p;\n\t c2 = *s;\n\t}\n\tif ((match->cp_flags & CP_ICASE)\n\t\t? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))\n\t break;\n\tif (has_mbyte)\n\t{\n\t MB_PTR_ADV(p);\n\t MB_PTR_ADV(s);\n\t}\n\telse\n\t{\n\t ++p;\n\t ++s;\n\t}\n }", " if (*p != NUL)\n {\n\t// Leader was shortened, need to change the inserted text.\n\t*p = NUL;\n\thad_match = (curwin->w_cursor.col > compl_col);\n\tins_compl_delete();\n\tins_bytes(compl_leader + get_compl_len());\n\tins_redraw(FALSE);", "\t// When the match isn't there (to avoid matching itself) remove it\n\t// again after redrawing.\n\tif (!had_match)\n\t ins_compl_delete();\n }", " compl_used_match = FALSE;\n}", "/*\n * Add an array of matches to the list of matches.\n * Frees matches[].\n */\n static void\nins_compl_add_matches(\n int\t\tnum_matches,\n char_u\t**matches,\n int\t\ticase)\n{\n int\t\ti;\n int\t\tadd_r = OK;\n int\t\tdir = compl_direction;", " for (i = 0; i < num_matches && add_r != FAIL; i++)\n\tif ((add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,\n\t\t\t CP_FAST | (icase ? CP_ICASE : 0), FALSE)) == OK)\n\t // if dir was BACKWARD then honor it just once\n\t dir = FORWARD;\n FreeWild(num_matches, matches);\n}", "/*\n * Make the completion list cyclic.\n * Return the number of matches (excluding the original).\n */\n static int\nins_compl_make_cyclic(void)\n{\n compl_T *match;\n int\t count = 0;", " if (compl_first_match == NULL)\n\treturn 0;", " // Find the end of the list.\n match = compl_first_match;\n // there's always an entry for the compl_orig_text, it doesn't count.\n while (match->cp_next != NULL && !is_first_match(match->cp_next))\n {\n\tmatch = match->cp_next;\n\t++count;\n }\n match->cp_next = compl_first_match;\n compl_first_match->cp_prev = match;", " return count;\n}", "/*\n * Return whether there currently is a shown match.\n */\n int\nins_compl_has_shown_match(void)\n{\n return compl_shown_match == NULL\n\t|| compl_shown_match != compl_shown_match->cp_next;\n}", "/*\n * Return whether the shown match is long enough.\n */\n int\nins_compl_long_shown_match(void)\n{\n return (int)STRLEN(compl_shown_match->cp_str)\n\t\t\t\t\t > curwin->w_cursor.col - compl_col;\n}", "/*\n * Set variables that store noselect and noinsert behavior from the\n * 'completeopt' value.\n */\n void\ncompleteopt_was_set(void)\n{\n compl_no_insert = FALSE;\n compl_no_select = FALSE;\n if (strstr((char *)p_cot, \"noselect\") != NULL)\n\tcompl_no_select = TRUE;\n if (strstr((char *)p_cot, \"noinsert\") != NULL)\n\tcompl_no_insert = TRUE;\n}", "\n// \"compl_match_array\" points the currently displayed list of entries in the\n// popup menu. It is NULL when there is no popup menu.\nstatic pumitem_T *compl_match_array = NULL;\nstatic int compl_match_arraysize;", "/*\n * Update the screen and when there is any scrolling remove the popup menu.\n */\n static void\nins_compl_upd_pum(void)\n{\n int\t\th;", " if (compl_match_array == NULL)\n\treturn;", " h = curwin->w_cline_height;\n // Update the screen later, before drawing the popup menu over it.\n pum_call_update_screen();\n if (h != curwin->w_cline_height)\n\tins_compl_del_pum();\n}", "/*\n * Remove any popup menu.\n */\n static void\nins_compl_del_pum(void)\n{\n if (compl_match_array == NULL)\n\treturn;", " pum_undisplay();\n VIM_CLEAR(compl_match_array);\n}", "/*\n * Return TRUE if the popup menu should be displayed.\n */\n int\npum_wanted(void)\n{\n // 'completeopt' must contain \"menu\" or \"menuone\"\n if (vim_strchr(p_cot, 'm') == NULL)\n\treturn FALSE;", " // The display looks bad on a B&W display.\n if (t_colors < 8\n#ifdef FEAT_GUI\n\t && !gui.in_use\n#endif\n\t )\n\treturn FALSE;\n return TRUE;\n}", "/*\n * Return TRUE if there are two or more matches to be shown in the popup menu.\n * One if 'completopt' contains \"menuone\".\n */\n static int\npum_enough_matches(void)\n{\n compl_T *compl;\n int\t\ti;", " // Don't display the popup menu if there are no matches or there is only\n // one (ignoring the original text).\n compl = compl_first_match;\n i = 0;\n do\n {\n\tif (compl == NULL || (!match_at_original_text(compl) && ++i == 2))\n\t break;\n\tcompl = compl->cp_next;\n } while (!is_first_match(compl));", " if (strstr((char *)p_cot, \"menuone\") != NULL)\n\treturn (i >= 1);\n return (i >= 2);\n}", "#if defined(FEAT_EVAL) || defined(PROTO)\n/*\n * Allocate Dict for the completed item.\n * { word, abbr, menu, kind, info }\n */\n static dict_T *\nins_compl_dict_alloc(compl_T *match)\n{\n dict_T *dict = dict_alloc_lock(VAR_FIXED);", " if (dict == NULL)\n\treturn NULL;", " dict_add_string(dict, \"word\", match->cp_str);\n dict_add_string(dict, \"abbr\", match->cp_text[CPT_ABBR]);\n dict_add_string(dict, \"menu\", match->cp_text[CPT_MENU]);\n dict_add_string(dict, \"kind\", match->cp_text[CPT_KIND]);\n dict_add_string(dict, \"info\", match->cp_text[CPT_INFO]);\n if (match->cp_user_data.v_type == VAR_UNKNOWN)\n\tdict_add_string(dict, \"user_data\", (char_u *)\"\");\n else\n\tdict_add_tv(dict, \"user_data\", &match->cp_user_data);", " return dict;\n}", "/*\n * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode\n * completion menu is changed.\n */\n static void\ntrigger_complete_changed_event(int cur)\n{\n dict_T\t *v_event;\n dict_T\t *item;\n static int\t recursive = FALSE;\n save_v_event_T save_v_event;", " if (recursive)\n\treturn;", " if (cur < 0)\n\titem = dict_alloc();\n else\n\titem = ins_compl_dict_alloc(compl_curr_match);\n if (item == NULL)\n\treturn;\n v_event = get_v_event(&save_v_event);\n dict_add_dict(v_event, \"completed_item\", item);\n pum_set_event_info(v_event);\n dict_set_items_ro(v_event);", " recursive = TRUE;\n textlock++;\n apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);\n textlock--;\n recursive = FALSE;", " restore_v_event(v_event, &save_v_event);\n}\n#endif", "/*\n * Build a popup menu to show the completion matches.\n * Returns the popup menu entry that should be selected. Returns -1 if nothing\n * should be selected.\n */\n static int\nins_compl_build_pum(void)\n{\n compl_T *compl;\n compl_T *shown_compl = NULL;\n int\t\tdid_find_shown_match = FALSE;\n int\t\tshown_match_ok = FALSE;\n int\t\ti;\n int\t\tcur = -1;\n int\t\tlead_len = 0;", " // Need to build the popup menu list.\n compl_match_arraysize = 0;\n compl = compl_first_match;\n if (compl_leader != NULL)\n\tlead_len = (int)STRLEN(compl_leader);", " do\n {\n\tif (!match_at_original_text(compl)\n\t\t&& (compl_leader == NULL\n\t\t || ins_compl_equal(compl, compl_leader, lead_len)))\n\t ++compl_match_arraysize;\n\tcompl = compl->cp_next;\n } while (compl != NULL && !is_first_match(compl));", " if (compl_match_arraysize == 0)\n\treturn -1;", " compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);\n if (compl_match_array == NULL)\n\treturn -1;", " // If the current match is the original text don't find the first\n // match after it, don't highlight anything.\n if (match_at_original_text(compl_shown_match))\n\tshown_match_ok = TRUE;", " i = 0;\n compl = compl_first_match;\n do\n {\n\tif (!match_at_original_text(compl)\n\t\t&& (compl_leader == NULL\n\t\t || ins_compl_equal(compl, compl_leader, lead_len)))\n\t{\n\t if (!shown_match_ok)\n\t {\n\t\tif (compl == compl_shown_match || did_find_shown_match)\n\t\t{\n\t\t // This item is the shown match or this is the\n\t\t // first displayed item after the shown match.\n\t\t compl_shown_match = compl;\n\t\t did_find_shown_match = TRUE;\n\t\t shown_match_ok = TRUE;\n\t\t}\n\t\telse\n\t\t // Remember this displayed match for when the\n\t\t // shown match is just below it.\n\t\t shown_compl = compl;\n\t\tcur = i;\n\t }", "\t if (compl->cp_text[CPT_ABBR] != NULL)\n\t\tcompl_match_array[i].pum_text =\n\t\t compl->cp_text[CPT_ABBR];\n\t else\n\t\tcompl_match_array[i].pum_text = compl->cp_str;\n\t compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];\n\t compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];\n\t if (compl->cp_text[CPT_MENU] != NULL)\n\t\tcompl_match_array[i++].pum_extra =\n\t\t compl->cp_text[CPT_MENU];\n\t else\n\t\tcompl_match_array[i++].pum_extra = compl->cp_fname;\n\t}", "\tif (compl == compl_shown_match)\n\t{\n\t did_find_shown_match = TRUE;", "\t // When the original text is the shown match don't set\n\t // compl_shown_match.\n\t if (match_at_original_text(compl))\n\t\tshown_match_ok = TRUE;", "\t if (!shown_match_ok && shown_compl != NULL)\n\t {\n\t\t// The shown match isn't displayed, set it to the\n\t\t// previously displayed match.\n\t\tcompl_shown_match = shown_compl;\n\t\tshown_match_ok = TRUE;\n\t }\n\t}\n\tcompl = compl->cp_next;\n } while (compl != NULL && !is_first_match(compl));", " if (!shown_match_ok) // no displayed match at all\n\tcur = -1;", " return cur;\n}", "/*\n * Show the popup menu for the list of matches.\n * Also adjusts \"compl_shown_match\" to an entry that is actually displayed.\n */\n void\nins_compl_show_pum(void)\n{\n int\t\ti;\n int\t\tcur = -1;\n colnr_T\tcol;", " if (!pum_wanted() || !pum_enough_matches())\n\treturn;", "#if defined(FEAT_EVAL)\n // Dirty hard-coded hack: remove any matchparen highlighting.\n do_cmdline_cmd((char_u *)\"if exists('g:loaded_matchparen')|:3match none|endif\");\n#endif", " // Update the screen later, before drawing the popup menu over it.\n pum_call_update_screen();", " if (compl_match_array == NULL)\n\t// Need to build the popup menu list.\n\tcur = ins_compl_build_pum();\n else\n {\n\t// popup menu already exists, only need to find the current item.\n\tfor (i = 0; i < compl_match_arraysize; ++i)\n\t if (compl_match_array[i].pum_text == compl_shown_match->cp_str\n\t\t || compl_match_array[i].pum_text\n\t\t\t\t == compl_shown_match->cp_text[CPT_ABBR])\n\t {\n\t\tcur = i;\n\t\tbreak;\n\t }\n }", " if (compl_match_array == NULL)\n\treturn;", " // In Replace mode when a $ is displayed at the end of the line only\n // part of the screen would be updated. We do need to redraw here.\n dollar_vcol = -1;", " // Compute the screen column of the start of the completed text.\n // Use the cursor to get all wrapping and other settings right.\n col = curwin->w_cursor.col;\n curwin->w_cursor.col = compl_col;\n pum_display(compl_match_array, compl_match_arraysize, cur);\n curwin->w_cursor.col = col;", "#ifdef FEAT_EVAL\n if (has_completechanged())\n\ttrigger_complete_changed_event(cur);\n#endif\n}", "#define DICT_FIRST\t(1)\t// use just first element in \"dict\"\n#define DICT_EXACT\t(2)\t// \"dict\" is the exact name of a file", "/*\n * Add any identifiers that match the given pattern \"pat\" in the list of\n * dictionary files \"dict_start\" to the list of completions.\n */\n static void\nins_compl_dictionaries(\n char_u\t*dict_start,\n char_u\t*pat,\n int\t\tflags,\t\t// DICT_FIRST and/or DICT_EXACT\n int\t\tthesaurus)\t// Thesaurus completion\n{\n char_u\t*dict = dict_start;\n char_u\t*ptr;\n char_u\t*buf;\n regmatch_T\tregmatch;\n char_u\t**files;\n int\t\tcount;\n int\t\tsave_p_scs;\n int\t\tdir = compl_direction;", " if (*dict == NUL)\n {\n#ifdef FEAT_SPELL\n\t// When 'dictionary' is empty and spell checking is enabled use\n\t// \"spell\".\n\tif (!thesaurus && curwin->w_p_spell)\n\t dict = (char_u *)\"spell\";\n\telse\n#endif\n\t return;\n }", " buf = alloc(LSIZE);\n if (buf == NULL)\n\treturn;\n regmatch.regprog = NULL;\t// so that we can goto theend", " // If 'infercase' is set, don't use 'smartcase' here\n save_p_scs = p_scs;\n if (curbuf->b_p_inf)\n\tp_scs = FALSE;", " // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern\n // to only match at the start of a line. Otherwise just match the\n // pattern. Also need to double backslashes.\n if (ctrl_x_mode_line_or_eval())\n {\n\tchar_u *pat_esc = vim_strsave_escaped(pat, (char_u *)\"\\\\\");\n\tsize_t len;", "\tif (pat_esc == NULL)\n\t goto theend;\n\tlen = STRLEN(pat_esc) + 10;\n\tptr = alloc(len);\n\tif (ptr == NULL)\n\t{\n\t vim_free(pat_esc);\n\t goto theend;\n\t}\n\tvim_snprintf((char *)ptr, len, \"^\\\\s*\\\\zs\\\\V%s\", pat_esc);\n\tregmatch.regprog = vim_regcomp(ptr, RE_MAGIC);\n\tvim_free(pat_esc);\n\tvim_free(ptr);\n }\n else\n {\n\tregmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);\n\tif (regmatch.regprog == NULL)\n\t goto theend;\n }", " // ignore case depends on 'ignorecase', 'smartcase' and \"pat\"\n regmatch.rm_ic = ignorecase(pat);\n while (*dict != NUL && !got_int && !compl_interrupted)\n {\n\t// copy one dictionary file name into buf\n\tif (flags == DICT_EXACT)\n\t{\n\t count = 1;\n\t files = &dict;\n\t}\n\telse\n\t{\n\t // Expand wildcards in the dictionary name, but do not allow\n\t // backticks (for security, the 'dict' option may have been set in\n\t // a modeline).\n\t copy_option_part(&dict, buf, LSIZE, \",\");\n# ifdef FEAT_SPELL\n\t if (!thesaurus && STRCMP(buf, \"spell\") == 0)\n\t\tcount = -1;\n\t else\n# endif\n\t\tif (vim_strchr(buf, '`') != NULL\n\t\t || expand_wildcards(1, &buf, &count, &files,\n\t\t\t\t\t\t EW_FILE|EW_SILENT) != OK)\n\t\tcount = 0;\n\t}", "# ifdef FEAT_SPELL\n\tif (count == -1)\n\t{\n\t // Complete from active spelling. Skip \"\\<\" in the pattern, we\n\t // don't use it as a RE.\n\t if (pat[0] == '\\\\' && pat[1] == '<')\n\t\tptr = pat + 2;\n\t else\n\t\tptr = pat;\n\t spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);\n\t}\n\telse\n# endif\n\t if (count > 0)\t// avoid warning for using \"files\" uninit\n\t{\n\t ins_compl_files(count, files, thesaurus, flags,\n\t\t\t\t\t\t\t&regmatch, buf, &dir);\n\t if (flags != DICT_EXACT)\n\t\tFreeWild(count, files);\n\t}\n\tif (flags != 0)\n\t break;\n }", "theend:\n p_scs = save_p_scs;\n vim_regfree(regmatch.regprog);\n vim_free(buf);\n}", "/*\n * Add all the words in the line \"*buf_arg\" from the thesaurus file \"fname\"\n * skipping the word at 'skip_word'. Returns OK on success.\n */\n static int\nthesarurs_add_words_in_line(\n\tchar_u\t*fname,\n\tchar_u\t**buf_arg,\n\tint\tdir,\n\tchar_u\t*skip_word)\n{\n int\t\tstatus = OK;\n char_u\t*ptr;\n char_u\t*wstart;", " // Add the other matches on the line\n ptr = *buf_arg;\n while (!got_int)\n {\n\t// Find start of the next word. Skip white\n\t// space and punctuation.\n\tptr = find_word_start(ptr);\n\tif (*ptr == NUL || *ptr == NL)\n\t break;\n\twstart = ptr;", "\t// Find end of the word.\n\tif (has_mbyte)\n\t // Japanese words may have characters in\n\t // different classes, only separate words\n\t // with single-byte non-word characters.\n\t while (*ptr != NUL)\n\t {\n\t\tint l = (*mb_ptr2len)(ptr);", "\t\tif (l < 2 && !vim_iswordc(*ptr))\n\t\t break;\n\t\tptr += l;\n\t }\n\telse\n\t ptr = find_word_end(ptr);", "\t// Add the word. Skip the regexp match.\n\tif (wstart != skip_word)\n\t{\n\t status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,\n\t\t\t\t\t\t\tfname, dir, FALSE);\n\t if (status == FAIL)\n\t\tbreak;\n\t}\n }", " *buf_arg = ptr;\n return status;\n}", "/*\n * Process \"count\" dictionary/thesaurus \"files\" and add the text matching\n * \"regmatch\".\n */\n static void\nins_compl_files(\n int\t\tcount,\n char_u\t**files,\n int\t\tthesaurus,\n int\t\tflags,\n regmatch_T\t*regmatch,\n char_u\t*buf,\n int\t\t*dir)\n{\n char_u\t*ptr;\n int\t\ti;\n FILE\t*fp;\n int\t\tadd_r;", " for (i = 0; i < count && !got_int && !compl_interrupted; i++)\n {\n\tfp = mch_fopen((char *)files[i], \"r\"); // open dictionary file\n\tif (flags != DICT_EXACT)\n\t{\n\t msg_hist_off = TRUE;\t// reset in msg_trunc_attr()\n\t vim_snprintf((char *)IObuff, IOSIZE,\n\t\t\t _(\"Scanning dictionary: %s\"), (char *)files[i]);\n\t (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));\n\t}", "\tif (fp == NULL)\n\t continue;", "\t// Read dictionary file line by line.\n\t// Check each line for a match.\n\twhile (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))\n\t{\n\t ptr = buf;\n\t while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))\n\t {\n\t\tptr = regmatch->startp[0];\n\t\tif (ctrl_x_mode_line_or_eval())\n\t\t ptr = find_line_end(ptr);\n\t\telse\n\t\t ptr = find_word_end(ptr);\n\t\tadd_r = ins_compl_add_infercase(regmatch->startp[0],\n\t\t\t(int)(ptr - regmatch->startp[0]),\n\t\t\tp_ic, files[i], *dir, FALSE);\n\t\tif (thesaurus)\n\t\t{\n\t\t // For a thesaurus, add all the words in the line\n\t\t ptr = buf;\n\t\t add_r = thesarurs_add_words_in_line(files[i], &ptr, *dir,\n\t\t\t\t\t\t\tregmatch->startp[0]);\n\t\t}\n\t\tif (add_r == OK)\n\t\t // if dir was BACKWARD then honor it just once\n\t\t *dir = FORWARD;\n\t\telse if (add_r == FAIL)\n\t\t break;\n\t\t// avoid expensive call to vim_regexec() when at end\n\t\t// of line\n\t\tif (*ptr == '\\n' || got_int)\n\t\t break;\n\t }\n\t line_breakcheck();\n\t ins_compl_check_keys(50, FALSE);\n\t}\n\tfclose(fp);\n }\n}", "/*\n * Find the start of the next word.\n * Returns a pointer to the first char of the word. Also stops at a NUL.\n */\n char_u *\nfind_word_start(char_u *ptr)\n{\n if (has_mbyte)\n\twhile (*ptr != NUL && *ptr != '\\n' && mb_get_class(ptr) <= 1)\n\t ptr += (*mb_ptr2len)(ptr);\n else\n\twhile (*ptr != NUL && *ptr != '\\n' && !vim_iswordc(*ptr))\n\t ++ptr;\n return ptr;\n}", "/*\n * Find the end of the word. Assumes it starts inside a word.\n * Returns a pointer to just after the word.\n */\n char_u *\nfind_word_end(char_u *ptr)\n{\n int\t\tstart_class;", " if (has_mbyte)\n {\n\tstart_class = mb_get_class(ptr);\n\tif (start_class > 1)\n\t while (*ptr != NUL)\n\t {\n\t\tptr += (*mb_ptr2len)(ptr);\n\t\tif (mb_get_class(ptr) != start_class)\n\t\t break;\n\t }\n }\n else\n\twhile (vim_iswordc(*ptr))\n\t ++ptr;\n return ptr;\n}", "/*\n * Find the end of the line, omitting CR and NL at the end.\n * Returns a pointer to just after the line.\n */\n static char_u *\nfind_line_end(char_u *ptr)\n{\n char_u\t*s;", " s = ptr + STRLEN(ptr);\n while (s > ptr && (s[-1] == CAR || s[-1] == NL))\n\t--s;\n return s;\n}", "/*\n * Free the list of completions\n */\n static void\nins_compl_free(void)\n{\n compl_T *match;\n int\t i;", " VIM_CLEAR(compl_pattern);\n VIM_CLEAR(compl_leader);", " if (compl_first_match == NULL)\n\treturn;", " ins_compl_del_pum();\n pum_clear();", " compl_curr_match = compl_first_match;\n do\n {\n\tmatch = compl_curr_match;\n\tcompl_curr_match = compl_curr_match->cp_next;\n\tvim_free(match->cp_str);\n\t// several entries may use the same fname, free it just once.\n\tif (match->cp_flags & CP_FREE_FNAME)\n\t vim_free(match->cp_fname);\n\tfor (i = 0; i < CPT_COUNT; ++i)\n\t vim_free(match->cp_text[i]);\n#ifdef FEAT_EVAL\n\tclear_tv(&match->cp_user_data);\n#endif\n\tvim_free(match);\n } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));\n compl_first_match = compl_curr_match = NULL;\n compl_shown_match = NULL;\n compl_old_match = NULL;\n}", "/*\n * Reset/clear the completion state.\n */\n void\nins_compl_clear(void)\n{\n compl_cont_status = 0;\n compl_started = FALSE;\n compl_matches = 0;\n VIM_CLEAR(compl_pattern);\n VIM_CLEAR(compl_leader);\n edit_submode_extra = NULL;\n VIM_CLEAR(compl_orig_text);\n compl_enter_selects = FALSE;\n#ifdef FEAT_EVAL\n // clear v:completed_item\n set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));\n#endif\n}", "/*\n * Return TRUE when Insert completion is active.\n */\n int\nins_compl_active(void)\n{\n return compl_started;\n}", "/*\n * Selected one of the matches. When FALSE the match was edited or using the\n * longest common string.\n */\n int\nins_compl_used_match(void)\n{\n return compl_used_match;\n}", "/*\n * Initialize get longest common string.\n */\n void\nins_compl_init_get_longest(void)\n{\n compl_get_longest = FALSE;\n}", "/*\n * Returns TRUE when insert completion is interrupted.\n */\n int\nins_compl_interrupted(void)\n{\n return compl_interrupted;\n}", "/*\n * Returns TRUE if the <Enter> key selects a match in the completion popup\n * menu.\n */\n int\nins_compl_enter_selects(void)\n{\n return compl_enter_selects;\n}", "/*\n * Return the column where the text starts that is being completed\n */\n colnr_T\nins_compl_col(void)\n{\n return compl_col;\n}", "/*\n * Return the length in bytes of the text being completed\n */\n int\nins_compl_len(void)\n{\n return compl_length;\n}", "/*\n * Delete one character before the cursor and show the subset of the matches\n * that match the word that is now before the cursor.\n * Returns the character to be used, NUL if the work is done and another char\n * to be got from the user.\n */\n int\nins_compl_bs(void)\n{\n char_u\t*line;\n char_u\t*p;", " line = ml_get_curline();\n p = line + curwin->w_cursor.col;\n MB_PTR_BACK(line, p);", " // Stop completion when the whole word was deleted. For Omni completion\n // allow the word to be deleted, we won't match everything.\n // Respect the 'backspace' option.\n if ((int)(p - line) - (int)compl_col < 0\n\t || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())\n\t || ctrl_x_mode_eval()\n\t || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col\n\t\t\t\t\t\t\t- compl_length < 0))\n\treturn K_BS;", " // Deleted more than what was used to find matches or didn't finish\n // finding all matches: need to look for matches all over again.\n if (curwin->w_cursor.col <= compl_col + compl_length\n\t\t\t\t\t\t || ins_compl_need_restart())\n\tins_compl_restart();", " vim_free(compl_leader);\n compl_leader = vim_strnsave(line + compl_col, (p - line) - compl_col);\n if (compl_leader == NULL)\n\treturn K_BS;", " ins_compl_new_leader();\n if (compl_shown_match != NULL)\n\t// Make sure current match is not a hidden item.\n\tcompl_curr_match = compl_shown_match;\n return NUL;\n}", "/*\n * Return TRUE when we need to find matches again, ins_compl_restart() is to\n * be called.\n */\n static int\nins_compl_need_restart(void)\n{\n // Return TRUE if we didn't complete finding matches or when the\n // 'completefunc' returned \"always\" in the \"refresh\" dictionary item.\n return compl_was_interrupted\n\t|| ((ctrl_x_mode_function() || ctrl_x_mode_omni())\n\t\t\t\t\t\t && compl_opt_refresh_always);\n}", "/*\n * Called after changing \"compl_leader\".\n * Show the popup menu with a different set of matches.\n * May also search for matches again if the previous search was interrupted.\n */\n static void\nins_compl_new_leader(void)\n{\n ins_compl_del_pum();\n ins_compl_delete();\n ins_bytes(compl_leader + get_compl_len());\n compl_used_match = FALSE;", " if (compl_started)\n\tins_compl_set_original_text(compl_leader);\n else\n {\n#ifdef FEAT_SPELL\n\tspell_bad_len = 0;\t// need to redetect bad word\n#endif\n\t// Matches were cleared, need to search for them now. Before drawing\n\t// the popup menu display the changed text before the cursor. Set\n\t// \"compl_restarting\" to avoid that the first match is inserted.\n\tpum_call_update_screen();\n#ifdef FEAT_GUI\n\tif (gui.in_use)\n\t{\n\t // Show the cursor after the match, not after the redrawn text.\n\t setcursor();\n\t out_flush_cursor(FALSE, FALSE);\n\t}\n#endif\n\tcompl_restarting = TRUE;\n\tif (ins_complete(Ctrl_N, TRUE) == FAIL)\n\t compl_cont_status = 0;\n\tcompl_restarting = FALSE;\n }", " compl_enter_selects = !compl_used_match;", " // Show the popup menu with a different set of matches.\n ins_compl_show_pum();", " // Don't let Enter select the original text when there is no popup menu.\n if (compl_match_array == NULL)\n\tcompl_enter_selects = FALSE;\n}", "/*\n * Return the length of the completion, from the completion start column to\n * the cursor column. Making sure it never goes below zero.\n */\n static int\nget_compl_len(void)\n{\n int off = (int)curwin->w_cursor.col - (int)compl_col;", " if (off < 0)\n\treturn 0;\n return off;\n}", "/*\n * Append one character to the match leader. May reduce the number of\n * matches.\n */\n void\nins_compl_addleader(int c)\n{\n int\t\tcc;", " if (stop_arrow() == FAIL)\n\treturn;\n if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)\n {\n\tchar_u\tbuf[MB_MAXBYTES + 1];", "\t(*mb_char2bytes)(c, buf);\n\tbuf[cc] = NUL;\n\tins_char_bytes(buf, cc);\n\tif (compl_opt_refresh_always)\n\t AppendToRedobuff(buf);\n }\n else\n {\n\tins_char(c);\n\tif (compl_opt_refresh_always)\n\t AppendCharToRedobuff(c);\n }", " // If we didn't complete finding matches we must search again.\n if (ins_compl_need_restart())\n\tins_compl_restart();", " // When 'always' is set, don't reset compl_leader. While completing,\n // cursor doesn't point original position, changing compl_leader would\n // break redo.\n if (!compl_opt_refresh_always)\n {\n\tvim_free(compl_leader);\n\tcompl_leader = vim_strnsave(ml_get_curline() + compl_col,\n\t\t\t\t\t curwin->w_cursor.col - compl_col);\n\tif (compl_leader != NULL)\n\t ins_compl_new_leader();\n }\n}", "/*\n * Setup for finding completions again without leaving CTRL-X mode. Used when\n * BS or a key was typed while still searching for matches.\n */\n static void\nins_compl_restart(void)\n{\n ins_compl_free();\n compl_started = FALSE;\n compl_matches = 0;\n compl_cont_status = 0;\n compl_cont_mode = 0;\n}", "/*\n * Set the first match, the original text.\n */\n static void\nins_compl_set_original_text(char_u *str)\n{\n char_u\t*p;", " // Replace the original text entry.\n // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly\n // be at the last item for backward completion\n if (match_at_original_text(compl_first_match))\t// safety check\n {\n\tp = vim_strsave(str);\n\tif (p != NULL)\n\t{\n\t vim_free(compl_first_match->cp_str);\n\t compl_first_match->cp_str = p;\n\t}\n }\n else if (compl_first_match->cp_prev != NULL\n\t && match_at_original_text(compl_first_match->cp_prev))\n {\n p = vim_strsave(str);\n if (p != NULL)\n {\n\t vim_free(compl_first_match->cp_prev->cp_str);\n\t compl_first_match->cp_prev->cp_str = p;\n }\n }\n}", "/*\n * Append one character to the match leader. May reduce the number of\n * matches.\n */\n void\nins_compl_addfrommatch(void)\n{\n char_u\t*p;\n int\t\tlen = (int)curwin->w_cursor.col - (int)compl_col;\n int\t\tc;\n compl_T\t*cp;", " p = compl_shown_match->cp_str;\n if ((int)STRLEN(p) <= len) // the match is too short\n {\n\t// When still at the original match use the first entry that matches\n\t// the leader.\n\tif (!match_at_original_text(compl_shown_match))\n\t return;", "\tp = NULL;\n\tfor (cp = compl_shown_match->cp_next; cp != NULL\n\t\t&& !is_first_match(cp); cp = cp->cp_next)\n\t{\n\t if (compl_leader == NULL\n\t\t || ins_compl_equal(cp, compl_leader,\n\t\t\t(int)STRLEN(compl_leader)))\n\t {\n\t\tp = cp->cp_str;\n\t\tbreak;\n\t }\n\t}\n\tif (p == NULL || (int)STRLEN(p) <= len)\n\t return;\n }\n p += len;\n c = PTR2CHAR(p);\n ins_compl_addleader(c);\n}", "/*\n * Set the CTRL-X completion mode based on the key \"c\" typed after a CTRL-X.\n * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,\n * compl_cont_mode and compl_cont_status.\n * Returns TRUE when the character is not to be inserted.\n */\n static int\nset_ctrl_x_mode(int c)\n{\n int retval = FALSE;", " switch (c)\n {\n\tcase Ctrl_E:\n\tcase Ctrl_Y:\n\t // scroll the window one line up or down\n\t ctrl_x_mode = CTRL_X_SCROLL;\n\t if (!(State & REPLACE_FLAG))\n\t\tedit_submode = (char_u *)_(\" (insert) Scroll (^E/^Y)\");\n\t else\n\t\tedit_submode = (char_u *)_(\" (replace) Scroll (^E/^Y)\");\n\t edit_submode_pre = NULL;\n\t showmode();\n\t break;\n\tcase Ctrl_L:\n\t // complete whole line\n\t ctrl_x_mode = CTRL_X_WHOLE_LINE;\n\t break;\n\tcase Ctrl_F:\n\t // complete filenames\n\t ctrl_x_mode = CTRL_X_FILES;\n\t break;\n\tcase Ctrl_K:\n\t // complete words from a dictinoary\n\t ctrl_x_mode = CTRL_X_DICTIONARY;\n\t break;\n\tcase Ctrl_R:\n\t // Register insertion without exiting CTRL-X mode\n\t // Simply allow ^R to happen without affecting ^X mode\n\t break;\n\tcase Ctrl_T:\n\t // complete words from a thesaurus\n\t ctrl_x_mode = CTRL_X_THESAURUS;\n\t break;\n#ifdef FEAT_COMPL_FUNC\n\tcase Ctrl_U:\n\t // user defined completion\n\t ctrl_x_mode = CTRL_X_FUNCTION;\n\t break;\n\tcase Ctrl_O:\n\t // omni completion\n\t ctrl_x_mode = CTRL_X_OMNI;\n\t break;\n#endif\n\tcase 's':\n\tcase Ctrl_S:\n\t // complete spelling suggestions\n\t ctrl_x_mode = CTRL_X_SPELL;\n#ifdef FEAT_SPELL\n\t ++emsg_off;\t// Avoid getting the E756 error twice.\n\t spell_back_to_badword();\n\t --emsg_off;\n#endif\n\t break;\n\tcase Ctrl_RSB:\n\t // complete tag names\n\t ctrl_x_mode = CTRL_X_TAGS;\n\t break;\n#ifdef FEAT_FIND_ID\n\tcase Ctrl_I:\n\tcase K_S_TAB:\n\t // complete keywords from included files\n\t ctrl_x_mode = CTRL_X_PATH_PATTERNS;\n\t break;\n\tcase Ctrl_D:\n\t // complete definitions from included files\n\t ctrl_x_mode = CTRL_X_PATH_DEFINES;\n\t break;\n#endif\n\tcase Ctrl_V:\n\tcase Ctrl_Q:\n\t // complete vim commands\n\t ctrl_x_mode = CTRL_X_CMDLINE;\n\t break;\n\tcase Ctrl_Z:\n\t // stop completion\n\t ctrl_x_mode = CTRL_X_NORMAL;\n\t edit_submode = NULL;\n\t showmode();\n\t retval = TRUE;\n\t break;\n\tcase Ctrl_P:\n\tcase Ctrl_N:\n\t // ^X^P means LOCAL expansion if nothing interrupted (eg we\n\t // just started ^X mode, or there were enough ^X's to cancel\n\t // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)\n\t // do normal expansion when interrupting a different mode (say\n\t // ^X^F^X^P or ^P^X^X^P, see below)\n\t // nothing changes if interrupting mode 0, (eg, the flag\n\t // doesn't change when going to ADDING mode -- Acevedo\n\t if (!(compl_cont_status & CONT_INTRPT))\n\t\tcompl_cont_status |= CONT_LOCAL;\n\t else if (compl_cont_mode != 0)\n\t\tcompl_cont_status &= ~CONT_LOCAL;\n\t // FALLTHROUGH\n\tdefault:\n\t // If we have typed at least 2 ^X's... for modes != 0, we set\n\t // compl_cont_status = 0 (eg, as if we had just started ^X\n\t // mode).\n\t // For mode 0, we set \"compl_cont_mode\" to an impossible\n\t // value, in both cases ^X^X can be used to restart the same\n\t // mode (avoiding ADDING mode).\n\t // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start\n\t // 'complete' and local ^P expansions respectively.\n\t // In mode 0 an extra ^X is needed since ^X^P goes to ADDING\n\t // mode -- Acevedo\n\t if (c == Ctrl_X)\n\t {\n\t\tif (compl_cont_mode != 0)\n\t\t compl_cont_status = 0;\n\t\telse\n\t\t compl_cont_mode = CTRL_X_NOT_DEFINED_YET;\n\t }\n\t ctrl_x_mode = CTRL_X_NORMAL;\n\t edit_submode = NULL;\n\t showmode();\n\t break;\n }", " return retval;\n}", "/*\n * Stop insert completion mode\n */\n static int\nins_compl_stop(int c, int prev_mode, int retval)\n{\n char_u\t*ptr;\n int\t\twant_cindent;", " // Get here when we have finished typing a sequence of ^N and\n // ^P or other completion characters in CTRL-X mode. Free up\n // memory that was used, and make sure we can redo the insert.\n if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)\n {\n\t// If any of the original typed text has been changed, eg when\n\t// ignorecase is set, we must add back-spaces to the redo\n\t// buffer. We add as few as necessary to delete just the part\n\t// of the original text that has changed.\n\t// When using the longest match, edited the match or used\n\t// CTRL-E then don't use the current match.\n\tif (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)\n\t ptr = compl_curr_match->cp_str;\n\telse\n\t ptr = NULL;\n\tins_compl_fixRedoBufForLeader(ptr);\n }", " want_cindent = (get_can_cindent() && cindent_on());", " // When completing whole lines: fix indent for 'cindent'.\n // Otherwise, break line if it's too long.\n if (compl_cont_mode == CTRL_X_WHOLE_LINE)\n {\n\t// re-indent the current line\n\tif (want_cindent)\n\t{\n\t do_c_expr_indent();\n\t want_cindent = FALSE;\t// don't do it again\n\t}\n }\n else\n {\n\tint prev_col = curwin->w_cursor.col;", "\t// put the cursor on the last char, for 'tw' formatting\n\tif (prev_col > 0)\n\t dec_cursor();\n\t// only format when something was inserted\n\tif (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)\n\t insertchar(NUL, 0, -1);\n\tif (prev_col > 0\n\t\t&& ml_get_curline()[curwin->w_cursor.col] != NUL)\n\t inc_cursor();\n }", " // If the popup menu is displayed pressing CTRL-Y means accepting\n // the selection without inserting anything. When\n // compl_enter_selects is set the Enter key does the same.\n if ((c == Ctrl_Y || (compl_enter_selects\n\t\t && (c == CAR || c == K_KENTER || c == NL)))\n\t && pum_visible())\n\tretval = TRUE;", " // CTRL-E means completion is Ended, go back to the typed text.\n // but only do this, if the Popup is still visible\n if (c == Ctrl_E)\n {\n\tchar_u *p = NULL;", "\tins_compl_delete();\n\tif (compl_leader != NULL)\n\t p = compl_leader;\n\telse if (compl_first_match != NULL)\n\t p = compl_orig_text;\n\tif (p != NULL)\n\t{\n\t int\t compl_len = get_compl_len();\n\t int\t len = (int)STRLEN(p);", "\t if (len > compl_len)\n\t\tins_bytes_len(p + compl_len, len - compl_len);\n\t}\n\tretval = TRUE;\n }", " auto_format(FALSE, TRUE);", " // Trigger the CompleteDonePre event to give scripts a chance to\n // act upon the completion before clearing the info, and restore\n // ctrl_x_mode, so that complete_info() can be used.\n ctrl_x_mode = prev_mode;\n ins_apply_autocmds(EVENT_COMPLETEDONEPRE);", " ins_compl_free();\n compl_started = FALSE;\n compl_matches = 0;\n if (!shortmess(SHM_COMPLETIONMENU))\n\tmsg_clr_cmdline();\t// necessary for \"noshowmode\"\n ctrl_x_mode = CTRL_X_NORMAL;\n compl_enter_selects = FALSE;\n if (edit_submode != NULL)\n {\n\tedit_submode = NULL;\n\tshowmode();\n }", "#ifdef FEAT_CMDWIN\n if (c == Ctrl_C && cmdwin_type != 0)\n\t// Avoid the popup menu remains displayed when leaving the\n\t// command line window.\n\tupdate_screen(0);\n#endif\n // Indent now if a key was typed that is in 'cinkeys'.\n if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))\n\tdo_c_expr_indent();\n // Trigger the CompleteDone event to give scripts a chance to act\n // upon the end of completion.\n ins_apply_autocmds(EVENT_COMPLETEDONE);", " return retval;\n}", "/*\n * Prepare for Insert mode completion, or stop it.\n * Called just after typing a character in Insert mode.\n * Returns TRUE when the character is not to be inserted;\n */\n int\nins_compl_prep(int c)\n{\n int\t\tretval = FALSE;\n int\t\tprev_mode = ctrl_x_mode;", " // Forget any previous 'special' messages if this is actually\n // a ^X mode key - bar ^R, in which case we wait to see what it gives us.\n if (c != Ctrl_R && vim_is_ctrl_x_key(c))\n\tedit_submode_extra = NULL;", " // Ignore end of Select mode mapping and mouse scroll buttons.\n if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP\n\t || c == K_MOUSELEFT || c == K_MOUSERIGHT\n\t || c == K_COMMAND || c == K_SCRIPT_COMMAND)\n\treturn retval;", "#ifdef FEAT_PROP_POPUP\n // Ignore mouse events in a popup window\n if (is_mouse_key(c))\n {\n\t// Ignore drag and release events, the position does not need to be in\n\t// the popup and it may have just closed.\n\tif (c == K_LEFTRELEASE\n\t\t|| c == K_LEFTRELEASE_NM\n\t\t|| c == K_MIDDLERELEASE\n\t\t|| c == K_RIGHTRELEASE\n\t\t|| c == K_X1RELEASE\n\t\t|| c == K_X2RELEASE\n\t\t|| c == K_LEFTDRAG\n\t\t|| c == K_MIDDLEDRAG\n\t\t|| c == K_RIGHTDRAG\n\t\t|| c == K_X1DRAG\n\t\t|| c == K_X2DRAG)\n\t return retval;\n\tif (popup_visible)\n\t{\n\t int\t row = mouse_row;\n\t int\t col = mouse_col;\n\t win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);", "\t if (wp != NULL && WIN_IS_POPUP(wp))\n\t\treturn retval;\n\t}\n }\n#endif", " if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)\n {\n\tif (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)\n\t\t|| !vim_is_ctrl_x_key(c))\n\t{\n\t // Not starting another completion mode.\n\t ctrl_x_mode = CTRL_X_CMDLINE;", "\t // CTRL-X CTRL-Z should stop completion without inserting anything\n\t if (c == Ctrl_Z)\n\t\tretval = TRUE;\n\t}\n\telse\n\t{\n\t ctrl_x_mode = CTRL_X_CMDLINE;", "\t // Other CTRL-X keys first stop completion, then start another\n\t // completion mode.\n\t ins_compl_prep(' ');\n\t ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;\n\t}\n }", " // Set \"compl_get_longest\" when finding the first matches.\n if (ctrl_x_mode_not_defined_yet()\n\t\t\t || (ctrl_x_mode_normal() && !compl_started))\n {\n\tcompl_get_longest = (strstr((char *)p_cot, \"longest\") != NULL);\n\tcompl_used_match = TRUE;", " }", " if (ctrl_x_mode_not_defined_yet())\n\t// We have just typed CTRL-X and aren't quite sure which CTRL-X mode\n\t// it will be yet. Now we decide.\n\tretval = set_ctrl_x_mode(c);\n else if (ctrl_x_mode_not_default())\n {\n\t// We're already in CTRL-X mode, do we stay in it?\n\tif (!vim_is_ctrl_x_key(c))\n\t{\n\t if (ctrl_x_mode_scroll())\n\t\tctrl_x_mode = CTRL_X_NORMAL;\n\t else\n\t\tctrl_x_mode = CTRL_X_FINISHED;\n\t edit_submode = NULL;\n\t}\n\tshowmode();\n }", " if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)\n {\n\t// Show error message from attempted keyword completion (probably\n\t// 'Pattern not found') until another key is hit, then go back to\n\t// showing what mode we are in.\n\tshowmode();\n\tif ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P\n\t\t\t\t && c != Ctrl_R && !ins_compl_pum_key(c))\n\t\t|| ctrl_x_mode == CTRL_X_FINISHED)\n\t retval = ins_compl_stop(c, prev_mode, retval);\n }\n else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)\n\t// Trigger the CompleteDone event to give scripts a chance to act\n\t// upon the (possibly failed) completion.\n\tins_apply_autocmds(EVENT_COMPLETEDONE);", " may_trigger_modechanged();", " // reset continue_* if we left expansion-mode, if we stay they'll be\n // (re)set properly in ins_complete()\n if (!vim_is_ctrl_x_key(c))\n {\n\tcompl_cont_status = 0;\n\tcompl_cont_mode = 0;\n }", " return retval;\n}", "/*\n * Fix the redo buffer for the completion leader replacing some of the typed\n * text. This inserts backspaces and appends the changed text.\n * \"ptr\" is the known leader text or NUL.\n */\n static void\nins_compl_fixRedoBufForLeader(char_u *ptr_arg)\n{\n int\t len;\n char_u *p;\n char_u *ptr = ptr_arg;", " if (ptr == NULL)\n {\n\tif (compl_leader != NULL)\n\t ptr = compl_leader;\n\telse\n\t return; // nothing to do\n }\n if (compl_orig_text != NULL)\n {\n\tp = compl_orig_text;\n\tfor (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)\n\t ;\n\tif (len > 0)\n\t len -= (*mb_head_off)(p, p + len);\n\tfor (p += len; *p != NUL; MB_PTR_ADV(p))\n\t AppendCharToRedobuff(K_BS);\n }\n else\n\tlen = 0;\n if (ptr != NULL)\n\tAppendToRedobuffLit(ptr + len, -1);\n}", "/*\n * Loops through the list of windows, loaded-buffers or non-loaded-buffers\n * (depending on flag) starting from buf and looking for a non-scanned\n * buffer (other than curbuf).\tcurbuf is special, if it is called with\n * buf=curbuf then it has to be the first call for a given flag/expansion.\n *\n * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo\n */\n static buf_T *\nins_compl_next_buf(buf_T *buf, int flag)\n{\n static win_T *wp = NULL;", " if (flag == 'w')\t\t// just windows\n {\n\tif (buf == curbuf || wp == NULL) // first call for this flag/expansion\n\t wp = curwin;\n\twhile ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin\n\t\t&& wp->w_buffer->b_scanned)\n\t ;\n\tbuf = wp->w_buffer;\n }\n else\n\t// 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'\n\t// (unlisted buffers)\n\t// When completing whole lines skip unloaded buffers.\n\twhile ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf\n\t\t&& ((flag == 'U'\n\t\t\t? buf->b_p_bl\n\t\t\t: (!buf->b_p_bl\n\t\t\t || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))\n\t\t || buf->b_scanned))\n\t ;\n return buf;\n}", "#ifdef FEAT_COMPL_FUNC", "# ifdef FEAT_EVAL\nstatic callback_T cfu_cb;\t // 'completefunc' callback function\nstatic callback_T ofu_cb;\t // 'omnifunc' callback function\nstatic callback_T tsrfu_cb;\t // 'thesaurusfunc' callback function\n# endif", "/*\n * Copy a global callback function to a buffer local callback.\n */\n static void\ncopy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)\n{\n free_callback(bufcb);\n if (globcb->cb_name != NULL && *globcb->cb_name != NUL)\n\tcopy_callback(bufcb, globcb);\n}", "/*\n * Parse the 'completefunc' option value and set the callback function.\n * Invoked when the 'completefunc' option is set. The option value can be a\n * name of a function (string), or function(<name>) or funcref(<name>) or a\n * lambda expression.\n */\n int\nset_completefunc_option(void)\n{\n int\tretval;", " retval = option_set_callback_func(curbuf->b_p_cfu, &cfu_cb);\n if (retval == OK)\n\tset_buflocal_cfu_callback(curbuf);", " return retval;\n}", "/*\n * Copy the global 'completefunc' callback function to the buffer-local\n * 'completefunc' callback for \"buf\".\n */\n void\nset_buflocal_cfu_callback(buf_T *buf UNUSED)\n{\n# ifdef FEAT_EVAL\n copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);\n# endif\n}", "/*\n * Parse the 'omnifunc' option value and set the callback function.\n * Invoked when the 'omnifunc' option is set. The option value can be a\n * name of a function (string), or function(<name>) or funcref(<name>) or a\n * lambda expression.\n */\n int\nset_omnifunc_option(void)\n{\n int\tretval;", " retval = option_set_callback_func(curbuf->b_p_ofu, &ofu_cb);\n if (retval == OK)\n\tset_buflocal_ofu_callback(curbuf);", " return retval;\n}", "/*\n * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'\n * callback for \"buf\".\n */\n void\nset_buflocal_ofu_callback(buf_T *buf UNUSED)\n{\n# ifdef FEAT_EVAL\n copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);\n# endif\n}", "/*\n * Parse the 'thesaurusfunc' option value and set the callback function.\n * Invoked when the 'thesaurusfunc' option is set. The option value can be a\n * name of a function (string), or function(<name>) or funcref(<name>) or a\n * lambda expression.\n */\n int\nset_thesaurusfunc_option(void)\n{\n int\tretval;", " if (*curbuf->b_p_tsrfu != NUL)\n {\n\t// buffer-local option set\n\tretval = option_set_callback_func(curbuf->b_p_tsrfu,\n\t\t\t\t\t\t\t&curbuf->b_tsrfu_cb);\n }\n else\n {\n\t// global option set\n\tretval = option_set_callback_func(p_tsrfu, &tsrfu_cb);\n }", " return retval;\n}", "/*\n * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with\n * \"copyID\" so that they are not garbage collected.\n */\n int\nset_ref_in_insexpand_funcs(int copyID)\n{\n int abort = FALSE;", " abort = set_ref_in_callback(&cfu_cb, copyID);\n abort = abort || set_ref_in_callback(&ofu_cb, copyID);\n abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);", " return abort;\n}", "/*\n * Get the user-defined completion function name for completion \"type\"\n */\n static char_u *\nget_complete_funcname(int type)\n{\n switch (type)\n {\n\tcase CTRL_X_FUNCTION:\n\t return curbuf->b_p_cfu;\n\tcase CTRL_X_OMNI:\n\t return curbuf->b_p_ofu;\n\tcase CTRL_X_THESAURUS:\n\t return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;\n\tdefault:\n\t return (char_u *)\"\";\n }\n}", "/*\n * Get the callback to use for insert mode completion.\n */\n static callback_T *\nget_insert_callback(int type)\n{\n if (type == CTRL_X_FUNCTION)\n\treturn &curbuf->b_cfu_cb;\n if (type == CTRL_X_OMNI)\n\treturn &curbuf->b_ofu_cb;\n // CTRL_X_THESAURUS\n return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;\n}", "/*\n * Execute user defined complete function 'completefunc', 'omnifunc' or\n * 'thesaurusfunc', and get matches in \"matches\".\n * \"type\" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.\n */\n static void\nexpand_by_function(int type, char_u *base)\n{\n list_T *matchlist = NULL;\n dict_T\t*matchdict = NULL;\n typval_T\targs[3];\n char_u\t*funcname;\n pos_T\tpos;\n callback_T\t*cb;\n typval_T\trettv;\n int\t\tsave_State = State;\n int\t\tretval;", " funcname = get_complete_funcname(type);\n if (*funcname == NUL)\n\treturn;", " // Call 'completefunc' to obtain the list of matches.\n args[0].v_type = VAR_NUMBER;\n args[0].vval.v_number = 0;\n args[1].v_type = VAR_STRING;\n args[1].vval.v_string = base != NULL ? base : (char_u *)\"\";\n args[2].v_type = VAR_UNKNOWN;", " pos = curwin->w_cursor;\n // Lock the text to avoid weird things from happening. Also disallow\n // switching to another window, it should not be needed and may end up in\n // Insert mode in another buffer.\n ++textlock;", " cb = get_insert_callback(type);\n retval = call_callback(cb, 0, &rettv, 2, args);", " // Call a function, which returns a list or dict.\n if (retval == OK)\n {\n\tswitch (rettv.v_type)\n\t{\n\t case VAR_LIST:\n\t\tmatchlist = rettv.vval.v_list;\n\t\tbreak;\n\t case VAR_DICT:\n\t\tmatchdict = rettv.vval.v_dict;\n\t\tbreak;\n\t case VAR_SPECIAL:\n\t\tif (rettv.vval.v_number == VVAL_NONE)\n\t\t compl_opt_suppress_empty = TRUE;\n\t\t// FALLTHROUGH\n\t default:\n\t\t// TODO: Give error message?\n\t\tclear_tv(&rettv);\n\t\tbreak;\n\t}\n }\n --textlock;", " curwin->w_cursor = pos;\t// restore the cursor position\n validate_cursor();\n if (!EQUAL_POS(curwin->w_cursor, pos))\n {\n\temsg(_(e_complete_function_deleted_text));\n\tgoto theend;\n }", " if (matchlist != NULL)\n\tins_compl_add_list(matchlist);\n else if (matchdict != NULL)\n\tins_compl_add_dict(matchdict);", "theend:\n // Restore State, it might have been changed.\n State = save_State;", " if (matchdict != NULL)\n\tdict_unref(matchdict);\n if (matchlist != NULL)\n\tlist_unref(matchlist);\n}\n#endif // FEAT_COMPL_FUNC", "#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)\n/*\n * Add a match to the list of matches from a typeval_T.\n * If the given string is already in the list of completions, then return\n * NOTDONE, otherwise add it to the list and return OK. If there is an error,\n * maybe because alloc() returns NULL, then FAIL is returned.\n * When \"fast\" is TRUE use fast_breakcheck() instead of ui_breakcheck().\n */\n static int\nins_compl_add_tv(typval_T *tv, int dir, int fast)\n{\n char_u\t*word;\n int\t\tdup = FALSE;\n int\t\tempty = FALSE;\n int\t\tflags = fast ? CP_FAST : 0;\n char_u\t*(cptext[CPT_COUNT]);\n typval_T\tuser_data;\n int\t\tstatus;", " user_data.v_type = VAR_UNKNOWN;\n if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)\n {\n\tword = dict_get_string(tv->vval.v_dict, (char_u *)\"word\", FALSE);\n\tcptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict,\n\t\t\t\t\t\t (char_u *)\"abbr\", FALSE);\n\tcptext[CPT_MENU] = dict_get_string(tv->vval.v_dict,\n\t\t\t\t\t\t (char_u *)\"menu\", FALSE);\n\tcptext[CPT_KIND] = dict_get_string(tv->vval.v_dict,\n\t\t\t\t\t\t (char_u *)\"kind\", FALSE);\n\tcptext[CPT_INFO] = dict_get_string(tv->vval.v_dict,\n\t\t\t\t\t\t (char_u *)\"info\", FALSE);\n\tdict_get_tv(tv->vval.v_dict, (char_u *)\"user_data\", &user_data);\n\tif (dict_get_string(tv->vval.v_dict, (char_u *)\"icase\", FALSE) != NULL\n\t\t\t&& dict_get_number(tv->vval.v_dict, (char_u *)\"icase\"))\n\t flags |= CP_ICASE;\n\tif (dict_get_string(tv->vval.v_dict, (char_u *)\"dup\", FALSE) != NULL)\n\t dup = dict_get_number(tv->vval.v_dict, (char_u *)\"dup\");\n\tif (dict_get_string(tv->vval.v_dict, (char_u *)\"empty\", FALSE) != NULL)\n\t empty = dict_get_number(tv->vval.v_dict, (char_u *)\"empty\");\n\tif (dict_get_string(tv->vval.v_dict, (char_u *)\"equal\", FALSE) != NULL\n\t\t\t&& dict_get_number(tv->vval.v_dict, (char_u *)\"equal\"))\n\t flags |= CP_EQUAL;\n }\n else\n {\n\tword = tv_get_string_chk(tv);\n\tCLEAR_FIELD(cptext);\n }\n if (word == NULL || (!empty && *word == NUL))\n {\n\tclear_tv(&user_data);\n\treturn FAIL;\n }\n status = ins_compl_add(word, -1, NULL, cptext, &user_data, dir, flags, dup);\n if (status != OK)\n\tclear_tv(&user_data);\n return status;\n}", "/*\n * Add completions from a list.\n */\n static void\nins_compl_add_list(list_T *list)\n{\n listitem_T\t*li;\n int\t\tdir = compl_direction;", " // Go through the List with matches and add each of them.\n CHECK_LIST_MATERIALIZE(list);\n FOR_ALL_LIST_ITEMS(list, li)\n {\n\tif (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)\n\t // if dir was BACKWARD then honor it just once\n\t dir = FORWARD;\n\telse if (did_emsg)\n\t break;\n }\n}", "/*\n * Add completions from a dict.\n */\n static void\nins_compl_add_dict(dict_T *dict)\n{\n dictitem_T\t*di_refresh;\n dictitem_T\t*di_words;", " // Check for optional \"refresh\" item.\n compl_opt_refresh_always = FALSE;\n di_refresh = dict_find(dict, (char_u *)\"refresh\", 7);\n if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)\n {\n\tchar_u\t*v = di_refresh->di_tv.vval.v_string;", "\tif (v != NULL && STRCMP(v, (char_u *)\"always\") == 0)\n\t compl_opt_refresh_always = TRUE;\n }", " // Add completions from a \"words\" list.\n di_words = dict_find(dict, (char_u *)\"words\", 5);\n if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)\n\tins_compl_add_list(di_words->di_tv.vval.v_list);\n}", "/*\n * Start completion for the complete() function.\n * \"startcol\" is where the matched text starts (1 is first column).\n * \"list\" is the list of matches.\n */\n static void\nset_completion(colnr_T startcol, list_T *list)\n{\n int save_w_wrow = curwin->w_wrow;\n int save_w_leftcol = curwin->w_leftcol;\n int flags = CP_ORIGINAL_TEXT;", " // If already doing completions stop it.\n if (ctrl_x_mode_not_default())\n\tins_compl_prep(' ');\n ins_compl_clear();\n ins_compl_free();", " compl_direction = FORWARD;\n if (startcol > curwin->w_cursor.col)\n\tstartcol = curwin->w_cursor.col;\n compl_col = startcol;\n compl_length = (int)curwin->w_cursor.col - (int)startcol;\n // compl_pattern doesn't need to be set\n compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);\n if (p_ic)\n\tflags |= CP_ICASE;\n if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,\n\t\t\t\t\t -1, NULL, NULL, NULL, 0,\n\t\t\t\t\t flags | CP_FAST, FALSE) != OK)\n\treturn;", " ctrl_x_mode = CTRL_X_EVAL;", " ins_compl_add_list(list);\n compl_matches = ins_compl_make_cyclic();\n compl_started = TRUE;\n compl_used_match = TRUE;\n compl_cont_status = 0;", " compl_curr_match = compl_first_match;\n if (compl_no_insert || compl_no_select)\n {\n\tins_complete(K_DOWN, FALSE);\n\tif (compl_no_select)\n\t // Down/Up has no real effect.\n\t ins_complete(K_UP, FALSE);\n }\n else\n\tins_complete(Ctrl_N, FALSE);\n compl_enter_selects = compl_no_insert;", " // Lazily show the popup menu, unless we got interrupted.\n if (!compl_interrupted)\n\tshow_pum(save_w_wrow, save_w_leftcol);\n may_trigger_modechanged();\n out_flush();\n}", "/*\n * \"complete()\" function\n */\n void\nf_complete(typval_T *argvars, typval_T *rettv UNUSED)\n{\n int\t startcol;", " if (in_vim9script()\n\t && (check_for_number_arg(argvars, 0) == FAIL\n\t\t|| check_for_list_arg(argvars, 1) == FAIL))\n\treturn;", " if ((State & MODE_INSERT) == 0)\n {\n\temsg(_(e_complete_can_only_be_used_in_insert_mode));\n\treturn;\n }", " // Check for undo allowed here, because if something was already inserted\n // the line was already saved for undo and this check isn't done.\n if (!undo_allowed())\n\treturn;", " if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)\n\temsg(_(e_invalid_argument));\n else\n {\n\tstartcol = (int)tv_get_number_chk(&argvars[0], NULL);\n\tif (startcol > 0)\n\t set_completion(startcol - 1, argvars[1].vval.v_list);\n }\n}", "/*\n * \"complete_add()\" function\n */\n void\nf_complete_add(typval_T *argvars, typval_T *rettv)\n{\n if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)\n\treturn;", " rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);\n}", "/*\n * \"complete_check()\" function\n */\n void\nf_complete_check(typval_T *argvars UNUSED, typval_T *rettv)\n{\n int\t\tsaved = RedrawingDisabled;", " RedrawingDisabled = 0;\n ins_compl_check_keys(0, TRUE);\n rettv->vval.v_number = ins_compl_interrupted();\n RedrawingDisabled = saved;\n}", "/*\n * Return Insert completion mode name string\n */\n static char_u *\nins_compl_mode(void)\n{\n if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)\n\treturn (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];", " return (char_u *)\"\";\n}", "/*\n * Assign the sequence number to all the completion matches which don't have\n * one assigned yet.\n */\n static void\nins_compl_update_sequence_numbers()\n{\n int\t\tnumber = 0;\n compl_T\t*match;", " if (compl_dir_forward())\n {\n\t// search backwards for the first valid (!= -1) number.\n\t// This should normally succeed already at the first loop\n\t// cycle, so it's fast!\n\tfor (match = compl_curr_match->cp_prev; match != NULL\n\t\t&& !is_first_match(match); match = match->cp_prev)\n\t if (match->cp_number != -1)\n\t {\n\t\tnumber = match->cp_number;\n\t\tbreak;\n\t }\n\tif (match != NULL)\n\t // go up and assign all numbers which are not assigned\n\t // yet\n\t for (match = match->cp_next;\n\t\t match != NULL && match->cp_number == -1;\n\t\t\t\t\t match = match->cp_next)\n\t\tmatch->cp_number = ++number;\n }\n else // BACKWARD\n {\n\t// search forwards (upwards) for the first valid (!= -1)\n\t// number. This should normally succeed already at the\n\t// first loop cycle, so it's fast!\n\tfor (match = compl_curr_match->cp_next; match != NULL\n\t\t&& !is_first_match(match); match = match->cp_next)\n\t if (match->cp_number != -1)\n\t {\n\t\tnumber = match->cp_number;\n\t\tbreak;\n\t }\n\tif (match != NULL)\n\t // go down and assign all numbers which are not\n\t // assigned yet\n\t for (match = match->cp_prev; match\n\t\t && match->cp_number == -1;\n\t\t\t\t\t match = match->cp_prev)\n\t\tmatch->cp_number = ++number;\n }\n}", "/*\n * Get complete information\n */\n static void\nget_complete_info(list_T *what_list, dict_T *retdict)\n{\n int\t\tret = OK;\n listitem_T\t*item;\n#define CI_WHAT_MODE\t\t0x01\n#define CI_WHAT_PUM_VISIBLE\t0x02\n#define CI_WHAT_ITEMS\t\t0x04\n#define CI_WHAT_SELECTED\t0x08\n#define CI_WHAT_INSERTED\t0x10\n#define CI_WHAT_ALL\t\t0xff\n int\t\twhat_flag;", " if (what_list == NULL)\n\twhat_flag = CI_WHAT_ALL;\n else\n {\n\twhat_flag = 0;\n\tCHECK_LIST_MATERIALIZE(what_list);\n\tFOR_ALL_LIST_ITEMS(what_list, item)\n\t{\n\t char_u *what = tv_get_string(&item->li_tv);", "\t if (STRCMP(what, \"mode\") == 0)\n\t\twhat_flag |= CI_WHAT_MODE;\n\t else if (STRCMP(what, \"pum_visible\") == 0)\n\t\twhat_flag |= CI_WHAT_PUM_VISIBLE;\n\t else if (STRCMP(what, \"items\") == 0)\n\t\twhat_flag |= CI_WHAT_ITEMS;\n\t else if (STRCMP(what, \"selected\") == 0)\n\t\twhat_flag |= CI_WHAT_SELECTED;\n\t else if (STRCMP(what, \"inserted\") == 0)\n\t\twhat_flag |= CI_WHAT_INSERTED;\n\t}\n }", " if (ret == OK && (what_flag & CI_WHAT_MODE))\n\tret = dict_add_string(retdict, \"mode\", ins_compl_mode());", " if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))\n\tret = dict_add_number(retdict, \"pum_visible\", pum_visible());", " if (ret == OK && (what_flag & CI_WHAT_ITEMS))\n {\n\tlist_T\t *li;\n\tdict_T\t *di;\n\tcompl_T *match;", "\tli = list_alloc();\n\tif (li == NULL)\n\t return;\n\tret = dict_add_list(retdict, \"items\", li);\n\tif (ret == OK && compl_first_match != NULL)\n\t{\n\t match = compl_first_match;\n\t do\n\t {\n\t\tif (!match_at_original_text(match))\n\t\t{\n\t\t di = dict_alloc();\n\t\t if (di == NULL)\n\t\t\treturn;\n\t\t ret = list_append_dict(li, di);\n\t\t if (ret != OK)\n\t\t\treturn;\n\t\t dict_add_string(di, \"word\", match->cp_str);\n\t\t dict_add_string(di, \"abbr\", match->cp_text[CPT_ABBR]);\n\t\t dict_add_string(di, \"menu\", match->cp_text[CPT_MENU]);\n\t\t dict_add_string(di, \"kind\", match->cp_text[CPT_KIND]);\n\t\t dict_add_string(di, \"info\", match->cp_text[CPT_INFO]);\n\t\t if (match->cp_user_data.v_type == VAR_UNKNOWN)\n\t\t\t// Add an empty string for backwards compatibility\n\t\t\tdict_add_string(di, \"user_data\", (char_u *)\"\");\n\t\t else\n\t\t\tdict_add_tv(di, \"user_data\", &match->cp_user_data);\n\t\t}\n\t\tmatch = match->cp_next;\n\t }\n\t while (match != NULL && !is_first_match(match));\n\t}\n }", " if (ret == OK && (what_flag & CI_WHAT_SELECTED))\n {\n\tif (compl_curr_match != NULL && compl_curr_match->cp_number == -1)\n\t ins_compl_update_sequence_numbers();\n\tret = dict_add_number(retdict, \"selected\", compl_curr_match != NULL\n\t\t\t\t ? compl_curr_match->cp_number - 1 : -1);\n }", " // TODO\n // if (ret == OK && (what_flag & CI_WHAT_INSERTED))\n}", "/*\n * \"complete_info()\" function\n */\n void\nf_complete_info(typval_T *argvars, typval_T *rettv)\n{\n list_T\t*what_list = NULL;", " if (rettv_dict_alloc(rettv) == FAIL)\n\treturn;", " if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)\n\treturn;", " if (argvars[0].v_type != VAR_UNKNOWN)\n {\n\tif (argvars[0].v_type != VAR_LIST)\n\t{\n\t emsg(_(e_list_required));\n\t return;\n\t}\n\twhat_list = argvars[0].vval.v_list;\n }\n get_complete_info(what_list, rettv->vval.v_dict);\n}\n#endif", "/*\n * Returns TRUE when using a user-defined function for thesaurus completion.\n */\n static int\nthesaurus_func_complete(int type UNUSED)\n{\n#ifdef FEAT_COMPL_FUNC\n return type == CTRL_X_THESAURUS\n\t\t&& (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);\n#else\n return FALSE;\n#endif\n}", "/*\n * Return value of process_next_cpt_value()\n */\nenum\n{\n INS_COMPL_CPT_OK = 1,\n INS_COMPL_CPT_CONT,\n INS_COMPL_CPT_END\n};", "/*\n * state information used for getting the next set of insert completion\n * matches.\n */\ntypedef struct\n{\n char_u\t*e_cpt;\t\t\t// current entry in 'complete'\n buf_T\t*ins_buf;\t\t// buffer being scanned\n pos_T\t*cur_match_pos;\t\t\t// current match position\n pos_T\tprev_match_pos;\t\t// previous match position\n int\t\tset_match_pos;\t\t// save first_match_pos/last_match_pos\n pos_T\tfirst_match_pos;\t// first match position\n pos_T\tlast_match_pos;\t\t// last match position\n int\t\tfound_all;\t\t// found all matches of a certain type.\n char_u\t*dict;\t\t\t// dictionary file to search\n int\t\tdict_f;\t\t\t// \"dict\" is an exact file name or not\n} ins_compl_next_state_T;", "/*\n * Process the next 'complete' option value in st->e_cpt.\n *\n * If successful, the arguments are set as below:\n * st->cpt - pointer to the next option value in \"st->cpt\"\n * compl_type_arg - type of insert mode completion to use\n * st->found_all - all matches of this type are found\n * st->ins_buf - search for completions in this buffer\n * st->first_match_pos - position of the first completion match\n * st->last_match_pos - position of the last completion match\n * st->set_match_pos - TRUE if the first match position should be saved to\n *\t\t\t avoid loops after the search wraps around.\n * st->dict - name of the dictionary or thesaurus file to search\n * st->dict_f - flag specifying whether \"dict\" is an exact file name or not\n *\n * Returns INS_COMPL_CPT_OK if the next value is processed successfully.\n * Returns INS_COMPL_CPT_CONT to skip the current completion source matching\n * the \"st->e_cpt\" option value and process the next matching source.\n * Returns INS_COMPL_CPT_END if all the values in \"st->e_cpt\" are processed.\n */\n static int\nprocess_next_cpt_value(\n\tins_compl_next_state_T *st,\n\tint\t\t*compl_type_arg,\n\tpos_T\t\t*start_match_pos)\n{\n int\t compl_type = -1;\n int\t status = INS_COMPL_CPT_OK;", " st->found_all = FALSE;", " while (*st->e_cpt == ',' || *st->e_cpt == ' ')\n\tst->e_cpt++;", " if (*st->e_cpt == '.' && !curbuf->b_scanned)\n {\n\tst->ins_buf = curbuf;\n\tst->first_match_pos = *start_match_pos;\n\t// Move the cursor back one character so that ^N can match the\n\t// word immediately after the cursor.\n\tif (ctrl_x_mode_normal() && dec(&st->first_match_pos) < 0)\n\t{\n\t // Move the cursor to after the last character in the\n\t // buffer, so that word at start of buffer is found\n\t // correctly.\n\t st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;\n\t st->first_match_pos.col =\n\t\t(colnr_T)STRLEN(ml_get(st->first_match_pos.lnum));\n\t}\n\tst->last_match_pos = st->first_match_pos;\n\tcompl_type = 0;", "\t// Remember the first match so that the loop stops when we\n\t// wrap and come back there a second time.\n\tst->set_match_pos = TRUE;\n }\n else if (vim_strchr((char_u *)\"buwU\", *st->e_cpt) != NULL\n\t && (st->ins_buf = ins_compl_next_buf(st->ins_buf, *st->e_cpt)) != curbuf)\n {\n\t// Scan a buffer, but not the current one.\n\tif (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer\n\t{\n\t compl_started = TRUE;\n\t st->first_match_pos.col = st->last_match_pos.col = 0;\n\t st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;\n\t st->last_match_pos.lnum = 0;\n\t compl_type = 0;\n\t}\n\telse\t// unloaded buffer, scan like dictionary\n\t{\n\t st->found_all = TRUE;\n\t if (st->ins_buf->b_fname == NULL)\n\t {\n\t\tstatus = INS_COMPL_CPT_CONT;\n\t\tgoto done;\n\t }\n\t compl_type = CTRL_X_DICTIONARY;\n\t st->dict = st->ins_buf->b_fname;\n\t st->dict_f = DICT_EXACT;\n\t}\n\tmsg_hist_off = TRUE;\t// reset in msg_trunc_attr()\n\tvim_snprintf((char *)IObuff, IOSIZE, _(\"Scanning: %s\"),\n\t\tst->ins_buf->b_fname == NULL\n\t\t ? buf_spname(st->ins_buf)\n\t\t : st->ins_buf->b_sfname == NULL\n\t\t\t? st->ins_buf->b_fname\n\t\t\t: st->ins_buf->b_sfname);\n\t(void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));\n }\n else if (*st->e_cpt == NUL)\n\tstatus = INS_COMPL_CPT_END;\n else\n {\n\tif (ctrl_x_mode_line_or_eval())\n\t compl_type = -1;\n\telse if (*st->e_cpt == 'k' || *st->e_cpt == 's')\n\t{\n\t if (*st->e_cpt == 'k')\n\t\tcompl_type = CTRL_X_DICTIONARY;\n\t else\n\t\tcompl_type = CTRL_X_THESAURUS;\n\t if (*++st->e_cpt != ',' && *st->e_cpt != NUL)\n\t {\n\t\tst->dict = st->e_cpt;\n\t\tst->dict_f = DICT_FIRST;\n\t }\n\t}\n#ifdef FEAT_FIND_ID\n\telse if (*st->e_cpt == 'i')\n\t compl_type = CTRL_X_PATH_PATTERNS;\n\telse if (*st->e_cpt == 'd')\n\t compl_type = CTRL_X_PATH_DEFINES;\n#endif\n\telse if (*st->e_cpt == ']' || *st->e_cpt == 't')\n\t{\n\t msg_hist_off = TRUE;\t// reset in msg_trunc_attr()\n\t compl_type = CTRL_X_TAGS;\n\t vim_snprintf((char *)IObuff, IOSIZE, _(\"Scanning tags.\"));\n\t (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));\n\t}\n\telse\n\t compl_type = -1;", "\t// in any case e_cpt is advanced to the next entry\n\t(void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, \",\");", "\tst->found_all = TRUE;\n\tif (compl_type == -1)\n\t status = INS_COMPL_CPT_CONT;\n }", "done:\n *compl_type_arg = compl_type;\n return status;\n}", "#ifdef FEAT_FIND_ID\n/*\n * Get the next set of identifiers or defines matching \"compl_pattern\" in\n * included files.\n */\n static void\nget_next_include_file_completion(int compl_type)\n{\n find_pattern_in_path(compl_pattern, compl_direction,\n\t (int)STRLEN(compl_pattern), FALSE, FALSE,\n\t (compl_type == CTRL_X_PATH_DEFINES\n\t && !(compl_cont_status & CONT_SOL))\n\t ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,\n\t (linenr_T)1, (linenr_T)MAXLNUM);\n}\n#endif", "/*\n * Get the next set of words matching \"compl_pattern\" in dictionary or\n * thesaurus files.\n */\n static void\nget_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)\n{\n#ifdef FEAT_COMPL_FUNC\n if (thesaurus_func_complete(compl_type))\n\texpand_by_function(compl_type, compl_pattern);\n else\n#endif\n\tins_compl_dictionaries(\n\t\tdict != NULL ? dict\n\t\t: (compl_type == CTRL_X_THESAURUS\n\t\t ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)\n\t\t : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),\n\t\tcompl_pattern,\n\t\tdict != NULL ? dict_f : 0,\n\t\tcompl_type == CTRL_X_THESAURUS);\n}", "/*\n * Get the next set of tag names matching \"compl_pattern\".\n */\n static void\nget_next_tag_completion(void)\n{\n int\t\tsave_p_ic;\n char_u\t**matches;\n int\t\tnum_matches;", " // set p_ic according to p_ic, p_scs and pat for find_tags().\n save_p_ic = p_ic;\n p_ic = ignorecase(compl_pattern);", " // Find up to TAG_MANY matches. Avoids that an enormous number\n // of matches is found when compl_pattern is empty\n g_tag_at_cursor = TRUE;\n if (find_tags(compl_pattern, &num_matches, &matches,\n\t\tTAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP\n\t\t| (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),\n\t\tTAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)\n\tins_compl_add_matches(num_matches, matches, p_ic);\n g_tag_at_cursor = FALSE;\n p_ic = save_p_ic;\n}", "/*\n * Get the next set of filename matching \"compl_pattern\".\n */\n static void\nget_next_filename_completion(void)\n{\n char_u\t**matches;\n int\t\tnum_matches;", " if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,\n\t\tEW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)\n\treturn;", " // May change home directory back to \"~\".\n tilde_replace(compl_pattern, num_matches, matches);\n#ifdef BACKSLASH_IN_FILENAME\n if (curbuf->b_p_csl[0] != NUL)\n {\n\tint\t i;", "\tfor (i = 0; i < num_matches; ++i)\n\t{\n\t char_u\t*ptr = matches[i];", "\t while (*ptr != NUL)\n\t {\n\t\tif (curbuf->b_p_csl[0] == 's' && *ptr == '\\\\')\n\t\t *ptr = '/';\n\t\telse if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')\n\t\t *ptr = '\\\\';\n\t\tptr += (*mb_ptr2len)(ptr);\n\t }\n\t}\n }\n#endif\n ins_compl_add_matches(num_matches, matches, p_fic || p_wic);\n}", "/*\n * Get the next set of command-line completions matching \"compl_pattern\".\n */\n static void\nget_next_cmdline_completion()\n{\n char_u\t**matches;\n int\t\tnum_matches;", " if (expand_cmdline(&compl_xp, compl_pattern,\n\t\t(int)STRLEN(compl_pattern),\n\t\t&num_matches, &matches) == EXPAND_OK)\n\tins_compl_add_matches(num_matches, matches, FALSE);\n}", "/*\n * Get the next set of spell suggestions matching \"compl_pattern\".\n */\n static void\nget_next_spell_completion(linenr_T lnum UNUSED)\n{\n#ifdef FEAT_SPELL\n char_u\t**matches;\n int\t\tnum_matches;", " num_matches = expand_spelling(lnum, compl_pattern, &matches);\n if (num_matches > 0)\n\tins_compl_add_matches(num_matches, matches, p_ic);\n else\n\tvim_free(matches);\n#endif\n}", "/*\n * Return the next word or line from buffer \"ins_buf\" at position\n * \"cur_match_pos\" for completion. The length of the match is set in \"len\".\n */\n static char_u *\nins_comp_get_next_word_or_line(\n\tbuf_T\t*ins_buf,\t\t// buffer being scanned\n\tpos_T\t*cur_match_pos,\t\t// current match position\n\tint\t*match_len,\n\tint\t*cont_s_ipos)\t\t// next ^X<> will set initial_pos\n{\n char_u\t*ptr;\n int\t\tlen;", " *match_len = 0;\n ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +\n\tcur_match_pos->col;\n if (ctrl_x_mode_line_or_eval())\n {\n\tif (compl_status_adding())\n\t{\n\t if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)\n\t\treturn NULL;\n\t ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);\n\t if (!p_paste)\n\t\tptr = skipwhite(ptr);\n\t}\n\tlen = (int)STRLEN(ptr);\n }\n else\n {\n\tchar_u\t*tmp_ptr = ptr;", "\tif (compl_status_adding())\n\t{\n\t tmp_ptr += compl_length;\n\t // Skip if already inside a word.\n\t if (vim_iswordp(tmp_ptr))\n\t\treturn NULL;\n\t // Find start of next word.\n\t tmp_ptr = find_word_start(tmp_ptr);\n\t}\n\t// Find end of this word.\n\ttmp_ptr = find_word_end(tmp_ptr);\n\tlen = (int)(tmp_ptr - ptr);", "\tif (compl_status_adding() && len == compl_length)\n\t{\n\t if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)\n\t {\n\t\t// Try next line, if any. the new word will be\n\t\t// \"join\" as if the normal command \"J\" was used.\n\t\t// IOSIZE is always greater than\n\t\t// compl_length, so the next STRNCPY always\n\t\t// works -- Acevedo\n\t\tSTRNCPY(IObuff, ptr, len);\n\t\tptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);\n\t\ttmp_ptr = ptr = skipwhite(ptr);\n\t\t// Find start of next word.\n\t\ttmp_ptr = find_word_start(tmp_ptr);\n\t\t// Find end of next word.\n\t\ttmp_ptr = find_word_end(tmp_ptr);\n\t\tif (tmp_ptr > ptr)\n\t\t{\n\t\t if (*ptr != ')' && IObuff[len - 1] != TAB)\n\t\t {\n\t\t\tif (IObuff[len - 1] != ' ')\n\t\t\t IObuff[len++] = ' ';\n\t\t\t// IObuf =~ \"\\k.* \", thus len >= 2\n\t\t\tif (p_js\n\t\t\t\t&& (IObuff[len - 2] == '.'\n\t\t\t\t || (vim_strchr(p_cpo, CPO_JOINSP)\n\t\t\t\t\t== NULL\n\t\t\t\t\t&& (IObuff[len - 2] == '?'\n\t\t\t\t\t || IObuff[len - 2] == '!'))))\n\t\t\t IObuff[len++] = ' ';\n\t\t }\n\t\t // copy as much as possible of the new word\n\t\t if (tmp_ptr - ptr >= IOSIZE - len)\n\t\t\ttmp_ptr = ptr + IOSIZE - len - 1;\n\t\t STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);\n\t\t len += (int)(tmp_ptr - ptr);\n\t\t *cont_s_ipos = TRUE;\n\t\t}\n\t\tIObuff[len] = NUL;\n\t\tptr = IObuff;\n\t }\n\t if (len == compl_length)\n\t\treturn NULL;\n\t}\n }", " *match_len = len;\n return ptr;\n}", "/*\n * Get the next set of words matching \"compl_pattern\" for default completion(s)\n * (normal ^P/^N and ^X^L).\n * Search for \"compl_pattern\" in the buffer \"st->ins_buf\" starting from the\n * position \"st->start_pos\" in the \"compl_direction\" direction. If\n * \"st->set_match_pos\" is TRUE, then set the \"st->first_match_pos\" and\n * \"st->last_match_pos\".\n * Returns OK if a new next match is found, otherwise returns FAIL.\n */\n static int\nget_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)\n{\n int\t\tfound_new_match = FAIL;\n int\t\tsave_p_scs;\n int\t\tsave_p_ws;\n int\t\tlooped_around = FALSE;\n char_u\t*ptr;\n int\t\tlen;", " // If 'infercase' is set, don't use 'smartcase' here\n save_p_scs = p_scs;\n if (st->ins_buf->b_p_inf)\n\tp_scs = FALSE;", " //\tBuffers other than curbuf are scanned from the beginning or the\n //\tend but never from the middle, thus setting nowrapscan in this\n //\tbuffer is a good idea, on the other hand, we always set\n //\twrapscan for curbuf to avoid missing matches -- Acevedo,Webb\n save_p_ws = p_ws;\n if (st->ins_buf != curbuf)\n\tp_ws = FALSE;\n else if (*st->e_cpt == '.')\n\tp_ws = TRUE;\n looped_around = FALSE;\n for (;;)\n {\n\tint\tcont_s_ipos = FALSE;", "\t++msg_silent; // Don't want messages for wrapscan.", "\t// ctrl_x_mode_line_or_eval() || word-wise search that\n\t// has added a word that was at the beginning of the line\n\tif (ctrl_x_mode_line_or_eval() || (compl_cont_status & CONT_SOL))\n\t found_new_match = search_for_exact_line(st->ins_buf,\n\t\t\t st->cur_match_pos, compl_direction, compl_pattern);\n\telse\n\t found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,\n\t\t\t\tNULL, compl_direction, compl_pattern, 1L,\n\t\t\t\tSEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);\n\t--msg_silent;\n\tif (!compl_started || st->set_match_pos)\n\t{\n\t // set \"compl_started\" even on fail\n\t compl_started = TRUE;\n\t st->first_match_pos = *st->cur_match_pos;\n\t st->last_match_pos = *st->cur_match_pos;\n\t st->set_match_pos = FALSE;\n\t}\n\telse if (st->first_match_pos.lnum == st->last_match_pos.lnum\n\t\t&& st->first_match_pos.col == st->last_match_pos.col)\n\t{\n\t found_new_match = FAIL;\n\t}\n\telse if (compl_dir_forward()\n\t\t&& (st->prev_match_pos.lnum > st->cur_match_pos->lnum\n\t\t || (st->prev_match_pos.lnum == st->cur_match_pos->lnum\n\t\t\t&& st->prev_match_pos.col >= st->cur_match_pos->col)))\n\t{\n\t if (looped_around)\n\t\tfound_new_match = FAIL;\n\t else\n\t\tlooped_around = TRUE;\n\t}\n\telse if (!compl_dir_forward()\n\t\t&& (st->prev_match_pos.lnum < st->cur_match_pos->lnum\n\t\t || (st->prev_match_pos.lnum == st->cur_match_pos->lnum\n\t\t\t&& st->prev_match_pos.col <= st->cur_match_pos->col)))\n\t{\n\t if (looped_around)\n\t\tfound_new_match = FAIL;\n\t else\n\t\tlooped_around = TRUE;\n\t}\n\tst->prev_match_pos = *st->cur_match_pos;\n\tif (found_new_match == FAIL)\n\t break;", "\t// when ADDING, the text before the cursor matches, skip it\n\tif (compl_status_adding() && st->ins_buf == curbuf\n\t\t&& start_pos->lnum == st->cur_match_pos->lnum\n\t\t&& start_pos->col == st->cur_match_pos->col)\n\t continue;", "\tptr = ins_comp_get_next_word_or_line(st->ins_buf, st->cur_match_pos,\n\t\t\t\t\t\t\t&len, &cont_s_ipos);\n\tif (ptr == NULL)\n\t continue;", "\tif (ins_compl_add_infercase(ptr, len, p_ic,\n\t\t st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,\n\t\t 0, cont_s_ipos) != NOTDONE)\n\t{\n\t found_new_match = OK;\n\t break;\n\t}\n }\n p_scs = save_p_scs;\n p_ws = save_p_ws;", " return found_new_match;\n}", "/*\n * get the next set of completion matches for \"type\".\n * Returns TRUE if a new match is found. Otherwise returns FALSE.\n */\n static int\nget_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)\n{\n int\tfound_new_match = FALSE;", " switch (type)\n {\n\tcase -1:\n\t break;\n#ifdef FEAT_FIND_ID\n\tcase CTRL_X_PATH_PATTERNS:\n\tcase CTRL_X_PATH_DEFINES:\n\t get_next_include_file_completion(type);\n\t break;\n#endif", "\tcase CTRL_X_DICTIONARY:\n\tcase CTRL_X_THESAURUS:\n\t get_next_dict_tsr_completion(type, st->dict, st->dict_f);\n\t st->dict = NULL;\n\t break;", "\tcase CTRL_X_TAGS:\n\t get_next_tag_completion();\n\t break;", "\tcase CTRL_X_FILES:\n\t get_next_filename_completion();\n\t break;", "\tcase CTRL_X_CMDLINE:\n\tcase CTRL_X_CMDLINE_CTRL_X:\n\t get_next_cmdline_completion();\n\t break;", "#ifdef FEAT_COMPL_FUNC\n\tcase CTRL_X_FUNCTION:\n\tcase CTRL_X_OMNI:\n\t expand_by_function(type, compl_pattern);\n\t break;\n#endif", "\tcase CTRL_X_SPELL:\n\t get_next_spell_completion(st->first_match_pos.lnum);\n\t break;", "\tdefault:\t// normal ^P/^N and ^X^L\n\t found_new_match = get_next_default_completion(st, ini);\n\t if (found_new_match == FAIL && st->ins_buf == curbuf)\n\t\tst->found_all = TRUE;\n }", " // check if compl_curr_match has changed, (e.g. other type of\n // expansion added something)\n if (type != 0 && compl_curr_match != compl_old_match)\n\tfound_new_match = OK;", " return found_new_match;\n}", "/*\n * Get the next expansion(s), using \"compl_pattern\".\n * The search starts at position \"ini\" in curbuf and in the direction\n * compl_direction.\n * When \"compl_started\" is FALSE start at that position, otherwise continue\n * where we stopped searching before.\n * This may return before finding all the matches.\n * Return the total number of matches or -1 if still unknown -- Acevedo\n */\n static int\nins_compl_get_exp(pos_T *ini)\n{\n static ins_compl_next_state_T st;\n int\t\ti;\n int\t\tfound_new_match;\n int\t\ttype = ctrl_x_mode;", " if (!compl_started)\n {\n\tFOR_ALL_BUFFERS(st.ins_buf)\n\t st.ins_buf->b_scanned = 0;\n\tst.found_all = FALSE;\n\tst.ins_buf = curbuf;\n\tst.e_cpt = (compl_cont_status & CONT_LOCAL)\n\t\t\t\t\t ? (char_u *)\".\" : curbuf->b_p_cpt;\n\tst.last_match_pos = st.first_match_pos = *ini;\n }\n else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))\n\tst.ins_buf = curbuf; // In case the buffer was wiped out.", " compl_old_match = compl_curr_match;\t// remember the last current match\n st.cur_match_pos = (compl_dir_forward())\n\t\t\t\t? &st.last_match_pos : &st.first_match_pos;", " // For ^N/^P loop over all the flags/windows/buffers in 'complete'.\n for (;;)\n {\n\tfound_new_match = FAIL;\n\tst.set_match_pos = FALSE;", "\t// For ^N/^P pick a new entry from e_cpt if compl_started is off,\n\t// or if found_all says this entry is done. For ^X^L only use the\n\t// entries from 'complete' that look in loaded buffers.\n\tif ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())\n\t\t\t\t\t&& (!compl_started || st.found_all))\n\t{\n\t int status = process_next_cpt_value(&st, &type, ini);", "\t if (status == INS_COMPL_CPT_END)\n\t\tbreak;\n\t if (status == INS_COMPL_CPT_CONT)\n\t\tcontinue;\n\t}", "\t// If complete() was called then compl_pattern has been reset. The\n\t// following won't work then, bail out.\n\tif (compl_pattern == NULL)\n\t break;", "\t// get the next set of completion matches\n\tfound_new_match = get_next_completion_match(type, &st, ini);", "\t// break the loop for specialized modes (use 'complete' just for the\n\t// generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new\n\t// match\n\tif ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())\n\t\t\t\t\t\t|| found_new_match != FAIL)\n\t{\n\t if (got_int)\n\t\tbreak;\n\t // Fill the popup menu as soon as possible.\n\t if (type != -1)\n\t\tins_compl_check_keys(0, FALSE);", "\t if ((ctrl_x_mode_not_default()\n\t\t\t&& !ctrl_x_mode_line_or_eval()) || compl_interrupted)\n\t\tbreak;\n\t compl_started = TRUE;\n\t}\n\telse\n\t{\n\t // Mark a buffer scanned when it has been scanned completely\n\t if (type == 0 || type == CTRL_X_PATH_PATTERNS)\n\t\tst.ins_buf->b_scanned = TRUE;", "\t compl_started = FALSE;\n\t}\n }\n compl_started = TRUE;", " if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())\n\t && *st.e_cpt == NUL)\t\t// Got to end of 'complete'\n\tfound_new_match = FAIL;", " i = -1;\t\t// total of matches, unknown\n if (found_new_match == FAIL || (ctrl_x_mode_not_default()\n\t\t\t\t\t && !ctrl_x_mode_line_or_eval()))\n\ti = ins_compl_make_cyclic();", " if (compl_old_match != NULL)\n {\n\t// If several matches were added (FORWARD) or the search failed and has\n\t// just been made cyclic then we have to move compl_curr_match to the\n\t// next or previous entry (if any) -- Acevedo\n\tcompl_curr_match = compl_dir_forward() ? compl_old_match->cp_next\n\t\t\t\t\t\t : compl_old_match->cp_prev;\n\tif (compl_curr_match == NULL)\n\t compl_curr_match = compl_old_match;\n }\n may_trigger_modechanged();", " return i;\n}", "/*\n * Update \"compl_shown_match\" to the actually shown match, it may differ when\n * \"compl_leader\" is used to omit some of the matches.\n */\n static void\nins_compl_update_shown_match(void)\n{\n while (!ins_compl_equal(compl_shown_match,\n\t\tcompl_leader, (int)STRLEN(compl_leader))\n\t && compl_shown_match->cp_next != NULL\n\t && !is_first_match(compl_shown_match->cp_next))\n\tcompl_shown_match = compl_shown_match->cp_next;", " // If we didn't find it searching forward, and compl_shows_dir is\n // backward, find the last match.\n if (compl_shows_dir_backward()\n\t && !ins_compl_equal(compl_shown_match,\n\t\tcompl_leader, (int)STRLEN(compl_leader))\n\t && (compl_shown_match->cp_next == NULL\n\t\t|| is_first_match(compl_shown_match->cp_next)))\n {\n\twhile (!ins_compl_equal(compl_shown_match,\n\t\t compl_leader, (int)STRLEN(compl_leader))\n\t\t&& compl_shown_match->cp_prev != NULL\n\t\t&& !is_first_match(compl_shown_match->cp_prev))\n\t compl_shown_match = compl_shown_match->cp_prev;\n }\n}", "/*\n * Delete the old text being completed.\n */\n void\nins_compl_delete(void)\n{\n int\t col;", " // In insert mode: Delete the typed part.\n // In replace mode: Put the old characters back, if any.\n col = compl_col + (compl_status_adding() ? compl_length : 0);\n if ((int)curwin->w_cursor.col > col)\n {\n\tif (stop_arrow() == FAIL)\n\t return;\n\tbackspace_until_column(col);\n }", " // TODO: is this sufficient for redrawing? Redrawing everything causes\n // flicker, thus we can't do that.\n changed_cline_bef_curs();\n#ifdef FEAT_EVAL\n // clear v:completed_item\n set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));\n#endif\n}", "/*\n * Insert the new text being completed.\n * \"in_compl_func\" is TRUE when called from complete_check().\n */\n void\nins_compl_insert(int in_compl_func)\n{\n int compl_len = get_compl_len();", " // Make sure we don't go over the end of the string, this can happen with\n // illegal bytes.\n if (compl_len < (int)STRLEN(compl_shown_match->cp_str))\n\tins_bytes(compl_shown_match->cp_str + compl_len);\n if (match_at_original_text(compl_shown_match))\n\tcompl_used_match = FALSE;\n else\n\tcompl_used_match = TRUE;\n#ifdef FEAT_EVAL\n {\n\tdict_T *dict = ins_compl_dict_alloc(compl_shown_match);", "\tset_vim_var_dict(VV_COMPLETED_ITEM, dict);\n }\n#endif\n if (!in_compl_func)\n\tcompl_curr_match = compl_shown_match;\n}", "/*\n * show the file name for the completion match (if any). Truncate the file\n * name to avoid a wait for return.\n */\n static void\nins_compl_show_filename(void)\n{\n char\t*lead = _(\"match in file\");\n int\t\tspace = sc_col - vim_strsize((char_u *)lead) - 2;\n char_u\t*s;\n char_u\t*e;", " if (space <= 0)\n\treturn;", " // We need the tail that fits. With double-byte encoding going\n // back from the end is very slow, thus go from the start and keep\n // the text that fits in \"space\" between \"s\" and \"e\".\n for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))\n {\n\tspace -= ptr2cells(e);\n\twhile (space < 0)\n\t{\n\t space += ptr2cells(s);\n\t MB_PTR_ADV(s);\n\t}\n }\n msg_hist_off = TRUE;\n vim_snprintf((char *)IObuff, IOSIZE, \"%s %s%s\", lead,\n\t s > compl_shown_match->cp_fname ? \"<\" : \"\", s);\n msg((char *)IObuff);\n msg_hist_off = FALSE;\n redraw_cmdline = FALSE;\t // don't overwrite!\n}", "/*\n * Find the next set of matches for completion. Repeat the completion \"todo\"\n * times. The number of matches found is returned in 'num_matches'.\n *\n * If \"allow_get_expansion\" is TRUE, then ins_compl_get_exp() may be called to\n * get more completions. If it is FALSE, then do nothing when there are no more\n * completions in the given direction.\n *\n * If \"advance\" is TRUE, then completion will move to the first match.\n * Otherwise, the original text will be shown.\n *\n * Returns OK on success and -1 if the number of matches are unknown.\n */\n static int\nfind_next_completion_match(\n\tint\tallow_get_expansion,\n\tint\ttodo,\t\t// repeat completion this many times\n\tint\tadvance,\n\tint\t*num_matches)\n{\n int\t found_end = FALSE;\n compl_T *found_compl = NULL;", " while (--todo >= 0)\n {\n\tif (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)\n\t{\n\t compl_shown_match = compl_shown_match->cp_next;\n\t found_end = (compl_first_match != NULL\n\t\t && (is_first_match(compl_shown_match->cp_next)\n\t\t\t|| is_first_match(compl_shown_match)));\n\t}\n\telse if (compl_shows_dir_backward()\n\t\t&& compl_shown_match->cp_prev != NULL)\n\t{\n\t found_end = is_first_match(compl_shown_match);\n\t compl_shown_match = compl_shown_match->cp_prev;\n\t found_end |= is_first_match(compl_shown_match);\n\t}\n\telse\n\t{\n\t if (!allow_get_expansion)\n\t {\n\t\tif (advance)\n\t\t{\n\t\t if (compl_shows_dir_backward())\n\t\t\tcompl_pending -= todo + 1;\n\t\t else\n\t\t\tcompl_pending += todo + 1;\n\t\t}\n\t\treturn -1;\n\t }", "\t if (!compl_no_select && advance)\n\t {\n\t\tif (compl_shows_dir_backward())\n\t\t --compl_pending;\n\t\telse\n\t\t ++compl_pending;\n\t }", "\t // Find matches.\n\t *num_matches = ins_compl_get_exp(&compl_startpos);", "\t // handle any pending completions\n\t while (compl_pending != 0 && compl_direction == compl_shows_dir\n\t\t && advance)\n\t {\n\t\tif (compl_pending > 0 && compl_shown_match->cp_next != NULL)\n\t\t{\n\t\t compl_shown_match = compl_shown_match->cp_next;\n\t\t --compl_pending;\n\t\t}\n\t\tif (compl_pending < 0 && compl_shown_match->cp_prev != NULL)\n\t\t{\n\t\t compl_shown_match = compl_shown_match->cp_prev;\n\t\t ++compl_pending;\n\t\t}\n\t\telse\n\t\t break;\n\t }\n\t found_end = FALSE;\n\t}\n\tif (!match_at_original_text(compl_shown_match)\n\t\t&& compl_leader != NULL\n\t\t&& !ins_compl_equal(compl_shown_match,\n\t\t compl_leader, (int)STRLEN(compl_leader)))\n\t ++todo;\n\telse\n\t // Remember a matching item.\n\t found_compl = compl_shown_match;", "\t// Stop at the end of the list when we found a usable match.\n\tif (found_end)\n\t{\n\t if (found_compl != NULL)\n\t {\n\t\tcompl_shown_match = found_compl;\n\t\tbreak;\n\t }\n\t todo = 1;\t // use first usable match after wrapping around\n\t}\n }", " return OK;\n}", "/*\n * Fill in the next completion in the current direction.\n * If \"allow_get_expansion\" is TRUE, then we may call ins_compl_get_exp() to\n * get more completions. If it is FALSE, then we just do nothing when there\n * are no more completions in a given direction. The latter case is used when\n * we are still in the middle of finding completions, to allow browsing\n * through the ones found so far.\n * Return the total number of matches, or -1 if still unknown -- webb.\n *\n * compl_curr_match is currently being used by ins_compl_get_exp(), so we use\n * compl_shown_match here.\n *\n * Note that this function may be called recursively once only. First with\n * \"allow_get_expansion\" TRUE, which calls ins_compl_get_exp(), which in turn\n * calls this function with \"allow_get_expansion\" FALSE.\n */\n static int\nins_compl_next(\n int\t allow_get_expansion,\n int\t count,\t\t// repeat completion this many times; should\n\t\t\t\t// be at least 1\n int\t insert_match,\t// Insert the newly selected match\n int\t in_compl_func)\t// called from complete_check()\n{\n int\t num_matches = -1;\n int\t todo = count;\n int\t advance;\n int\t started = compl_started;", " // When user complete function return -1 for findstart which is next\n // time of 'always', compl_shown_match become NULL.\n if (compl_shown_match == NULL)\n\treturn -1;", " if (compl_leader != NULL && !match_at_original_text(compl_shown_match))\n\t// Update \"compl_shown_match\" to the actually shown match\n\tins_compl_update_shown_match();", " if (allow_get_expansion && insert_match\n\t && (!(compl_get_longest || compl_restarting) || compl_used_match))\n\t// Delete old text to be replaced\n\tins_compl_delete();", " // When finding the longest common text we stick at the original text,\n // don't let CTRL-N or CTRL-P move to the first match.\n advance = count != 1 || !allow_get_expansion || !compl_get_longest;", " // When restarting the search don't insert the first match either.\n if (compl_restarting)\n {\n\tadvance = FALSE;\n\tcompl_restarting = FALSE;\n }", " // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap\n // around.\n if (find_next_completion_match(allow_get_expansion, todo, advance,\n\t\t\t\t\t\t\t&num_matches) == -1)\n\treturn -1;", " // Insert the text of the new completion, or the compl_leader.\n if (compl_no_insert && !started)\n {\n\tins_bytes(compl_orig_text + get_compl_len());\n\tcompl_used_match = FALSE;\n }\n else if (insert_match)\n {\n\tif (!compl_get_longest || compl_used_match)\n\t ins_compl_insert(in_compl_func);\n\telse\n\t ins_bytes(compl_leader + get_compl_len());\n }\n else\n\tcompl_used_match = FALSE;", " if (!allow_get_expansion)\n {\n\t// may undisplay the popup menu first\n\tins_compl_upd_pum();", "\tif (pum_enough_matches())\n\t // Will display the popup menu, don't redraw yet to avoid flicker.\n\t pum_call_update_screen();\n\telse\n\t // Not showing the popup menu yet, redraw to show the user what was\n\t // inserted.\n\t update_screen(0);", "\t// display the updated popup menu\n\tins_compl_show_pum();\n#ifdef FEAT_GUI\n\tif (gui.in_use)\n\t{\n\t // Show the cursor after the match, not after the redrawn text.\n\t setcursor();\n\t out_flush_cursor(FALSE, FALSE);\n\t}\n#endif", "\t// Delete old text to be replaced, since we're still searching and\n\t// don't want to match ourselves!\n\tins_compl_delete();\n }", " // Enter will select a match when the match wasn't inserted and the popup\n // menu is visible.\n if (compl_no_insert && !started)\n\tcompl_enter_selects = TRUE;\n else\n\tcompl_enter_selects = !insert_match && compl_match_array != NULL;", " // Show the file name for the match (if any)\n if (compl_shown_match->cp_fname != NULL)\n\tins_compl_show_filename();", " return num_matches;\n}", "/*\n * Call this while finding completions, to check whether the user has hit a key\n * that should change the currently displayed completion, or exit completion\n * mode. Also, when compl_pending is not zero, show a completion as soon as\n * possible. -- webb\n * \"frequency\" specifies out of how many calls we actually check.\n * \"in_compl_func\" is TRUE when called from complete_check(), don't set\n * compl_curr_match.\n */\n void\nins_compl_check_keys(int frequency, int in_compl_func)\n{\n static int\tcount = 0;\n int\t\tc;", " // Don't check when reading keys from a script, :normal or feedkeys().\n // That would break the test scripts. But do check for keys when called\n // from complete_check().\n if (!in_compl_func && (using_script() || ex_normal_busy))\n\treturn;", " // Only do this at regular intervals\n if (++count < frequency)\n\treturn;\n count = 0;", " // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()\n // can't do its work correctly.\n c = vpeekc_any();\n if (c != NUL)\n {\n\tif (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)\n\t{\n\t c = safe_vgetc();\t// Eat the character\n\t compl_shows_dir = ins_compl_key2dir(c);\n\t (void)ins_compl_next(FALSE, ins_compl_key2count(c),\n\t\t\t\t c != K_UP && c != K_DOWN, in_compl_func);\n\t}\n\telse\n\t{\n\t // Need to get the character to have KeyTyped set. We'll put it\n\t // back with vungetc() below. But skip K_IGNORE.\n\t c = safe_vgetc();\n\t if (c != K_IGNORE)\n\t {\n\t\t// Don't interrupt completion when the character wasn't typed,\n\t\t// e.g., when doing @q to replay keys.\n\t\tif (c != Ctrl_R && KeyTyped)\n\t\t compl_interrupted = TRUE;", "\t\tvungetc(c);\n\t }\n\t}\n }\n if (compl_pending != 0 && !got_int && !compl_no_insert)\n {\n\tint todo = compl_pending > 0 ? compl_pending : -compl_pending;", "\tcompl_pending = 0;\n\t(void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);\n }\n}", "/*\n * Decide the direction of Insert mode complete from the key typed.\n * Returns BACKWARD or FORWARD.\n */\n static int\nins_compl_key2dir(int c)\n{\n if (c == Ctrl_P || c == Ctrl_L\n\t || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)\n\treturn BACKWARD;\n return FORWARD;\n}", "/*\n * Return TRUE for keys that are used for completion only when the popup menu\n * is visible.\n */\n static int\nins_compl_pum_key(int c)\n{\n return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP\n\t\t || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN\n\t\t || c == K_UP || c == K_DOWN);\n}", "/*\n * Decide the number of completions to move forward.\n * Returns 1 for most keys, height of the popup menu for page-up/down keys.\n */\n static int\nins_compl_key2count(int c)\n{\n int\t\th;", " if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)\n {\n\th = pum_get_height();\n\tif (h > 3)\n\t h -= 2; // keep some context\n\treturn h;\n }\n return 1;\n}", "/*\n * Return TRUE if completion with \"c\" should insert the match, FALSE if only\n * to change the currently selected completion.\n */\n static int\nins_compl_use_match(int c)\n{\n switch (c)\n {\n\tcase K_UP:\n\tcase K_DOWN:\n\tcase K_PAGEDOWN:\n\tcase K_KPAGEDOWN:\n\tcase K_S_DOWN:\n\tcase K_PAGEUP:\n\tcase K_KPAGEUP:\n\tcase K_S_UP:\n\t return FALSE;\n }\n return TRUE;\n}", "/*\n * Get the pattern, column and length for normal completion (CTRL-N CTRL-P\n * completion)\n * Sets the global variables: compl_col, compl_length and compl_pattern.\n * Uses the global variables: compl_cont_status and ctrl_x_mode\n */\n static int\nget_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)\n{\n if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())\n {\n\tif (!compl_status_adding())\n\t{\n\t while (--startcol >= 0 && vim_isIDc(line[startcol]))\n\t\t;\n\t compl_col += ++startcol;\n\t compl_length = curs_col - startcol;\n\t}\n\tif (p_ic)\n\t compl_pattern = str_foldcase(line + compl_col,\n\t\t compl_length, NULL, 0);\n\telse\n\t compl_pattern = vim_strnsave(line + compl_col, compl_length);\n\tif (compl_pattern == NULL)\n\t return FAIL;\n }\n else if (compl_status_adding())\n {\n\tchar_u\t *prefix = (char_u *)\"\\\\<\";", "\t// we need up to 2 extra chars for the prefix\n\tcompl_pattern = alloc(quote_meta(NULL, line + compl_col,\n\t\t compl_length) + 2);\n\tif (compl_pattern == NULL)\n\t return FAIL;\n\tif (!vim_iswordp(line + compl_col)\n\t\t|| (compl_col > 0\n\t\t && (vim_iswordp(mb_prevptr(line, line + compl_col)))))\n\t prefix = (char_u *)\"\";\n\tSTRCPY((char *)compl_pattern, prefix);\n\t(void)quote_meta(compl_pattern + STRLEN(prefix),\n\t\tline + compl_col, compl_length);\n }\n else if (--startcol < 0\n\t || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))\n {\n\t// Match any word of at least two chars\n\tcompl_pattern = vim_strsave((char_u *)\"\\\\<\\\\k\\\\k\");\n\tif (compl_pattern == NULL)\n\t return FAIL;\n\tcompl_col += curs_col;\n\tcompl_length = 0;\n }\n else\n {\n\t// Search the point of change class of multibyte character\n\t// or not a word single byte character backward.\n\tif (has_mbyte)\n\t{\n\t int base_class;\n\t int head_off;", "\t startcol -= (*mb_head_off)(line, line + startcol);\n\t base_class = mb_get_class(line + startcol);\n\t while (--startcol >= 0)\n\t {\n\t\thead_off = (*mb_head_off)(line, line + startcol);\n\t\tif (base_class != mb_get_class(line + startcol\n\t\t\t - head_off))\n\t\t break;\n\t\tstartcol -= head_off;\n\t }\n\t}\n\telse\n\t while (--startcol >= 0 && vim_iswordc(line[startcol]))\n\t\t;\n\tcompl_col += ++startcol;\n\tcompl_length = (int)curs_col - startcol;\n\tif (compl_length == 1)\n\t{\n\t // Only match word with at least two chars -- webb\n\t // there's no need to call quote_meta,\n\t // alloc(7) is enough -- Acevedo\n\t compl_pattern = alloc(7);\n\t if (compl_pattern == NULL)\n\t\treturn FAIL;\n\t STRCPY((char *)compl_pattern, \"\\\\<\");\n\t (void)quote_meta(compl_pattern + 2, line + compl_col, 1);\n\t STRCAT((char *)compl_pattern, \"\\\\k\");\n\t}\n\telse\n\t{\n\t compl_pattern = alloc(quote_meta(NULL, line + compl_col,\n\t\t\tcompl_length) + 2);\n\t if (compl_pattern == NULL)\n\t\treturn FAIL;\n\t STRCPY((char *)compl_pattern, \"\\\\<\");\n\t (void)quote_meta(compl_pattern + 2, line + compl_col,\n\t\t compl_length);\n\t}\n }", " return OK;\n}", "/*\n * Get the pattern, column and length for whole line completion or for the\n * complete() function.\n * Sets the global variables: compl_col, compl_length and compl_pattern.\n */\n static int\nget_wholeline_compl_info(char_u *line, colnr_T curs_col)\n{\n compl_col = (colnr_T)getwhitecols(line);\n compl_length = (int)curs_col - (int)compl_col;\n if (compl_length < 0)\t// cursor in indent: empty pattern\n\tcompl_length = 0;\n if (p_ic)\n\tcompl_pattern = str_foldcase(line + compl_col, compl_length,\n\t\tNULL, 0);\n else\n\tcompl_pattern = vim_strnsave(line + compl_col, compl_length);\n if (compl_pattern == NULL)\n\treturn FAIL;", " return OK;\n}", "/*\n * Get the pattern, column and length for filename completion.\n * Sets the global variables: compl_col, compl_length and compl_pattern.\n */\n static int\nget_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)\n{\n // Go back to just before the first filename character.\n if (startcol > 0)\n {\n\tchar_u\t*p = line + startcol;", "\tMB_PTR_BACK(line, p);\n\twhile (p > line && vim_isfilec(PTR2CHAR(p)))\n\t MB_PTR_BACK(line, p);\n\tif (p == line && vim_isfilec(PTR2CHAR(p)))\n\t startcol = 0;\n\telse\n\t startcol = (int)(p - line) + 1;\n }", " compl_col += startcol;\n compl_length = (int)curs_col - startcol;\n compl_pattern = addstar(line + compl_col, compl_length, EXPAND_FILES);\n if (compl_pattern == NULL)\n\treturn FAIL;", " return OK;\n}", "/*\n * Get the pattern, column and length for command-line completion.\n * Sets the global variables: compl_col, compl_length and compl_pattern.\n */\n static int\nget_cmdline_compl_info(char_u *line, colnr_T curs_col)\n{\n compl_pattern = vim_strnsave(line, curs_col);\n if (compl_pattern == NULL)\n\treturn FAIL;\n set_cmd_context(&compl_xp, compl_pattern,\n\t (int)STRLEN(compl_pattern), curs_col, FALSE);\n if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL\n\t || compl_xp.xp_context == EXPAND_NOTHING)\n\t// No completion possible, use an empty pattern to get a\n\t// \"pattern not found\" message.\n\tcompl_col = curs_col;\n else\n\tcompl_col = (int)(compl_xp.xp_pattern - compl_pattern);\n compl_length = curs_col - compl_col;", " return OK;\n}", "/*\n * Get the pattern, column and length for user defined completion ('omnifunc',\n * 'completefunc' and 'thesaurusfunc')\n * Sets the global variables: compl_col, compl_length and compl_pattern.\n * Uses the global variable: spell_bad_len\n */\n static int\nget_userdefined_compl_info(colnr_T curs_col UNUSED)\n{\n int\t\tret = FAIL;", "#ifdef FEAT_COMPL_FUNC\n // Call user defined function 'completefunc' with \"a:findstart\"\n // set to 1 to obtain the length of text to use for completion.\n char_u\t*line;\n typval_T\targs[3];\n int\t\tcol;\n char_u\t*funcname;\n pos_T\tpos;\n int\t\tsave_State = State;\n callback_T\t*cb;", " // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern\n // length as a string\n funcname = get_complete_funcname(ctrl_x_mode);\n if (*funcname == NUL)\n {\n\tsemsg(_(e_option_str_is_not_set), ctrl_x_mode_function()\n\t\t? \"completefunc\" : \"omnifunc\");\n\treturn FAIL;\n }", " args[0].v_type = VAR_NUMBER;\n args[0].vval.v_number = 1;\n args[1].v_type = VAR_STRING;\n args[1].vval.v_string = (char_u *)\"\";\n args[2].v_type = VAR_UNKNOWN;\n pos = curwin->w_cursor;\n ++textlock;\n cb = get_insert_callback(ctrl_x_mode);\n col = call_callback_retnr(cb, 2, args);\n --textlock;", " State = save_State;\n curwin->w_cursor = pos;\t// restore the cursor position\n validate_cursor();\n if (!EQUAL_POS(curwin->w_cursor, pos))\n {\n\temsg(_(e_complete_function_deleted_text));\n\treturn FAIL;\n }", " // Return value -2 means the user complete function wants to cancel the\n // complete without an error, do the same if the function did not execute\n // successfully.\n if (col == -2 || aborting())\n\treturn FAIL;\n // Return value -3 does the same as -2 and leaves CTRL-X mode.\n if (col == -3)\n {\n\tctrl_x_mode = CTRL_X_NORMAL;\n\tedit_submode = NULL;\n\tif (!shortmess(SHM_COMPLETIONMENU))\n\t msg_clr_cmdline();\n\treturn FAIL;\n }", " // Reset extended parameters of completion, when starting new\n // completion.\n compl_opt_refresh_always = FALSE;\n compl_opt_suppress_empty = FALSE;", " if (col < 0)\n\tcol = curs_col;\n compl_col = col;\n if (compl_col > curs_col)\n\tcompl_col = curs_col;", " // Setup variables for completion. Need to obtain \"line\" again,\n // it may have become invalid.\n line = ml_get(curwin->w_cursor.lnum);\n compl_length = curs_col - compl_col;\n compl_pattern = vim_strnsave(line + compl_col, compl_length);\n if (compl_pattern == NULL)\n\treturn FAIL;", " ret = OK;\n#endif", " return ret;\n}", "/*\n * Get the pattern, column and length for spell completion.\n * Sets the global variables: compl_col, compl_length and compl_pattern.\n * Uses the global variable: spell_bad_len\n */\n static int\nget_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)\n{\n int\t\tret = FAIL;\n#ifdef FEAT_SPELL\n char_u\t*line;", " if (spell_bad_len > 0)\n\tcompl_col = curs_col - spell_bad_len;\n else\n\tcompl_col = spell_word_start(startcol);\n if (compl_col >= (colnr_T)startcol)\n {\n\tcompl_length = 0;\n\tcompl_col = curs_col;\n }\n else\n {\n\tspell_expand_check_cap(compl_col);\n\tcompl_length = (int)curs_col - compl_col;\n }\n // Need to obtain \"line\" again, it may have become invalid.\n line = ml_get(curwin->w_cursor.lnum);\n compl_pattern = vim_strnsave(line + compl_col, compl_length);\n if (compl_pattern == NULL)\n\treturn FAIL;", " ret = OK;\n#endif", " return ret;\n}", "/*\n * Get the completion pattern, column and length.\n * \"startcol\" - start column number of the completion pattern/text\n * \"cur_col\" - current cursor column\n * On return, \"line_invalid\" is set to TRUE, if the current line may have\n * become invalid and needs to be fetched again.\n * Returns OK on success.\n */\n static int\ncompl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)\n{\n if (ctrl_x_mode_normal()\n\t || (ctrl_x_mode & CTRL_X_WANT_IDENT\n\t\t&& !thesaurus_func_complete(ctrl_x_mode)))\n {\n\treturn get_normal_compl_info(line, startcol, curs_col);\n }\n else if (ctrl_x_mode_line_or_eval())\n {\n\treturn get_wholeline_compl_info(line, curs_col);\n }\n else if (ctrl_x_mode_files())\n {\n\treturn get_filename_compl_info(line, startcol, curs_col);\n }\n else if (ctrl_x_mode == CTRL_X_CMDLINE)\n {\n\treturn get_cmdline_compl_info(line, curs_col);\n }\n else if (ctrl_x_mode_function() || ctrl_x_mode_omni()\n\t || thesaurus_func_complete(ctrl_x_mode))\n {\n\tif (get_userdefined_compl_info(curs_col) == FAIL)\n\t return FAIL;\n\t*line_invalid = TRUE;\t// \"line\" may have become invalid\n }\n else if (ctrl_x_mode_spell())\n {\n\tif (get_spell_compl_info(startcol, curs_col) == FAIL)\n\t return FAIL;\n\t*line_invalid = TRUE;\t// \"line\" may have become invalid\n }\n else\n {\n\tinternal_error(\"ins_complete()\");\n\treturn FAIL;\n }", " return OK;\n}", "/*\n * Continue an interrupted completion mode search in \"line\".\n *\n * If this same ctrl_x_mode has been interrupted use the text from\n * \"compl_startpos\" to the cursor as a pattern to add a new word instead of\n * expand the one before the cursor, in word-wise if \"compl_startpos\" is not in\n * the same line as the cursor then fix it (the line has been split because it\n * was longer than 'tw'). if SOL is set then skip the previous pattern, a word\n * at the beginning of the line has been inserted, we'll look for that.\n */\n static void\nins_compl_continue_search(char_u *line)\n{\n // it is a continued search\n compl_cont_status &= ~CONT_INTRPT;\t// remove INTRPT\n if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()\n\t\t\t\t\t\t|| ctrl_x_mode_path_defines())\n {\n\tif (compl_startpos.lnum != curwin->w_cursor.lnum)\n\t{\n\t // line (probably) wrapped, set compl_startpos to the\n\t // first non_blank in the line, if it is not a wordchar\n\t // include it to get a better pattern, but then we don't\n\t // want the \"\\\\<\" prefix, check it below\n\t compl_col = (colnr_T)getwhitecols(line);\n\t compl_startpos.col = compl_col;\n\t compl_startpos.lnum = curwin->w_cursor.lnum;\n\t compl_cont_status &= ~CONT_SOL; // clear SOL if present\n\t}\n\telse\n\t{\n\t // S_IPOS was set when we inserted a word that was at the\n\t // beginning of the line, which means that we'll go to SOL\n\t // mode but first we need to redefine compl_startpos\n\t if (compl_cont_status & CONT_S_IPOS)\n\t {\n\t\tcompl_cont_status |= CONT_SOL;\n\t\tcompl_startpos.col = (colnr_T)(skipwhite(\n\t\t\t line + compl_length\n\t\t\t + compl_startpos.col) - line);\n\t }\n\t compl_col = compl_startpos.col;\n\t}\n\tcompl_length = curwin->w_cursor.col - (int)compl_col;\n\t// IObuff is used to add a \"word from the next line\" would we\n\t// have enough space? just being paranoid\n#define\tMIN_SPACE 75\n\tif (compl_length > (IOSIZE - MIN_SPACE))\n\t{\n\t compl_cont_status &= ~CONT_SOL;\n\t compl_length = (IOSIZE - MIN_SPACE);\n\t compl_col = curwin->w_cursor.col - compl_length;\n\t}\n\tcompl_cont_status |= CONT_ADDING | CONT_N_ADDS;\n\tif (compl_length < 1)\n\t compl_cont_status &= CONT_LOCAL;\n }\n else if (ctrl_x_mode_line_or_eval())\n\tcompl_cont_status = CONT_ADDING | CONT_N_ADDS;\n else\n\tcompl_cont_status = 0;\n}", "/*\n * start insert mode completion\n */\n static int\nins_compl_start(void)\n{\n char_u\t*line;\n int\t\tstartcol = 0;\t // column where searched text starts\n colnr_T\tcurs_col;\t // cursor column\n int\t\tline_invalid = FALSE;\n int\t\tsave_did_ai = did_ai;\n int\t\tflags = CP_ORIGINAL_TEXT;", " // First time we hit ^N or ^P (in a row, I mean)", " did_ai = FALSE;\n did_si = FALSE;\n can_si = FALSE;\n can_si_back = FALSE;\n if (stop_arrow() == FAIL)\n\treturn FAIL;", " line = ml_get(curwin->w_cursor.lnum);\n curs_col = curwin->w_cursor.col;\n compl_pending = 0;", " if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT\n\t && compl_cont_mode == ctrl_x_mode)\n\t// this same ctrl-x_mode was interrupted previously. Continue the\n\t// completion.\n\tins_compl_continue_search(line);\n else\n\tcompl_cont_status &= CONT_LOCAL;", " if (!compl_status_adding())\t// normal expansion\n {\n\tcompl_cont_mode = ctrl_x_mode;\n\tif (ctrl_x_mode_not_default())\n\t // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL\n\t compl_cont_status = 0;\n\tcompl_cont_status |= CONT_N_ADDS;\n\tcompl_startpos = curwin->w_cursor;\n\tstartcol = (int)curs_col;\n\tcompl_col = 0;\n }", " // Work out completion pattern and original text -- webb\n if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)\n {\n\tif (ctrl_x_mode_function() || ctrl_x_mode_omni()\n\t\t\t\t|| thesaurus_func_complete(ctrl_x_mode))\n\t // restore did_ai, so that adding comment leader works\n\t did_ai = save_did_ai;\n\treturn FAIL;\n }\n // If \"line\" was changed while getting completion info get it again.\n if (line_invalid)\n\tline = ml_get(curwin->w_cursor.lnum);", " if (compl_status_adding())\n {\n\tedit_submode_pre = (char_u *)_(\" Adding\");\n\tif (ctrl_x_mode_line_or_eval())\n\t{\n\t // Insert a new line, keep indentation but ignore 'comments'.\n\t char_u *old = curbuf->b_p_com;", "\t curbuf->b_p_com = (char_u *)\"\";\n\t compl_startpos.lnum = curwin->w_cursor.lnum;\n\t compl_startpos.col = compl_col;\n\t ins_eol('\\r');\n\t curbuf->b_p_com = old;\n\t compl_length = 0;\n\t compl_col = curwin->w_cursor.col;\n\t}\n }\n else\n {\n\tedit_submode_pre = NULL;\n\tcompl_startpos.col = compl_col;\n }", " if (compl_cont_status & CONT_LOCAL)\n\tedit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);\n else\n\tedit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));", " // If any of the original typed text has been changed we need to fix\n // the redo buffer.\n ins_compl_fixRedoBufForLeader(NULL);", " // Always add completion for the original text.\n vim_free(compl_orig_text);\n compl_orig_text = vim_strnsave(line + compl_col, compl_length);\n if (p_ic)\n\tflags |= CP_ICASE;\n if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,\n\t\t-1, NULL, NULL, NULL, 0, flags, FALSE) != OK)\n {\n\tVIM_CLEAR(compl_pattern);\n\tVIM_CLEAR(compl_orig_text);\n\treturn FAIL;\n }", " // showmode might reset the internal line pointers, so it must\n // be called before line = ml_get(), or when this address is no\n // longer needed. -- Acevedo.\n edit_submode_extra = (char_u *)_(\"-- Searching...\");\n edit_submode_highl = HLF_COUNT;\n showmode();\n edit_submode_extra = NULL;\n out_flush();", " return OK;\n}", "/*\n * display the completion status message\n */\n static void\nins_compl_show_statusmsg(void)\n{\n // we found no match if the list has only the \"compl_orig_text\"-entry\n if (is_first_match(compl_first_match->cp_next))\n {\n\tedit_submode_extra = compl_status_adding() && compl_length > 1\n\t\t\t\t? (char_u *)_(e_hitend)\n\t\t\t\t: (char_u *)_(e_pattern_not_found);\n\tedit_submode_highl = HLF_E;\n }", " if (edit_submode_extra == NULL)\n {\n\tif (match_at_original_text(compl_curr_match))\n\t{\n\t edit_submode_extra = (char_u *)_(\"Back at original\");\n\t edit_submode_highl = HLF_W;\n\t}\n\telse if (compl_cont_status & CONT_S_IPOS)\n\t{\n\t edit_submode_extra = (char_u *)_(\"Word from other line\");\n\t edit_submode_highl = HLF_COUNT;\n\t}\n\telse if (compl_curr_match->cp_next == compl_curr_match->cp_prev)\n\t{\n\t edit_submode_extra = (char_u *)_(\"The only match\");\n\t edit_submode_highl = HLF_COUNT;\n\t compl_curr_match->cp_number = 1;\n\t}\n\telse\n\t{\n#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)\n\t // Update completion sequence number when needed.\n\t if (compl_curr_match->cp_number == -1)\n\t\tins_compl_update_sequence_numbers();\n#endif\n\t // The match should always have a sequence number now, this is\n\t // just a safety check.\n\t if (compl_curr_match->cp_number != -1)\n\t {\n\t\t// Space for 10 text chars. + 2x10-digit no.s = 31.\n\t\t// Translations may need more than twice that.\n\t\tstatic char_u match_ref[81];", "\t\tif (compl_matches > 0)\n\t\t vim_snprintf((char *)match_ref, sizeof(match_ref),\n\t\t\t _(\"match %d of %d\"),\n\t\t\t compl_curr_match->cp_number, compl_matches);\n\t\telse\n\t\t vim_snprintf((char *)match_ref, sizeof(match_ref),\n\t\t\t _(\"match %d\"),\n\t\t\t compl_curr_match->cp_number);\n\t\tedit_submode_extra = match_ref;\n\t\tedit_submode_highl = HLF_R;\n\t\tif (dollar_vcol >= 0)\n\t\t curs_columns(FALSE);\n\t }\n\t}\n }", " // Show a message about what (completion) mode we're in.\n if (!compl_opt_suppress_empty)\n {\n\tshowmode();\n\tif (!shortmess(SHM_COMPLETIONMENU))\n\t{\n\t if (edit_submode_extra != NULL)\n\t {\n\t\tif (!p_smd)\n\t\t{\n\t\t msg_hist_off = TRUE;\n\t\t msg_attr((char *)edit_submode_extra,\n\t\t\t edit_submode_highl < HLF_COUNT\n\t\t\t ? HL_ATTR(edit_submode_highl) : 0);\n\t\t msg_hist_off = FALSE;\n\t\t}\n\t }\n\t else\n\t\tmsg_clr_cmdline();\t// necessary for \"noshowmode\"\n\t}\n }\n}", "/*\n * Do Insert mode completion.\n * Called when character \"c\" was typed, which has a meaning for completion.\n * Returns OK if completion was done, FAIL if something failed (out of mem).\n */\n int\nins_complete(int c, int enable_pum)\n{\n int\t\tn;\n int\t\tsave_w_wrow;\n int\t\tsave_w_leftcol;\n int\t\tinsert_match;", " compl_direction = ins_compl_key2dir(c);\n insert_match = ins_compl_use_match(c);", " if (!compl_started)\n {\n\tif (ins_compl_start() == FAIL)\n\t return FAIL;\n }\n else if (insert_match && stop_arrow() == FAIL)\n\treturn FAIL;", " compl_shown_match = compl_curr_match;\n compl_shows_dir = compl_direction;", " // Find next match (and following matches).\n save_w_wrow = curwin->w_wrow;\n save_w_leftcol = curwin->w_leftcol;\n n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);", " // may undisplay the popup menu\n ins_compl_upd_pum();", " if (n > 1)\t\t// all matches have been found\n\tcompl_matches = n;\n compl_curr_match = compl_shown_match;\n compl_direction = compl_shows_dir;", " // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert\n // mode.\n if (got_int && !global_busy)\n {\n\t(void)vgetc();\n\tgot_int = FALSE;\n }", " // we found no match if the list has only the \"compl_orig_text\"-entry\n if (is_first_match(compl_first_match->cp_next))\n {\n\t// remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,\n\t// because we couldn't expand anything at first place, but if we used\n\t// ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word\n\t// (such as M in M'exico) if not tried already. -- Acevedo\n\tif (compl_length > 1\n\t\t|| compl_status_adding()\n\t\t|| (ctrl_x_mode_not_default()\n\t\t && !ctrl_x_mode_path_patterns()\n\t\t && !ctrl_x_mode_path_defines()))\n\t compl_cont_status &= ~CONT_N_ADDS;\n }", " if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)\n\tcompl_cont_status |= CONT_S_IPOS;\n else\n\tcompl_cont_status &= ~CONT_S_IPOS;", " ins_compl_show_statusmsg();", " // Show the popup menu, unless we got interrupted.\n if (enable_pum && !compl_interrupted)\n\tshow_pum(save_w_wrow, save_w_leftcol);", " compl_was_interrupted = compl_interrupted;\n compl_interrupted = FALSE;", " return OK;\n}", "/*\n * Remove (if needed) and show the popup menu\n */\n static void\nshow_pum(int prev_w_wrow, int prev_w_leftcol)\n{\n // RedrawingDisabled may be set when invoked through complete().\n int n = RedrawingDisabled;", " RedrawingDisabled = 0;", " // If the cursor moved or the display scrolled we need to remove the pum\n // first.\n setcursor();\n if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)\n\tins_compl_del_pum();", " ins_compl_show_pum();\n setcursor();\n RedrawingDisabled = n;\n}", "/*\n * Looks in the first \"len\" chars. of \"src\" for search-metachars.\n * If dest is not NULL the chars. are copied there quoting (with\n * a backslash) the metachars, and dest would be NUL terminated.\n * Returns the length (needed) of dest\n */\n static unsigned\nquote_meta(char_u *dest, char_u *src, int len)\n{\n unsigned\tm = (unsigned)len + 1; // one extra for the NUL", " for ( ; --len >= 0; src++)\n {\n\tswitch (*src)\n\t{\n\t case '.':\n\t case '*':\n\t case '[':\n\t\tif (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())\n\t\t break;\n\t\t// FALLTHROUGH\n\t case '~':\n\t\tif (!magic_isset())\t// quote these only if magic is set\n\t\t break;\n\t\t// FALLTHROUGH\n\t case '\\\\':\n\t\tif (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())\n\t\t break;\n\t\t// FALLTHROUGH\n\t case '^':\t\t// currently it's not needed.\n\t case '$':\n\t\tm++;\n\t\tif (dest != NULL)\n\t\t *dest++ = '\\\\';\n\t\tbreak;\n\t}\n\tif (dest != NULL)\n\t *dest++ = *src;\n\t// Copy remaining bytes of a multibyte character.\n\tif (has_mbyte)\n\t{\n\t int i, mb_len;", "\t mb_len = (*mb_ptr2len)(src) - 1;\n\t if (mb_len > 0 && len >= mb_len)\n\t\tfor (i = 0; i < mb_len; ++i)\n\t\t{\n\t\t --len;\n\t\t ++src;\n\t\t if (dest != NULL)\n\t\t\t*dest++ = *src;\n\t\t}\n\t}\n }\n if (dest != NULL)\n\t*dest = NUL;", " return m;\n}", "#if defined(EXITFREE) || defined(PROTO)\n void\nfree_insexpand_stuff(void)\n{\n VIM_CLEAR(compl_orig_text);\n# ifdef FEAT_EVAL\n free_callback(&cfu_cb);\n free_callback(&ofu_cb);\n free_callback(&tsrfu_cb);\n# endif\n}\n#endif", "#ifdef FEAT_SPELL\n/*\n * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly\n * spelled word, if there is one.\n */\n static void\nspell_back_to_badword(void)\n{\n pos_T\ttpos = curwin->w_cursor;", " spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL);\n if (curwin->w_cursor.col != tpos.col)\n\tstart_arrow(&tpos);\n}\n#endif" ]
[ 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [698, 2100, 737], "buggy_code_start_loc": [526, 2100, 737], "filenames": ["src/insexpand.c", "src/testdir/test_ins_complete.vim", "src/version.c"], "fixing_code_end_loc": [736, 2117, 740], "fixing_code_start_loc": [527, 2101, 738], "message": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0044.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "0069C36F-19A3-4647-B84F-84CE62E8A554", "versionEndExcluding": "9.0.0044", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:35:*:*:*:*:*:*:*", "matchCriteriaId": "80E516C0-98A4-4ADE-B69F-66A772E2BAAA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0044."}, {"lang": "es", "value": "Un Desbordamiento de B\u00fafer en la Regi\u00f3n Heap de la Memoria en el repositorio de GitHub vim/vim versiones anteriores a 9.0.0044"}], "evaluatorComment": null, "id": "CVE-2022-2343", "lastModified": "2023-05-03T12:15:58.413", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-07-08T18:15:09.820", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/caea66442d86e7bbba3bf3dc202c3c0d549b9853"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2ecb4345-2fc7-4e7f-adb0-83a20bb458f5"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/43Y3VJPOTTY3NTREDIFUPITM2POG4ZLP/"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/202208-32"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-122"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/caea66442d86e7bbba3bf3dc202c3c0d549b9853"}, "type": "CWE-122"}
172
Determine whether the {function_name} code is vulnerable or not.
[ "\" Test for insert completion", "source screendump.vim\nsource check.vim\nimport './vim9.vim' as v9", "\" Test for insert expansion\nfunc Test_ins_complete()\n edit test_ins_complete.vim\n \" The files in the current directory interferes with the files\n \" used by this test. So use a separate directory for the test.\n call mkdir('Xdir')\n cd Xdir", " set ff=unix\n call writefile([\"test11\\t36Gepeto\\t/Tag/\",\n\t \\ \"asd\\ttest11file\\t36G\",\n\t \\ \"Makefile\\tto\\trun\"], 'Xtestfile')\n call writefile(['', 'start of testfile',\n\t \\ 'ru',\n\t \\ 'run1',\n\t \\ 'run2',\n\t \\ 'STARTTEST',\n\t \\ 'ENDTEST',\n\t \\ 'end of testfile'], 'Xtestdata')\n set ff&", " enew!\n edit Xtestdata\n new\n call append(0, ['#include \"Xtestfile\"', ''])\n call cursor(2, 1)", " set cot=\n set cpt=.,w\n \" add-expands (word from next line) from other window\n exe \"normal iru\\<C-N>\\<C-N>\\<C-X>\\<C-N>\\<Esc>\\<C-A>\"\n call assert_equal('run1 run3', getline('.'))\n \" add-expands (current buffer first)\n exe \"normal o\\<C-P>\\<C-X>\\<C-N>\"\n call assert_equal('run3 run3', getline('.'))\n \" Local expansion, ends in an empty line (unless it becomes a global\n \" expansion)\n exe \"normal o\\<C-X>\\<C-P>\\<C-P>\\<C-P>\\<C-P>\\<C-P>\"\n call assert_equal('', getline('.'))\n \" starts Local and switches to global add-expansion\n exe \"normal o\\<C-X>\\<C-P>\\<C-P>\\<C-X>\\<C-X>\\<C-N>\\<C-X>\\<C-N>\\<C-N>\"\n call assert_equal('run1 run2', getline('.'))", " set cpt=.,\\ ,w,i\n \" i-add-expands and switches to local\n exe \"normal OM\\<C-N>\\<C-X>\\<C-N>\\<C-X>\\<C-N>\\<C-X>\\<C-X>\\<C-X>\\<C-P>\"\n call assert_equal(\"Makefile\\tto\\trun3\", getline('.'))\n \" add-expands lines (it would end in an empty line if it didn't ignore\n \" itself)\n exe \"normal o\\<C-X>\\<C-L>\\<C-X>\\<C-L>\\<C-P>\\<C-P>\"\n call assert_equal(\"Makefile\\tto\\trun3\", getline('.'))\n call assert_equal(\"Makefile\\tto\\trun3\", getline(line('.') - 1))", " set cpt=kXtestfile\n \" checks k-expansion, and file expansion (use Xtest11 instead of test11,\n \" because TEST11.OUT may match first on DOS)\n write Xtest11.one\n write Xtest11.two\n exe \"normal o\\<C-N>\\<Esc>IX\\<Esc>A\\<C-X>\\<C-F>\\<C-N>\"\n call assert_equal('Xtest11.two', getline('.'))", " \" use CTRL-X CTRL-F to complete Xtest11.one, remove it and then use CTRL-X\n \" CTRL-F again to verify this doesn't cause trouble.\n exe \"normal oXt\\<C-X>\\<C-F>\\<BS>\\<BS>\\<BS>\\<BS>\\<BS>\\<BS>\\<BS>\\<BS>\\<C-X>\\<C-F>\"\n call assert_equal('Xtest11.one', getline('.'))\n normal ddk", " \" Test for expanding a non-existing filename\n exe \"normal oa1b2X3Y4\\<C-X>\\<C-F>\"\n call assert_equal('a1b2X3Y4', getline('.'))\n normal ddk", " set cpt=w\n \" checks make_cyclic in other window\n exe \"normal oST\\<C-N>\\<C-P>\\<C-P>\\<C-P>\\<C-P>\"\n call assert_equal('STARTTEST', getline('.'))", " set cpt=u nohid\n \" checks unloaded buffer expansion\n only\n exe \"normal oEN\\<C-N>\"\n call assert_equal('ENDTEST', getline('.'))\n \" checks adding mode abortion\n exe \"normal ounl\\<C-N>\\<C-X>\\<C-X>\\<C-P>\"\n call assert_equal('unless', getline('.'))", " set cpt=t,d def=^\\\\k* tags=Xtestfile notagbsearch\n \" tag expansion, define add-expansion interrupted\n exe \"normal o\\<C-X>\\<C-]>\\<C-X>\\<C-D>\\<C-X>\\<C-D>\\<C-X>\\<C-X>\\<C-D>\\<C-X>\\<C-D>\\<C-X>\\<C-D>\\<C-X>\\<C-D>\"\n call assert_equal('test11file\t36Gepeto\t/Tag/ asd', getline('.'))\n \" t-expansion\n exe \"normal oa\\<C-N>\\<Esc>\"\n call assert_equal('asd', getline('.'))", " %bw!\n call delete('Xtestfile')\n call delete('Xtest11.one')\n call delete('Xtest11.two')\n call delete('Xtestdata')\n set cpt& cot& def& tags& tagbsearch& hidden&\n cd ..\n call delete('Xdir', 'rf')\nendfunc", "func Test_ins_complete_invalid_byte()\n if has('unix') && executable('base64')\n \" this weird command was causing an illegal memory access\n call writefile(['bm9ybTlvMDCAMM4Dbw4OGA4ODg=='], 'Xinvalid64')\n call system('base64 -d Xinvalid64 > Xinvalid')\n call writefile(['qa!'], 'Xexit')\n call RunVim([], [], \" -i NONE -n -X -Z -e -m -s -S Xinvalid -S Xexit\")\n call delete('Xinvalid64')\n call delete('Xinvalid')\n call delete('Xexit')\n endif\nendfunc", "func Test_omni_dash()\n func Omni(findstart, base)\n if a:findstart\n return 5\n else\n echom a:base\n\treturn ['-help', '-v']\n endif\n endfunc\n set omnifunc=Omni\n new\n exe \"normal Gofind -\\<C-x>\\<C-o>\"\n call assert_equal(\"find -help\", getline('$'))", " bwipe!\n delfunc Omni\n set omnifunc=\nendfunc", "func Test_omni_throw()\n let g:CallCount = 0\n func Omni(findstart, base)\n let g:CallCount += 1\n if a:findstart\n throw \"he he he\"\n endif\n endfunc\n set omnifunc=Omni\n new\n try\n exe \"normal ifoo\\<C-x>\\<C-o>\"\n call assert_false(v:true, 'command should have failed')\n catch\n call assert_exception('he he he')\n call assert_equal(1, g:CallCount)\n endtry", " bwipe!\n delfunc Omni\n unlet g:CallCount\n set omnifunc=\nendfunc", "func Test_omni_autoload()\n let save_rtp = &rtp\n set rtp=Xruntime/some\n let dir = 'Xruntime/some/autoload'\n call mkdir(dir, 'p')", " let lines =<< trim END\n vim9script\n export def Func(findstart: bool, base: string): any\n if findstart\n return 1\n else\n return ['match']\n endif\n enddef\n {\n eval 1 + 2\n }\n END\n call writefile(lines, dir .. '/omni.vim')", " new\n setlocal omnifunc=omni#Func\n call feedkeys(\"i\\<C-X>\\<C-O>\\<Esc>\", 'xt')", " bwipe!\n call delete('Xruntime', 'rf')\n set omnifunc=\n let &rtp = save_rtp\nendfunc", "func Test_completefunc_args()\n let s:args = []\n func! CompleteFunc(findstart, base)\n let s:args += [[a:findstart, empty(a:base)]]\n endfunc\n new", " set completefunc=CompleteFunc\n call feedkeys(\"i\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([1, 1], s:args[0])\n call assert_equal(0, s:args[1][0])\n set completefunc=", " let s:args = []\n set omnifunc=CompleteFunc\n call feedkeys(\"i\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([1, 1], s:args[0])\n call assert_equal(0, s:args[1][0])\n set omnifunc=", " bwipe!\n unlet s:args\n delfunc CompleteFunc\nendfunc", "func s:CompleteDone_CompleteFuncNone( findstart, base )\n if a:findstart\n return 0\n endif", " return v:none\nendfunc", "func s:CompleteDone_CompleteFuncDict( findstart, base )\n if a:findstart\n return 0\n endif", " return {\n\t \\ 'words': [\n\t \\ {\n\t \\ 'word': 'aword',\n\t \\ 'abbr': 'wrd',\n\t \\ 'menu': 'extra text',\n\t \\ 'info': 'words are cool',\n\t \\ 'kind': 'W',\n\t \\ 'user_data': 'test'\n\t \\ }\n\t \\ ]\n\t\\ }\nendfunc", "func s:CompleteDone_CheckCompletedItemNone()\n let s:called_completedone = 1\nendfunc", "func s:CompleteDone_CheckCompletedItemDict(pre)\n call assert_equal( 'aword', v:completed_item[ 'word' ] )\n call assert_equal( 'wrd', v:completed_item[ 'abbr' ] )\n call assert_equal( 'extra text', v:completed_item[ 'menu' ] )\n call assert_equal( 'words are cool', v:completed_item[ 'info' ] )\n call assert_equal( 'W', v:completed_item[ 'kind' ] )\n call assert_equal( 'test', v:completed_item[ 'user_data' ] )", " if a:pre\n call assert_equal('function', complete_info().mode)\n endif", " let s:called_completedone = 1\nendfunc", "func Test_CompleteDoneNone()\n au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemNone()\n let oldline = join(map(range(&columns), 'nr2char(screenchar(&lines-1, v:val+1))'), '')", " set completefunc=<SID>CompleteDone_CompleteFuncNone\n execute \"normal a\\<C-X>\\<C-U>\\<C-Y>\"\n set completefunc&\n let newline = join(map(range(&columns), 'nr2char(screenchar(&lines-1, v:val+1))'), '')", " call assert_true(s:called_completedone)\n call assert_equal(oldline, newline)", " let s:called_completedone = 0\n au! CompleteDone\nendfunc", "func Test_CompleteDoneDict()\n au CompleteDonePre * :call <SID>CompleteDone_CheckCompletedItemDict(1)\n au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemDict(0)", " set completefunc=<SID>CompleteDone_CompleteFuncDict\n execute \"normal a\\<C-X>\\<C-U>\\<C-Y>\"\n set completefunc&", " call assert_equal('test', v:completed_item[ 'user_data' ])\n call assert_true(s:called_completedone)", " let s:called_completedone = 0\n au! CompleteDone\nendfunc", "func s:CompleteDone_CompleteFuncDictNoUserData(findstart, base)\n if a:findstart\n return 0\n endif", " return {\n\t \\ 'words': [\n\t \\ {\n\t \\ 'word': 'aword',\n\t \\ 'abbr': 'wrd',\n\t \\ 'menu': 'extra text',\n\t \\ 'info': 'words are cool',\n\t \\ 'kind': 'W',\n\t \\ 'user_data': ['one', 'two'],\n\t \\ }\n\t \\ ]\n\t\\ }\nendfunc", "func s:CompleteDone_CheckCompletedItemDictNoUserData()\n call assert_equal( 'aword', v:completed_item[ 'word' ] )\n call assert_equal( 'wrd', v:completed_item[ 'abbr' ] )\n call assert_equal( 'extra text', v:completed_item[ 'menu' ] )\n call assert_equal( 'words are cool', v:completed_item[ 'info' ] )\n call assert_equal( 'W', v:completed_item[ 'kind' ] )\n call assert_equal( ['one', 'two'], v:completed_item[ 'user_data' ] )", " let s:called_completedone = 1\nendfunc", "func Test_CompleteDoneDictNoUserData()\n au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemDictNoUserData()", " set completefunc=<SID>CompleteDone_CompleteFuncDictNoUserData\n execute \"normal a\\<C-X>\\<C-U>\\<C-Y>\"\n set completefunc&", " call assert_equal(['one', 'two'], v:completed_item[ 'user_data' ])\n call assert_true(s:called_completedone)", " let s:called_completedone = 0\n au! CompleteDone\nendfunc", "func s:CompleteDone_CompleteFuncList(findstart, base)\n if a:findstart\n return 0\n endif", " return [ 'aword' ]\nendfunc", "func s:CompleteDone_CheckCompletedItemList()\n call assert_equal( 'aword', v:completed_item[ 'word' ] )\n call assert_equal( '', v:completed_item[ 'abbr' ] )\n call assert_equal( '', v:completed_item[ 'menu' ] )\n call assert_equal( '', v:completed_item[ 'info' ] )\n call assert_equal( '', v:completed_item[ 'kind' ] )\n call assert_equal( '', v:completed_item[ 'user_data' ] )", " let s:called_completedone = 1\nendfunc", "func Test_CompleteDoneList()\n au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemList()", " set completefunc=<SID>CompleteDone_CompleteFuncList\n execute \"normal a\\<C-X>\\<C-U>\\<C-Y>\"\n set completefunc&", " call assert_equal('', v:completed_item[ 'user_data' ])\n call assert_true(s:called_completedone)", " let s:called_completedone = 0\n au! CompleteDone\nendfunc", "func Test_CompleteDone_undo()\n au CompleteDone * call append(0, \"prepend1\")\n new\n call setline(1, [\"line1\", \"line2\"])\n call feedkeys(\"Go\\<C-X>\\<C-N>\\<CR>\\<ESC>\", \"tx\")\n call assert_equal([\"prepend1\", \"line1\", \"line2\", \"line1\", \"\"],\n \\ getline(1, '$'))\n undo\n call assert_equal([\"line1\", \"line2\"], getline(1, '$'))\n bwipe!\n au! CompleteDone\nendfunc", "func CompleteTest(findstart, query)\n if a:findstart\n return col('.')\n endif\n return ['matched']\nendfunc", "func Test_completefunc_info()\n new\n set completeopt=menuone\n set completefunc=CompleteTest\n call feedkeys(\"i\\<C-X>\\<C-U>\\<C-R>\\<C-R>=string(complete_info())\\<CR>\\<ESC>\", \"tx\")\n call assert_equal(\"matched{'pum_visible': 1, 'mode': 'function', 'selected': 0, 'items': [{'word': 'matched', 'menu': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''}]}\", getline(1))\n bwipe!\n set completeopt&\n set completefunc&\nendfunc", "\" Check that when using feedkeys() typeahead does not interrupt searching for\n\" completions.\nfunc Test_compl_feedkeys()\n new\n set completeopt=menuone,noselect\n call feedkeys(\"ajump ju\\<C-X>\\<C-N>\\<C-P>\\<ESC>\", \"tx\")\n call assert_equal(\"jump jump\", getline(1))\n bwipe!\n set completeopt&\nendfunc", "\" Test for insert path completion with completeslash option\nfunc Test_ins_completeslash()\n CheckMSWindows", " call mkdir('Xdir')\n let orig_shellslash = &shellslash\n set cpt&\n new", " set noshellslash", " set completeslash=\n exe \"normal oXd\\<C-X>\\<C-F>\"\n call assert_equal('Xdir\\', getline('.'))", " set completeslash=backslash\n exe \"normal oXd\\<C-X>\\<C-F>\"\n call assert_equal('Xdir\\', getline('.'))", " set completeslash=slash\n exe \"normal oXd\\<C-X>\\<C-F>\"\n call assert_equal('Xdir/', getline('.'))", " set shellslash", " set completeslash=\n exe \"normal oXd\\<C-X>\\<C-F>\"\n call assert_equal('Xdir/', getline('.'))", " set completeslash=backslash\n exe \"normal oXd\\<C-X>\\<C-F>\"\n call assert_equal('Xdir\\', getline('.'))", " set completeslash=slash\n exe \"normal oXd\\<C-X>\\<C-F>\"\n call assert_equal('Xdir/', getline('.'))\n %bw!\n call delete('Xdir', 'rf')", " set noshellslash\n set completeslash=slash\n call assert_true(stridx(globpath(&rtp, 'syntax/*.vim', 1, 1)[0], '\\') != -1)", " let &shellslash = orig_shellslash\n set completeslash=\nendfunc", "func Test_pum_stopped_by_timer()\n CheckScreendump", " let lines =<< trim END\n call setline(1, ['hello', 'hullo', 'heeee', ''])\n func StartCompl()\n call timer_start(100, { -> execute('stopinsert') })\n call feedkeys(\"Gah\\<C-N>\")\n endfunc\n END", " call writefile(lines, 'Xpumscript')\n let buf = RunVimInTerminal('-S Xpumscript', #{rows: 12})\n call term_sendkeys(buf, \":call StartCompl()\\<CR>\")\n call TermWait(buf, 200)\n call term_sendkeys(buf, \"k\")\n call VerifyScreenDump(buf, 'Test_pum_stopped_by_timer', {})", " call StopVimInTerminal(buf)\n call delete('Xpumscript')\nendfunc", "func Test_complete_stopinsert_startinsert()\n nnoremap <F2> <Cmd>startinsert<CR>\n inoremap <F2> <Cmd>stopinsert<CR>\n \" This just checks if this causes an error\n call feedkeys(\"i\\<C-X>\\<C-N>\\<F2>\\<F2>\", 'x')\n nunmap <F2>\n iunmap <F2>\nendfunc", "func Test_pum_with_folds_two_tabs()\n CheckScreendump", " let lines =<< trim END\n set fdm=marker\n call setline(1, ['\" x {{{1', '\" a some text'])\n call setline(3, range(&lines)->map({_, val -> '\" a' .. val}))\n norm! zm\n tab sp\n call feedkeys('2Gzv', 'xt')\n call feedkeys(\"0fa\", 'xt')\n END", " call writefile(lines, 'Xpumscript')\n let buf = RunVimInTerminal('-S Xpumscript', #{rows: 10})\n call TermWait(buf, 50)\n call term_sendkeys(buf, \"a\\<C-N>\")\n call VerifyScreenDump(buf, 'Test_pum_with_folds_two_tabs', {})", " call term_sendkeys(buf, \"\\<Esc>\")\n call StopVimInTerminal(buf)\n call delete('Xpumscript')\nendfunc", "func Test_pum_with_preview_win()\n CheckScreendump", " let lines =<< trim END\n funct Omni_test(findstart, base)\n\tif a:findstart\n\t return col(\".\") - 1\n\tendif\n\treturn [#{word: \"one\", info: \"1info\"}, #{word: \"two\", info: \"2info\"}, #{word: \"three\", info: \"3info\"}]\n endfunc\n set omnifunc=Omni_test\n set completeopt+=longest\n END", " call writefile(lines, 'Xpreviewscript')\n let buf = RunVimInTerminal('-S Xpreviewscript', #{rows: 12})\n call TermWait(buf, 50)\n call term_sendkeys(buf, \"Gi\\<C-X>\\<C-O>\")\n call TermWait(buf, 100)\n call term_sendkeys(buf, \"\\<C-N>\")\n call VerifyScreenDump(buf, 'Test_pum_with_preview_win', {})", " call term_sendkeys(buf, \"\\<Esc>\")\n call StopVimInTerminal(buf)\n call delete('Xpreviewscript')\nendfunc", "func Test_scrollbar_on_wide_char()\n CheckScreendump", " let lines =<< trim END\n call setline(1, ['a', ' 啊啊啊',\n \\ ' 哦哦哦',\n \\ ' 呃呃呃'])\n call setline(5, range(10)->map({i, v -> 'aa' .. v .. 'bb'}))\n END\n call writefile(lines, 'Xwidescript')\n let buf = RunVimInTerminal('-S Xwidescript', #{rows: 10})\n call term_sendkeys(buf, \"A\\<C-N>\")\n call VerifyScreenDump(buf, 'Test_scrollbar_on_wide_char', {})", " call StopVimInTerminal(buf)\n call delete('Xwidescript')\nendfunc", "\" Test for inserting the tag search pattern in insert mode\nfunc Test_ins_compl_tag_sft()\n call writefile([\n \\ \"!_TAG_FILE_ENCODING\\tutf-8\\t//\",\n \\ \"first\\tXfoo\\t/^int first() {}$/\",\n \\ \"second\\tXfoo\\t/^int second() {}$/\",\n \\ \"third\\tXfoo\\t/^int third() {}$/\"],\n \\ 'Xtags')\n set tags=Xtags\n let code =<< trim [CODE]\n int first() {}\n int second() {}\n int third() {}\n [CODE]\n call writefile(code, 'Xfoo')", " enew\n set showfulltag\n exe \"normal isec\\<C-X>\\<C-]>\\<C-N>\\<CR>\"\n call assert_equal('int second() {}', getline(1))\n set noshowfulltag", " call delete('Xtags')\n call delete('Xfoo')\n set tags&\n %bwipe!\nendfunc", "\" Test for 'completefunc' deleting text\nfunc Test_completefunc_error()\n new\n \" delete text when called for the first time\n func CompleteFunc(findstart, base)\n if a:findstart == 1\n normal dd\n return col('.') - 1\n endif\n return ['a', 'b']\n endfunc\n set completefunc=CompleteFunc\n call setline(1, ['', 'abcd', ''])\n call assert_fails('exe \"normal 2G$a\\<C-X>\\<C-U>\"', 'E565:')", " \" delete text when called for the second time\n func CompleteFunc2(findstart, base)\n if a:findstart == 1\n return col('.') - 1\n endif\n normal dd\n return ['a', 'b']\n endfunc\n set completefunc=CompleteFunc2\n call setline(1, ['', 'abcd', ''])\n call assert_fails('exe \"normal 2G$a\\<C-X>\\<C-U>\"', 'E565:')", " \" Jump to a different window from the complete function\n func CompleteFunc3(findstart, base)\n if a:findstart == 1\n return col('.') - 1\n endif\n wincmd p\n return ['a', 'b']\n endfunc\n set completefunc=CompleteFunc3\n new\n call assert_fails('exe \"normal a\\<C-X>\\<C-U>\"', 'E565:')\n close!", " set completefunc&\n delfunc CompleteFunc\n delfunc CompleteFunc2\n delfunc CompleteFunc3\n close!\nendfunc", "\" Test for returning non-string values from 'completefunc'\nfunc Test_completefunc_invalid_data()\n new\n func! CompleteFunc(findstart, base)\n if a:findstart == 1\n return col('.') - 1\n endif\n return [{}, '', 'moon']\n endfunc\n set completefunc=CompleteFunc\n exe \"normal i\\<C-X>\\<C-U>\"\n call assert_equal('moon', getline(1))\n set completefunc&\n close!\nendfunc", "\" Test for errors in using complete() function\nfunc Test_complete_func_error()\n call assert_fails('call complete(1, [\"a\"])', 'E785:')\n func ListColors()\n call complete(col('.'), \"blue\")\n endfunc\n call assert_fails('exe \"normal i\\<C-R>=ListColors()\\<CR>\"', 'E474:')\n func ListMonths()\n call complete(col('.'), test_null_list())\n endfunc\n call assert_fails('exe \"normal i\\<C-R>=ListMonths()\\<CR>\"', 'E474:')\n delfunc ListColors\n delfunc ListMonths\n call assert_fails('call complete_info({})', 'E714:')\n call assert_equal([], complete_info(['items']).items)\nendfunc", "\" Test for recursively starting completion mode using complete()\nfunc Test_recursive_complete_func()\n func ListColors()\n call complete(5, [\"red\", \"blue\"])\n return ''\n endfunc\n new\n call setline(1, ['a1', 'a2'])\n set complete=.\n exe \"normal Goa\\<C-X>\\<C-L>\\<C-R>=ListColors()\\<CR>\\<C-N>\"\n call assert_equal('a2blue', getline(3))\n delfunc ListColors\n bw!\nendfunc", "\" Test for completing words following a completed word in a line\nfunc Test_complete_wrapscan()\n \" complete words from another buffer\n new\n call setline(1, ['one two', 'three four'])\n new\n setlocal complete=w\n call feedkeys(\"itw\\<C-N>\\<C-X>\\<C-N>\\<C-X>\\<C-N>\\<C-X>\\<C-N>\", 'xt')\n call assert_equal('two three four', getline(1))\n close!\n \" complete words from the current buffer\n setlocal complete=.\n %d\n call setline(1, ['one two', ''])\n call cursor(2, 1)\n call feedkeys(\"ion\\<C-N>\\<C-X>\\<C-N>\\<C-X>\\<C-N>\\<C-X>\\<C-N>\", 'xt')\n call assert_equal('one two one two', getline(2))\n close!\nendfunc", "\" Test for completing special characters\nfunc Test_complete_special_chars()\n new\n call setline(1, 'int .*[-\\^$ func float')\n call feedkeys(\"oin\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\", 'xt')\n call assert_equal('int .*[-\\^$ func float', getline(2))\n close!\nendfunc", "\" Test for completion when text is wrapped across lines.\nfunc Test_complete_across_line()\n new\n call setline(1, ['red green blue', 'one two three'])\n setlocal textwidth=20\n exe \"normal 2G$a re\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\"\n call assert_equal(['one two three red', 'green blue one'], getline(2, '$'))\n close!\nendfunc", "\" Test for completing words with a '.' at the end of a word.\nfunc Test_complete_joinspaces()\n new\n call setline(1, ['one two.', 'three. four'])\n set joinspaces\n exe \"normal Goon\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\"\n call assert_equal(\"one two. three. four\", getline(3))\n set joinspaces&\n bw!\nendfunc", "\" Test for using CTRL-L to add one character when completing matching\nfunc Test_complete_add_onechar()\n new\n call setline(1, ['wool', 'woodwork'])\n call feedkeys(\"Gowoo\\<C-P>\\<C-P>\\<C-P>\\<C-L>f\", 'xt')\n call assert_equal('woof', getline(3))", " \" use 'ignorecase' and backspace to erase characters from the prefix string\n \" and then add letters using CTRL-L\n %d\n set ignorecase backspace=2\n setlocal complete=.\n call setline(1, ['workhorse', 'workload'])\n normal Go\n exe \"normal aWOR\\<C-P>\\<bs>\\<bs>\\<bs>\\<bs>\\<bs>\\<bs>\\<C-L>r\\<C-L>\\<C-L>\"\n call assert_equal('workh', getline(3))\n set ignorecase& backspace&\n close!\nendfunc", "\" Test for using CTRL-X CTRL-L to complete whole lines lines\nfunc Test_complete_wholeline()\n new\n \" complete one-line\n call setline(1, ['a1', 'a2'])\n exe \"normal ggoa\\<C-X>\\<C-L>\"\n call assert_equal(['a1', 'a1', 'a2'], getline(1, '$'))\n \" go to the next match (wrapping around the buffer)\n exe \"normal 2GCa\\<C-X>\\<C-L>\\<C-N>\"\n call assert_equal(['a1', 'a', 'a2'], getline(1, '$'))\n \" go to the next match\n exe \"normal 2GCa\\<C-X>\\<C-L>\\<C-N>\\<C-N>\"\n call assert_equal(['a1', 'a2', 'a2'], getline(1, '$'))\n exe \"normal 2GCa\\<C-X>\\<C-L>\\<C-N>\\<C-N>\\<C-N>\"\n call assert_equal(['a1', 'a1', 'a2'], getline(1, '$'))\n \" repeat the test using CTRL-L\n \" go to the next match (wrapping around the buffer)\n exe \"normal 2GCa\\<C-X>\\<C-L>\\<C-L>\"\n call assert_equal(['a1', 'a2', 'a2'], getline(1, '$'))\n \" go to the next match\n exe \"normal 2GCa\\<C-X>\\<C-L>\\<C-L>\\<C-L>\"\n call assert_equal(['a1', 'a', 'a2'], getline(1, '$'))\n exe \"normal 2GCa\\<C-X>\\<C-L>\\<C-L>\\<C-L>\\<C-L>\"\n call assert_equal(['a1', 'a1', 'a2'], getline(1, '$'))\n %d\n \" use CTRL-X CTRL-L to add one more line\n call setline(1, ['a1', 'b1'])\n setlocal complete=.\n exe \"normal ggOa\\<C-X>\\<C-L>\\<C-X>\\<C-L>\\<C-X>\\<C-L>\"\n call assert_equal(['a1', 'b1', '', 'a1', 'b1'], getline(1, '$'))\n bw!\nendfunc", "\" Test insert completion with 'cindent' (adjust the indent)\nfunc Test_complete_with_cindent()\n new\n setlocal cindent\n call setline(1, ['if (i == 1)', \" j = 2;\"])\n exe \"normal Go{\\<CR>i\\<C-X>\\<C-L>\\<C-X>\\<C-L>\\<CR>}\"\n call assert_equal(['{', \"\\tif (i == 1)\", \"\\t\\tj = 2;\", '}'], getline(3, '$'))", " %d\n call setline(1, ['when while', '{', ''])\n setlocal cinkeys+==while\n exe \"normal Giwh\\<C-P> \"\n call assert_equal(\"\\twhile \", getline('$'))\n close!\nendfunc", "\" Test for <CTRL-X> <CTRL-V> completion. Complete commands and functions\nfunc Test_complete_cmdline()\n new\n exe \"normal icaddb\\<C-X>\\<C-V>\"\n call assert_equal('caddbuffer', getline(1))\n exe \"normal ocall getqf\\<C-X>\\<C-V>\"\n call assert_equal('call getqflist(', getline(2))\n exe \"normal oabcxyz(\\<C-X>\\<C-V>\"\n call assert_equal('abcxyz(', getline(3))\n com! -buffer TestCommand1 echo 'TestCommand1'\n com! -buffer TestCommand2 echo 'TestCommand2'\n write TestCommand1Test\n write TestCommand2Test\n \" Test repeating <CTRL-X> <CTRL-V> and switching to another CTRL-X mode\n exe \"normal oT\\<C-X>\\<C-V>\\<C-X>\\<C-V>\\<C-X>\\<C-F>\\<Esc>\"\n call assert_equal('TestCommand2Test', getline(4))\n call delete('TestCommand1Test')\n call delete('TestCommand2Test')\n delcom TestCommand1\n delcom TestCommand2\n close!\nendfunc", "\" Test for <CTRL-X> <CTRL-Z> stopping completion without changing the match\nfunc Test_complete_stop()\n new\n func Save_mode1()\n let g:mode1 = mode(1)\n return ''\n endfunc\n func Save_mode2()\n let g:mode2 = mode(1)\n return ''\n endfunc\n inoremap <F1> <C-R>=Save_mode1()<CR>\n inoremap <F2> <C-R>=Save_mode2()<CR>\n call setline(1, ['aaa bbb ccc '])\n exe \"normal A\\<C-N>\\<C-P>\\<F1>\\<C-X>\\<C-Z>\\<F2>\\<Esc>\"\n call assert_equal('ic', g:mode1)\n call assert_equal('i', g:mode2)\n call assert_equal('aaa bbb ccc ', getline(1))\n exe \"normal A\\<C-N>\\<Down>\\<F1>\\<C-X>\\<C-Z>\\<F2>\\<Esc>\"\n call assert_equal('ic', g:mode1)\n call assert_equal('i', g:mode2)\n call assert_equal('aaa bbb ccc aaa', getline(1))\n set completeopt+=noselect\n exe \"normal A \\<C-N>\\<Down>\\<Down>\\<C-L>\\<C-L>\\<F1>\\<C-X>\\<C-Z>\\<F2>\\<Esc>\"\n call assert_equal('ic', g:mode1)\n call assert_equal('i', g:mode2)\n call assert_equal('aaa bbb ccc aaa bb', getline(1))\n set completeopt&\n exe \"normal A d\\<C-N>\\<F1>\\<C-X>\\<C-Z>\\<F2>\\<Esc>\"\n call assert_equal('ic', g:mode1)\n call assert_equal('i', g:mode2)\n call assert_equal('aaa bbb ccc aaa bb d', getline(1))\n com! -buffer TestCommand1 echo 'TestCommand1'\n com! -buffer TestCommand2 echo 'TestCommand2'\n exe \"normal oT\\<C-X>\\<C-V>\\<C-X>\\<C-V>\\<F1>\\<C-X>\\<C-Z>\\<F2>\\<Esc>\"\n call assert_equal('ic', g:mode1)\n call assert_equal('i', g:mode2)\n call assert_equal('TestCommand2', getline(2))\n delcom TestCommand1\n delcom TestCommand2\n unlet g:mode1\n unlet g:mode2\n iunmap <F1>\n iunmap <F2>\n delfunc Save_mode1\n delfunc Save_mode2\n close!\nendfunc", "\" Test for typing CTRL-R in insert completion mode to insert a register\n\" content.\nfunc Test_complete_reginsert()\n new\n call setline(1, ['a1', 'a12', 'a123', 'a1234'])", " \" if a valid CTRL-X mode key is returned from <C-R>=, then it should be\n \" processed. Otherwise, CTRL-X mode should be stopped and the key should be\n \" inserted.\n exe \"normal Goa\\<C-P>\\<C-R>=\\\"\\\\<C-P>\\\"\\<CR>\"\n call assert_equal('a123', getline(5))\n let @r = \"\\<C-P>\\<C-P>\"\n exe \"normal GCa\\<C-P>\\<C-R>r\"\n call assert_equal('a12', getline(5))\n exe \"normal GCa\\<C-P>\\<C-R>=\\\"x\\\"\\<CR>\"\n call assert_equal('a1234x', getline(5))\n bw!\nendfunc", "func Test_issue_7021()\n CheckMSWindows", " let orig_shellslash = &shellslash\n set noshellslash", " set completeslash=slash\n call assert_false(expand('~') =~ '/')", " let &shellslash = orig_shellslash\n set completeslash=\nendfunc", "\" Test for 'longest' setting in 'completeopt' with latin1 and utf-8 encodings\nfunc Test_complete_longest_match()\n for e in ['latin1', 'utf-8']\n exe 'set encoding=' .. e\n new\n set complete=.\n set completeopt=menu,longest\n call setline(1, ['pfx_a1', 'pfx_a12', 'pfx_a123', 'pfx_b1'])\n exe \"normal Gopfx\\<C-P>\"\n call assert_equal('pfx_', getline(5))\n bw!\n endfor", " \" Test for completing additional words with longest match set\n new\n call setline(1, ['abc1', 'abd2'])\n exe \"normal Goab\\<C-P>\\<C-X>\\<C-P>\"\n call assert_equal('ab', getline(3))\n bw!\n set complete& completeopt&\nendfunc", "\" Test for removing the first displayed completion match and selecting the\n\" match just before that.\nfunc Test_complete_erase_firstmatch()\n new\n call setline(1, ['a12', 'a34', 'a56'])\n set complete=.\n exe \"normal Goa\\<C-P>\\<BS>\\<BS>3\\<CR>\"\n call assert_equal('a34', getline('$'))\n set complete&\n bw!\nendfunc", "\" Test for completing words from unloaded buffers\nfunc Test_complete_from_unloadedbuf()\n call writefile(['abc'], \"Xfile1\")\n call writefile(['def'], \"Xfile2\")\n edit Xfile1\n edit Xfile2\n new | close\n enew\n bunload Xfile1 Xfile2\n set complete=u\n \" complete from an unloaded buffer\n exe \"normal! ia\\<C-P>\"\n call assert_equal('abc', getline(1))\n exe \"normal! od\\<C-P>\"\n call assert_equal('def', getline(2))\n set complete&\n %bw!\n call delete(\"Xfile1\")\n call delete(\"Xfile2\")\nendfunc", "\" Test for completing whole lines from unloaded buffers\nfunc Test_complete_wholeline_unloadedbuf()\n call writefile(['a line1', 'a line2', 'a line3'], \"Xfile1\")\n edit Xfile1\n enew\n set complete=u\n exe \"normal! ia\\<C-X>\\<C-L>\\<C-P>\"\n call assert_equal('a line2', getline(1))\n %d\n \" completing from an unlisted buffer should fail\n bdel Xfile1\n exe \"normal! ia\\<C-X>\\<C-L>\\<C-P>\"\n call assert_equal('a', getline(1))\n set complete&\n %bw!\n call delete(\"Xfile1\")\nendfunc", "\" Test for completing words from unlisted buffers\nfunc Test_complete_from_unlistedbuf()\n call writefile(['abc'], \"Xfile1\")\n call writefile(['def'], \"Xfile2\")\n edit Xfile1\n edit Xfile2\n new | close\n bdel Xfile1 Xfile2\n set complete=U\n \" complete from an unlisted buffer\n exe \"normal! ia\\<C-P>\"\n call assert_equal('abc', getline(1))\n exe \"normal! od\\<C-P>\"\n call assert_equal('def', getline(2))\n set complete&\n %bw!\n call delete(\"Xfile1\")\n call delete(\"Xfile2\")\nendfunc", "\" Test for completing whole lines from unlisted buffers\nfunc Test_complete_wholeline_unlistedbuf()\n call writefile(['a line1', 'a line2', 'a line3'], \"Xfile1\")\n edit Xfile1\n enew\n set complete=U\n \" completing from a unloaded buffer should fail\n exe \"normal! ia\\<C-X>\\<C-L>\\<C-P>\"\n call assert_equal('a', getline(1))\n %d\n bdel Xfile1\n exe \"normal! ia\\<C-X>\\<C-L>\\<C-P>\"\n call assert_equal('a line2', getline(1))\n set complete&\n %bw!\n call delete(\"Xfile1\")\nendfunc", "\" Test for adding a multibyte character using CTRL-L in completion mode\nfunc Test_complete_mbyte_char_add()\n new\n set complete=.\n call setline(1, 'abė')\n exe \"normal! oa\\<C-P>\\<BS>\\<BS>\\<C-L>\\<C-L>\"\n call assert_equal('abė', getline(2))\n \" Test for a leader with multibyte character\n %d\n call setline(1, 'abėĕ')\n exe \"normal! oabė\\<C-P>\"\n call assert_equal('abėĕ', getline(2))\n bw!\nendfunc", "\" Test for using <C-X><C-P> for local expansion even if 'complete' is set to\n\" not to complete matches from the local buffer. Also test using multiple\n\" <C-X> to cancel the current completion mode.\nfunc Test_complete_local_expansion()\n new\n set complete=t\n call setline(1, ['abc', 'def'])\n exe \"normal! Go\\<C-X>\\<C-P>\"\n call assert_equal(\"def\", getline(3))\n exe \"normal! Go\\<C-P>\"\n call assert_equal(\"\", getline(4))\n exe \"normal! Go\\<C-X>\\<C-N>\"\n call assert_equal(\"abc\", getline(5))\n exe \"normal! Go\\<C-N>\"\n call assert_equal(\"\", getline(6))", " \" use multiple <C-X> to cancel the previous completion mode\n exe \"normal! Go\\<C-P>\\<C-X>\\<C-P>\"\n call assert_equal(\"\", getline(7))\n exe \"normal! Go\\<C-P>\\<C-X>\\<C-X>\\<C-P>\"\n call assert_equal(\"\", getline(8))\n exe \"normal! Go\\<C-P>\\<C-X>\\<C-X>\\<C-X>\\<C-P>\"\n call assert_equal(\"abc\", getline(9))", " \" interrupt the current completion mode\n set completeopt=menu,noinsert\n exe \"normal! Go\\<C-X>\\<C-F>\\<C-X>\\<C-X>\\<C-P>\\<C-Y>\"\n call assert_equal(\"abc\", getline(10))", " \" when only one <C-X> is used to interrupt, do normal expansion\n exe \"normal! Go\\<C-X>\\<C-F>\\<C-X>\\<C-P>\"\n call assert_equal(\"\", getline(11))\n set completeopt&", " \" using two <C-X> in non-completion mode and restarting the same mode\n exe \"normal! God\\<C-X>\\<C-X>\\<C-P>\\<C-X>\\<C-X>\\<C-P>\\<C-Y>\"\n call assert_equal(\"def\", getline(12))", " \" test for adding a match from the original empty text\n %d\n call setline(1, 'abc def g')\n exe \"normal! o\\<C-X>\\<C-P>\\<C-N>\\<C-X>\\<C-P>\"\n call assert_equal('def', getline(2))\n exe \"normal! 0C\\<C-X>\\<C-N>\\<C-P>\\<C-X>\\<C-N>\"\n call assert_equal('abc', getline(2))", " bw!\nendfunc", "\" Test for undoing changes after a insert-mode completion\nfunc Test_complete_undo()\n new\n set complete=.\n \" undo with 'ignorecase'\n call setline(1, ['ABOVE', 'BELOW'])\n set ignorecase\n exe \"normal! Goab\\<C-G>u\\<C-P>\"\n call assert_equal(\"ABOVE\", getline(3))\n undo\n call assert_equal(\"ab\", getline(3))\n set ignorecase&\n %d\n \" undo with longest match\n set completeopt=menu,longest\n call setline(1, ['above', 'about'])\n exe \"normal! Goa\\<C-G>u\\<C-P>\"\n call assert_equal(\"abo\", getline(3))\n undo\n call assert_equal(\"a\", getline(3))\n set completeopt&\n %d\n \" undo for line completion\n call setline(1, ['above that change', 'below that change'])\n exe \"normal! Goabove\\<C-G>u\\<C-X>\\<C-L>\"\n call assert_equal(\"above that change\", getline(3))\n undo\n call assert_equal(\"above\", getline(3))", " bw!\nendfunc", "\" Test for completing a very long word\nfunc Test_complete_long_word()\n set complete&\n new\n call setline(1, repeat('x', 950) .. ' one two three')\n exe \"normal! Gox\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\"\n call assert_equal(repeat('x', 950) .. ' one two three', getline(2))\n %d\n \" should fail when more than 950 characters are in a word\n call setline(1, repeat('x', 951) .. ' one two three')\n exe \"normal! Gox\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\"\n call assert_equal(repeat('x', 951), getline(2))", " \" Test for adding a very long word to an existing completion\n %d\n call setline(1, ['abc', repeat('x', 1016) .. '012345'])\n exe \"normal! Goab\\<C-P>\\<C-X>\\<C-P>\"\n call assert_equal('abc ' .. repeat('x', 1016) .. '0123', getline(3))\n bw!\nendfunc", "\" Test for some fields in the complete items used by complete()\nfunc Test_complete_items()\n func CompleteItems(idx)\n let items = [[#{word: \"one\", dup: 1, user_data: 'u1'}, #{word: \"one\", dup: 1, user_data: 'u2'}],\n \\ [#{word: \"one\", dup: 0, user_data: 'u3'}, #{word: \"one\", dup: 0, user_data: 'u4'}],\n \\ [#{word: \"one\", icase: 1, user_data: 'u7'}, #{word: \"oNE\", icase: 1, user_data: 'u8'}],\n \\ [#{user_data: 'u9'}],\n \\ [#{word: \"\", user_data: 'u10'}],\n \\ [#{word: \"\", empty: 1, user_data: 'u11'}]]\n call complete(col('.'), items[a:idx])\n return ''\n endfunc\n new\n exe \"normal! i\\<C-R>=CompleteItems(0)\\<CR>\\<C-N>\\<C-Y>\"\n call assert_equal('u2', v:completed_item.user_data)\n call assert_equal('one', getline(1))\n exe \"normal! o\\<C-R>=CompleteItems(1)\\<CR>\\<C-Y>\"\n call assert_equal('u3', v:completed_item.user_data)\n call assert_equal('one', getline(2))\n exe \"normal! o\\<C-R>=CompleteItems(1)\\<CR>\\<C-N>\"\n call assert_equal('', getline(3))\n set completeopt=menu,noinsert\n exe \"normal! o\\<C-R>=CompleteItems(2)\\<CR>one\\<C-N>\\<C-Y>\"\n call assert_equal('oNE', getline(4))\n call assert_equal('u8', v:completed_item.user_data)\n set completeopt&\n exe \"normal! o\\<C-R>=CompleteItems(3)\\<CR>\"\n call assert_equal('', getline(5))\n exe \"normal! o\\<C-R>=CompleteItems(4)\\<CR>\"\n call assert_equal('', getline(6))\n exe \"normal! o\\<C-R>=CompleteItems(5)\\<CR>\"\n call assert_equal('', getline(7))\n call assert_equal('u11', v:completed_item.user_data)\n \" pass invalid argument to complete()\n let cmd = \"normal! o\\<C-R>=complete(1, [[]])\\<CR>\"\n call assert_fails('exe cmd', 'E730:')\n bw!\n delfunc CompleteItems\nendfunc", "\" Test for the \"refresh\" item in the dict returned by an insert completion\n\" function\nfunc Test_complete_item_refresh_always()\n let g:CallCount = 0\n func! Tcomplete(findstart, base)\n if a:findstart\n \" locate the start of the word\n let line = getline('.')\n let start = col('.') - 1\n while start > 0 && line[start - 1] =~ '\\a'\n let start -= 1\n endwhile\n return start\n else\n let g:CallCount += 1\n let res = [\"update1\", \"update12\", \"update123\"]\n return #{words: res, refresh: 'always'}\n endif\n endfunc\n new\n set completeopt=menu,longest\n set completefunc=Tcomplete\n exe \"normal! iup\\<C-X>\\<C-U>\\<BS>\\<BS>\\<BS>\\<BS>\\<BS>\"\n call assert_equal('up', getline(1))\n call assert_equal(2, g:CallCount)\n set completeopt&\n set completefunc&\n bw!\n delfunc Tcomplete\nendfunc", "\" Test for completing from a thesaurus file without read permission\nfunc Test_complete_unreadable_thesaurus_file()\n CheckUnix\n CheckNotRoot", " call writefile(['about', 'above'], 'Xfile')\n call setfperm('Xfile', '---r--r--')\n new\n set complete=sXfile\n exe \"normal! ia\\<C-P>\"\n call assert_equal('a', getline(1))\n bw!\n call delete('Xfile')\n set complete&\nendfunc", "\" Test to ensure 'Scanning...' messages are not recorded in messages history\nfunc Test_z1_complete_no_history()\n new\n messages clear\n let currmess = execute('messages')\n setlocal dictionary=README.txt\n exe \"normal owh\\<C-X>\\<C-K>\"\n exe \"normal owh\\<C-N>\"\n call assert_equal(currmess, execute('messages'))\n bwipe!\nendfunc", "\" A mapping is not used for the key after CTRL-X.\nfunc Test_no_mapping_for_ctrl_x_key()\n new\n inoremap <C-K> <Cmd>let was_mapped = 'yes'<CR>\n setlocal dictionary=README.txt\n call feedkeys(\"aexam\\<C-X>\\<C-K> \", 'xt')\n call assert_equal('example ', getline(1))\n call assert_false(exists('was_mapped'))\n bwipe!\nendfunc", "\" Test for different ways of setting the 'completefunc' option\nfunc Test_completefunc_callback()\n func CompleteFunc1(callnr, findstart, base)\n call add(g:CompleteFunc1Args, [a:callnr, a:findstart, a:base])\n return a:findstart ? 0 : []\n endfunc\n func CompleteFunc2(findstart, base)\n call add(g:CompleteFunc2Args, [a:findstart, a:base])\n return a:findstart ? 0 : []\n endfunc", " let lines =<< trim END\n #\" Test for using a global function name\n LET &completefunc = 'g:CompleteFunc2'\n new\n call setline(1, 'global')\n LET g:CompleteFunc2Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'global']], g:CompleteFunc2Args)\n bw!", " #\" Test for using a function()\n set completefunc=function('g:CompleteFunc1',\\ [10])\n new\n call setline(1, 'one')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[10, 1, ''], [10, 0, 'one']], g:CompleteFunc1Args)\n bw!", " #\" Using a funcref variable to set 'completefunc'\n VAR Fn = function('g:CompleteFunc1', [11])\n LET &completefunc = Fn\n new\n call setline(1, 'two')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[11, 1, ''], [11, 0, 'two']], g:CompleteFunc1Args)\n bw!", " #\" Using string(funcref_variable) to set 'completefunc'\n LET Fn = function('g:CompleteFunc1', [12])\n LET &completefunc = string(Fn)\n new\n call setline(1, 'two')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[12, 1, ''], [12, 0, 'two']], g:CompleteFunc1Args)\n bw!", " #\" Test for using a funcref()\n set completefunc=funcref('g:CompleteFunc1',\\ [13])\n new\n call setline(1, 'three')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[13, 1, ''], [13, 0, 'three']], g:CompleteFunc1Args)\n bw!", " #\" Using a funcref variable to set 'completefunc'\n LET Fn = funcref('g:CompleteFunc1', [14])\n LET &completefunc = Fn\n new\n call setline(1, 'four')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[14, 1, ''], [14, 0, 'four']], g:CompleteFunc1Args)\n bw!", " #\" Using a string(funcref_variable) to set 'completefunc'\n LET Fn = funcref('g:CompleteFunc1', [15])\n LET &completefunc = string(Fn)\n new\n call setline(1, 'four')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[15, 1, ''], [15, 0, 'four']], g:CompleteFunc1Args)\n bw!", " #\" Test for using a lambda function with set\n VAR optval = \"LSTART a, b LMIDDLE g:CompleteFunc1(16, a, b) LEND\"\n LET optval = substitute(optval, ' ', '\\\\ ', 'g')\n exe \"set completefunc=\" .. optval\n new\n call setline(1, 'five')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[16, 1, ''], [16, 0, 'five']], g:CompleteFunc1Args)\n bw!", " #\" Set 'completefunc' to a lambda expression\n LET &completefunc = LSTART a, b LMIDDLE g:CompleteFunc1(17, a, b) LEND\n new\n call setline(1, 'six')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[17, 1, ''], [17, 0, 'six']], g:CompleteFunc1Args)\n bw!", " #\" Set 'completefunc' to string(lambda_expression)\n LET &completefunc = 'LSTART a, b LMIDDLE g:CompleteFunc1(18, a, b) LEND'\n new\n call setline(1, 'six')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[18, 1, ''], [18, 0, 'six']], g:CompleteFunc1Args)\n bw!", " #\" Set 'completefunc' to a variable with a lambda expression\n VAR Lambda = LSTART a, b LMIDDLE g:CompleteFunc1(19, a, b) LEND\n LET &completefunc = Lambda\n new\n call setline(1, 'seven')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[19, 1, ''], [19, 0, 'seven']], g:CompleteFunc1Args)\n bw!", " #\" Set 'completefunc' to a string(variable with a lambda expression)\n LET Lambda = LSTART a, b LMIDDLE g:CompleteFunc1(20, a, b) LEND\n LET &completefunc = string(Lambda)\n new\n call setline(1, 'seven')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[20, 1, ''], [20, 0, 'seven']], g:CompleteFunc1Args)\n bw!", " #\" Test for using a lambda function with incorrect return value\n LET Lambda = LSTART a, b LMIDDLE strlen(a) LEND\n LET &completefunc = Lambda\n new\n call setline(1, 'eight')\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n bw!", " #\" Test for clearing the 'completefunc' option\n set completefunc=''\n set completefunc&\n call assert_fails(\"set completefunc=function('abc')\", \"E700:\")\n call assert_fails(\"set completefunc=funcref('abc')\", \"E700:\")", " #\" set 'completefunc' to a non-existing function\n set completefunc=g:CompleteFunc2\n call setline(1, 'five')\n call assert_fails(\"set completefunc=function('NonExistingFunc')\", 'E700:')\n call assert_fails(\"LET &completefunc = function('NonExistingFunc')\", 'E700:')\n LET g:CompleteFunc2Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'five']], g:CompleteFunc2Args)\n bw!\n END\n call v9.CheckLegacyAndVim9Success(lines)", " \" Test for using a script-local function name\n func s:CompleteFunc3(findstart, base)\n call add(g:CompleteFunc3Args, [a:findstart, a:base])\n return a:findstart ? 0 : []\n endfunc\n set completefunc=s:CompleteFunc3\n new\n call setline(1, 'script1')\n let g:CompleteFunc3Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'script1']], g:CompleteFunc3Args)\n bw!", " let &completefunc = 's:CompleteFunc3'\n new\n call setline(1, 'script2')\n let g:CompleteFunc3Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'script2']], g:CompleteFunc3Args)\n bw!\n delfunc s:CompleteFunc3", " \" In Vim9 script s: can be omitted\n let lines =<< trim END\n vim9script\n var CompleteFunc4Args = []\n def CompleteFunc4(findstart: bool, base: string): any\n add(CompleteFunc4Args, [findstart, base])\n return findstart ? 0 : []\n enddef\n set completefunc=CompleteFunc4\n new\n setline(1, 'script1')\n feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n assert_equal([[1, ''], [0, 'script1']], CompleteFunc4Args)\n bw!\n END\n call v9.CheckScriptSuccess(lines)", " \" invalid return value\n let &completefunc = {a -> 'abc'}\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')", " \" Using Vim9 lambda expression in legacy context should fail\n set completefunc=(a,\\ b)\\ =>\\ g:CompleteFunc1(21,\\ a,\\ b)\n new | only\n let g:CompleteFunc1Args = []\n call assert_fails('call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", \"x\")', 'E117:')\n call assert_equal([], g:CompleteFunc1Args)", " \" set 'completefunc' to a partial with dict. This used to cause a crash.\n func SetCompleteFunc()\n let params = {'complete': function('g:DictCompleteFunc')}\n let &completefunc = params.complete\n endfunc\n func g:DictCompleteFunc(_) dict\n endfunc\n call SetCompleteFunc()\n new\n call SetCompleteFunc()\n bw\n call test_garbagecollect_now()\n new\n set completefunc=\n wincmd w\n set completefunc=\n %bw!\n delfunc g:DictCompleteFunc\n delfunc SetCompleteFunc", " \" Vim9 tests\n let lines =<< trim END\n vim9script", " def Vim9CompleteFunc(callnr: number, findstart: number, base: string): any\n add(g:Vim9completeFuncArgs, [callnr, findstart, base])\n return findstart ? 0 : []\n enddef", " # Test for using a def function with completefunc\n set completefunc=function('Vim9CompleteFunc',\\ [60])\n new | only\n setline(1, 'one')\n g:Vim9completeFuncArgs = []\n feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n assert_equal([[60, 1, ''], [60, 0, 'one']], g:Vim9completeFuncArgs)\n bw!", " # Test for using a global function name\n &completefunc = g:CompleteFunc2\n new | only\n setline(1, 'two')\n g:CompleteFunc2Args = []\n feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n assert_equal([[1, ''], [0, 'two']], g:CompleteFunc2Args)\n bw!", " # Test for using a script-local function name\n def LocalCompleteFunc(findstart: number, base: string): any\n add(g:LocalCompleteFuncArgs, [findstart, base])\n return findstart ? 0 : []\n enddef\n &completefunc = LocalCompleteFunc\n new | only\n setline(1, 'three')\n g:LocalCompleteFuncArgs = []\n feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n assert_equal([[1, ''], [0, 'three']], g:LocalCompleteFuncArgs)\n bw!\n END\n call v9.CheckScriptSuccess(lines)", " \" cleanup\n set completefunc&\n delfunc CompleteFunc1\n delfunc CompleteFunc2\n unlet g:CompleteFunc1Args g:CompleteFunc2Args\n %bw!\nendfunc", "\" Test for different ways of setting the 'omnifunc' option\nfunc Test_omnifunc_callback()\n func OmniFunc1(callnr, findstart, base)\n call add(g:OmniFunc1Args, [a:callnr, a:findstart, a:base])\n return a:findstart ? 0 : []\n endfunc\n func OmniFunc2(findstart, base)\n call add(g:OmniFunc2Args, [a:findstart, a:base])\n return a:findstart ? 0 : []\n endfunc", " let lines =<< trim END\n #\" Test for using a function name\n LET &omnifunc = 'g:OmniFunc2'\n new\n call setline(1, 'zero')\n LET g:OmniFunc2Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'zero']], g:OmniFunc2Args)\n bw!", " #\" Test for using a function()\n set omnifunc=function('g:OmniFunc1',\\ [10])\n new\n call setline(1, 'one')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[10, 1, ''], [10, 0, 'one']], g:OmniFunc1Args)\n bw!", " #\" Using a funcref variable to set 'omnifunc'\n VAR Fn = function('g:OmniFunc1', [11])\n LET &omnifunc = Fn\n new\n call setline(1, 'two')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[11, 1, ''], [11, 0, 'two']], g:OmniFunc1Args)\n bw!", " #\" Using a string(funcref_variable) to set 'omnifunc'\n LET Fn = function('g:OmniFunc1', [12])\n LET &omnifunc = string(Fn)\n new\n call setline(1, 'two')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[12, 1, ''], [12, 0, 'two']], g:OmniFunc1Args)\n bw!", " #\" Test for using a funcref()\n set omnifunc=funcref('g:OmniFunc1',\\ [13])\n new\n call setline(1, 'three')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[13, 1, ''], [13, 0, 'three']], g:OmniFunc1Args)\n bw!", " #\" Use let to set 'omnifunc' to a funcref\n LET Fn = funcref('g:OmniFunc1', [14])\n LET &omnifunc = Fn\n new\n call setline(1, 'four')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[14, 1, ''], [14, 0, 'four']], g:OmniFunc1Args)\n bw!", " #\" Using a string(funcref) to set 'omnifunc'\n LET Fn = funcref(\"g:OmniFunc1\", [15])\n LET &omnifunc = string(Fn)\n new\n call setline(1, 'four')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[15, 1, ''], [15, 0, 'four']], g:OmniFunc1Args)\n bw!", " #\" Test for using a lambda function with set\n VAR optval = \"LSTART a, b LMIDDLE g:OmniFunc1(16, a, b) LEND\"\n LET optval = substitute(optval, ' ', '\\\\ ', 'g')\n exe \"set omnifunc=\" .. optval\n new\n call setline(1, 'five')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[16, 1, ''], [16, 0, 'five']], g:OmniFunc1Args)\n bw!", " #\" Set 'omnifunc' to a lambda expression\n LET &omnifunc = LSTART a, b LMIDDLE g:OmniFunc1(17, a, b) LEND\n new\n call setline(1, 'six')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[17, 1, ''], [17, 0, 'six']], g:OmniFunc1Args)\n bw!", " #\" Set 'omnifunc' to a string(lambda_expression)\n LET &omnifunc = 'LSTART a, b LMIDDLE g:OmniFunc1(18, a, b) LEND'\n new\n call setline(1, 'six')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[18, 1, ''], [18, 0, 'six']], g:OmniFunc1Args)\n bw!", " #\" Set 'omnifunc' to a variable with a lambda expression\n VAR Lambda = LSTART a, b LMIDDLE g:OmniFunc1(19, a, b) LEND\n LET &omnifunc = Lambda\n new\n call setline(1, 'seven')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[19, 1, ''], [19, 0, 'seven']], g:OmniFunc1Args)\n bw!", " #\" Set 'omnifunc' to a string(variable with a lambda expression)\n LET Lambda = LSTART a, b LMIDDLE g:OmniFunc1(20, a, b) LEND\n LET &omnifunc = string(Lambda)\n new\n call setline(1, 'seven')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[20, 1, ''], [20, 0, 'seven']], g:OmniFunc1Args)\n bw!", " #\" Test for using a lambda function with incorrect return value\n LET Lambda = LSTART a, b LMIDDLE strlen(a) LEND\n LET &omnifunc = Lambda\n new\n call setline(1, 'eight')\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n bw!", " #\" Test for clearing the 'omnifunc' option\n set omnifunc=''\n set omnifunc&\n call assert_fails(\"set omnifunc=function('abc')\", \"E700:\")\n call assert_fails(\"set omnifunc=funcref('abc')\", \"E700:\")", " #\" set 'omnifunc' to a non-existing function\n set omnifunc=g:OmniFunc2\n call setline(1, 'nine')\n call assert_fails(\"set omnifunc=function('NonExistingFunc')\", 'E700:')\n call assert_fails(\"LET &omnifunc = function('NonExistingFunc')\", 'E700:')\n LET g:OmniFunc2Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'nine']], g:OmniFunc2Args)\n bw!\n END\n call v9.CheckLegacyAndVim9Success(lines)", " \" Test for using a script-local function name\n func s:OmniFunc3(findstart, base)\n call add(g:OmniFunc3Args, [a:findstart, a:base])\n return a:findstart ? 0 : []\n endfunc\n set omnifunc=s:OmniFunc3\n new\n call setline(1, 'script1')\n let g:OmniFunc3Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'script1']], g:OmniFunc3Args)\n bw!", " let &omnifunc = 's:OmniFunc3'\n new\n call setline(1, 'script2')\n let g:OmniFunc3Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'script2']], g:OmniFunc3Args)\n bw!\n delfunc s:OmniFunc3", " \" invalid return value\n let &omnifunc = {a -> 'abc'}\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')", " \" Using Vim9 lambda expression in legacy context should fail\n set omnifunc=(a,\\ b)\\ =>\\ OmniFunc1(21,\\ a,\\ b)\n new | only\n let g:OmniFunc1Args = []\n call assert_fails('call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", \"x\")', 'E117:')\n call assert_equal([], g:OmniFunc1Args)", " \" set 'omnifunc' to a partial with dict. This used to cause a crash.\n func SetOmniFunc()\n let params = {'omni': function('g:DictOmniFunc')}\n let &omnifunc = params.omni\n endfunc\n func g:DictOmniFunc(_) dict\n endfunc\n call SetOmniFunc()\n new\n call SetOmniFunc()\n bw\n call test_garbagecollect_now()\n new\n set omnifunc=\n wincmd w\n set omnifunc=\n %bw!\n delfunc g:DictOmniFunc\n delfunc SetOmniFunc", " \" Vim9 tests\n let lines =<< trim END\n vim9script", " def Vim9omniFunc(callnr: number, findstart: number, base: string): any\n add(g:Vim9omniFunc_Args, [callnr, findstart, base])\n return findstart ? 0 : []\n enddef", " # Test for using a def function with omnifunc\n set omnifunc=function('Vim9omniFunc',\\ [60])\n new | only\n setline(1, 'one')\n g:Vim9omniFunc_Args = []\n feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n assert_equal([[60, 1, ''], [60, 0, 'one']], g:Vim9omniFunc_Args)\n bw!", " # Test for using a global function name\n &omnifunc = g:OmniFunc2\n new | only\n setline(1, 'two')\n g:OmniFunc2Args = []\n feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n assert_equal([[1, ''], [0, 'two']], g:OmniFunc2Args)\n bw!", " # Test for using a script-local function name\n def LocalOmniFunc(findstart: number, base: string): any\n add(g:LocalOmniFuncArgs, [findstart, base])\n return findstart ? 0 : []\n enddef\n &omnifunc = LocalOmniFunc\n new | only\n setline(1, 'three')\n g:LocalOmniFuncArgs = []\n feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n assert_equal([[1, ''], [0, 'three']], g:LocalOmniFuncArgs)\n bw!\n END\n call v9.CheckScriptSuccess(lines)", " \" cleanup\n set omnifunc&\n delfunc OmniFunc1\n delfunc OmniFunc2\n unlet g:OmniFunc1Args g:OmniFunc2Args\n %bw!\nendfunc", "\" Test for different ways of setting the 'thesaurusfunc' option\nfunc Test_thesaurusfunc_callback()\n func TsrFunc1(callnr, findstart, base)\n call add(g:TsrFunc1Args, [a:callnr, a:findstart, a:base])\n return a:findstart ? 0 : []\n endfunc\n func TsrFunc2(findstart, base)\n call add(g:TsrFunc2Args, [a:findstart, a:base])\n return a:findstart ? 0 : ['sunday']\n endfunc", " let lines =<< trim END\n #\" Test for using a function name\n LET &thesaurusfunc = 'g:TsrFunc2'\n new\n call setline(1, 'zero')\n LET g:TsrFunc2Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'zero']], g:TsrFunc2Args)\n bw!", " #\" Test for using a function()\n set thesaurusfunc=function('g:TsrFunc1',\\ [10])\n new\n call setline(1, 'one')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[10, 1, ''], [10, 0, 'one']], g:TsrFunc1Args)\n bw!", " #\" Using a funcref variable to set 'thesaurusfunc'\n VAR Fn = function('g:TsrFunc1', [11])\n LET &thesaurusfunc = Fn\n new\n call setline(1, 'two')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[11, 1, ''], [11, 0, 'two']], g:TsrFunc1Args)\n bw!", " #\" Using a string(funcref_variable) to set 'thesaurusfunc'\n LET Fn = function('g:TsrFunc1', [12])\n LET &thesaurusfunc = string(Fn)\n new\n call setline(1, 'two')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[12, 1, ''], [12, 0, 'two']], g:TsrFunc1Args)\n bw!", " #\" Test for using a funcref()\n set thesaurusfunc=funcref('g:TsrFunc1',\\ [13])\n new\n call setline(1, 'three')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[13, 1, ''], [13, 0, 'three']], g:TsrFunc1Args)\n bw!", " #\" Using a funcref variable to set 'thesaurusfunc'\n LET Fn = funcref('g:TsrFunc1', [14])\n LET &thesaurusfunc = Fn\n new\n call setline(1, 'four')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[14, 1, ''], [14, 0, 'four']], g:TsrFunc1Args)\n bw!", " #\" Using a string(funcref_variable) to set 'thesaurusfunc'\n LET Fn = funcref('g:TsrFunc1', [15])\n LET &thesaurusfunc = string(Fn)\n new\n call setline(1, 'four')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[15, 1, ''], [15, 0, 'four']], g:TsrFunc1Args)\n bw!", " #\" Test for using a lambda function\n VAR optval = \"LSTART a, b LMIDDLE g:TsrFunc1(16, a, b) LEND\"\n LET optval = substitute(optval, ' ', '\\\\ ', 'g')\n exe \"set thesaurusfunc=\" .. optval\n new\n call setline(1, 'five')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[16, 1, ''], [16, 0, 'five']], g:TsrFunc1Args)\n bw!", " #\" Test for using a lambda function with set\n LET &thesaurusfunc = LSTART a, b LMIDDLE g:TsrFunc1(17, a, b) LEND\n new\n call setline(1, 'six')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[17, 1, ''], [17, 0, 'six']], g:TsrFunc1Args)\n bw!", " #\" Set 'thesaurusfunc' to a string(lambda expression)\n LET &thesaurusfunc = 'LSTART a, b LMIDDLE g:TsrFunc1(18, a, b) LEND'\n new\n call setline(1, 'six')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[18, 1, ''], [18, 0, 'six']], g:TsrFunc1Args)\n bw!", " #\" Set 'thesaurusfunc' to a variable with a lambda expression\n VAR Lambda = LSTART a, b LMIDDLE g:TsrFunc1(19, a, b) LEND\n LET &thesaurusfunc = Lambda\n new\n call setline(1, 'seven')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[19, 1, ''], [19, 0, 'seven']], g:TsrFunc1Args)\n bw!", " #\" Set 'thesaurusfunc' to a string(variable with a lambda expression)\n LET Lambda = LSTART a, b LMIDDLE g:TsrFunc1(20, a, b) LEND\n LET &thesaurusfunc = string(Lambda)\n new\n call setline(1, 'seven')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[20, 1, ''], [20, 0, 'seven']], g:TsrFunc1Args)\n bw!", " #\" Test for using a lambda function with incorrect return value\n LET Lambda = LSTART a, b LMIDDLE strlen(a) LEND\n LET &thesaurusfunc = Lambda\n new\n call setline(1, 'eight')\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n bw!", " #\" Test for clearing the 'thesaurusfunc' option\n set thesaurusfunc=''\n set thesaurusfunc&\n call assert_fails(\"set thesaurusfunc=function('abc')\", \"E700:\")\n call assert_fails(\"set thesaurusfunc=funcref('abc')\", \"E700:\")", " #\" set 'thesaurusfunc' to a non-existing function\n set thesaurusfunc=g:TsrFunc2\n call setline(1, 'ten')\n call assert_fails(\"set thesaurusfunc=function('NonExistingFunc')\", 'E700:')\n call assert_fails(\"LET &thesaurusfunc = function('NonExistingFunc')\", 'E700:')\n LET g:TsrFunc2Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'ten']], g:TsrFunc2Args)\n bw!", " #\" Use a buffer-local value and a global value\n set thesaurusfunc&\n setlocal thesaurusfunc=function('g:TsrFunc1',\\ [22])\n call setline(1, 'sun')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", \"x\")\n call assert_equal('sun', getline(1))\n call assert_equal([[22, 1, ''], [22, 0, 'sun']], g:TsrFunc1Args)\n new\n call setline(1, 'sun')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", \"x\")\n call assert_equal('sun', getline(1))\n call assert_equal([], g:TsrFunc1Args)\n set thesaurusfunc=function('g:TsrFunc1',\\ [23])\n wincmd w\n call setline(1, 'sun')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", \"x\")\n call assert_equal('sun', getline(1))\n call assert_equal([[22, 1, ''], [22, 0, 'sun']], g:TsrFunc1Args)\n :%bw!\n END\n call v9.CheckLegacyAndVim9Success(lines)", " \" Test for using a script-local function name\n func s:TsrFunc3(findstart, base)\n call add(g:TsrFunc3Args, [a:findstart, a:base])\n return a:findstart ? 0 : []\n endfunc\n set tsrfu=s:TsrFunc3\n new\n call setline(1, 'script1')\n let g:TsrFunc3Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'script1']], g:TsrFunc3Args)\n bw!", " let &tsrfu = 's:TsrFunc3'\n new\n call setline(1, 'script2')\n let g:TsrFunc3Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'script2']], g:TsrFunc3Args)\n bw!\n delfunc s:TsrFunc3", " \" invalid return value\n let &thesaurusfunc = {a -> 'abc'}\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')", " \" Using Vim9 lambda expression in legacy context should fail\n set thesaurusfunc=(a,\\ b)\\ =>\\ TsrFunc1(21,\\ a,\\ b)\n new | only\n let g:TsrFunc1Args = []\n call assert_fails('call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", \"x\")', 'E117:')\n call assert_equal([], g:TsrFunc1Args)\n bw!", " \" set 'thesaurusfunc' to a partial with dict. This used to cause a crash.\n func SetTsrFunc()\n let params = {'thesaurus': function('g:DictTsrFunc')}\n let &thesaurusfunc = params.thesaurus\n endfunc\n func g:DictTsrFunc(_) dict\n endfunc\n call SetTsrFunc()\n new\n call SetTsrFunc()\n bw\n call test_garbagecollect_now()\n new\n set thesaurusfunc=\n wincmd w\n %bw!\n delfunc SetTsrFunc", " \" set buffer-local 'thesaurusfunc' to a partial with dict. This used to\n \" cause a crash.\n func SetLocalTsrFunc()\n let params = {'thesaurus': function('g:DictTsrFunc')}\n let &l:thesaurusfunc = params.thesaurus\n endfunc\n call SetLocalTsrFunc()\n call test_garbagecollect_now()\n call SetLocalTsrFunc()\n set thesaurusfunc=\n bw!\n delfunc g:DictTsrFunc\n delfunc SetLocalTsrFunc", " \" Vim9 tests\n let lines =<< trim END\n vim9script", " def Vim9tsrFunc(callnr: number, findstart: number, base: string): any\n add(g:Vim9tsrFunc_Args, [callnr, findstart, base])\n return findstart ? 0 : []\n enddef", " # Test for using a def function with thesaurusfunc\n set thesaurusfunc=function('Vim9tsrFunc',\\ [60])\n new | only\n setline(1, 'one')\n g:Vim9tsrFunc_Args = []\n feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n assert_equal([[60, 1, ''], [60, 0, 'one']], g:Vim9tsrFunc_Args)\n bw!", " # Test for using a global function name\n &thesaurusfunc = g:TsrFunc2\n new | only\n setline(1, 'two')\n g:TsrFunc2Args = []\n feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n assert_equal([[1, ''], [0, 'two']], g:TsrFunc2Args)\n bw!", " # Test for using a script-local function name\n def LocalTsrFunc(findstart: number, base: string): any\n add(g:LocalTsrFuncArgs, [findstart, base])\n return findstart ? 0 : []\n enddef\n &thesaurusfunc = LocalTsrFunc\n new | only\n setline(1, 'three')\n g:LocalTsrFuncArgs = []\n feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n assert_equal([[1, ''], [0, 'three']], g:LocalTsrFuncArgs)\n bw!\n END\n call v9.CheckScriptSuccess(lines)", " \" cleanup\n set thesaurusfunc&\n delfunc TsrFunc1\n delfunc TsrFunc2\n unlet g:TsrFunc1Args g:TsrFunc2Args\n %bw!\nendfunc", "func FooBarComplete(findstart, base)\n if a:findstart\n return col('.') - 1\n else\n return [\"Foo\", \"Bar\", \"}\"]\n endif\nendfunc", "func Test_complete_smartindent()\n new\n setlocal smartindent completefunc=FooBarComplete", " exe \"norm! o{\\<cr>\\<c-x>\\<c-u>\\<c-p>}\\<cr>\\<esc>\"\n let result = getline(1,'$')\n call assert_equal(['', '{','}',''], result)\n bw!\n delfunction! FooBarComplete\nendfunc", "func Test_complete_overrun()\n \" this was going past the end of the copied text\n new\n sil norm si”\u00140\u0003s\u000f0\u0018\f\u0005\n bwipe!\nendfunc\n", "", "\" vim: shiftwidth=2 sts=2 expandtab" ]
[ 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, 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, 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, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [698, 2100, 737], "buggy_code_start_loc": [526, 2100, 737], "filenames": ["src/insexpand.c", "src/testdir/test_ins_complete.vim", "src/version.c"], "fixing_code_end_loc": [736, 2117, 740], "fixing_code_start_loc": [527, 2101, 738], "message": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0044.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "0069C36F-19A3-4647-B84F-84CE62E8A554", "versionEndExcluding": "9.0.0044", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:35:*:*:*:*:*:*:*", "matchCriteriaId": "80E516C0-98A4-4ADE-B69F-66A772E2BAAA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0044."}, {"lang": "es", "value": "Un Desbordamiento de B\u00fafer en la Regi\u00f3n Heap de la Memoria en el repositorio de GitHub vim/vim versiones anteriores a 9.0.0044"}], "evaluatorComment": null, "id": "CVE-2022-2343", "lastModified": "2023-05-03T12:15:58.413", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-07-08T18:15:09.820", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/caea66442d86e7bbba3bf3dc202c3c0d549b9853"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2ecb4345-2fc7-4e7f-adb0-83a20bb458f5"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/43Y3VJPOTTY3NTREDIFUPITM2POG4ZLP/"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/202208-32"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-122"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/caea66442d86e7bbba3bf3dc202c3c0d549b9853"}, "type": "CWE-122"}
172
Determine whether the {function_name} code is vulnerable or not.
[ "\" Test for insert completion", "source screendump.vim\nsource check.vim\nimport './vim9.vim' as v9", "\" Test for insert expansion\nfunc Test_ins_complete()\n edit test_ins_complete.vim\n \" The files in the current directory interferes with the files\n \" used by this test. So use a separate directory for the test.\n call mkdir('Xdir')\n cd Xdir", " set ff=unix\n call writefile([\"test11\\t36Gepeto\\t/Tag/\",\n\t \\ \"asd\\ttest11file\\t36G\",\n\t \\ \"Makefile\\tto\\trun\"], 'Xtestfile')\n call writefile(['', 'start of testfile',\n\t \\ 'ru',\n\t \\ 'run1',\n\t \\ 'run2',\n\t \\ 'STARTTEST',\n\t \\ 'ENDTEST',\n\t \\ 'end of testfile'], 'Xtestdata')\n set ff&", " enew!\n edit Xtestdata\n new\n call append(0, ['#include \"Xtestfile\"', ''])\n call cursor(2, 1)", " set cot=\n set cpt=.,w\n \" add-expands (word from next line) from other window\n exe \"normal iru\\<C-N>\\<C-N>\\<C-X>\\<C-N>\\<Esc>\\<C-A>\"\n call assert_equal('run1 run3', getline('.'))\n \" add-expands (current buffer first)\n exe \"normal o\\<C-P>\\<C-X>\\<C-N>\"\n call assert_equal('run3 run3', getline('.'))\n \" Local expansion, ends in an empty line (unless it becomes a global\n \" expansion)\n exe \"normal o\\<C-X>\\<C-P>\\<C-P>\\<C-P>\\<C-P>\\<C-P>\"\n call assert_equal('', getline('.'))\n \" starts Local and switches to global add-expansion\n exe \"normal o\\<C-X>\\<C-P>\\<C-P>\\<C-X>\\<C-X>\\<C-N>\\<C-X>\\<C-N>\\<C-N>\"\n call assert_equal('run1 run2', getline('.'))", " set cpt=.,\\ ,w,i\n \" i-add-expands and switches to local\n exe \"normal OM\\<C-N>\\<C-X>\\<C-N>\\<C-X>\\<C-N>\\<C-X>\\<C-X>\\<C-X>\\<C-P>\"\n call assert_equal(\"Makefile\\tto\\trun3\", getline('.'))\n \" add-expands lines (it would end in an empty line if it didn't ignore\n \" itself)\n exe \"normal o\\<C-X>\\<C-L>\\<C-X>\\<C-L>\\<C-P>\\<C-P>\"\n call assert_equal(\"Makefile\\tto\\trun3\", getline('.'))\n call assert_equal(\"Makefile\\tto\\trun3\", getline(line('.') - 1))", " set cpt=kXtestfile\n \" checks k-expansion, and file expansion (use Xtest11 instead of test11,\n \" because TEST11.OUT may match first on DOS)\n write Xtest11.one\n write Xtest11.two\n exe \"normal o\\<C-N>\\<Esc>IX\\<Esc>A\\<C-X>\\<C-F>\\<C-N>\"\n call assert_equal('Xtest11.two', getline('.'))", " \" use CTRL-X CTRL-F to complete Xtest11.one, remove it and then use CTRL-X\n \" CTRL-F again to verify this doesn't cause trouble.\n exe \"normal oXt\\<C-X>\\<C-F>\\<BS>\\<BS>\\<BS>\\<BS>\\<BS>\\<BS>\\<BS>\\<BS>\\<C-X>\\<C-F>\"\n call assert_equal('Xtest11.one', getline('.'))\n normal ddk", " \" Test for expanding a non-existing filename\n exe \"normal oa1b2X3Y4\\<C-X>\\<C-F>\"\n call assert_equal('a1b2X3Y4', getline('.'))\n normal ddk", " set cpt=w\n \" checks make_cyclic in other window\n exe \"normal oST\\<C-N>\\<C-P>\\<C-P>\\<C-P>\\<C-P>\"\n call assert_equal('STARTTEST', getline('.'))", " set cpt=u nohid\n \" checks unloaded buffer expansion\n only\n exe \"normal oEN\\<C-N>\"\n call assert_equal('ENDTEST', getline('.'))\n \" checks adding mode abortion\n exe \"normal ounl\\<C-N>\\<C-X>\\<C-X>\\<C-P>\"\n call assert_equal('unless', getline('.'))", " set cpt=t,d def=^\\\\k* tags=Xtestfile notagbsearch\n \" tag expansion, define add-expansion interrupted\n exe \"normal o\\<C-X>\\<C-]>\\<C-X>\\<C-D>\\<C-X>\\<C-D>\\<C-X>\\<C-X>\\<C-D>\\<C-X>\\<C-D>\\<C-X>\\<C-D>\\<C-X>\\<C-D>\"\n call assert_equal('test11file\t36Gepeto\t/Tag/ asd', getline('.'))\n \" t-expansion\n exe \"normal oa\\<C-N>\\<Esc>\"\n call assert_equal('asd', getline('.'))", " %bw!\n call delete('Xtestfile')\n call delete('Xtest11.one')\n call delete('Xtest11.two')\n call delete('Xtestdata')\n set cpt& cot& def& tags& tagbsearch& hidden&\n cd ..\n call delete('Xdir', 'rf')\nendfunc", "func Test_ins_complete_invalid_byte()\n if has('unix') && executable('base64')\n \" this weird command was causing an illegal memory access\n call writefile(['bm9ybTlvMDCAMM4Dbw4OGA4ODg=='], 'Xinvalid64')\n call system('base64 -d Xinvalid64 > Xinvalid')\n call writefile(['qa!'], 'Xexit')\n call RunVim([], [], \" -i NONE -n -X -Z -e -m -s -S Xinvalid -S Xexit\")\n call delete('Xinvalid64')\n call delete('Xinvalid')\n call delete('Xexit')\n endif\nendfunc", "func Test_omni_dash()\n func Omni(findstart, base)\n if a:findstart\n return 5\n else\n echom a:base\n\treturn ['-help', '-v']\n endif\n endfunc\n set omnifunc=Omni\n new\n exe \"normal Gofind -\\<C-x>\\<C-o>\"\n call assert_equal(\"find -help\", getline('$'))", " bwipe!\n delfunc Omni\n set omnifunc=\nendfunc", "func Test_omni_throw()\n let g:CallCount = 0\n func Omni(findstart, base)\n let g:CallCount += 1\n if a:findstart\n throw \"he he he\"\n endif\n endfunc\n set omnifunc=Omni\n new\n try\n exe \"normal ifoo\\<C-x>\\<C-o>\"\n call assert_false(v:true, 'command should have failed')\n catch\n call assert_exception('he he he')\n call assert_equal(1, g:CallCount)\n endtry", " bwipe!\n delfunc Omni\n unlet g:CallCount\n set omnifunc=\nendfunc", "func Test_omni_autoload()\n let save_rtp = &rtp\n set rtp=Xruntime/some\n let dir = 'Xruntime/some/autoload'\n call mkdir(dir, 'p')", " let lines =<< trim END\n vim9script\n export def Func(findstart: bool, base: string): any\n if findstart\n return 1\n else\n return ['match']\n endif\n enddef\n {\n eval 1 + 2\n }\n END\n call writefile(lines, dir .. '/omni.vim')", " new\n setlocal omnifunc=omni#Func\n call feedkeys(\"i\\<C-X>\\<C-O>\\<Esc>\", 'xt')", " bwipe!\n call delete('Xruntime', 'rf')\n set omnifunc=\n let &rtp = save_rtp\nendfunc", "func Test_completefunc_args()\n let s:args = []\n func! CompleteFunc(findstart, base)\n let s:args += [[a:findstart, empty(a:base)]]\n endfunc\n new", " set completefunc=CompleteFunc\n call feedkeys(\"i\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([1, 1], s:args[0])\n call assert_equal(0, s:args[1][0])\n set completefunc=", " let s:args = []\n set omnifunc=CompleteFunc\n call feedkeys(\"i\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([1, 1], s:args[0])\n call assert_equal(0, s:args[1][0])\n set omnifunc=", " bwipe!\n unlet s:args\n delfunc CompleteFunc\nendfunc", "func s:CompleteDone_CompleteFuncNone( findstart, base )\n if a:findstart\n return 0\n endif", " return v:none\nendfunc", "func s:CompleteDone_CompleteFuncDict( findstart, base )\n if a:findstart\n return 0\n endif", " return {\n\t \\ 'words': [\n\t \\ {\n\t \\ 'word': 'aword',\n\t \\ 'abbr': 'wrd',\n\t \\ 'menu': 'extra text',\n\t \\ 'info': 'words are cool',\n\t \\ 'kind': 'W',\n\t \\ 'user_data': 'test'\n\t \\ }\n\t \\ ]\n\t\\ }\nendfunc", "func s:CompleteDone_CheckCompletedItemNone()\n let s:called_completedone = 1\nendfunc", "func s:CompleteDone_CheckCompletedItemDict(pre)\n call assert_equal( 'aword', v:completed_item[ 'word' ] )\n call assert_equal( 'wrd', v:completed_item[ 'abbr' ] )\n call assert_equal( 'extra text', v:completed_item[ 'menu' ] )\n call assert_equal( 'words are cool', v:completed_item[ 'info' ] )\n call assert_equal( 'W', v:completed_item[ 'kind' ] )\n call assert_equal( 'test', v:completed_item[ 'user_data' ] )", " if a:pre\n call assert_equal('function', complete_info().mode)\n endif", " let s:called_completedone = 1\nendfunc", "func Test_CompleteDoneNone()\n au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemNone()\n let oldline = join(map(range(&columns), 'nr2char(screenchar(&lines-1, v:val+1))'), '')", " set completefunc=<SID>CompleteDone_CompleteFuncNone\n execute \"normal a\\<C-X>\\<C-U>\\<C-Y>\"\n set completefunc&\n let newline = join(map(range(&columns), 'nr2char(screenchar(&lines-1, v:val+1))'), '')", " call assert_true(s:called_completedone)\n call assert_equal(oldline, newline)", " let s:called_completedone = 0\n au! CompleteDone\nendfunc", "func Test_CompleteDoneDict()\n au CompleteDonePre * :call <SID>CompleteDone_CheckCompletedItemDict(1)\n au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemDict(0)", " set completefunc=<SID>CompleteDone_CompleteFuncDict\n execute \"normal a\\<C-X>\\<C-U>\\<C-Y>\"\n set completefunc&", " call assert_equal('test', v:completed_item[ 'user_data' ])\n call assert_true(s:called_completedone)", " let s:called_completedone = 0\n au! CompleteDone\nendfunc", "func s:CompleteDone_CompleteFuncDictNoUserData(findstart, base)\n if a:findstart\n return 0\n endif", " return {\n\t \\ 'words': [\n\t \\ {\n\t \\ 'word': 'aword',\n\t \\ 'abbr': 'wrd',\n\t \\ 'menu': 'extra text',\n\t \\ 'info': 'words are cool',\n\t \\ 'kind': 'W',\n\t \\ 'user_data': ['one', 'two'],\n\t \\ }\n\t \\ ]\n\t\\ }\nendfunc", "func s:CompleteDone_CheckCompletedItemDictNoUserData()\n call assert_equal( 'aword', v:completed_item[ 'word' ] )\n call assert_equal( 'wrd', v:completed_item[ 'abbr' ] )\n call assert_equal( 'extra text', v:completed_item[ 'menu' ] )\n call assert_equal( 'words are cool', v:completed_item[ 'info' ] )\n call assert_equal( 'W', v:completed_item[ 'kind' ] )\n call assert_equal( ['one', 'two'], v:completed_item[ 'user_data' ] )", " let s:called_completedone = 1\nendfunc", "func Test_CompleteDoneDictNoUserData()\n au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemDictNoUserData()", " set completefunc=<SID>CompleteDone_CompleteFuncDictNoUserData\n execute \"normal a\\<C-X>\\<C-U>\\<C-Y>\"\n set completefunc&", " call assert_equal(['one', 'two'], v:completed_item[ 'user_data' ])\n call assert_true(s:called_completedone)", " let s:called_completedone = 0\n au! CompleteDone\nendfunc", "func s:CompleteDone_CompleteFuncList(findstart, base)\n if a:findstart\n return 0\n endif", " return [ 'aword' ]\nendfunc", "func s:CompleteDone_CheckCompletedItemList()\n call assert_equal( 'aword', v:completed_item[ 'word' ] )\n call assert_equal( '', v:completed_item[ 'abbr' ] )\n call assert_equal( '', v:completed_item[ 'menu' ] )\n call assert_equal( '', v:completed_item[ 'info' ] )\n call assert_equal( '', v:completed_item[ 'kind' ] )\n call assert_equal( '', v:completed_item[ 'user_data' ] )", " let s:called_completedone = 1\nendfunc", "func Test_CompleteDoneList()\n au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemList()", " set completefunc=<SID>CompleteDone_CompleteFuncList\n execute \"normal a\\<C-X>\\<C-U>\\<C-Y>\"\n set completefunc&", " call assert_equal('', v:completed_item[ 'user_data' ])\n call assert_true(s:called_completedone)", " let s:called_completedone = 0\n au! CompleteDone\nendfunc", "func Test_CompleteDone_undo()\n au CompleteDone * call append(0, \"prepend1\")\n new\n call setline(1, [\"line1\", \"line2\"])\n call feedkeys(\"Go\\<C-X>\\<C-N>\\<CR>\\<ESC>\", \"tx\")\n call assert_equal([\"prepend1\", \"line1\", \"line2\", \"line1\", \"\"],\n \\ getline(1, '$'))\n undo\n call assert_equal([\"line1\", \"line2\"], getline(1, '$'))\n bwipe!\n au! CompleteDone\nendfunc", "func CompleteTest(findstart, query)\n if a:findstart\n return col('.')\n endif\n return ['matched']\nendfunc", "func Test_completefunc_info()\n new\n set completeopt=menuone\n set completefunc=CompleteTest\n call feedkeys(\"i\\<C-X>\\<C-U>\\<C-R>\\<C-R>=string(complete_info())\\<CR>\\<ESC>\", \"tx\")\n call assert_equal(\"matched{'pum_visible': 1, 'mode': 'function', 'selected': 0, 'items': [{'word': 'matched', 'menu': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''}]}\", getline(1))\n bwipe!\n set completeopt&\n set completefunc&\nendfunc", "\" Check that when using feedkeys() typeahead does not interrupt searching for\n\" completions.\nfunc Test_compl_feedkeys()\n new\n set completeopt=menuone,noselect\n call feedkeys(\"ajump ju\\<C-X>\\<C-N>\\<C-P>\\<ESC>\", \"tx\")\n call assert_equal(\"jump jump\", getline(1))\n bwipe!\n set completeopt&\nendfunc", "\" Test for insert path completion with completeslash option\nfunc Test_ins_completeslash()\n CheckMSWindows", " call mkdir('Xdir')\n let orig_shellslash = &shellslash\n set cpt&\n new", " set noshellslash", " set completeslash=\n exe \"normal oXd\\<C-X>\\<C-F>\"\n call assert_equal('Xdir\\', getline('.'))", " set completeslash=backslash\n exe \"normal oXd\\<C-X>\\<C-F>\"\n call assert_equal('Xdir\\', getline('.'))", " set completeslash=slash\n exe \"normal oXd\\<C-X>\\<C-F>\"\n call assert_equal('Xdir/', getline('.'))", " set shellslash", " set completeslash=\n exe \"normal oXd\\<C-X>\\<C-F>\"\n call assert_equal('Xdir/', getline('.'))", " set completeslash=backslash\n exe \"normal oXd\\<C-X>\\<C-F>\"\n call assert_equal('Xdir\\', getline('.'))", " set completeslash=slash\n exe \"normal oXd\\<C-X>\\<C-F>\"\n call assert_equal('Xdir/', getline('.'))\n %bw!\n call delete('Xdir', 'rf')", " set noshellslash\n set completeslash=slash\n call assert_true(stridx(globpath(&rtp, 'syntax/*.vim', 1, 1)[0], '\\') != -1)", " let &shellslash = orig_shellslash\n set completeslash=\nendfunc", "func Test_pum_stopped_by_timer()\n CheckScreendump", " let lines =<< trim END\n call setline(1, ['hello', 'hullo', 'heeee', ''])\n func StartCompl()\n call timer_start(100, { -> execute('stopinsert') })\n call feedkeys(\"Gah\\<C-N>\")\n endfunc\n END", " call writefile(lines, 'Xpumscript')\n let buf = RunVimInTerminal('-S Xpumscript', #{rows: 12})\n call term_sendkeys(buf, \":call StartCompl()\\<CR>\")\n call TermWait(buf, 200)\n call term_sendkeys(buf, \"k\")\n call VerifyScreenDump(buf, 'Test_pum_stopped_by_timer', {})", " call StopVimInTerminal(buf)\n call delete('Xpumscript')\nendfunc", "func Test_complete_stopinsert_startinsert()\n nnoremap <F2> <Cmd>startinsert<CR>\n inoremap <F2> <Cmd>stopinsert<CR>\n \" This just checks if this causes an error\n call feedkeys(\"i\\<C-X>\\<C-N>\\<F2>\\<F2>\", 'x')\n nunmap <F2>\n iunmap <F2>\nendfunc", "func Test_pum_with_folds_two_tabs()\n CheckScreendump", " let lines =<< trim END\n set fdm=marker\n call setline(1, ['\" x {{{1', '\" a some text'])\n call setline(3, range(&lines)->map({_, val -> '\" a' .. val}))\n norm! zm\n tab sp\n call feedkeys('2Gzv', 'xt')\n call feedkeys(\"0fa\", 'xt')\n END", " call writefile(lines, 'Xpumscript')\n let buf = RunVimInTerminal('-S Xpumscript', #{rows: 10})\n call TermWait(buf, 50)\n call term_sendkeys(buf, \"a\\<C-N>\")\n call VerifyScreenDump(buf, 'Test_pum_with_folds_two_tabs', {})", " call term_sendkeys(buf, \"\\<Esc>\")\n call StopVimInTerminal(buf)\n call delete('Xpumscript')\nendfunc", "func Test_pum_with_preview_win()\n CheckScreendump", " let lines =<< trim END\n funct Omni_test(findstart, base)\n\tif a:findstart\n\t return col(\".\") - 1\n\tendif\n\treturn [#{word: \"one\", info: \"1info\"}, #{word: \"two\", info: \"2info\"}, #{word: \"three\", info: \"3info\"}]\n endfunc\n set omnifunc=Omni_test\n set completeopt+=longest\n END", " call writefile(lines, 'Xpreviewscript')\n let buf = RunVimInTerminal('-S Xpreviewscript', #{rows: 12})\n call TermWait(buf, 50)\n call term_sendkeys(buf, \"Gi\\<C-X>\\<C-O>\")\n call TermWait(buf, 100)\n call term_sendkeys(buf, \"\\<C-N>\")\n call VerifyScreenDump(buf, 'Test_pum_with_preview_win', {})", " call term_sendkeys(buf, \"\\<Esc>\")\n call StopVimInTerminal(buf)\n call delete('Xpreviewscript')\nendfunc", "func Test_scrollbar_on_wide_char()\n CheckScreendump", " let lines =<< trim END\n call setline(1, ['a', ' 啊啊啊',\n \\ ' 哦哦哦',\n \\ ' 呃呃呃'])\n call setline(5, range(10)->map({i, v -> 'aa' .. v .. 'bb'}))\n END\n call writefile(lines, 'Xwidescript')\n let buf = RunVimInTerminal('-S Xwidescript', #{rows: 10})\n call term_sendkeys(buf, \"A\\<C-N>\")\n call VerifyScreenDump(buf, 'Test_scrollbar_on_wide_char', {})", " call StopVimInTerminal(buf)\n call delete('Xwidescript')\nendfunc", "\" Test for inserting the tag search pattern in insert mode\nfunc Test_ins_compl_tag_sft()\n call writefile([\n \\ \"!_TAG_FILE_ENCODING\\tutf-8\\t//\",\n \\ \"first\\tXfoo\\t/^int first() {}$/\",\n \\ \"second\\tXfoo\\t/^int second() {}$/\",\n \\ \"third\\tXfoo\\t/^int third() {}$/\"],\n \\ 'Xtags')\n set tags=Xtags\n let code =<< trim [CODE]\n int first() {}\n int second() {}\n int third() {}\n [CODE]\n call writefile(code, 'Xfoo')", " enew\n set showfulltag\n exe \"normal isec\\<C-X>\\<C-]>\\<C-N>\\<CR>\"\n call assert_equal('int second() {}', getline(1))\n set noshowfulltag", " call delete('Xtags')\n call delete('Xfoo')\n set tags&\n %bwipe!\nendfunc", "\" Test for 'completefunc' deleting text\nfunc Test_completefunc_error()\n new\n \" delete text when called for the first time\n func CompleteFunc(findstart, base)\n if a:findstart == 1\n normal dd\n return col('.') - 1\n endif\n return ['a', 'b']\n endfunc\n set completefunc=CompleteFunc\n call setline(1, ['', 'abcd', ''])\n call assert_fails('exe \"normal 2G$a\\<C-X>\\<C-U>\"', 'E565:')", " \" delete text when called for the second time\n func CompleteFunc2(findstart, base)\n if a:findstart == 1\n return col('.') - 1\n endif\n normal dd\n return ['a', 'b']\n endfunc\n set completefunc=CompleteFunc2\n call setline(1, ['', 'abcd', ''])\n call assert_fails('exe \"normal 2G$a\\<C-X>\\<C-U>\"', 'E565:')", " \" Jump to a different window from the complete function\n func CompleteFunc3(findstart, base)\n if a:findstart == 1\n return col('.') - 1\n endif\n wincmd p\n return ['a', 'b']\n endfunc\n set completefunc=CompleteFunc3\n new\n call assert_fails('exe \"normal a\\<C-X>\\<C-U>\"', 'E565:')\n close!", " set completefunc&\n delfunc CompleteFunc\n delfunc CompleteFunc2\n delfunc CompleteFunc3\n close!\nendfunc", "\" Test for returning non-string values from 'completefunc'\nfunc Test_completefunc_invalid_data()\n new\n func! CompleteFunc(findstart, base)\n if a:findstart == 1\n return col('.') - 1\n endif\n return [{}, '', 'moon']\n endfunc\n set completefunc=CompleteFunc\n exe \"normal i\\<C-X>\\<C-U>\"\n call assert_equal('moon', getline(1))\n set completefunc&\n close!\nendfunc", "\" Test for errors in using complete() function\nfunc Test_complete_func_error()\n call assert_fails('call complete(1, [\"a\"])', 'E785:')\n func ListColors()\n call complete(col('.'), \"blue\")\n endfunc\n call assert_fails('exe \"normal i\\<C-R>=ListColors()\\<CR>\"', 'E474:')\n func ListMonths()\n call complete(col('.'), test_null_list())\n endfunc\n call assert_fails('exe \"normal i\\<C-R>=ListMonths()\\<CR>\"', 'E474:')\n delfunc ListColors\n delfunc ListMonths\n call assert_fails('call complete_info({})', 'E714:')\n call assert_equal([], complete_info(['items']).items)\nendfunc", "\" Test for recursively starting completion mode using complete()\nfunc Test_recursive_complete_func()\n func ListColors()\n call complete(5, [\"red\", \"blue\"])\n return ''\n endfunc\n new\n call setline(1, ['a1', 'a2'])\n set complete=.\n exe \"normal Goa\\<C-X>\\<C-L>\\<C-R>=ListColors()\\<CR>\\<C-N>\"\n call assert_equal('a2blue', getline(3))\n delfunc ListColors\n bw!\nendfunc", "\" Test for completing words following a completed word in a line\nfunc Test_complete_wrapscan()\n \" complete words from another buffer\n new\n call setline(1, ['one two', 'three four'])\n new\n setlocal complete=w\n call feedkeys(\"itw\\<C-N>\\<C-X>\\<C-N>\\<C-X>\\<C-N>\\<C-X>\\<C-N>\", 'xt')\n call assert_equal('two three four', getline(1))\n close!\n \" complete words from the current buffer\n setlocal complete=.\n %d\n call setline(1, ['one two', ''])\n call cursor(2, 1)\n call feedkeys(\"ion\\<C-N>\\<C-X>\\<C-N>\\<C-X>\\<C-N>\\<C-X>\\<C-N>\", 'xt')\n call assert_equal('one two one two', getline(2))\n close!\nendfunc", "\" Test for completing special characters\nfunc Test_complete_special_chars()\n new\n call setline(1, 'int .*[-\\^$ func float')\n call feedkeys(\"oin\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\", 'xt')\n call assert_equal('int .*[-\\^$ func float', getline(2))\n close!\nendfunc", "\" Test for completion when text is wrapped across lines.\nfunc Test_complete_across_line()\n new\n call setline(1, ['red green blue', 'one two three'])\n setlocal textwidth=20\n exe \"normal 2G$a re\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\"\n call assert_equal(['one two three red', 'green blue one'], getline(2, '$'))\n close!\nendfunc", "\" Test for completing words with a '.' at the end of a word.\nfunc Test_complete_joinspaces()\n new\n call setline(1, ['one two.', 'three. four'])\n set joinspaces\n exe \"normal Goon\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\"\n call assert_equal(\"one two. three. four\", getline(3))\n set joinspaces&\n bw!\nendfunc", "\" Test for using CTRL-L to add one character when completing matching\nfunc Test_complete_add_onechar()\n new\n call setline(1, ['wool', 'woodwork'])\n call feedkeys(\"Gowoo\\<C-P>\\<C-P>\\<C-P>\\<C-L>f\", 'xt')\n call assert_equal('woof', getline(3))", " \" use 'ignorecase' and backspace to erase characters from the prefix string\n \" and then add letters using CTRL-L\n %d\n set ignorecase backspace=2\n setlocal complete=.\n call setline(1, ['workhorse', 'workload'])\n normal Go\n exe \"normal aWOR\\<C-P>\\<bs>\\<bs>\\<bs>\\<bs>\\<bs>\\<bs>\\<C-L>r\\<C-L>\\<C-L>\"\n call assert_equal('workh', getline(3))\n set ignorecase& backspace&\n close!\nendfunc", "\" Test for using CTRL-X CTRL-L to complete whole lines lines\nfunc Test_complete_wholeline()\n new\n \" complete one-line\n call setline(1, ['a1', 'a2'])\n exe \"normal ggoa\\<C-X>\\<C-L>\"\n call assert_equal(['a1', 'a1', 'a2'], getline(1, '$'))\n \" go to the next match (wrapping around the buffer)\n exe \"normal 2GCa\\<C-X>\\<C-L>\\<C-N>\"\n call assert_equal(['a1', 'a', 'a2'], getline(1, '$'))\n \" go to the next match\n exe \"normal 2GCa\\<C-X>\\<C-L>\\<C-N>\\<C-N>\"\n call assert_equal(['a1', 'a2', 'a2'], getline(1, '$'))\n exe \"normal 2GCa\\<C-X>\\<C-L>\\<C-N>\\<C-N>\\<C-N>\"\n call assert_equal(['a1', 'a1', 'a2'], getline(1, '$'))\n \" repeat the test using CTRL-L\n \" go to the next match (wrapping around the buffer)\n exe \"normal 2GCa\\<C-X>\\<C-L>\\<C-L>\"\n call assert_equal(['a1', 'a2', 'a2'], getline(1, '$'))\n \" go to the next match\n exe \"normal 2GCa\\<C-X>\\<C-L>\\<C-L>\\<C-L>\"\n call assert_equal(['a1', 'a', 'a2'], getline(1, '$'))\n exe \"normal 2GCa\\<C-X>\\<C-L>\\<C-L>\\<C-L>\\<C-L>\"\n call assert_equal(['a1', 'a1', 'a2'], getline(1, '$'))\n %d\n \" use CTRL-X CTRL-L to add one more line\n call setline(1, ['a1', 'b1'])\n setlocal complete=.\n exe \"normal ggOa\\<C-X>\\<C-L>\\<C-X>\\<C-L>\\<C-X>\\<C-L>\"\n call assert_equal(['a1', 'b1', '', 'a1', 'b1'], getline(1, '$'))\n bw!\nendfunc", "\" Test insert completion with 'cindent' (adjust the indent)\nfunc Test_complete_with_cindent()\n new\n setlocal cindent\n call setline(1, ['if (i == 1)', \" j = 2;\"])\n exe \"normal Go{\\<CR>i\\<C-X>\\<C-L>\\<C-X>\\<C-L>\\<CR>}\"\n call assert_equal(['{', \"\\tif (i == 1)\", \"\\t\\tj = 2;\", '}'], getline(3, '$'))", " %d\n call setline(1, ['when while', '{', ''])\n setlocal cinkeys+==while\n exe \"normal Giwh\\<C-P> \"\n call assert_equal(\"\\twhile \", getline('$'))\n close!\nendfunc", "\" Test for <CTRL-X> <CTRL-V> completion. Complete commands and functions\nfunc Test_complete_cmdline()\n new\n exe \"normal icaddb\\<C-X>\\<C-V>\"\n call assert_equal('caddbuffer', getline(1))\n exe \"normal ocall getqf\\<C-X>\\<C-V>\"\n call assert_equal('call getqflist(', getline(2))\n exe \"normal oabcxyz(\\<C-X>\\<C-V>\"\n call assert_equal('abcxyz(', getline(3))\n com! -buffer TestCommand1 echo 'TestCommand1'\n com! -buffer TestCommand2 echo 'TestCommand2'\n write TestCommand1Test\n write TestCommand2Test\n \" Test repeating <CTRL-X> <CTRL-V> and switching to another CTRL-X mode\n exe \"normal oT\\<C-X>\\<C-V>\\<C-X>\\<C-V>\\<C-X>\\<C-F>\\<Esc>\"\n call assert_equal('TestCommand2Test', getline(4))\n call delete('TestCommand1Test')\n call delete('TestCommand2Test')\n delcom TestCommand1\n delcom TestCommand2\n close!\nendfunc", "\" Test for <CTRL-X> <CTRL-Z> stopping completion without changing the match\nfunc Test_complete_stop()\n new\n func Save_mode1()\n let g:mode1 = mode(1)\n return ''\n endfunc\n func Save_mode2()\n let g:mode2 = mode(1)\n return ''\n endfunc\n inoremap <F1> <C-R>=Save_mode1()<CR>\n inoremap <F2> <C-R>=Save_mode2()<CR>\n call setline(1, ['aaa bbb ccc '])\n exe \"normal A\\<C-N>\\<C-P>\\<F1>\\<C-X>\\<C-Z>\\<F2>\\<Esc>\"\n call assert_equal('ic', g:mode1)\n call assert_equal('i', g:mode2)\n call assert_equal('aaa bbb ccc ', getline(1))\n exe \"normal A\\<C-N>\\<Down>\\<F1>\\<C-X>\\<C-Z>\\<F2>\\<Esc>\"\n call assert_equal('ic', g:mode1)\n call assert_equal('i', g:mode2)\n call assert_equal('aaa bbb ccc aaa', getline(1))\n set completeopt+=noselect\n exe \"normal A \\<C-N>\\<Down>\\<Down>\\<C-L>\\<C-L>\\<F1>\\<C-X>\\<C-Z>\\<F2>\\<Esc>\"\n call assert_equal('ic', g:mode1)\n call assert_equal('i', g:mode2)\n call assert_equal('aaa bbb ccc aaa bb', getline(1))\n set completeopt&\n exe \"normal A d\\<C-N>\\<F1>\\<C-X>\\<C-Z>\\<F2>\\<Esc>\"\n call assert_equal('ic', g:mode1)\n call assert_equal('i', g:mode2)\n call assert_equal('aaa bbb ccc aaa bb d', getline(1))\n com! -buffer TestCommand1 echo 'TestCommand1'\n com! -buffer TestCommand2 echo 'TestCommand2'\n exe \"normal oT\\<C-X>\\<C-V>\\<C-X>\\<C-V>\\<F1>\\<C-X>\\<C-Z>\\<F2>\\<Esc>\"\n call assert_equal('ic', g:mode1)\n call assert_equal('i', g:mode2)\n call assert_equal('TestCommand2', getline(2))\n delcom TestCommand1\n delcom TestCommand2\n unlet g:mode1\n unlet g:mode2\n iunmap <F1>\n iunmap <F2>\n delfunc Save_mode1\n delfunc Save_mode2\n close!\nendfunc", "\" Test for typing CTRL-R in insert completion mode to insert a register\n\" content.\nfunc Test_complete_reginsert()\n new\n call setline(1, ['a1', 'a12', 'a123', 'a1234'])", " \" if a valid CTRL-X mode key is returned from <C-R>=, then it should be\n \" processed. Otherwise, CTRL-X mode should be stopped and the key should be\n \" inserted.\n exe \"normal Goa\\<C-P>\\<C-R>=\\\"\\\\<C-P>\\\"\\<CR>\"\n call assert_equal('a123', getline(5))\n let @r = \"\\<C-P>\\<C-P>\"\n exe \"normal GCa\\<C-P>\\<C-R>r\"\n call assert_equal('a12', getline(5))\n exe \"normal GCa\\<C-P>\\<C-R>=\\\"x\\\"\\<CR>\"\n call assert_equal('a1234x', getline(5))\n bw!\nendfunc", "func Test_issue_7021()\n CheckMSWindows", " let orig_shellslash = &shellslash\n set noshellslash", " set completeslash=slash\n call assert_false(expand('~') =~ '/')", " let &shellslash = orig_shellslash\n set completeslash=\nendfunc", "\" Test for 'longest' setting in 'completeopt' with latin1 and utf-8 encodings\nfunc Test_complete_longest_match()\n for e in ['latin1', 'utf-8']\n exe 'set encoding=' .. e\n new\n set complete=.\n set completeopt=menu,longest\n call setline(1, ['pfx_a1', 'pfx_a12', 'pfx_a123', 'pfx_b1'])\n exe \"normal Gopfx\\<C-P>\"\n call assert_equal('pfx_', getline(5))\n bw!\n endfor", " \" Test for completing additional words with longest match set\n new\n call setline(1, ['abc1', 'abd2'])\n exe \"normal Goab\\<C-P>\\<C-X>\\<C-P>\"\n call assert_equal('ab', getline(3))\n bw!\n set complete& completeopt&\nendfunc", "\" Test for removing the first displayed completion match and selecting the\n\" match just before that.\nfunc Test_complete_erase_firstmatch()\n new\n call setline(1, ['a12', 'a34', 'a56'])\n set complete=.\n exe \"normal Goa\\<C-P>\\<BS>\\<BS>3\\<CR>\"\n call assert_equal('a34', getline('$'))\n set complete&\n bw!\nendfunc", "\" Test for completing words from unloaded buffers\nfunc Test_complete_from_unloadedbuf()\n call writefile(['abc'], \"Xfile1\")\n call writefile(['def'], \"Xfile2\")\n edit Xfile1\n edit Xfile2\n new | close\n enew\n bunload Xfile1 Xfile2\n set complete=u\n \" complete from an unloaded buffer\n exe \"normal! ia\\<C-P>\"\n call assert_equal('abc', getline(1))\n exe \"normal! od\\<C-P>\"\n call assert_equal('def', getline(2))\n set complete&\n %bw!\n call delete(\"Xfile1\")\n call delete(\"Xfile2\")\nendfunc", "\" Test for completing whole lines from unloaded buffers\nfunc Test_complete_wholeline_unloadedbuf()\n call writefile(['a line1', 'a line2', 'a line3'], \"Xfile1\")\n edit Xfile1\n enew\n set complete=u\n exe \"normal! ia\\<C-X>\\<C-L>\\<C-P>\"\n call assert_equal('a line2', getline(1))\n %d\n \" completing from an unlisted buffer should fail\n bdel Xfile1\n exe \"normal! ia\\<C-X>\\<C-L>\\<C-P>\"\n call assert_equal('a', getline(1))\n set complete&\n %bw!\n call delete(\"Xfile1\")\nendfunc", "\" Test for completing words from unlisted buffers\nfunc Test_complete_from_unlistedbuf()\n call writefile(['abc'], \"Xfile1\")\n call writefile(['def'], \"Xfile2\")\n edit Xfile1\n edit Xfile2\n new | close\n bdel Xfile1 Xfile2\n set complete=U\n \" complete from an unlisted buffer\n exe \"normal! ia\\<C-P>\"\n call assert_equal('abc', getline(1))\n exe \"normal! od\\<C-P>\"\n call assert_equal('def', getline(2))\n set complete&\n %bw!\n call delete(\"Xfile1\")\n call delete(\"Xfile2\")\nendfunc", "\" Test for completing whole lines from unlisted buffers\nfunc Test_complete_wholeline_unlistedbuf()\n call writefile(['a line1', 'a line2', 'a line3'], \"Xfile1\")\n edit Xfile1\n enew\n set complete=U\n \" completing from a unloaded buffer should fail\n exe \"normal! ia\\<C-X>\\<C-L>\\<C-P>\"\n call assert_equal('a', getline(1))\n %d\n bdel Xfile1\n exe \"normal! ia\\<C-X>\\<C-L>\\<C-P>\"\n call assert_equal('a line2', getline(1))\n set complete&\n %bw!\n call delete(\"Xfile1\")\nendfunc", "\" Test for adding a multibyte character using CTRL-L in completion mode\nfunc Test_complete_mbyte_char_add()\n new\n set complete=.\n call setline(1, 'abė')\n exe \"normal! oa\\<C-P>\\<BS>\\<BS>\\<C-L>\\<C-L>\"\n call assert_equal('abė', getline(2))\n \" Test for a leader with multibyte character\n %d\n call setline(1, 'abėĕ')\n exe \"normal! oabė\\<C-P>\"\n call assert_equal('abėĕ', getline(2))\n bw!\nendfunc", "\" Test for using <C-X><C-P> for local expansion even if 'complete' is set to\n\" not to complete matches from the local buffer. Also test using multiple\n\" <C-X> to cancel the current completion mode.\nfunc Test_complete_local_expansion()\n new\n set complete=t\n call setline(1, ['abc', 'def'])\n exe \"normal! Go\\<C-X>\\<C-P>\"\n call assert_equal(\"def\", getline(3))\n exe \"normal! Go\\<C-P>\"\n call assert_equal(\"\", getline(4))\n exe \"normal! Go\\<C-X>\\<C-N>\"\n call assert_equal(\"abc\", getline(5))\n exe \"normal! Go\\<C-N>\"\n call assert_equal(\"\", getline(6))", " \" use multiple <C-X> to cancel the previous completion mode\n exe \"normal! Go\\<C-P>\\<C-X>\\<C-P>\"\n call assert_equal(\"\", getline(7))\n exe \"normal! Go\\<C-P>\\<C-X>\\<C-X>\\<C-P>\"\n call assert_equal(\"\", getline(8))\n exe \"normal! Go\\<C-P>\\<C-X>\\<C-X>\\<C-X>\\<C-P>\"\n call assert_equal(\"abc\", getline(9))", " \" interrupt the current completion mode\n set completeopt=menu,noinsert\n exe \"normal! Go\\<C-X>\\<C-F>\\<C-X>\\<C-X>\\<C-P>\\<C-Y>\"\n call assert_equal(\"abc\", getline(10))", " \" when only one <C-X> is used to interrupt, do normal expansion\n exe \"normal! Go\\<C-X>\\<C-F>\\<C-X>\\<C-P>\"\n call assert_equal(\"\", getline(11))\n set completeopt&", " \" using two <C-X> in non-completion mode and restarting the same mode\n exe \"normal! God\\<C-X>\\<C-X>\\<C-P>\\<C-X>\\<C-X>\\<C-P>\\<C-Y>\"\n call assert_equal(\"def\", getline(12))", " \" test for adding a match from the original empty text\n %d\n call setline(1, 'abc def g')\n exe \"normal! o\\<C-X>\\<C-P>\\<C-N>\\<C-X>\\<C-P>\"\n call assert_equal('def', getline(2))\n exe \"normal! 0C\\<C-X>\\<C-N>\\<C-P>\\<C-X>\\<C-N>\"\n call assert_equal('abc', getline(2))", " bw!\nendfunc", "\" Test for undoing changes after a insert-mode completion\nfunc Test_complete_undo()\n new\n set complete=.\n \" undo with 'ignorecase'\n call setline(1, ['ABOVE', 'BELOW'])\n set ignorecase\n exe \"normal! Goab\\<C-G>u\\<C-P>\"\n call assert_equal(\"ABOVE\", getline(3))\n undo\n call assert_equal(\"ab\", getline(3))\n set ignorecase&\n %d\n \" undo with longest match\n set completeopt=menu,longest\n call setline(1, ['above', 'about'])\n exe \"normal! Goa\\<C-G>u\\<C-P>\"\n call assert_equal(\"abo\", getline(3))\n undo\n call assert_equal(\"a\", getline(3))\n set completeopt&\n %d\n \" undo for line completion\n call setline(1, ['above that change', 'below that change'])\n exe \"normal! Goabove\\<C-G>u\\<C-X>\\<C-L>\"\n call assert_equal(\"above that change\", getline(3))\n undo\n call assert_equal(\"above\", getline(3))", " bw!\nendfunc", "\" Test for completing a very long word\nfunc Test_complete_long_word()\n set complete&\n new\n call setline(1, repeat('x', 950) .. ' one two three')\n exe \"normal! Gox\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\"\n call assert_equal(repeat('x', 950) .. ' one two three', getline(2))\n %d\n \" should fail when more than 950 characters are in a word\n call setline(1, repeat('x', 951) .. ' one two three')\n exe \"normal! Gox\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\\<C-X>\\<C-P>\"\n call assert_equal(repeat('x', 951), getline(2))", " \" Test for adding a very long word to an existing completion\n %d\n call setline(1, ['abc', repeat('x', 1016) .. '012345'])\n exe \"normal! Goab\\<C-P>\\<C-X>\\<C-P>\"\n call assert_equal('abc ' .. repeat('x', 1016) .. '0123', getline(3))\n bw!\nendfunc", "\" Test for some fields in the complete items used by complete()\nfunc Test_complete_items()\n func CompleteItems(idx)\n let items = [[#{word: \"one\", dup: 1, user_data: 'u1'}, #{word: \"one\", dup: 1, user_data: 'u2'}],\n \\ [#{word: \"one\", dup: 0, user_data: 'u3'}, #{word: \"one\", dup: 0, user_data: 'u4'}],\n \\ [#{word: \"one\", icase: 1, user_data: 'u7'}, #{word: \"oNE\", icase: 1, user_data: 'u8'}],\n \\ [#{user_data: 'u9'}],\n \\ [#{word: \"\", user_data: 'u10'}],\n \\ [#{word: \"\", empty: 1, user_data: 'u11'}]]\n call complete(col('.'), items[a:idx])\n return ''\n endfunc\n new\n exe \"normal! i\\<C-R>=CompleteItems(0)\\<CR>\\<C-N>\\<C-Y>\"\n call assert_equal('u2', v:completed_item.user_data)\n call assert_equal('one', getline(1))\n exe \"normal! o\\<C-R>=CompleteItems(1)\\<CR>\\<C-Y>\"\n call assert_equal('u3', v:completed_item.user_data)\n call assert_equal('one', getline(2))\n exe \"normal! o\\<C-R>=CompleteItems(1)\\<CR>\\<C-N>\"\n call assert_equal('', getline(3))\n set completeopt=menu,noinsert\n exe \"normal! o\\<C-R>=CompleteItems(2)\\<CR>one\\<C-N>\\<C-Y>\"\n call assert_equal('oNE', getline(4))\n call assert_equal('u8', v:completed_item.user_data)\n set completeopt&\n exe \"normal! o\\<C-R>=CompleteItems(3)\\<CR>\"\n call assert_equal('', getline(5))\n exe \"normal! o\\<C-R>=CompleteItems(4)\\<CR>\"\n call assert_equal('', getline(6))\n exe \"normal! o\\<C-R>=CompleteItems(5)\\<CR>\"\n call assert_equal('', getline(7))\n call assert_equal('u11', v:completed_item.user_data)\n \" pass invalid argument to complete()\n let cmd = \"normal! o\\<C-R>=complete(1, [[]])\\<CR>\"\n call assert_fails('exe cmd', 'E730:')\n bw!\n delfunc CompleteItems\nendfunc", "\" Test for the \"refresh\" item in the dict returned by an insert completion\n\" function\nfunc Test_complete_item_refresh_always()\n let g:CallCount = 0\n func! Tcomplete(findstart, base)\n if a:findstart\n \" locate the start of the word\n let line = getline('.')\n let start = col('.') - 1\n while start > 0 && line[start - 1] =~ '\\a'\n let start -= 1\n endwhile\n return start\n else\n let g:CallCount += 1\n let res = [\"update1\", \"update12\", \"update123\"]\n return #{words: res, refresh: 'always'}\n endif\n endfunc\n new\n set completeopt=menu,longest\n set completefunc=Tcomplete\n exe \"normal! iup\\<C-X>\\<C-U>\\<BS>\\<BS>\\<BS>\\<BS>\\<BS>\"\n call assert_equal('up', getline(1))\n call assert_equal(2, g:CallCount)\n set completeopt&\n set completefunc&\n bw!\n delfunc Tcomplete\nendfunc", "\" Test for completing from a thesaurus file without read permission\nfunc Test_complete_unreadable_thesaurus_file()\n CheckUnix\n CheckNotRoot", " call writefile(['about', 'above'], 'Xfile')\n call setfperm('Xfile', '---r--r--')\n new\n set complete=sXfile\n exe \"normal! ia\\<C-P>\"\n call assert_equal('a', getline(1))\n bw!\n call delete('Xfile')\n set complete&\nendfunc", "\" Test to ensure 'Scanning...' messages are not recorded in messages history\nfunc Test_z1_complete_no_history()\n new\n messages clear\n let currmess = execute('messages')\n setlocal dictionary=README.txt\n exe \"normal owh\\<C-X>\\<C-K>\"\n exe \"normal owh\\<C-N>\"\n call assert_equal(currmess, execute('messages'))\n bwipe!\nendfunc", "\" A mapping is not used for the key after CTRL-X.\nfunc Test_no_mapping_for_ctrl_x_key()\n new\n inoremap <C-K> <Cmd>let was_mapped = 'yes'<CR>\n setlocal dictionary=README.txt\n call feedkeys(\"aexam\\<C-X>\\<C-K> \", 'xt')\n call assert_equal('example ', getline(1))\n call assert_false(exists('was_mapped'))\n bwipe!\nendfunc", "\" Test for different ways of setting the 'completefunc' option\nfunc Test_completefunc_callback()\n func CompleteFunc1(callnr, findstart, base)\n call add(g:CompleteFunc1Args, [a:callnr, a:findstart, a:base])\n return a:findstart ? 0 : []\n endfunc\n func CompleteFunc2(findstart, base)\n call add(g:CompleteFunc2Args, [a:findstart, a:base])\n return a:findstart ? 0 : []\n endfunc", " let lines =<< trim END\n #\" Test for using a global function name\n LET &completefunc = 'g:CompleteFunc2'\n new\n call setline(1, 'global')\n LET g:CompleteFunc2Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'global']], g:CompleteFunc2Args)\n bw!", " #\" Test for using a function()\n set completefunc=function('g:CompleteFunc1',\\ [10])\n new\n call setline(1, 'one')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[10, 1, ''], [10, 0, 'one']], g:CompleteFunc1Args)\n bw!", " #\" Using a funcref variable to set 'completefunc'\n VAR Fn = function('g:CompleteFunc1', [11])\n LET &completefunc = Fn\n new\n call setline(1, 'two')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[11, 1, ''], [11, 0, 'two']], g:CompleteFunc1Args)\n bw!", " #\" Using string(funcref_variable) to set 'completefunc'\n LET Fn = function('g:CompleteFunc1', [12])\n LET &completefunc = string(Fn)\n new\n call setline(1, 'two')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[12, 1, ''], [12, 0, 'two']], g:CompleteFunc1Args)\n bw!", " #\" Test for using a funcref()\n set completefunc=funcref('g:CompleteFunc1',\\ [13])\n new\n call setline(1, 'three')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[13, 1, ''], [13, 0, 'three']], g:CompleteFunc1Args)\n bw!", " #\" Using a funcref variable to set 'completefunc'\n LET Fn = funcref('g:CompleteFunc1', [14])\n LET &completefunc = Fn\n new\n call setline(1, 'four')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[14, 1, ''], [14, 0, 'four']], g:CompleteFunc1Args)\n bw!", " #\" Using a string(funcref_variable) to set 'completefunc'\n LET Fn = funcref('g:CompleteFunc1', [15])\n LET &completefunc = string(Fn)\n new\n call setline(1, 'four')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[15, 1, ''], [15, 0, 'four']], g:CompleteFunc1Args)\n bw!", " #\" Test for using a lambda function with set\n VAR optval = \"LSTART a, b LMIDDLE g:CompleteFunc1(16, a, b) LEND\"\n LET optval = substitute(optval, ' ', '\\\\ ', 'g')\n exe \"set completefunc=\" .. optval\n new\n call setline(1, 'five')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[16, 1, ''], [16, 0, 'five']], g:CompleteFunc1Args)\n bw!", " #\" Set 'completefunc' to a lambda expression\n LET &completefunc = LSTART a, b LMIDDLE g:CompleteFunc1(17, a, b) LEND\n new\n call setline(1, 'six')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[17, 1, ''], [17, 0, 'six']], g:CompleteFunc1Args)\n bw!", " #\" Set 'completefunc' to string(lambda_expression)\n LET &completefunc = 'LSTART a, b LMIDDLE g:CompleteFunc1(18, a, b) LEND'\n new\n call setline(1, 'six')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[18, 1, ''], [18, 0, 'six']], g:CompleteFunc1Args)\n bw!", " #\" Set 'completefunc' to a variable with a lambda expression\n VAR Lambda = LSTART a, b LMIDDLE g:CompleteFunc1(19, a, b) LEND\n LET &completefunc = Lambda\n new\n call setline(1, 'seven')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[19, 1, ''], [19, 0, 'seven']], g:CompleteFunc1Args)\n bw!", " #\" Set 'completefunc' to a string(variable with a lambda expression)\n LET Lambda = LSTART a, b LMIDDLE g:CompleteFunc1(20, a, b) LEND\n LET &completefunc = string(Lambda)\n new\n call setline(1, 'seven')\n LET g:CompleteFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[20, 1, ''], [20, 0, 'seven']], g:CompleteFunc1Args)\n bw!", " #\" Test for using a lambda function with incorrect return value\n LET Lambda = LSTART a, b LMIDDLE strlen(a) LEND\n LET &completefunc = Lambda\n new\n call setline(1, 'eight')\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n bw!", " #\" Test for clearing the 'completefunc' option\n set completefunc=''\n set completefunc&\n call assert_fails(\"set completefunc=function('abc')\", \"E700:\")\n call assert_fails(\"set completefunc=funcref('abc')\", \"E700:\")", " #\" set 'completefunc' to a non-existing function\n set completefunc=g:CompleteFunc2\n call setline(1, 'five')\n call assert_fails(\"set completefunc=function('NonExistingFunc')\", 'E700:')\n call assert_fails(\"LET &completefunc = function('NonExistingFunc')\", 'E700:')\n LET g:CompleteFunc2Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'five']], g:CompleteFunc2Args)\n bw!\n END\n call v9.CheckLegacyAndVim9Success(lines)", " \" Test for using a script-local function name\n func s:CompleteFunc3(findstart, base)\n call add(g:CompleteFunc3Args, [a:findstart, a:base])\n return a:findstart ? 0 : []\n endfunc\n set completefunc=s:CompleteFunc3\n new\n call setline(1, 'script1')\n let g:CompleteFunc3Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'script1']], g:CompleteFunc3Args)\n bw!", " let &completefunc = 's:CompleteFunc3'\n new\n call setline(1, 'script2')\n let g:CompleteFunc3Args = []\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'script2']], g:CompleteFunc3Args)\n bw!\n delfunc s:CompleteFunc3", " \" In Vim9 script s: can be omitted\n let lines =<< trim END\n vim9script\n var CompleteFunc4Args = []\n def CompleteFunc4(findstart: bool, base: string): any\n add(CompleteFunc4Args, [findstart, base])\n return findstart ? 0 : []\n enddef\n set completefunc=CompleteFunc4\n new\n setline(1, 'script1')\n feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n assert_equal([[1, ''], [0, 'script1']], CompleteFunc4Args)\n bw!\n END\n call v9.CheckScriptSuccess(lines)", " \" invalid return value\n let &completefunc = {a -> 'abc'}\n call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')", " \" Using Vim9 lambda expression in legacy context should fail\n set completefunc=(a,\\ b)\\ =>\\ g:CompleteFunc1(21,\\ a,\\ b)\n new | only\n let g:CompleteFunc1Args = []\n call assert_fails('call feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", \"x\")', 'E117:')\n call assert_equal([], g:CompleteFunc1Args)", " \" set 'completefunc' to a partial with dict. This used to cause a crash.\n func SetCompleteFunc()\n let params = {'complete': function('g:DictCompleteFunc')}\n let &completefunc = params.complete\n endfunc\n func g:DictCompleteFunc(_) dict\n endfunc\n call SetCompleteFunc()\n new\n call SetCompleteFunc()\n bw\n call test_garbagecollect_now()\n new\n set completefunc=\n wincmd w\n set completefunc=\n %bw!\n delfunc g:DictCompleteFunc\n delfunc SetCompleteFunc", " \" Vim9 tests\n let lines =<< trim END\n vim9script", " def Vim9CompleteFunc(callnr: number, findstart: number, base: string): any\n add(g:Vim9completeFuncArgs, [callnr, findstart, base])\n return findstart ? 0 : []\n enddef", " # Test for using a def function with completefunc\n set completefunc=function('Vim9CompleteFunc',\\ [60])\n new | only\n setline(1, 'one')\n g:Vim9completeFuncArgs = []\n feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n assert_equal([[60, 1, ''], [60, 0, 'one']], g:Vim9completeFuncArgs)\n bw!", " # Test for using a global function name\n &completefunc = g:CompleteFunc2\n new | only\n setline(1, 'two')\n g:CompleteFunc2Args = []\n feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n assert_equal([[1, ''], [0, 'two']], g:CompleteFunc2Args)\n bw!", " # Test for using a script-local function name\n def LocalCompleteFunc(findstart: number, base: string): any\n add(g:LocalCompleteFuncArgs, [findstart, base])\n return findstart ? 0 : []\n enddef\n &completefunc = LocalCompleteFunc\n new | only\n setline(1, 'three')\n g:LocalCompleteFuncArgs = []\n feedkeys(\"A\\<C-X>\\<C-U>\\<Esc>\", 'x')\n assert_equal([[1, ''], [0, 'three']], g:LocalCompleteFuncArgs)\n bw!\n END\n call v9.CheckScriptSuccess(lines)", " \" cleanup\n set completefunc&\n delfunc CompleteFunc1\n delfunc CompleteFunc2\n unlet g:CompleteFunc1Args g:CompleteFunc2Args\n %bw!\nendfunc", "\" Test for different ways of setting the 'omnifunc' option\nfunc Test_omnifunc_callback()\n func OmniFunc1(callnr, findstart, base)\n call add(g:OmniFunc1Args, [a:callnr, a:findstart, a:base])\n return a:findstart ? 0 : []\n endfunc\n func OmniFunc2(findstart, base)\n call add(g:OmniFunc2Args, [a:findstart, a:base])\n return a:findstart ? 0 : []\n endfunc", " let lines =<< trim END\n #\" Test for using a function name\n LET &omnifunc = 'g:OmniFunc2'\n new\n call setline(1, 'zero')\n LET g:OmniFunc2Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'zero']], g:OmniFunc2Args)\n bw!", " #\" Test for using a function()\n set omnifunc=function('g:OmniFunc1',\\ [10])\n new\n call setline(1, 'one')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[10, 1, ''], [10, 0, 'one']], g:OmniFunc1Args)\n bw!", " #\" Using a funcref variable to set 'omnifunc'\n VAR Fn = function('g:OmniFunc1', [11])\n LET &omnifunc = Fn\n new\n call setline(1, 'two')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[11, 1, ''], [11, 0, 'two']], g:OmniFunc1Args)\n bw!", " #\" Using a string(funcref_variable) to set 'omnifunc'\n LET Fn = function('g:OmniFunc1', [12])\n LET &omnifunc = string(Fn)\n new\n call setline(1, 'two')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[12, 1, ''], [12, 0, 'two']], g:OmniFunc1Args)\n bw!", " #\" Test for using a funcref()\n set omnifunc=funcref('g:OmniFunc1',\\ [13])\n new\n call setline(1, 'three')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[13, 1, ''], [13, 0, 'three']], g:OmniFunc1Args)\n bw!", " #\" Use let to set 'omnifunc' to a funcref\n LET Fn = funcref('g:OmniFunc1', [14])\n LET &omnifunc = Fn\n new\n call setline(1, 'four')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[14, 1, ''], [14, 0, 'four']], g:OmniFunc1Args)\n bw!", " #\" Using a string(funcref) to set 'omnifunc'\n LET Fn = funcref(\"g:OmniFunc1\", [15])\n LET &omnifunc = string(Fn)\n new\n call setline(1, 'four')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[15, 1, ''], [15, 0, 'four']], g:OmniFunc1Args)\n bw!", " #\" Test for using a lambda function with set\n VAR optval = \"LSTART a, b LMIDDLE g:OmniFunc1(16, a, b) LEND\"\n LET optval = substitute(optval, ' ', '\\\\ ', 'g')\n exe \"set omnifunc=\" .. optval\n new\n call setline(1, 'five')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[16, 1, ''], [16, 0, 'five']], g:OmniFunc1Args)\n bw!", " #\" Set 'omnifunc' to a lambda expression\n LET &omnifunc = LSTART a, b LMIDDLE g:OmniFunc1(17, a, b) LEND\n new\n call setline(1, 'six')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[17, 1, ''], [17, 0, 'six']], g:OmniFunc1Args)\n bw!", " #\" Set 'omnifunc' to a string(lambda_expression)\n LET &omnifunc = 'LSTART a, b LMIDDLE g:OmniFunc1(18, a, b) LEND'\n new\n call setline(1, 'six')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[18, 1, ''], [18, 0, 'six']], g:OmniFunc1Args)\n bw!", " #\" Set 'omnifunc' to a variable with a lambda expression\n VAR Lambda = LSTART a, b LMIDDLE g:OmniFunc1(19, a, b) LEND\n LET &omnifunc = Lambda\n new\n call setline(1, 'seven')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[19, 1, ''], [19, 0, 'seven']], g:OmniFunc1Args)\n bw!", " #\" Set 'omnifunc' to a string(variable with a lambda expression)\n LET Lambda = LSTART a, b LMIDDLE g:OmniFunc1(20, a, b) LEND\n LET &omnifunc = string(Lambda)\n new\n call setline(1, 'seven')\n LET g:OmniFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[20, 1, ''], [20, 0, 'seven']], g:OmniFunc1Args)\n bw!", " #\" Test for using a lambda function with incorrect return value\n LET Lambda = LSTART a, b LMIDDLE strlen(a) LEND\n LET &omnifunc = Lambda\n new\n call setline(1, 'eight')\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n bw!", " #\" Test for clearing the 'omnifunc' option\n set omnifunc=''\n set omnifunc&\n call assert_fails(\"set omnifunc=function('abc')\", \"E700:\")\n call assert_fails(\"set omnifunc=funcref('abc')\", \"E700:\")", " #\" set 'omnifunc' to a non-existing function\n set omnifunc=g:OmniFunc2\n call setline(1, 'nine')\n call assert_fails(\"set omnifunc=function('NonExistingFunc')\", 'E700:')\n call assert_fails(\"LET &omnifunc = function('NonExistingFunc')\", 'E700:')\n LET g:OmniFunc2Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'nine']], g:OmniFunc2Args)\n bw!\n END\n call v9.CheckLegacyAndVim9Success(lines)", " \" Test for using a script-local function name\n func s:OmniFunc3(findstart, base)\n call add(g:OmniFunc3Args, [a:findstart, a:base])\n return a:findstart ? 0 : []\n endfunc\n set omnifunc=s:OmniFunc3\n new\n call setline(1, 'script1')\n let g:OmniFunc3Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'script1']], g:OmniFunc3Args)\n bw!", " let &omnifunc = 's:OmniFunc3'\n new\n call setline(1, 'script2')\n let g:OmniFunc3Args = []\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'script2']], g:OmniFunc3Args)\n bw!\n delfunc s:OmniFunc3", " \" invalid return value\n let &omnifunc = {a -> 'abc'}\n call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')", " \" Using Vim9 lambda expression in legacy context should fail\n set omnifunc=(a,\\ b)\\ =>\\ OmniFunc1(21,\\ a,\\ b)\n new | only\n let g:OmniFunc1Args = []\n call assert_fails('call feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", \"x\")', 'E117:')\n call assert_equal([], g:OmniFunc1Args)", " \" set 'omnifunc' to a partial with dict. This used to cause a crash.\n func SetOmniFunc()\n let params = {'omni': function('g:DictOmniFunc')}\n let &omnifunc = params.omni\n endfunc\n func g:DictOmniFunc(_) dict\n endfunc\n call SetOmniFunc()\n new\n call SetOmniFunc()\n bw\n call test_garbagecollect_now()\n new\n set omnifunc=\n wincmd w\n set omnifunc=\n %bw!\n delfunc g:DictOmniFunc\n delfunc SetOmniFunc", " \" Vim9 tests\n let lines =<< trim END\n vim9script", " def Vim9omniFunc(callnr: number, findstart: number, base: string): any\n add(g:Vim9omniFunc_Args, [callnr, findstart, base])\n return findstart ? 0 : []\n enddef", " # Test for using a def function with omnifunc\n set omnifunc=function('Vim9omniFunc',\\ [60])\n new | only\n setline(1, 'one')\n g:Vim9omniFunc_Args = []\n feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n assert_equal([[60, 1, ''], [60, 0, 'one']], g:Vim9omniFunc_Args)\n bw!", " # Test for using a global function name\n &omnifunc = g:OmniFunc2\n new | only\n setline(1, 'two')\n g:OmniFunc2Args = []\n feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n assert_equal([[1, ''], [0, 'two']], g:OmniFunc2Args)\n bw!", " # Test for using a script-local function name\n def LocalOmniFunc(findstart: number, base: string): any\n add(g:LocalOmniFuncArgs, [findstart, base])\n return findstart ? 0 : []\n enddef\n &omnifunc = LocalOmniFunc\n new | only\n setline(1, 'three')\n g:LocalOmniFuncArgs = []\n feedkeys(\"A\\<C-X>\\<C-O>\\<Esc>\", 'x')\n assert_equal([[1, ''], [0, 'three']], g:LocalOmniFuncArgs)\n bw!\n END\n call v9.CheckScriptSuccess(lines)", " \" cleanup\n set omnifunc&\n delfunc OmniFunc1\n delfunc OmniFunc2\n unlet g:OmniFunc1Args g:OmniFunc2Args\n %bw!\nendfunc", "\" Test for different ways of setting the 'thesaurusfunc' option\nfunc Test_thesaurusfunc_callback()\n func TsrFunc1(callnr, findstart, base)\n call add(g:TsrFunc1Args, [a:callnr, a:findstart, a:base])\n return a:findstart ? 0 : []\n endfunc\n func TsrFunc2(findstart, base)\n call add(g:TsrFunc2Args, [a:findstart, a:base])\n return a:findstart ? 0 : ['sunday']\n endfunc", " let lines =<< trim END\n #\" Test for using a function name\n LET &thesaurusfunc = 'g:TsrFunc2'\n new\n call setline(1, 'zero')\n LET g:TsrFunc2Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'zero']], g:TsrFunc2Args)\n bw!", " #\" Test for using a function()\n set thesaurusfunc=function('g:TsrFunc1',\\ [10])\n new\n call setline(1, 'one')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[10, 1, ''], [10, 0, 'one']], g:TsrFunc1Args)\n bw!", " #\" Using a funcref variable to set 'thesaurusfunc'\n VAR Fn = function('g:TsrFunc1', [11])\n LET &thesaurusfunc = Fn\n new\n call setline(1, 'two')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[11, 1, ''], [11, 0, 'two']], g:TsrFunc1Args)\n bw!", " #\" Using a string(funcref_variable) to set 'thesaurusfunc'\n LET Fn = function('g:TsrFunc1', [12])\n LET &thesaurusfunc = string(Fn)\n new\n call setline(1, 'two')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[12, 1, ''], [12, 0, 'two']], g:TsrFunc1Args)\n bw!", " #\" Test for using a funcref()\n set thesaurusfunc=funcref('g:TsrFunc1',\\ [13])\n new\n call setline(1, 'three')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[13, 1, ''], [13, 0, 'three']], g:TsrFunc1Args)\n bw!", " #\" Using a funcref variable to set 'thesaurusfunc'\n LET Fn = funcref('g:TsrFunc1', [14])\n LET &thesaurusfunc = Fn\n new\n call setline(1, 'four')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[14, 1, ''], [14, 0, 'four']], g:TsrFunc1Args)\n bw!", " #\" Using a string(funcref_variable) to set 'thesaurusfunc'\n LET Fn = funcref('g:TsrFunc1', [15])\n LET &thesaurusfunc = string(Fn)\n new\n call setline(1, 'four')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[15, 1, ''], [15, 0, 'four']], g:TsrFunc1Args)\n bw!", " #\" Test for using a lambda function\n VAR optval = \"LSTART a, b LMIDDLE g:TsrFunc1(16, a, b) LEND\"\n LET optval = substitute(optval, ' ', '\\\\ ', 'g')\n exe \"set thesaurusfunc=\" .. optval\n new\n call setline(1, 'five')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[16, 1, ''], [16, 0, 'five']], g:TsrFunc1Args)\n bw!", " #\" Test for using a lambda function with set\n LET &thesaurusfunc = LSTART a, b LMIDDLE g:TsrFunc1(17, a, b) LEND\n new\n call setline(1, 'six')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[17, 1, ''], [17, 0, 'six']], g:TsrFunc1Args)\n bw!", " #\" Set 'thesaurusfunc' to a string(lambda expression)\n LET &thesaurusfunc = 'LSTART a, b LMIDDLE g:TsrFunc1(18, a, b) LEND'\n new\n call setline(1, 'six')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[18, 1, ''], [18, 0, 'six']], g:TsrFunc1Args)\n bw!", " #\" Set 'thesaurusfunc' to a variable with a lambda expression\n VAR Lambda = LSTART a, b LMIDDLE g:TsrFunc1(19, a, b) LEND\n LET &thesaurusfunc = Lambda\n new\n call setline(1, 'seven')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[19, 1, ''], [19, 0, 'seven']], g:TsrFunc1Args)\n bw!", " #\" Set 'thesaurusfunc' to a string(variable with a lambda expression)\n LET Lambda = LSTART a, b LMIDDLE g:TsrFunc1(20, a, b) LEND\n LET &thesaurusfunc = string(Lambda)\n new\n call setline(1, 'seven')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[20, 1, ''], [20, 0, 'seven']], g:TsrFunc1Args)\n bw!", " #\" Test for using a lambda function with incorrect return value\n LET Lambda = LSTART a, b LMIDDLE strlen(a) LEND\n LET &thesaurusfunc = Lambda\n new\n call setline(1, 'eight')\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n bw!", " #\" Test for clearing the 'thesaurusfunc' option\n set thesaurusfunc=''\n set thesaurusfunc&\n call assert_fails(\"set thesaurusfunc=function('abc')\", \"E700:\")\n call assert_fails(\"set thesaurusfunc=funcref('abc')\", \"E700:\")", " #\" set 'thesaurusfunc' to a non-existing function\n set thesaurusfunc=g:TsrFunc2\n call setline(1, 'ten')\n call assert_fails(\"set thesaurusfunc=function('NonExistingFunc')\", 'E700:')\n call assert_fails(\"LET &thesaurusfunc = function('NonExistingFunc')\", 'E700:')\n LET g:TsrFunc2Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'ten']], g:TsrFunc2Args)\n bw!", " #\" Use a buffer-local value and a global value\n set thesaurusfunc&\n setlocal thesaurusfunc=function('g:TsrFunc1',\\ [22])\n call setline(1, 'sun')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", \"x\")\n call assert_equal('sun', getline(1))\n call assert_equal([[22, 1, ''], [22, 0, 'sun']], g:TsrFunc1Args)\n new\n call setline(1, 'sun')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", \"x\")\n call assert_equal('sun', getline(1))\n call assert_equal([], g:TsrFunc1Args)\n set thesaurusfunc=function('g:TsrFunc1',\\ [23])\n wincmd w\n call setline(1, 'sun')\n LET g:TsrFunc1Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", \"x\")\n call assert_equal('sun', getline(1))\n call assert_equal([[22, 1, ''], [22, 0, 'sun']], g:TsrFunc1Args)\n :%bw!\n END\n call v9.CheckLegacyAndVim9Success(lines)", " \" Test for using a script-local function name\n func s:TsrFunc3(findstart, base)\n call add(g:TsrFunc3Args, [a:findstart, a:base])\n return a:findstart ? 0 : []\n endfunc\n set tsrfu=s:TsrFunc3\n new\n call setline(1, 'script1')\n let g:TsrFunc3Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'script1']], g:TsrFunc3Args)\n bw!", " let &tsrfu = 's:TsrFunc3'\n new\n call setline(1, 'script2')\n let g:TsrFunc3Args = []\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n call assert_equal([[1, ''], [0, 'script2']], g:TsrFunc3Args)\n bw!\n delfunc s:TsrFunc3", " \" invalid return value\n let &thesaurusfunc = {a -> 'abc'}\n call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')", " \" Using Vim9 lambda expression in legacy context should fail\n set thesaurusfunc=(a,\\ b)\\ =>\\ TsrFunc1(21,\\ a,\\ b)\n new | only\n let g:TsrFunc1Args = []\n call assert_fails('call feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", \"x\")', 'E117:')\n call assert_equal([], g:TsrFunc1Args)\n bw!", " \" set 'thesaurusfunc' to a partial with dict. This used to cause a crash.\n func SetTsrFunc()\n let params = {'thesaurus': function('g:DictTsrFunc')}\n let &thesaurusfunc = params.thesaurus\n endfunc\n func g:DictTsrFunc(_) dict\n endfunc\n call SetTsrFunc()\n new\n call SetTsrFunc()\n bw\n call test_garbagecollect_now()\n new\n set thesaurusfunc=\n wincmd w\n %bw!\n delfunc SetTsrFunc", " \" set buffer-local 'thesaurusfunc' to a partial with dict. This used to\n \" cause a crash.\n func SetLocalTsrFunc()\n let params = {'thesaurus': function('g:DictTsrFunc')}\n let &l:thesaurusfunc = params.thesaurus\n endfunc\n call SetLocalTsrFunc()\n call test_garbagecollect_now()\n call SetLocalTsrFunc()\n set thesaurusfunc=\n bw!\n delfunc g:DictTsrFunc\n delfunc SetLocalTsrFunc", " \" Vim9 tests\n let lines =<< trim END\n vim9script", " def Vim9tsrFunc(callnr: number, findstart: number, base: string): any\n add(g:Vim9tsrFunc_Args, [callnr, findstart, base])\n return findstart ? 0 : []\n enddef", " # Test for using a def function with thesaurusfunc\n set thesaurusfunc=function('Vim9tsrFunc',\\ [60])\n new | only\n setline(1, 'one')\n g:Vim9tsrFunc_Args = []\n feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n assert_equal([[60, 1, ''], [60, 0, 'one']], g:Vim9tsrFunc_Args)\n bw!", " # Test for using a global function name\n &thesaurusfunc = g:TsrFunc2\n new | only\n setline(1, 'two')\n g:TsrFunc2Args = []\n feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n assert_equal([[1, ''], [0, 'two']], g:TsrFunc2Args)\n bw!", " # Test for using a script-local function name\n def LocalTsrFunc(findstart: number, base: string): any\n add(g:LocalTsrFuncArgs, [findstart, base])\n return findstart ? 0 : []\n enddef\n &thesaurusfunc = LocalTsrFunc\n new | only\n setline(1, 'three')\n g:LocalTsrFuncArgs = []\n feedkeys(\"A\\<C-X>\\<C-T>\\<Esc>\", 'x')\n assert_equal([[1, ''], [0, 'three']], g:LocalTsrFuncArgs)\n bw!\n END\n call v9.CheckScriptSuccess(lines)", " \" cleanup\n set thesaurusfunc&\n delfunc TsrFunc1\n delfunc TsrFunc2\n unlet g:TsrFunc1Args g:TsrFunc2Args\n %bw!\nendfunc", "func FooBarComplete(findstart, base)\n if a:findstart\n return col('.') - 1\n else\n return [\"Foo\", \"Bar\", \"}\"]\n endif\nendfunc", "func Test_complete_smartindent()\n new\n setlocal smartindent completefunc=FooBarComplete", " exe \"norm! o{\\<cr>\\<c-x>\\<c-u>\\<c-p>}\\<cr>\\<esc>\"\n let result = getline(1,'$')\n call assert_equal(['', '{','}',''], result)\n bw!\n delfunction! FooBarComplete\nendfunc", "func Test_complete_overrun()\n \" this was going past the end of the copied text\n new\n sil norm si”\u00140\u0003s\u000f0\u0018\f\u0005\n bwipe!\nendfunc\n", "func Test_infercase_very_long_line()\n \" this was truncating the line when inferring case\n new\n let longLine = \"blah \"->repeat(300)\n let verylongLine = \"blah \"->repeat(400)\n call setline(1, verylongLine)\n call setline(2, longLine)\n set ic infercase\n exe \"normal 2Go\\<C-X>\\<C-L>\\<Esc>\"\n call assert_equal(longLine, getline(3))", " bwipe!\n set noic noinfercase\nendfunc", "", "\" vim: shiftwidth=2 sts=2 expandtab" ]
[ 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, 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, 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, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [698, 2100, 737], "buggy_code_start_loc": [526, 2100, 737], "filenames": ["src/insexpand.c", "src/testdir/test_ins_complete.vim", "src/version.c"], "fixing_code_end_loc": [736, 2117, 740], "fixing_code_start_loc": [527, 2101, 738], "message": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0044.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "0069C36F-19A3-4647-B84F-84CE62E8A554", "versionEndExcluding": "9.0.0044", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:35:*:*:*:*:*:*:*", "matchCriteriaId": "80E516C0-98A4-4ADE-B69F-66A772E2BAAA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0044."}, {"lang": "es", "value": "Un Desbordamiento de B\u00fafer en la Regi\u00f3n Heap de la Memoria en el repositorio de GitHub vim/vim versiones anteriores a 9.0.0044"}], "evaluatorComment": null, "id": "CVE-2022-2343", "lastModified": "2023-05-03T12:15:58.413", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-07-08T18:15:09.820", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/caea66442d86e7bbba3bf3dc202c3c0d549b9853"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2ecb4345-2fc7-4e7f-adb0-83a20bb458f5"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/43Y3VJPOTTY3NTREDIFUPITM2POG4ZLP/"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/202208-32"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-122"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/caea66442d86e7bbba3bf3dc202c3c0d549b9853"}, "type": "CWE-122"}
172
Determine whether the {function_name} code is vulnerable or not.
[ "/* vi:set ts=8 sts=4 sw=4 noet:\n *\n * VIM - Vi IMproved\t\tby Bram Moolenaar\n *\n * Do \":help uganda\" in Vim to read copying and usage conditions.\n * Do \":help credits\" in Vim to see a list of people who contributed.\n * See README.txt for an overview of the Vim source code.\n */", "#include \"vim.h\"", "/*\n * Vim originated from Stevie version 3.6 (Fish disk 217) by GRWalter (Fred)\n * It has been changed beyond recognition since then.\n *\n * Differences between version 8.2 and 9.0 can be found with \":help version9\".\n * Differences between version 7.4 and 8.x can be found with \":help version8\".\n * Differences between version 6.4 and 7.x can be found with \":help version7\".\n * Differences between version 5.8 and 6.x can be found with \":help version6\".\n * Differences between version 4.x and 5.x can be found with \":help version5\".\n * Differences between version 3.0 and 4.x can be found with \":help version4\".\n * All the remarks about older versions have been removed, they are not very\n * interesting.\n */", "#include \"version.h\"", "char\t\t*Version = VIM_VERSION_SHORT;\nstatic char\t*mediumVersion = VIM_VERSION_MEDIUM;", "#if defined(HAVE_DATE_TIME) || defined(PROTO)\n# if (defined(VMS) && defined(VAXC)) || defined(PROTO)\nchar\tlongVersion[sizeof(VIM_VERSION_LONG_DATE) + sizeof(__DATE__)\n\t\t\t\t\t\t + sizeof(__TIME__) + 3];", " void\ninit_longVersion(void)\n{\n /*\n * Construct the long version string. Necessary because\n * VAX C can't concatenate strings in the preprocessor.\n */\n strcpy(longVersion, VIM_VERSION_LONG_DATE);\n#ifdef BUILD_DATE\n strcat(longVersion, BUILD_DATE);\n#else\n strcat(longVersion, __DATE__);\n strcat(longVersion, \" \");\n strcat(longVersion, __TIME__);\n#endif\n strcat(longVersion, \")\");\n}", "# else\nchar\t*longVersion = NULL;", " void\ninit_longVersion(void)\n{\n if (longVersion == NULL)\n {\n#ifdef BUILD_DATE\n\tchar *date_time = BUILD_DATE;\n#else\n\tchar *date_time = __DATE__ \" \" __TIME__;\n#endif\n\tchar *msg = _(\"%s (%s, compiled %s)\");\n\tsize_t len = strlen(msg)\n\t\t + strlen(VIM_VERSION_LONG_ONLY)\n\t\t + strlen(VIM_VERSION_DATE_ONLY)\n\t\t + strlen(date_time);", "\tlongVersion = alloc(len);\n\tif (longVersion == NULL)\n\t longVersion = VIM_VERSION_LONG;\n\telse\n\t vim_snprintf(longVersion, len, msg,\n\t\t VIM_VERSION_LONG_ONLY, VIM_VERSION_DATE_ONLY, date_time);\n }\n}\n# endif\n#else\nchar\t*longVersion = VIM_VERSION_LONG;", " void\ninit_longVersion(void)\n{\n // nothing to do\n}\n#endif", "static char *(features[]) =\n{\n#ifdef HAVE_ACL\n\t\"+acl\",\n#else\n\t\"-acl\",\n#endif\n#ifdef AMIGA\t\t// only for Amiga systems\n# ifdef FEAT_ARP\n\t\"+ARP\",\n# else\n\t\"-ARP\",\n# endif\n#endif\n#ifdef FEAT_ARABIC\n\t\"+arabic\",\n#else\n\t\"-arabic\",\n#endif\n\t\"+autocmd\",\n#ifdef FEAT_AUTOCHDIR\n \"+autochdir\",\n#else\n \"-autochdir\",\n#endif\n#ifdef FEAT_AUTOSERVERNAME\n\t\"+autoservername\",\n#else\n\t\"-autoservername\",\n#endif\n#ifdef FEAT_BEVAL_GUI\n\t\"+balloon_eval\",\n#else\n\t\"-balloon_eval\",\n#endif\n#ifdef FEAT_BEVAL_TERM\n\t\"+balloon_eval_term\",\n#else\n\t\"-balloon_eval_term\",\n#endif\n#ifdef FEAT_BROWSE\n\t\"+browse\",\n#else\n\t\"-browse\",\n#endif\n#ifdef NO_BUILTIN_TCAPS\n\t\"-builtin_terms\",\n#endif\n#ifdef SOME_BUILTIN_TCAPS\n\t\"+builtin_terms\",\n#endif\n#ifdef ALL_BUILTIN_TCAPS\n\t\"++builtin_terms\",\n#endif\n#ifdef FEAT_BYTEOFF\n\t\"+byte_offset\",\n#else\n\t\"-byte_offset\",\n#endif\n#ifdef FEAT_JOB_CHANNEL\n\t\"+channel\",\n#else\n\t\"-channel\",\n#endif\n\t\"+cindent\",\n#ifdef FEAT_CLIENTSERVER\n\t\"+clientserver\",\n#else\n\t\"-clientserver\",\n#endif\n#ifdef FEAT_CLIPBOARD\n\t\"+clipboard\",\n#else\n\t\"-clipboard\",\n#endif\n\t\"+cmdline_compl\",\n\t\"+cmdline_hist\",\n#ifdef FEAT_CMDL_INFO\n\t\"+cmdline_info\",\n#else\n\t\"-cmdline_info\",\n#endif\n\t\"+comments\",\n#ifdef FEAT_CONCEAL\n\t\"+conceal\",\n#else\n\t\"-conceal\",\n#endif\n#ifdef FEAT_CRYPT\n\t\"+cryptv\",\n#else\n\t\"-cryptv\",\n#endif\n#ifdef FEAT_CSCOPE\n\t\"+cscope\",\n#else\n\t\"-cscope\",\n#endif\n\t\"+cursorbind\",\n#ifdef CURSOR_SHAPE\n\t\"+cursorshape\",\n#else\n\t\"-cursorshape\",\n#endif\n#if defined(FEAT_CON_DIALOG) && defined(FEAT_GUI_DIALOG)\n\t\"+dialog_con_gui\",\n#else\n# if defined(FEAT_CON_DIALOG)\n\t\"+dialog_con\",\n# else\n# if defined(FEAT_GUI_DIALOG)\n\t\"+dialog_gui\",\n# else\n\t\"-dialog\",\n# endif\n# endif\n#endif\n#ifdef FEAT_DIFF\n\t\"+diff\",\n#else\n\t\"-diff\",\n#endif\n#ifdef FEAT_DIGRAPHS\n\t\"+digraphs\",\n#else\n\t\"-digraphs\",\n#endif\n#ifdef FEAT_GUI_MSWIN\n# ifdef FEAT_DIRECTX\n\t\"+directx\",\n# else\n\t\"-directx\",\n# endif\n#endif\n#ifdef FEAT_DND\n\t\"+dnd\",\n#else\n\t\"-dnd\",\n#endif\n\t\"-ebcdic\",\n#ifdef FEAT_EMACS_TAGS\n\t\"+emacs_tags\",\n#else\n\t\"-emacs_tags\",\n#endif\n#ifdef FEAT_EVAL\n\t\"+eval\",\n#else\n\t\"-eval\",\n#endif\n\t\"+ex_extra\",\n#ifdef FEAT_SEARCH_EXTRA\n\t\"+extra_search\",\n#else\n\t\"-extra_search\",\n#endif\n\t\"-farsi\",\n#ifdef FEAT_SEARCHPATH\n\t\"+file_in_path\",\n#else\n\t\"-file_in_path\",\n#endif\n#ifdef FEAT_FIND_ID\n\t\"+find_in_path\",\n#else\n\t\"-find_in_path\",\n#endif\n#ifdef FEAT_FLOAT\n\t\"+float\",\n#else\n\t\"-float\",\n#endif\n#ifdef FEAT_FOLDING\n\t\"+folding\",\n#else\n\t\"-folding\",\n#endif\n#ifdef FEAT_FOOTER\n\t\"+footer\",\n#else\n\t\"-footer\",\n#endif\n\t // only interesting on Unix systems\n#if !defined(USE_SYSTEM) && defined(UNIX)\n\t\"+fork()\",\n#endif\n#ifdef FEAT_GETTEXT\n# ifdef DYNAMIC_GETTEXT\n\t\"+gettext/dyn\",\n# else\n\t\"+gettext\",\n# endif\n#else\n\t\"-gettext\",\n#endif\n\t\"-hangul_input\",\n#if (defined(HAVE_ICONV_H) && defined(USE_ICONV)) || defined(DYNAMIC_ICONV)\n# ifdef DYNAMIC_ICONV\n\t\"+iconv/dyn\",\n# else\n\t\"+iconv\",\n# endif\n#else\n\t\"-iconv\",\n#endif\n\t\"+insert_expand\",\n#ifdef FEAT_IPV6\n\t\"+ipv6\",\n#else\n\t\"-ipv6\",\n#endif\n#ifdef FEAT_JOB_CHANNEL\n\t\"+job\",\n#else\n\t\"-job\",\n#endif\n\t\"+jumplist\",\n#ifdef FEAT_KEYMAP\n\t\"+keymap\",\n#else\n\t\"-keymap\",\n#endif\n#ifdef FEAT_EVAL\n\t\"+lambda\",\n#else\n\t\"-lambda\",\n#endif\n#ifdef FEAT_LANGMAP\n\t\"+langmap\",\n#else\n\t\"-langmap\",\n#endif\n#ifdef FEAT_LIBCALL\n\t\"+libcall\",\n#else\n\t\"-libcall\",\n#endif\n#ifdef FEAT_LINEBREAK\n\t\"+linebreak\",\n#else\n\t\"-linebreak\",\n#endif\n\t\"+lispindent\",\n\t\"+listcmds\",\n\t\"+localmap\",\n#ifdef FEAT_LUA\n# ifdef DYNAMIC_LUA\n\t\"+lua/dyn\",\n# else\n\t\"+lua\",\n# endif\n#else\n\t\"-lua\",\n#endif\n#ifdef FEAT_MENU\n\t\"+menu\",\n#else\n\t\"-menu\",\n#endif\n#ifdef FEAT_SESSION\n\t\"+mksession\",\n#else\n\t\"-mksession\",\n#endif\n\t\"+modify_fname\",\n\t\"+mouse\",\n#ifdef FEAT_MOUSESHAPE\n\t\"+mouseshape\",\n#else\n\t\"-mouseshape\",\n#endif", "#if defined(UNIX) || defined(VMS)\n# ifdef FEAT_MOUSE_DEC\n\t\"+mouse_dec\",\n# else\n\t\"-mouse_dec\",\n# endif\n# ifdef FEAT_MOUSE_GPM\n# ifdef DYNAMIC_GPM\n\t\"+mouse_gpm/dyn\",\n# else\n\t\"+mouse_gpm\",\n# endif\n# else\n\t\"-mouse_gpm\",\n# endif\n# ifdef FEAT_MOUSE_JSB\n\t\"+mouse_jsbterm\",\n# else\n\t\"-mouse_jsbterm\",\n# endif\n# ifdef FEAT_MOUSE_NET\n\t\"+mouse_netterm\",\n# else\n\t\"-mouse_netterm\",\n# endif\n#endif", "#ifdef __QNX__\n# ifdef FEAT_MOUSE_PTERM\n\t\"+mouse_pterm\",\n# else\n\t\"-mouse_pterm\",\n# endif\n#endif", "#if defined(UNIX) || defined(VMS)\n\t\"+mouse_sgr\",\n# ifdef FEAT_SYSMOUSE\n\t\"+mouse_sysmouse\",\n# else\n\t\"-mouse_sysmouse\",\n# endif\n# ifdef FEAT_MOUSE_URXVT\n\t\"+mouse_urxvt\",\n# else\n\t\"-mouse_urxvt\",\n# endif\n\t\"+mouse_xterm\",\n#endif", "#ifdef FEAT_MBYTE_IME\n# ifdef DYNAMIC_IME\n\t\"+multi_byte_ime/dyn\",\n# else\n\t\"+multi_byte_ime\",\n# endif\n#else\n\t\"+multi_byte\",\n#endif\n#ifdef FEAT_MULTI_LANG\n\t\"+multi_lang\",\n#else\n\t\"-multi_lang\",\n#endif\n#ifdef FEAT_MZSCHEME\n# ifdef DYNAMIC_MZSCHEME\n\t\"+mzscheme/dyn\",\n# else\n\t\"+mzscheme\",\n# endif\n#else\n\t\"-mzscheme\",\n#endif\n#ifdef FEAT_NETBEANS_INTG\n\t\"+netbeans_intg\",\n#else\n\t\"-netbeans_intg\",\n#endif\n\t\"+num64\",\n#ifdef FEAT_GUI_MSWIN\n# ifdef FEAT_OLE\n\t\"+ole\",\n# else\n\t\"-ole\",\n# endif\n#endif\n#ifdef FEAT_EVAL\n\t\"+packages\",\n#else\n\t\"-packages\",\n#endif\n#ifdef FEAT_PATH_EXTRA\n\t\"+path_extra\",\n#else\n\t\"-path_extra\",\n#endif\n#ifdef FEAT_PERL\n# ifdef DYNAMIC_PERL\n\t\"+perl/dyn\",\n# else\n\t\"+perl\",\n# endif\n#else\n\t\"-perl\",\n#endif\n#ifdef FEAT_PERSISTENT_UNDO\n\t\"+persistent_undo\",\n#else\n\t\"-persistent_undo\",\n#endif\n#ifdef FEAT_PROP_POPUP\n\t\"+popupwin\",\n#else\n\t\"-popupwin\",\n#endif\n#ifdef FEAT_PRINTER\n# ifdef FEAT_POSTSCRIPT\n\t\"+postscript\",\n# else\n\t\"-postscript\",\n# endif\n\t\"+printer\",\n#else\n\t\"-printer\",\n#endif\n#ifdef FEAT_PROFILE\n\t\"+profile\",\n#else\n\t\"-profile\",\n#endif\n#ifdef FEAT_PYTHON\n# ifdef DYNAMIC_PYTHON\n\t\"+python/dyn\",\n# else\n\t\"+python\",\n# endif\n#else\n\t\"-python\",\n#endif\n#ifdef FEAT_PYTHON3\n# ifdef DYNAMIC_PYTHON3\n\t\"+python3/dyn\",\n# else\n\t\"+python3\",\n# endif\n#else\n\t\"-python3\",\n#endif\n#ifdef FEAT_QUICKFIX\n\t\"+quickfix\",\n#else\n\t\"-quickfix\",\n#endif\n#ifdef FEAT_RELTIME\n\t\"+reltime\",\n#else\n\t\"-reltime\",\n#endif\n#ifdef FEAT_RIGHTLEFT\n\t\"+rightleft\",\n#else\n\t\"-rightleft\",\n#endif\n#ifdef FEAT_RUBY\n# ifdef DYNAMIC_RUBY\n\t\"+ruby/dyn\",\n# else\n\t\"+ruby\",\n# endif\n#else\n\t\"-ruby\",\n#endif\n\t\"+scrollbind\",\n#ifdef FEAT_SIGNS\n\t\"+signs\",\n#else\n\t\"-signs\",\n#endif\n\t\"+smartindent\",\n#ifdef FEAT_SODIUM\n# ifdef DYNAMIC_SODIUM\n\t\"+sodium/dyn\",\n# else\n\t\"+sodium\",\n# endif\n#else\n\t\"-sodium\",\n#endif\n#ifdef FEAT_SOUND\n\t\"+sound\",\n#else\n\t\"-sound\",\n#endif\n#ifdef FEAT_SPELL\n\t\"+spell\",\n#else\n\t\"-spell\",\n#endif\n#ifdef STARTUPTIME\n\t\"+startuptime\",\n#else\n\t\"-startuptime\",\n#endif\n#ifdef FEAT_STL_OPT\n\t\"+statusline\",\n#else\n\t\"-statusline\",\n#endif\n\t\"-sun_workshop\",\n#ifdef FEAT_SYN_HL\n\t\"+syntax\",\n#else\n\t\"-syntax\",\n#endif\n\t // only interesting on Unix systems\n#if defined(USE_SYSTEM) && defined(UNIX)\n\t\"+system()\",\n#endif\n\t\"+tag_binary\",\n\t\"-tag_old_static\",\n\t\"-tag_any_white\",\n#ifdef FEAT_TCL\n# ifdef DYNAMIC_TCL\n\t\"+tcl/dyn\",\n# else\n\t\"+tcl\",\n# endif\n#else\n\t\"-tcl\",\n#endif\n#ifdef FEAT_TERMGUICOLORS\n\t\"+termguicolors\",\n#else\n\t\"-termguicolors\",\n#endif\n#ifdef FEAT_TERMINAL\n\t\"+terminal\",\n#else\n\t\"-terminal\",\n#endif\n#if defined(UNIX)\n// only Unix can have terminfo instead of termcap\n# ifdef TERMINFO\n\t\"+terminfo\",\n# else\n\t\"-terminfo\",\n# endif\n#endif\n#ifdef FEAT_TERMRESPONSE\n\t\"+termresponse\",\n#else\n\t\"-termresponse\",\n#endif\n#ifdef FEAT_TEXTOBJ\n\t\"+textobjects\",\n#else\n\t\"-textobjects\",\n#endif\n#ifdef FEAT_PROP_POPUP\n\t\"+textprop\",\n#else\n\t\"-textprop\",\n#endif\n#if !defined(UNIX)\n// unix always includes termcap support\n# ifdef HAVE_TGETENT\n\t\"+tgetent\",\n# else\n\t\"-tgetent\",\n# endif\n#endif\n#ifdef FEAT_TIMERS\n\t\"+timers\",\n#else\n\t\"-timers\",\n#endif\n\t\"+title\",\n#ifdef FEAT_TOOLBAR\n\t\"+toolbar\",\n#else\n\t\"-toolbar\",\n#endif\n\t\"+user_commands\",\n#ifdef FEAT_VARTABS\n\t\"+vartabs\",\n#else\n\t\"-vartabs\",\n#endif\n\t\"+vertsplit\",\n\t\"+vim9script\",\n#ifdef FEAT_VIMINFO\n\t\"+viminfo\",\n#else\n\t\"-viminfo\",\n#endif\n\t\"+virtualedit\",\n\t\"+visual\",\n\t\"+visualextra\",\n\t\"+vreplace\",\n#ifdef MSWIN\n# ifdef FEAT_VTP\n\t\"+vtp\",\n# else\n\t\"-vtp\",\n# endif\n#endif\n#ifdef FEAT_WILDIGN\n\t\"+wildignore\",\n#else\n\t\"-wildignore\",\n#endif\n#ifdef FEAT_WILDMENU\n\t\"+wildmenu\",\n#else\n\t\"-wildmenu\",\n#endif\n\t\"+windows\",\n#ifdef FEAT_WRITEBACKUP\n\t\"+writebackup\",\n#else\n\t\"-writebackup\",\n#endif\n#if defined(UNIX) || defined(VMS)\n# ifdef FEAT_X11\n\t\"+X11\",\n# else\n\t\"-X11\",\n# endif\n#endif\n#ifdef FEAT_XFONTSET\n\t\"+xfontset\",\n#else\n\t\"-xfontset\",\n#endif\n#ifdef FEAT_XIM\n\t\"+xim\",\n#else\n\t\"-xim\",\n#endif\n#if defined(MSWIN)\n# ifdef FEAT_XPM_W32\n\t\"+xpm_w32\",\n# else\n\t\"-xpm_w32\",\n# endif\n#elif defined(HAVE_XPM)\n\t\"+xpm\",\n#else\n\t\"-xpm\",\n#endif\n#if defined(UNIX) || defined(VMS)\n# if defined(USE_XSMP_INTERACT)\n\t\"+xsmp_interact\",\n# elif defined(USE_XSMP)\n\t\"+xsmp\",\n# else\n\t\"-xsmp\",\n# endif\n# ifdef FEAT_XCLIPBOARD\n\t\"+xterm_clipboard\",\n# else\n\t\"-xterm_clipboard\",\n# endif\n#endif\n#ifdef FEAT_XTERM_SAVE\n\t\"+xterm_save\",\n#else\n\t\"-xterm_save\",\n#endif\n\tNULL\n};", "static int included_patches[] =\n{ /* Add new patch number below this line */", "", "/**/\n 44,\n/**/\n 43,\n/**/\n 42,\n/**/\n 41,\n/**/\n 40,\n/**/\n 39,\n/**/\n 38,\n/**/\n 37,\n/**/\n 36,\n/**/\n 35,\n/**/\n 34,\n/**/\n 33,\n/**/\n 32,\n/**/\n 31,\n/**/\n 30,\n/**/\n 29,\n/**/\n 28,\n/**/\n 27,\n/**/\n 26,\n/**/\n 25,\n/**/\n 24,\n/**/\n 23,\n/**/\n 22,\n/**/\n 21,\n/**/\n 20,\n/**/\n 19,\n/**/\n 18,\n/**/\n 17,\n/**/\n 16,\n/**/\n 15,\n/**/\n 14,\n/**/\n 13,\n/**/\n 12,\n/**/\n 11,\n/**/\n 10,\n/**/\n 9,\n/**/\n 8,\n/**/\n 7,\n/**/\n 6,\n/**/\n 5,\n/**/\n 4,\n/**/\n 3,\n/**/\n 2,\n/**/\n 1,\n/**/\n 0\n};", "/*\n * Place to put a short description when adding a feature with a patch.\n * Keep it short, e.g.,: \"relative numbers\", \"persistent undo\".\n * Also add a comment marker to separate the lines.\n * See the official Vim patches for the diff format: It must use a context of\n * one line only. Create it by hand or use \"diff -C2\" and edit the patch.\n */\nstatic char *(extra_patches[]) =\n{ /* Add your patch description below this line */\n/**/\n NULL\n};", " int\nhighest_patch(void)\n{\n // this relies on the highest patch number to be the first entry\n return included_patches[0];\n}", "#if defined(FEAT_EVAL) || defined(PROTO)\n/*\n * Return TRUE if patch \"n\" has been included.\n */\n int\nhas_patch(int n)\n{\n int\t\th, m, l;", " // Perform a binary search.\n l = 0;\n h = (int)ARRAY_LENGTH(included_patches) - 1;\n for (;;)\n {\n\tm = (l + h) / 2;\n\tif (included_patches[m] == n)\n\t return TRUE;\n\tif (l == h)\n\t break;\n\tif (included_patches[m] < n)\n\t h = m;\n\telse\n\t l = m + 1;\n }\n return FALSE;\n}\n#endif", " void\nex_version(exarg_T *eap)\n{\n /*\n * Ignore a \":version 9.99\" command.\n */\n if (*eap->arg == NUL)\n {\n\tmsg_putchar('\\n');\n\tlist_version();\n }\n}", "/*\n * Output a string for the version message. If it's going to wrap, output a\n * newline, unless the message is too long to fit on the screen anyway.\n * When \"wrap\" is TRUE wrap the string in [].\n */\n static void\nversion_msg_wrap(char_u *s, int wrap)\n{\n int\t\tlen = vim_strsize(s) + (wrap ? 2 : 0);", " if (!got_int && len < (int)Columns && msg_col + len >= (int)Columns\n\t\t\t\t\t\t\t\t&& *s != '\\n')\n\tmsg_putchar('\\n');\n if (!got_int)\n {\n\tif (wrap)\n\t msg_puts(\"[\");\n\tmsg_puts((char *)s);\n\tif (wrap)\n\t msg_puts(\"]\");\n }\n}", " static void\nversion_msg(char *s)\n{\n version_msg_wrap((char_u *)s, FALSE);\n}", "/*\n * List all features aligned in columns, dictionary style.\n */\n static void\nlist_features(void)\n{\n list_in_columns((char_u **)features, -1, -1);\n}", "/*\n * List string items nicely aligned in columns.\n * When \"size\" is < 0 then the last entry is marked with NULL.\n * The entry with index \"current\" is inclosed in [].\n */\n void\nlist_in_columns(char_u **items, int size, int current)\n{\n int\t\ti;\n int\t\tncol;\n int\t\tnrow;\n int\t\tcur_row = 1;\n int\t\titem_count = 0;\n int\t\twidth = 0;\n#ifdef FEAT_SYN_HL\n int\t\tuse_highlight = (items == (char_u **)features);\n#endif", " // Find the length of the longest item, use that + 1 as the column\n // width.\n for (i = 0; size < 0 ? items[i] != NULL : i < size; ++i)\n {\n\tint l = vim_strsize(items[i]) + (i == current ? 2 : 0);", "\tif (l > width)\n\t width = l;\n\t++item_count;\n }\n width += 1;", " if (Columns < width)\n {\n\t// Not enough screen columns - show one per line\n\tfor (i = 0; i < item_count; ++i)\n\t{\n\t version_msg_wrap(items[i], i == current);\n\t if (msg_col > 0 && i < item_count - 1)\n\t\tmsg_putchar('\\n');\n\t}\n\treturn;\n }", " // The rightmost column doesn't need a separator.\n // Sacrifice it to fit in one more column if possible.\n ncol = (int) (Columns + 1) / width;\n nrow = item_count / ncol + ((item_count % ncol) ? 1 : 0);", " // \"i\" counts columns then rows. \"idx\" counts rows then columns.\n for (i = 0; !got_int && i < nrow * ncol; ++i)\n {\n\tint idx = (i / ncol) + (i % ncol) * nrow;", "\tif (idx < item_count)\n\t{\n\t int last_col = (i + 1) % ncol == 0;", "\t if (idx == current)\n\t\tmsg_putchar('[');\n#ifdef FEAT_SYN_HL\n\t if (use_highlight && items[idx][0] == '-')\n\t\tmsg_puts_attr((char *)items[idx], HL_ATTR(HLF_W));\n\t else\n#endif\n\t\tmsg_puts((char *)items[idx]);\n\t if (idx == current)\n\t\tmsg_putchar(']');\n\t if (last_col)\n\t {\n\t\tif (msg_col > 0 && cur_row < nrow)\n\t\t msg_putchar('\\n');\n\t\t++cur_row;\n\t }\n\t else\n\t {\n\t\twhile (msg_col % width)\n\t\t msg_putchar(' ');\n\t }\n\t}\n\telse\n\t{\n\t // this row is out of items, thus at the end of the row\n\t if (msg_col > 0)\n\t {\n\t\tif (cur_row < nrow)\n\t\t msg_putchar('\\n');\n\t\t++cur_row;\n\t }\n\t}\n }\n}", " void\nlist_version(void)\n{\n int\t\ti;\n int\t\tfirst;\n char\t*s = \"\";", " /*\n * When adding features here, don't forget to update the list of\n * internal variables in eval.c!\n */\n init_longVersion();\n msg(longVersion);\n#ifdef MSWIN\n# ifdef FEAT_GUI_MSWIN\n# ifdef VIMDLL\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit GUI/console version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit GUI/console version\"));\n# endif\n# else\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit GUI version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit GUI version\"));\n# endif\n# endif\n# ifdef FEAT_OLE\n msg_puts(_(\" with OLE support\"));\n# endif\n# else\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit console version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit console version\"));\n# endif\n# endif\n#endif\n#if defined(MACOS_X)\n# if defined(MACOS_X_DARWIN)\n msg_puts(_(\"\\nmacOS version\"));\n# else\n msg_puts(_(\"\\nmacOS version w/o darwin feat.\"));\n# endif\n# if defined(__arm64__)\n msg_puts(\" - arm64\");\n# elif defined(__x86_64__)\n msg_puts(\" - x86_64\");\n# endif\n#endif", "#ifdef VMS\n msg_puts(_(\"\\nOpenVMS version\"));\n# ifdef HAVE_PATHDEF\n if (*compiled_arch != NUL)\n {\n\tmsg_puts(\" - \");\n\tmsg_puts((char *)compiled_arch);\n }\n# endif", "#endif", " // Print the list of patch numbers if there is at least one.\n // Print a range when patches are consecutive: \"1-10, 12, 15-40, 42-45\"\n if (included_patches[0] != 0)\n {\n\tmsg_puts(_(\"\\nIncluded patches: \"));\n\tfirst = -1;\n\ti = (int)ARRAY_LENGTH(included_patches) - 1;\n\twhile (--i >= 0)\n\t{\n\t if (first < 0)\n\t\tfirst = included_patches[i];\n\t if (i == 0 || included_patches[i - 1] != included_patches[i] + 1)\n\t {\n\t\tmsg_puts(s);\n\t\ts = \", \";\n\t\tmsg_outnum((long)first);\n\t\tif (first != included_patches[i])\n\t\t{\n\t\t msg_puts(\"-\");\n\t\t msg_outnum((long)included_patches[i]);\n\t\t}\n\t\tfirst = -1;\n\t }\n\t}\n }", " // Print the list of extra patch descriptions if there is at least one.\n if (extra_patches[0] != NULL)\n {\n\tmsg_puts(_(\"\\nExtra patches: \"));\n\ts = \"\";\n\tfor (i = 0; extra_patches[i] != NULL; ++i)\n\t{\n\t msg_puts(s);\n\t s = \", \";\n\t msg_puts(extra_patches[i]);\n\t}\n }", "#ifdef MODIFIED_BY\n msg_puts(\"\\n\");\n msg_puts(_(\"Modified by \"));\n msg_puts(MODIFIED_BY);\n#endif", "#ifdef HAVE_PATHDEF\n if (*compiled_user != NUL || *compiled_sys != NUL)\n {\n\tmsg_puts(_(\"\\nCompiled \"));\n\tif (*compiled_user != NUL)\n\t{\n\t msg_puts(_(\"by \"));\n\t msg_puts((char *)compiled_user);\n\t}\n\tif (*compiled_sys != NUL)\n\t{\n\t msg_puts(\"@\");\n\t msg_puts((char *)compiled_sys);\n\t}\n }\n#endif", "#if defined(FEAT_HUGE)\n msg_puts(_(\"\\nHuge version \"));\n#elif defined(FEAT_BIG)\n msg_puts(_(\"\\nBig version \"));\n#elif defined(FEAT_NORMAL)\n msg_puts(_(\"\\nNormal version \"));\n#elif defined(FEAT_SMALL)\n msg_puts(_(\"\\nSmall version \"));\n#else\n msg_puts(_(\"\\nTiny version \"));\n#endif\n#if !defined(FEAT_GUI)\n msg_puts(_(\"without GUI.\"));\n#elif defined(FEAT_GUI_GTK)\n# if defined(USE_GTK3)\n msg_puts(_(\"with GTK3 GUI.\"));\n# elif defined(FEAT_GUI_GNOME)\n msg_puts(_(\"with GTK2-GNOME GUI.\"));\n# else\n msg_puts(_(\"with GTK2 GUI.\"));\n# endif\n#elif defined(FEAT_GUI_MOTIF)\n msg_puts(_(\"with X11-Motif GUI.\"));\n#elif defined(FEAT_GUI_HAIKU)\n msg_puts(_(\"with Haiku GUI.\"));\n#elif defined(FEAT_GUI_PHOTON)\n msg_puts(_(\"with Photon GUI.\"));\n#elif defined(MSWIN)\n msg_puts(_(\"with GUI.\"));\n#endif\n version_msg(_(\" Features included (+) or not (-):\\n\"));", " list_features();\n if (msg_col > 0)\n\tmsg_putchar('\\n');", "#ifdef SYS_VIMRC_FILE\n version_msg(_(\" system vimrc file: \\\"\"));\n version_msg(SYS_VIMRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE\n version_msg(_(\" user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE2\n version_msg(_(\" 2nd user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE2);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE3\n version_msg(_(\" 3rd user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE3);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_EXRC_FILE\n version_msg(_(\" user exrc file: \\\"\"));\n version_msg(USR_EXRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_EXRC_FILE2\n version_msg(_(\" 2nd user exrc file: \\\"\"));\n version_msg(USR_EXRC_FILE2);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef FEAT_GUI\n# ifdef SYS_GVIMRC_FILE\n version_msg(_(\" system gvimrc file: \\\"\"));\n version_msg(SYS_GVIMRC_FILE);\n version_msg(\"\\\"\\n\");\n# endif\n version_msg(_(\" user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE);\n version_msg(\"\\\"\\n\");\n# ifdef USR_GVIMRC_FILE2\n version_msg(_(\"2nd user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE2);\n version_msg(\"\\\"\\n\");\n# endif\n# ifdef USR_GVIMRC_FILE3\n version_msg(_(\"3rd user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE3);\n version_msg(\"\\\"\\n\");\n# endif\n#endif\n version_msg(_(\" defaults file: \\\"\"));\n version_msg(VIM_DEFAULTS_FILE);\n version_msg(\"\\\"\\n\");\n#ifdef FEAT_GUI\n# ifdef SYS_MENU_FILE\n version_msg(_(\" system menu file: \\\"\"));\n version_msg(SYS_MENU_FILE);\n version_msg(\"\\\"\\n\");\n# endif\n#endif\n#ifdef HAVE_PATHDEF\n if (*default_vim_dir != NUL)\n {\n\tversion_msg(_(\" fall-back for $VIM: \\\"\"));\n\tversion_msg((char *)default_vim_dir);\n\tversion_msg(\"\\\"\\n\");\n }\n if (*default_vimruntime_dir != NUL)\n {\n\tversion_msg(_(\" f-b for $VIMRUNTIME: \\\"\"));\n\tversion_msg((char *)default_vimruntime_dir);\n\tversion_msg(\"\\\"\\n\");\n }\n version_msg(_(\"Compilation: \"));\n version_msg((char *)all_cflags);\n version_msg(\"\\n\");\n#ifdef VMS\n if (*compiler_version != NUL)\n {\n\tversion_msg(_(\"Compiler: \"));\n\tversion_msg((char *)compiler_version);\n\tversion_msg(\"\\n\");\n }\n#endif\n version_msg(_(\"Linking: \"));\n version_msg((char *)all_lflags);\n#endif\n#ifdef DEBUG\n version_msg(\"\\n\");\n version_msg(_(\" DEBUG BUILD\"));\n#endif\n}", "static void do_intro_line(int row, char_u *mesg, int add_version, int attr);\nstatic void intro_message(int colon);", "/*\n * Show the intro message when not editing a file.\n */\n void\nmaybe_intro_message(void)\n{\n if (BUFEMPTY()\n\t && curbuf->b_fname == NULL\n\t && firstwin->w_next == NULL\n\t && vim_strchr(p_shm, SHM_INTRO) == NULL)\n\tintro_message(FALSE);\n}", "/*\n * Give an introductory message about Vim.\n * Only used when starting Vim on an empty file, without a file name.\n * Or with the \":intro\" command (for Sven :-).\n */\n static void\nintro_message(\n int\t\tcolon)\t\t// TRUE for \":intro\"\n{\n int\t\ti;\n int\t\trow;\n int\t\tblanklines;\n int\t\tsponsor;\n char\t*p;\n static char\t*(lines[]) =\n {\n\tN_(\"VIM - Vi IMproved\"),\n\t\"\",\n\tN_(\"version \"),\n\tN_(\"by Bram Moolenaar et al.\"),\n#ifdef MODIFIED_BY\n\t\" \",\n#endif\n\tN_(\"Vim is open source and freely distributable\"),\n\t\"\",\n\tN_(\"Help poor children in Uganda!\"),\n\tN_(\"type :help iccf<Enter> for information \"),\n\t\"\",\n\tN_(\"type :q<Enter> to exit \"),\n\tN_(\"type :help<Enter> or <F1> for on-line help\"),\n\tN_(\"type :help version9<Enter> for version info\"),\n\tNULL,\n\t\"\",\n\tN_(\"Running in Vi compatible mode\"),\n\tN_(\"type :set nocp<Enter> for Vim defaults\"),\n\tN_(\"type :help cp-default<Enter> for info on this\"),\n };\n#ifdef FEAT_GUI\n static char\t*(gui_lines[]) =\n {\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n#ifdef MODIFIED_BY\n\tNULL,\n#endif\n\tNULL,\n\tNULL,\n\tNULL,\n\tN_(\"menu Help->Orphans for information \"),\n\tNULL,\n\tN_(\"Running modeless, typed text is inserted\"),\n\tN_(\"menu Edit->Global Settings->Toggle Insert Mode \"),\n\tN_(\" for two modes \"),\n\tNULL,\n\tNULL,\n\tNULL,\n\tN_(\"menu Edit->Global Settings->Toggle Vi Compatible\"),\n\tN_(\" for Vim defaults \"),\n };\n#endif", " // blanklines = screen height - # message lines\n blanklines = (int)Rows - (ARRAY_LENGTH(lines) - 1);\n if (!p_cp)\n\tblanklines += 4; // add 4 for not showing \"Vi compatible\" message", " // Don't overwrite a statusline. Depends on 'cmdheight'.\n if (p_ls > 1)\n\tblanklines -= Rows - topframe->fr_height;\n if (blanklines < 0)\n\tblanklines = 0;", " // Show the sponsor and register message one out of four times, the Uganda\n // message two out of four times.\n sponsor = (int)time(NULL);\n sponsor = ((sponsor & 2) == 0) - ((sponsor & 4) == 0);", " // start displaying the message lines after half of the blank lines\n row = blanklines / 2;\n if ((row >= 2 && Columns >= 50) || colon)\n {\n\tfor (i = 0; i < (int)ARRAY_LENGTH(lines); ++i)\n\t{\n\t p = lines[i];\n#ifdef FEAT_GUI\n\t if (p_im && gui.in_use && gui_lines[i] != NULL)\n\t\tp = gui_lines[i];\n#endif\n\t if (p == NULL)\n\t {\n\t\tif (!p_cp)\n\t\t break;\n\t\tcontinue;\n\t }\n\t if (sponsor != 0)\n\t {\n\t\tif (strstr(p, \"children\") != NULL)\n\t\t p = sponsor < 0\n\t\t\t? N_(\"Sponsor Vim development!\")\n\t\t\t: N_(\"Become a registered Vim user!\");\n\t\telse if (strstr(p, \"iccf\") != NULL)\n\t\t p = sponsor < 0\n\t\t\t? N_(\"type :help sponsor<Enter> for information \")\n\t\t\t: N_(\"type :help register<Enter> for information \");\n\t\telse if (strstr(p, \"Orphans\") != NULL)\n\t\t p = N_(\"menu Help->Sponsor/Register for information \");\n\t }\n\t if (*p != NUL)\n\t\tdo_intro_line(row, (char_u *)_(p), i == 2, 0);\n\t ++row;\n\t}\n }", " // Make the wait-return message appear just below the text.\n if (colon)\n\tmsg_row = row;\n}", " static void\ndo_intro_line(\n int\t\trow,\n char_u\t*mesg,\n int\t\tadd_version,\n int\t\tattr)\n{\n char_u\tvers[20];\n int\t\tcol;\n char_u\t*p;\n int\t\tl;\n int\t\tclen;\n#ifdef MODIFIED_BY\n# define MODBY_LEN 150\n char_u\tmodby[MODBY_LEN];", " if (*mesg == ' ')\n {\n\tvim_strncpy(modby, (char_u *)_(\"Modified by \"), MODBY_LEN - 1);\n\tl = (int)STRLEN(modby);\n\tvim_strncpy(modby + l, (char_u *)MODIFIED_BY, MODBY_LEN - l - 1);\n\tmesg = modby;\n }\n#endif", " // Center the message horizontally.\n col = vim_strsize(mesg);\n if (add_version)\n {\n\tSTRCPY(vers, mediumVersion);\n\tif (highest_patch())\n\t{\n\t // Check for 9.9x or 9.9xx, alpha/beta version\n\t if (isalpha((int)vers[3]))\n\t {\n\t\tint len = (isalpha((int)vers[4])) ? 5 : 4;\n\t\tsprintf((char *)vers + len, \".%d%s\", highest_patch(),\n\t\t\t\t\t\t\t mediumVersion + len);\n\t }\n\t else\n\t\tsprintf((char *)vers + 3, \".%d\", highest_patch());\n\t}\n\tcol += (int)STRLEN(vers);\n }\n col = (Columns - col) / 2;\n if (col < 0)\n\tcol = 0;", " // Split up in parts to highlight <> items differently.\n for (p = mesg; *p != NUL; p += l)\n {\n\tclen = 0;\n\tfor (l = 0; p[l] != NUL\n\t\t\t && (l == 0 || (p[l] != '<' && p[l - 1] != '>')); ++l)\n\t{\n\t if (has_mbyte)\n\t {\n\t\tclen += ptr2cells(p + l);\n\t\tl += (*mb_ptr2len)(p + l) - 1;\n\t }\n\t else\n\t\tclen += byte2cells(p[l]);\n\t}\n\tscreen_puts_len(p, l, row, col, *p == '<' ? HL_ATTR(HLF_8) : attr);\n\tcol += clen;\n }", " // Add the version number to the version line.\n if (add_version)\n\tscreen_puts(vers, row, col, 0);\n}", "/*\n * \":intro\": clear screen, display intro screen and wait for return.\n */\n void\nex_intro(exarg_T *eap UNUSED)\n{\n screenclear();\n intro_message(TRUE);\n wait_return(TRUE);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 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 ]
PreciseBugs
{"buggy_code_end_loc": [698, 2100, 737], "buggy_code_start_loc": [526, 2100, 737], "filenames": ["src/insexpand.c", "src/testdir/test_ins_complete.vim", "src/version.c"], "fixing_code_end_loc": [736, 2117, 740], "fixing_code_start_loc": [527, 2101, 738], "message": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0044.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "0069C36F-19A3-4647-B84F-84CE62E8A554", "versionEndExcluding": "9.0.0044", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:35:*:*:*:*:*:*:*", "matchCriteriaId": "80E516C0-98A4-4ADE-B69F-66A772E2BAAA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0044."}, {"lang": "es", "value": "Un Desbordamiento de B\u00fafer en la Regi\u00f3n Heap de la Memoria en el repositorio de GitHub vim/vim versiones anteriores a 9.0.0044"}], "evaluatorComment": null, "id": "CVE-2022-2343", "lastModified": "2023-05-03T12:15:58.413", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-07-08T18:15:09.820", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/caea66442d86e7bbba3bf3dc202c3c0d549b9853"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2ecb4345-2fc7-4e7f-adb0-83a20bb458f5"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/43Y3VJPOTTY3NTREDIFUPITM2POG4ZLP/"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/202208-32"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-122"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/caea66442d86e7bbba3bf3dc202c3c0d549b9853"}, "type": "CWE-122"}
172
Determine whether the {function_name} code is vulnerable or not.
[ "/* vi:set ts=8 sts=4 sw=4 noet:\n *\n * VIM - Vi IMproved\t\tby Bram Moolenaar\n *\n * Do \":help uganda\" in Vim to read copying and usage conditions.\n * Do \":help credits\" in Vim to see a list of people who contributed.\n * See README.txt for an overview of the Vim source code.\n */", "#include \"vim.h\"", "/*\n * Vim originated from Stevie version 3.6 (Fish disk 217) by GRWalter (Fred)\n * It has been changed beyond recognition since then.\n *\n * Differences between version 8.2 and 9.0 can be found with \":help version9\".\n * Differences between version 7.4 and 8.x can be found with \":help version8\".\n * Differences between version 6.4 and 7.x can be found with \":help version7\".\n * Differences between version 5.8 and 6.x can be found with \":help version6\".\n * Differences between version 4.x and 5.x can be found with \":help version5\".\n * Differences between version 3.0 and 4.x can be found with \":help version4\".\n * All the remarks about older versions have been removed, they are not very\n * interesting.\n */", "#include \"version.h\"", "char\t\t*Version = VIM_VERSION_SHORT;\nstatic char\t*mediumVersion = VIM_VERSION_MEDIUM;", "#if defined(HAVE_DATE_TIME) || defined(PROTO)\n# if (defined(VMS) && defined(VAXC)) || defined(PROTO)\nchar\tlongVersion[sizeof(VIM_VERSION_LONG_DATE) + sizeof(__DATE__)\n\t\t\t\t\t\t + sizeof(__TIME__) + 3];", " void\ninit_longVersion(void)\n{\n /*\n * Construct the long version string. Necessary because\n * VAX C can't concatenate strings in the preprocessor.\n */\n strcpy(longVersion, VIM_VERSION_LONG_DATE);\n#ifdef BUILD_DATE\n strcat(longVersion, BUILD_DATE);\n#else\n strcat(longVersion, __DATE__);\n strcat(longVersion, \" \");\n strcat(longVersion, __TIME__);\n#endif\n strcat(longVersion, \")\");\n}", "# else\nchar\t*longVersion = NULL;", " void\ninit_longVersion(void)\n{\n if (longVersion == NULL)\n {\n#ifdef BUILD_DATE\n\tchar *date_time = BUILD_DATE;\n#else\n\tchar *date_time = __DATE__ \" \" __TIME__;\n#endif\n\tchar *msg = _(\"%s (%s, compiled %s)\");\n\tsize_t len = strlen(msg)\n\t\t + strlen(VIM_VERSION_LONG_ONLY)\n\t\t + strlen(VIM_VERSION_DATE_ONLY)\n\t\t + strlen(date_time);", "\tlongVersion = alloc(len);\n\tif (longVersion == NULL)\n\t longVersion = VIM_VERSION_LONG;\n\telse\n\t vim_snprintf(longVersion, len, msg,\n\t\t VIM_VERSION_LONG_ONLY, VIM_VERSION_DATE_ONLY, date_time);\n }\n}\n# endif\n#else\nchar\t*longVersion = VIM_VERSION_LONG;", " void\ninit_longVersion(void)\n{\n // nothing to do\n}\n#endif", "static char *(features[]) =\n{\n#ifdef HAVE_ACL\n\t\"+acl\",\n#else\n\t\"-acl\",\n#endif\n#ifdef AMIGA\t\t// only for Amiga systems\n# ifdef FEAT_ARP\n\t\"+ARP\",\n# else\n\t\"-ARP\",\n# endif\n#endif\n#ifdef FEAT_ARABIC\n\t\"+arabic\",\n#else\n\t\"-arabic\",\n#endif\n\t\"+autocmd\",\n#ifdef FEAT_AUTOCHDIR\n \"+autochdir\",\n#else\n \"-autochdir\",\n#endif\n#ifdef FEAT_AUTOSERVERNAME\n\t\"+autoservername\",\n#else\n\t\"-autoservername\",\n#endif\n#ifdef FEAT_BEVAL_GUI\n\t\"+balloon_eval\",\n#else\n\t\"-balloon_eval\",\n#endif\n#ifdef FEAT_BEVAL_TERM\n\t\"+balloon_eval_term\",\n#else\n\t\"-balloon_eval_term\",\n#endif\n#ifdef FEAT_BROWSE\n\t\"+browse\",\n#else\n\t\"-browse\",\n#endif\n#ifdef NO_BUILTIN_TCAPS\n\t\"-builtin_terms\",\n#endif\n#ifdef SOME_BUILTIN_TCAPS\n\t\"+builtin_terms\",\n#endif\n#ifdef ALL_BUILTIN_TCAPS\n\t\"++builtin_terms\",\n#endif\n#ifdef FEAT_BYTEOFF\n\t\"+byte_offset\",\n#else\n\t\"-byte_offset\",\n#endif\n#ifdef FEAT_JOB_CHANNEL\n\t\"+channel\",\n#else\n\t\"-channel\",\n#endif\n\t\"+cindent\",\n#ifdef FEAT_CLIENTSERVER\n\t\"+clientserver\",\n#else\n\t\"-clientserver\",\n#endif\n#ifdef FEAT_CLIPBOARD\n\t\"+clipboard\",\n#else\n\t\"-clipboard\",\n#endif\n\t\"+cmdline_compl\",\n\t\"+cmdline_hist\",\n#ifdef FEAT_CMDL_INFO\n\t\"+cmdline_info\",\n#else\n\t\"-cmdline_info\",\n#endif\n\t\"+comments\",\n#ifdef FEAT_CONCEAL\n\t\"+conceal\",\n#else\n\t\"-conceal\",\n#endif\n#ifdef FEAT_CRYPT\n\t\"+cryptv\",\n#else\n\t\"-cryptv\",\n#endif\n#ifdef FEAT_CSCOPE\n\t\"+cscope\",\n#else\n\t\"-cscope\",\n#endif\n\t\"+cursorbind\",\n#ifdef CURSOR_SHAPE\n\t\"+cursorshape\",\n#else\n\t\"-cursorshape\",\n#endif\n#if defined(FEAT_CON_DIALOG) && defined(FEAT_GUI_DIALOG)\n\t\"+dialog_con_gui\",\n#else\n# if defined(FEAT_CON_DIALOG)\n\t\"+dialog_con\",\n# else\n# if defined(FEAT_GUI_DIALOG)\n\t\"+dialog_gui\",\n# else\n\t\"-dialog\",\n# endif\n# endif\n#endif\n#ifdef FEAT_DIFF\n\t\"+diff\",\n#else\n\t\"-diff\",\n#endif\n#ifdef FEAT_DIGRAPHS\n\t\"+digraphs\",\n#else\n\t\"-digraphs\",\n#endif\n#ifdef FEAT_GUI_MSWIN\n# ifdef FEAT_DIRECTX\n\t\"+directx\",\n# else\n\t\"-directx\",\n# endif\n#endif\n#ifdef FEAT_DND\n\t\"+dnd\",\n#else\n\t\"-dnd\",\n#endif\n\t\"-ebcdic\",\n#ifdef FEAT_EMACS_TAGS\n\t\"+emacs_tags\",\n#else\n\t\"-emacs_tags\",\n#endif\n#ifdef FEAT_EVAL\n\t\"+eval\",\n#else\n\t\"-eval\",\n#endif\n\t\"+ex_extra\",\n#ifdef FEAT_SEARCH_EXTRA\n\t\"+extra_search\",\n#else\n\t\"-extra_search\",\n#endif\n\t\"-farsi\",\n#ifdef FEAT_SEARCHPATH\n\t\"+file_in_path\",\n#else\n\t\"-file_in_path\",\n#endif\n#ifdef FEAT_FIND_ID\n\t\"+find_in_path\",\n#else\n\t\"-find_in_path\",\n#endif\n#ifdef FEAT_FLOAT\n\t\"+float\",\n#else\n\t\"-float\",\n#endif\n#ifdef FEAT_FOLDING\n\t\"+folding\",\n#else\n\t\"-folding\",\n#endif\n#ifdef FEAT_FOOTER\n\t\"+footer\",\n#else\n\t\"-footer\",\n#endif\n\t // only interesting on Unix systems\n#if !defined(USE_SYSTEM) && defined(UNIX)\n\t\"+fork()\",\n#endif\n#ifdef FEAT_GETTEXT\n# ifdef DYNAMIC_GETTEXT\n\t\"+gettext/dyn\",\n# else\n\t\"+gettext\",\n# endif\n#else\n\t\"-gettext\",\n#endif\n\t\"-hangul_input\",\n#if (defined(HAVE_ICONV_H) && defined(USE_ICONV)) || defined(DYNAMIC_ICONV)\n# ifdef DYNAMIC_ICONV\n\t\"+iconv/dyn\",\n# else\n\t\"+iconv\",\n# endif\n#else\n\t\"-iconv\",\n#endif\n\t\"+insert_expand\",\n#ifdef FEAT_IPV6\n\t\"+ipv6\",\n#else\n\t\"-ipv6\",\n#endif\n#ifdef FEAT_JOB_CHANNEL\n\t\"+job\",\n#else\n\t\"-job\",\n#endif\n\t\"+jumplist\",\n#ifdef FEAT_KEYMAP\n\t\"+keymap\",\n#else\n\t\"-keymap\",\n#endif\n#ifdef FEAT_EVAL\n\t\"+lambda\",\n#else\n\t\"-lambda\",\n#endif\n#ifdef FEAT_LANGMAP\n\t\"+langmap\",\n#else\n\t\"-langmap\",\n#endif\n#ifdef FEAT_LIBCALL\n\t\"+libcall\",\n#else\n\t\"-libcall\",\n#endif\n#ifdef FEAT_LINEBREAK\n\t\"+linebreak\",\n#else\n\t\"-linebreak\",\n#endif\n\t\"+lispindent\",\n\t\"+listcmds\",\n\t\"+localmap\",\n#ifdef FEAT_LUA\n# ifdef DYNAMIC_LUA\n\t\"+lua/dyn\",\n# else\n\t\"+lua\",\n# endif\n#else\n\t\"-lua\",\n#endif\n#ifdef FEAT_MENU\n\t\"+menu\",\n#else\n\t\"-menu\",\n#endif\n#ifdef FEAT_SESSION\n\t\"+mksession\",\n#else\n\t\"-mksession\",\n#endif\n\t\"+modify_fname\",\n\t\"+mouse\",\n#ifdef FEAT_MOUSESHAPE\n\t\"+mouseshape\",\n#else\n\t\"-mouseshape\",\n#endif", "#if defined(UNIX) || defined(VMS)\n# ifdef FEAT_MOUSE_DEC\n\t\"+mouse_dec\",\n# else\n\t\"-mouse_dec\",\n# endif\n# ifdef FEAT_MOUSE_GPM\n# ifdef DYNAMIC_GPM\n\t\"+mouse_gpm/dyn\",\n# else\n\t\"+mouse_gpm\",\n# endif\n# else\n\t\"-mouse_gpm\",\n# endif\n# ifdef FEAT_MOUSE_JSB\n\t\"+mouse_jsbterm\",\n# else\n\t\"-mouse_jsbterm\",\n# endif\n# ifdef FEAT_MOUSE_NET\n\t\"+mouse_netterm\",\n# else\n\t\"-mouse_netterm\",\n# endif\n#endif", "#ifdef __QNX__\n# ifdef FEAT_MOUSE_PTERM\n\t\"+mouse_pterm\",\n# else\n\t\"-mouse_pterm\",\n# endif\n#endif", "#if defined(UNIX) || defined(VMS)\n\t\"+mouse_sgr\",\n# ifdef FEAT_SYSMOUSE\n\t\"+mouse_sysmouse\",\n# else\n\t\"-mouse_sysmouse\",\n# endif\n# ifdef FEAT_MOUSE_URXVT\n\t\"+mouse_urxvt\",\n# else\n\t\"-mouse_urxvt\",\n# endif\n\t\"+mouse_xterm\",\n#endif", "#ifdef FEAT_MBYTE_IME\n# ifdef DYNAMIC_IME\n\t\"+multi_byte_ime/dyn\",\n# else\n\t\"+multi_byte_ime\",\n# endif\n#else\n\t\"+multi_byte\",\n#endif\n#ifdef FEAT_MULTI_LANG\n\t\"+multi_lang\",\n#else\n\t\"-multi_lang\",\n#endif\n#ifdef FEAT_MZSCHEME\n# ifdef DYNAMIC_MZSCHEME\n\t\"+mzscheme/dyn\",\n# else\n\t\"+mzscheme\",\n# endif\n#else\n\t\"-mzscheme\",\n#endif\n#ifdef FEAT_NETBEANS_INTG\n\t\"+netbeans_intg\",\n#else\n\t\"-netbeans_intg\",\n#endif\n\t\"+num64\",\n#ifdef FEAT_GUI_MSWIN\n# ifdef FEAT_OLE\n\t\"+ole\",\n# else\n\t\"-ole\",\n# endif\n#endif\n#ifdef FEAT_EVAL\n\t\"+packages\",\n#else\n\t\"-packages\",\n#endif\n#ifdef FEAT_PATH_EXTRA\n\t\"+path_extra\",\n#else\n\t\"-path_extra\",\n#endif\n#ifdef FEAT_PERL\n# ifdef DYNAMIC_PERL\n\t\"+perl/dyn\",\n# else\n\t\"+perl\",\n# endif\n#else\n\t\"-perl\",\n#endif\n#ifdef FEAT_PERSISTENT_UNDO\n\t\"+persistent_undo\",\n#else\n\t\"-persistent_undo\",\n#endif\n#ifdef FEAT_PROP_POPUP\n\t\"+popupwin\",\n#else\n\t\"-popupwin\",\n#endif\n#ifdef FEAT_PRINTER\n# ifdef FEAT_POSTSCRIPT\n\t\"+postscript\",\n# else\n\t\"-postscript\",\n# endif\n\t\"+printer\",\n#else\n\t\"-printer\",\n#endif\n#ifdef FEAT_PROFILE\n\t\"+profile\",\n#else\n\t\"-profile\",\n#endif\n#ifdef FEAT_PYTHON\n# ifdef DYNAMIC_PYTHON\n\t\"+python/dyn\",\n# else\n\t\"+python\",\n# endif\n#else\n\t\"-python\",\n#endif\n#ifdef FEAT_PYTHON3\n# ifdef DYNAMIC_PYTHON3\n\t\"+python3/dyn\",\n# else\n\t\"+python3\",\n# endif\n#else\n\t\"-python3\",\n#endif\n#ifdef FEAT_QUICKFIX\n\t\"+quickfix\",\n#else\n\t\"-quickfix\",\n#endif\n#ifdef FEAT_RELTIME\n\t\"+reltime\",\n#else\n\t\"-reltime\",\n#endif\n#ifdef FEAT_RIGHTLEFT\n\t\"+rightleft\",\n#else\n\t\"-rightleft\",\n#endif\n#ifdef FEAT_RUBY\n# ifdef DYNAMIC_RUBY\n\t\"+ruby/dyn\",\n# else\n\t\"+ruby\",\n# endif\n#else\n\t\"-ruby\",\n#endif\n\t\"+scrollbind\",\n#ifdef FEAT_SIGNS\n\t\"+signs\",\n#else\n\t\"-signs\",\n#endif\n\t\"+smartindent\",\n#ifdef FEAT_SODIUM\n# ifdef DYNAMIC_SODIUM\n\t\"+sodium/dyn\",\n# else\n\t\"+sodium\",\n# endif\n#else\n\t\"-sodium\",\n#endif\n#ifdef FEAT_SOUND\n\t\"+sound\",\n#else\n\t\"-sound\",\n#endif\n#ifdef FEAT_SPELL\n\t\"+spell\",\n#else\n\t\"-spell\",\n#endif\n#ifdef STARTUPTIME\n\t\"+startuptime\",\n#else\n\t\"-startuptime\",\n#endif\n#ifdef FEAT_STL_OPT\n\t\"+statusline\",\n#else\n\t\"-statusline\",\n#endif\n\t\"-sun_workshop\",\n#ifdef FEAT_SYN_HL\n\t\"+syntax\",\n#else\n\t\"-syntax\",\n#endif\n\t // only interesting on Unix systems\n#if defined(USE_SYSTEM) && defined(UNIX)\n\t\"+system()\",\n#endif\n\t\"+tag_binary\",\n\t\"-tag_old_static\",\n\t\"-tag_any_white\",\n#ifdef FEAT_TCL\n# ifdef DYNAMIC_TCL\n\t\"+tcl/dyn\",\n# else\n\t\"+tcl\",\n# endif\n#else\n\t\"-tcl\",\n#endif\n#ifdef FEAT_TERMGUICOLORS\n\t\"+termguicolors\",\n#else\n\t\"-termguicolors\",\n#endif\n#ifdef FEAT_TERMINAL\n\t\"+terminal\",\n#else\n\t\"-terminal\",\n#endif\n#if defined(UNIX)\n// only Unix can have terminfo instead of termcap\n# ifdef TERMINFO\n\t\"+terminfo\",\n# else\n\t\"-terminfo\",\n# endif\n#endif\n#ifdef FEAT_TERMRESPONSE\n\t\"+termresponse\",\n#else\n\t\"-termresponse\",\n#endif\n#ifdef FEAT_TEXTOBJ\n\t\"+textobjects\",\n#else\n\t\"-textobjects\",\n#endif\n#ifdef FEAT_PROP_POPUP\n\t\"+textprop\",\n#else\n\t\"-textprop\",\n#endif\n#if !defined(UNIX)\n// unix always includes termcap support\n# ifdef HAVE_TGETENT\n\t\"+tgetent\",\n# else\n\t\"-tgetent\",\n# endif\n#endif\n#ifdef FEAT_TIMERS\n\t\"+timers\",\n#else\n\t\"-timers\",\n#endif\n\t\"+title\",\n#ifdef FEAT_TOOLBAR\n\t\"+toolbar\",\n#else\n\t\"-toolbar\",\n#endif\n\t\"+user_commands\",\n#ifdef FEAT_VARTABS\n\t\"+vartabs\",\n#else\n\t\"-vartabs\",\n#endif\n\t\"+vertsplit\",\n\t\"+vim9script\",\n#ifdef FEAT_VIMINFO\n\t\"+viminfo\",\n#else\n\t\"-viminfo\",\n#endif\n\t\"+virtualedit\",\n\t\"+visual\",\n\t\"+visualextra\",\n\t\"+vreplace\",\n#ifdef MSWIN\n# ifdef FEAT_VTP\n\t\"+vtp\",\n# else\n\t\"-vtp\",\n# endif\n#endif\n#ifdef FEAT_WILDIGN\n\t\"+wildignore\",\n#else\n\t\"-wildignore\",\n#endif\n#ifdef FEAT_WILDMENU\n\t\"+wildmenu\",\n#else\n\t\"-wildmenu\",\n#endif\n\t\"+windows\",\n#ifdef FEAT_WRITEBACKUP\n\t\"+writebackup\",\n#else\n\t\"-writebackup\",\n#endif\n#if defined(UNIX) || defined(VMS)\n# ifdef FEAT_X11\n\t\"+X11\",\n# else\n\t\"-X11\",\n# endif\n#endif\n#ifdef FEAT_XFONTSET\n\t\"+xfontset\",\n#else\n\t\"-xfontset\",\n#endif\n#ifdef FEAT_XIM\n\t\"+xim\",\n#else\n\t\"-xim\",\n#endif\n#if defined(MSWIN)\n# ifdef FEAT_XPM_W32\n\t\"+xpm_w32\",\n# else\n\t\"-xpm_w32\",\n# endif\n#elif defined(HAVE_XPM)\n\t\"+xpm\",\n#else\n\t\"-xpm\",\n#endif\n#if defined(UNIX) || defined(VMS)\n# if defined(USE_XSMP_INTERACT)\n\t\"+xsmp_interact\",\n# elif defined(USE_XSMP)\n\t\"+xsmp\",\n# else\n\t\"-xsmp\",\n# endif\n# ifdef FEAT_XCLIPBOARD\n\t\"+xterm_clipboard\",\n# else\n\t\"-xterm_clipboard\",\n# endif\n#endif\n#ifdef FEAT_XTERM_SAVE\n\t\"+xterm_save\",\n#else\n\t\"-xterm_save\",\n#endif\n\tNULL\n};", "static int included_patches[] =\n{ /* Add new patch number below this line */", "/**/\n 45,", "/**/\n 44,\n/**/\n 43,\n/**/\n 42,\n/**/\n 41,\n/**/\n 40,\n/**/\n 39,\n/**/\n 38,\n/**/\n 37,\n/**/\n 36,\n/**/\n 35,\n/**/\n 34,\n/**/\n 33,\n/**/\n 32,\n/**/\n 31,\n/**/\n 30,\n/**/\n 29,\n/**/\n 28,\n/**/\n 27,\n/**/\n 26,\n/**/\n 25,\n/**/\n 24,\n/**/\n 23,\n/**/\n 22,\n/**/\n 21,\n/**/\n 20,\n/**/\n 19,\n/**/\n 18,\n/**/\n 17,\n/**/\n 16,\n/**/\n 15,\n/**/\n 14,\n/**/\n 13,\n/**/\n 12,\n/**/\n 11,\n/**/\n 10,\n/**/\n 9,\n/**/\n 8,\n/**/\n 7,\n/**/\n 6,\n/**/\n 5,\n/**/\n 4,\n/**/\n 3,\n/**/\n 2,\n/**/\n 1,\n/**/\n 0\n};", "/*\n * Place to put a short description when adding a feature with a patch.\n * Keep it short, e.g.,: \"relative numbers\", \"persistent undo\".\n * Also add a comment marker to separate the lines.\n * See the official Vim patches for the diff format: It must use a context of\n * one line only. Create it by hand or use \"diff -C2\" and edit the patch.\n */\nstatic char *(extra_patches[]) =\n{ /* Add your patch description below this line */\n/**/\n NULL\n};", " int\nhighest_patch(void)\n{\n // this relies on the highest patch number to be the first entry\n return included_patches[0];\n}", "#if defined(FEAT_EVAL) || defined(PROTO)\n/*\n * Return TRUE if patch \"n\" has been included.\n */\n int\nhas_patch(int n)\n{\n int\t\th, m, l;", " // Perform a binary search.\n l = 0;\n h = (int)ARRAY_LENGTH(included_patches) - 1;\n for (;;)\n {\n\tm = (l + h) / 2;\n\tif (included_patches[m] == n)\n\t return TRUE;\n\tif (l == h)\n\t break;\n\tif (included_patches[m] < n)\n\t h = m;\n\telse\n\t l = m + 1;\n }\n return FALSE;\n}\n#endif", " void\nex_version(exarg_T *eap)\n{\n /*\n * Ignore a \":version 9.99\" command.\n */\n if (*eap->arg == NUL)\n {\n\tmsg_putchar('\\n');\n\tlist_version();\n }\n}", "/*\n * Output a string for the version message. If it's going to wrap, output a\n * newline, unless the message is too long to fit on the screen anyway.\n * When \"wrap\" is TRUE wrap the string in [].\n */\n static void\nversion_msg_wrap(char_u *s, int wrap)\n{\n int\t\tlen = vim_strsize(s) + (wrap ? 2 : 0);", " if (!got_int && len < (int)Columns && msg_col + len >= (int)Columns\n\t\t\t\t\t\t\t\t&& *s != '\\n')\n\tmsg_putchar('\\n');\n if (!got_int)\n {\n\tif (wrap)\n\t msg_puts(\"[\");\n\tmsg_puts((char *)s);\n\tif (wrap)\n\t msg_puts(\"]\");\n }\n}", " static void\nversion_msg(char *s)\n{\n version_msg_wrap((char_u *)s, FALSE);\n}", "/*\n * List all features aligned in columns, dictionary style.\n */\n static void\nlist_features(void)\n{\n list_in_columns((char_u **)features, -1, -1);\n}", "/*\n * List string items nicely aligned in columns.\n * When \"size\" is < 0 then the last entry is marked with NULL.\n * The entry with index \"current\" is inclosed in [].\n */\n void\nlist_in_columns(char_u **items, int size, int current)\n{\n int\t\ti;\n int\t\tncol;\n int\t\tnrow;\n int\t\tcur_row = 1;\n int\t\titem_count = 0;\n int\t\twidth = 0;\n#ifdef FEAT_SYN_HL\n int\t\tuse_highlight = (items == (char_u **)features);\n#endif", " // Find the length of the longest item, use that + 1 as the column\n // width.\n for (i = 0; size < 0 ? items[i] != NULL : i < size; ++i)\n {\n\tint l = vim_strsize(items[i]) + (i == current ? 2 : 0);", "\tif (l > width)\n\t width = l;\n\t++item_count;\n }\n width += 1;", " if (Columns < width)\n {\n\t// Not enough screen columns - show one per line\n\tfor (i = 0; i < item_count; ++i)\n\t{\n\t version_msg_wrap(items[i], i == current);\n\t if (msg_col > 0 && i < item_count - 1)\n\t\tmsg_putchar('\\n');\n\t}\n\treturn;\n }", " // The rightmost column doesn't need a separator.\n // Sacrifice it to fit in one more column if possible.\n ncol = (int) (Columns + 1) / width;\n nrow = item_count / ncol + ((item_count % ncol) ? 1 : 0);", " // \"i\" counts columns then rows. \"idx\" counts rows then columns.\n for (i = 0; !got_int && i < nrow * ncol; ++i)\n {\n\tint idx = (i / ncol) + (i % ncol) * nrow;", "\tif (idx < item_count)\n\t{\n\t int last_col = (i + 1) % ncol == 0;", "\t if (idx == current)\n\t\tmsg_putchar('[');\n#ifdef FEAT_SYN_HL\n\t if (use_highlight && items[idx][0] == '-')\n\t\tmsg_puts_attr((char *)items[idx], HL_ATTR(HLF_W));\n\t else\n#endif\n\t\tmsg_puts((char *)items[idx]);\n\t if (idx == current)\n\t\tmsg_putchar(']');\n\t if (last_col)\n\t {\n\t\tif (msg_col > 0 && cur_row < nrow)\n\t\t msg_putchar('\\n');\n\t\t++cur_row;\n\t }\n\t else\n\t {\n\t\twhile (msg_col % width)\n\t\t msg_putchar(' ');\n\t }\n\t}\n\telse\n\t{\n\t // this row is out of items, thus at the end of the row\n\t if (msg_col > 0)\n\t {\n\t\tif (cur_row < nrow)\n\t\t msg_putchar('\\n');\n\t\t++cur_row;\n\t }\n\t}\n }\n}", " void\nlist_version(void)\n{\n int\t\ti;\n int\t\tfirst;\n char\t*s = \"\";", " /*\n * When adding features here, don't forget to update the list of\n * internal variables in eval.c!\n */\n init_longVersion();\n msg(longVersion);\n#ifdef MSWIN\n# ifdef FEAT_GUI_MSWIN\n# ifdef VIMDLL\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit GUI/console version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit GUI/console version\"));\n# endif\n# else\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit GUI version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit GUI version\"));\n# endif\n# endif\n# ifdef FEAT_OLE\n msg_puts(_(\" with OLE support\"));\n# endif\n# else\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit console version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit console version\"));\n# endif\n# endif\n#endif\n#if defined(MACOS_X)\n# if defined(MACOS_X_DARWIN)\n msg_puts(_(\"\\nmacOS version\"));\n# else\n msg_puts(_(\"\\nmacOS version w/o darwin feat.\"));\n# endif\n# if defined(__arm64__)\n msg_puts(\" - arm64\");\n# elif defined(__x86_64__)\n msg_puts(\" - x86_64\");\n# endif\n#endif", "#ifdef VMS\n msg_puts(_(\"\\nOpenVMS version\"));\n# ifdef HAVE_PATHDEF\n if (*compiled_arch != NUL)\n {\n\tmsg_puts(\" - \");\n\tmsg_puts((char *)compiled_arch);\n }\n# endif", "#endif", " // Print the list of patch numbers if there is at least one.\n // Print a range when patches are consecutive: \"1-10, 12, 15-40, 42-45\"\n if (included_patches[0] != 0)\n {\n\tmsg_puts(_(\"\\nIncluded patches: \"));\n\tfirst = -1;\n\ti = (int)ARRAY_LENGTH(included_patches) - 1;\n\twhile (--i >= 0)\n\t{\n\t if (first < 0)\n\t\tfirst = included_patches[i];\n\t if (i == 0 || included_patches[i - 1] != included_patches[i] + 1)\n\t {\n\t\tmsg_puts(s);\n\t\ts = \", \";\n\t\tmsg_outnum((long)first);\n\t\tif (first != included_patches[i])\n\t\t{\n\t\t msg_puts(\"-\");\n\t\t msg_outnum((long)included_patches[i]);\n\t\t}\n\t\tfirst = -1;\n\t }\n\t}\n }", " // Print the list of extra patch descriptions if there is at least one.\n if (extra_patches[0] != NULL)\n {\n\tmsg_puts(_(\"\\nExtra patches: \"));\n\ts = \"\";\n\tfor (i = 0; extra_patches[i] != NULL; ++i)\n\t{\n\t msg_puts(s);\n\t s = \", \";\n\t msg_puts(extra_patches[i]);\n\t}\n }", "#ifdef MODIFIED_BY\n msg_puts(\"\\n\");\n msg_puts(_(\"Modified by \"));\n msg_puts(MODIFIED_BY);\n#endif", "#ifdef HAVE_PATHDEF\n if (*compiled_user != NUL || *compiled_sys != NUL)\n {\n\tmsg_puts(_(\"\\nCompiled \"));\n\tif (*compiled_user != NUL)\n\t{\n\t msg_puts(_(\"by \"));\n\t msg_puts((char *)compiled_user);\n\t}\n\tif (*compiled_sys != NUL)\n\t{\n\t msg_puts(\"@\");\n\t msg_puts((char *)compiled_sys);\n\t}\n }\n#endif", "#if defined(FEAT_HUGE)\n msg_puts(_(\"\\nHuge version \"));\n#elif defined(FEAT_BIG)\n msg_puts(_(\"\\nBig version \"));\n#elif defined(FEAT_NORMAL)\n msg_puts(_(\"\\nNormal version \"));\n#elif defined(FEAT_SMALL)\n msg_puts(_(\"\\nSmall version \"));\n#else\n msg_puts(_(\"\\nTiny version \"));\n#endif\n#if !defined(FEAT_GUI)\n msg_puts(_(\"without GUI.\"));\n#elif defined(FEAT_GUI_GTK)\n# if defined(USE_GTK3)\n msg_puts(_(\"with GTK3 GUI.\"));\n# elif defined(FEAT_GUI_GNOME)\n msg_puts(_(\"with GTK2-GNOME GUI.\"));\n# else\n msg_puts(_(\"with GTK2 GUI.\"));\n# endif\n#elif defined(FEAT_GUI_MOTIF)\n msg_puts(_(\"with X11-Motif GUI.\"));\n#elif defined(FEAT_GUI_HAIKU)\n msg_puts(_(\"with Haiku GUI.\"));\n#elif defined(FEAT_GUI_PHOTON)\n msg_puts(_(\"with Photon GUI.\"));\n#elif defined(MSWIN)\n msg_puts(_(\"with GUI.\"));\n#endif\n version_msg(_(\" Features included (+) or not (-):\\n\"));", " list_features();\n if (msg_col > 0)\n\tmsg_putchar('\\n');", "#ifdef SYS_VIMRC_FILE\n version_msg(_(\" system vimrc file: \\\"\"));\n version_msg(SYS_VIMRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE\n version_msg(_(\" user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE2\n version_msg(_(\" 2nd user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE2);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE3\n version_msg(_(\" 3rd user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE3);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_EXRC_FILE\n version_msg(_(\" user exrc file: \\\"\"));\n version_msg(USR_EXRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_EXRC_FILE2\n version_msg(_(\" 2nd user exrc file: \\\"\"));\n version_msg(USR_EXRC_FILE2);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef FEAT_GUI\n# ifdef SYS_GVIMRC_FILE\n version_msg(_(\" system gvimrc file: \\\"\"));\n version_msg(SYS_GVIMRC_FILE);\n version_msg(\"\\\"\\n\");\n# endif\n version_msg(_(\" user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE);\n version_msg(\"\\\"\\n\");\n# ifdef USR_GVIMRC_FILE2\n version_msg(_(\"2nd user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE2);\n version_msg(\"\\\"\\n\");\n# endif\n# ifdef USR_GVIMRC_FILE3\n version_msg(_(\"3rd user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE3);\n version_msg(\"\\\"\\n\");\n# endif\n#endif\n version_msg(_(\" defaults file: \\\"\"));\n version_msg(VIM_DEFAULTS_FILE);\n version_msg(\"\\\"\\n\");\n#ifdef FEAT_GUI\n# ifdef SYS_MENU_FILE\n version_msg(_(\" system menu file: \\\"\"));\n version_msg(SYS_MENU_FILE);\n version_msg(\"\\\"\\n\");\n# endif\n#endif\n#ifdef HAVE_PATHDEF\n if (*default_vim_dir != NUL)\n {\n\tversion_msg(_(\" fall-back for $VIM: \\\"\"));\n\tversion_msg((char *)default_vim_dir);\n\tversion_msg(\"\\\"\\n\");\n }\n if (*default_vimruntime_dir != NUL)\n {\n\tversion_msg(_(\" f-b for $VIMRUNTIME: \\\"\"));\n\tversion_msg((char *)default_vimruntime_dir);\n\tversion_msg(\"\\\"\\n\");\n }\n version_msg(_(\"Compilation: \"));\n version_msg((char *)all_cflags);\n version_msg(\"\\n\");\n#ifdef VMS\n if (*compiler_version != NUL)\n {\n\tversion_msg(_(\"Compiler: \"));\n\tversion_msg((char *)compiler_version);\n\tversion_msg(\"\\n\");\n }\n#endif\n version_msg(_(\"Linking: \"));\n version_msg((char *)all_lflags);\n#endif\n#ifdef DEBUG\n version_msg(\"\\n\");\n version_msg(_(\" DEBUG BUILD\"));\n#endif\n}", "static void do_intro_line(int row, char_u *mesg, int add_version, int attr);\nstatic void intro_message(int colon);", "/*\n * Show the intro message when not editing a file.\n */\n void\nmaybe_intro_message(void)\n{\n if (BUFEMPTY()\n\t && curbuf->b_fname == NULL\n\t && firstwin->w_next == NULL\n\t && vim_strchr(p_shm, SHM_INTRO) == NULL)\n\tintro_message(FALSE);\n}", "/*\n * Give an introductory message about Vim.\n * Only used when starting Vim on an empty file, without a file name.\n * Or with the \":intro\" command (for Sven :-).\n */\n static void\nintro_message(\n int\t\tcolon)\t\t// TRUE for \":intro\"\n{\n int\t\ti;\n int\t\trow;\n int\t\tblanklines;\n int\t\tsponsor;\n char\t*p;\n static char\t*(lines[]) =\n {\n\tN_(\"VIM - Vi IMproved\"),\n\t\"\",\n\tN_(\"version \"),\n\tN_(\"by Bram Moolenaar et al.\"),\n#ifdef MODIFIED_BY\n\t\" \",\n#endif\n\tN_(\"Vim is open source and freely distributable\"),\n\t\"\",\n\tN_(\"Help poor children in Uganda!\"),\n\tN_(\"type :help iccf<Enter> for information \"),\n\t\"\",\n\tN_(\"type :q<Enter> to exit \"),\n\tN_(\"type :help<Enter> or <F1> for on-line help\"),\n\tN_(\"type :help version9<Enter> for version info\"),\n\tNULL,\n\t\"\",\n\tN_(\"Running in Vi compatible mode\"),\n\tN_(\"type :set nocp<Enter> for Vim defaults\"),\n\tN_(\"type :help cp-default<Enter> for info on this\"),\n };\n#ifdef FEAT_GUI\n static char\t*(gui_lines[]) =\n {\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n#ifdef MODIFIED_BY\n\tNULL,\n#endif\n\tNULL,\n\tNULL,\n\tNULL,\n\tN_(\"menu Help->Orphans for information \"),\n\tNULL,\n\tN_(\"Running modeless, typed text is inserted\"),\n\tN_(\"menu Edit->Global Settings->Toggle Insert Mode \"),\n\tN_(\" for two modes \"),\n\tNULL,\n\tNULL,\n\tNULL,\n\tN_(\"menu Edit->Global Settings->Toggle Vi Compatible\"),\n\tN_(\" for Vim defaults \"),\n };\n#endif", " // blanklines = screen height - # message lines\n blanklines = (int)Rows - (ARRAY_LENGTH(lines) - 1);\n if (!p_cp)\n\tblanklines += 4; // add 4 for not showing \"Vi compatible\" message", " // Don't overwrite a statusline. Depends on 'cmdheight'.\n if (p_ls > 1)\n\tblanklines -= Rows - topframe->fr_height;\n if (blanklines < 0)\n\tblanklines = 0;", " // Show the sponsor and register message one out of four times, the Uganda\n // message two out of four times.\n sponsor = (int)time(NULL);\n sponsor = ((sponsor & 2) == 0) - ((sponsor & 4) == 0);", " // start displaying the message lines after half of the blank lines\n row = blanklines / 2;\n if ((row >= 2 && Columns >= 50) || colon)\n {\n\tfor (i = 0; i < (int)ARRAY_LENGTH(lines); ++i)\n\t{\n\t p = lines[i];\n#ifdef FEAT_GUI\n\t if (p_im && gui.in_use && gui_lines[i] != NULL)\n\t\tp = gui_lines[i];\n#endif\n\t if (p == NULL)\n\t {\n\t\tif (!p_cp)\n\t\t break;\n\t\tcontinue;\n\t }\n\t if (sponsor != 0)\n\t {\n\t\tif (strstr(p, \"children\") != NULL)\n\t\t p = sponsor < 0\n\t\t\t? N_(\"Sponsor Vim development!\")\n\t\t\t: N_(\"Become a registered Vim user!\");\n\t\telse if (strstr(p, \"iccf\") != NULL)\n\t\t p = sponsor < 0\n\t\t\t? N_(\"type :help sponsor<Enter> for information \")\n\t\t\t: N_(\"type :help register<Enter> for information \");\n\t\telse if (strstr(p, \"Orphans\") != NULL)\n\t\t p = N_(\"menu Help->Sponsor/Register for information \");\n\t }\n\t if (*p != NUL)\n\t\tdo_intro_line(row, (char_u *)_(p), i == 2, 0);\n\t ++row;\n\t}\n }", " // Make the wait-return message appear just below the text.\n if (colon)\n\tmsg_row = row;\n}", " static void\ndo_intro_line(\n int\t\trow,\n char_u\t*mesg,\n int\t\tadd_version,\n int\t\tattr)\n{\n char_u\tvers[20];\n int\t\tcol;\n char_u\t*p;\n int\t\tl;\n int\t\tclen;\n#ifdef MODIFIED_BY\n# define MODBY_LEN 150\n char_u\tmodby[MODBY_LEN];", " if (*mesg == ' ')\n {\n\tvim_strncpy(modby, (char_u *)_(\"Modified by \"), MODBY_LEN - 1);\n\tl = (int)STRLEN(modby);\n\tvim_strncpy(modby + l, (char_u *)MODIFIED_BY, MODBY_LEN - l - 1);\n\tmesg = modby;\n }\n#endif", " // Center the message horizontally.\n col = vim_strsize(mesg);\n if (add_version)\n {\n\tSTRCPY(vers, mediumVersion);\n\tif (highest_patch())\n\t{\n\t // Check for 9.9x or 9.9xx, alpha/beta version\n\t if (isalpha((int)vers[3]))\n\t {\n\t\tint len = (isalpha((int)vers[4])) ? 5 : 4;\n\t\tsprintf((char *)vers + len, \".%d%s\", highest_patch(),\n\t\t\t\t\t\t\t mediumVersion + len);\n\t }\n\t else\n\t\tsprintf((char *)vers + 3, \".%d\", highest_patch());\n\t}\n\tcol += (int)STRLEN(vers);\n }\n col = (Columns - col) / 2;\n if (col < 0)\n\tcol = 0;", " // Split up in parts to highlight <> items differently.\n for (p = mesg; *p != NUL; p += l)\n {\n\tclen = 0;\n\tfor (l = 0; p[l] != NUL\n\t\t\t && (l == 0 || (p[l] != '<' && p[l - 1] != '>')); ++l)\n\t{\n\t if (has_mbyte)\n\t {\n\t\tclen += ptr2cells(p + l);\n\t\tl += (*mb_ptr2len)(p + l) - 1;\n\t }\n\t else\n\t\tclen += byte2cells(p[l]);\n\t}\n\tscreen_puts_len(p, l, row, col, *p == '<' ? HL_ATTR(HLF_8) : attr);\n\tcol += clen;\n }", " // Add the version number to the version line.\n if (add_version)\n\tscreen_puts(vers, row, col, 0);\n}", "/*\n * \":intro\": clear screen, display intro screen and wait for return.\n */\n void\nex_intro(exarg_T *eap UNUSED)\n{\n screenclear();\n intro_message(TRUE);\n wait_return(TRUE);\n}" ]
[ 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [698, 2100, 737], "buggy_code_start_loc": [526, 2100, 737], "filenames": ["src/insexpand.c", "src/testdir/test_ins_complete.vim", "src/version.c"], "fixing_code_end_loc": [736, 2117, 740], "fixing_code_start_loc": [527, 2101, 738], "message": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0044.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "0069C36F-19A3-4647-B84F-84CE62E8A554", "versionEndExcluding": "9.0.0044", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:35:*:*:*:*:*:*:*", "matchCriteriaId": "80E516C0-98A4-4ADE-B69F-66A772E2BAAA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Heap-based Buffer Overflow in GitHub repository vim/vim prior to 9.0.0044."}, {"lang": "es", "value": "Un Desbordamiento de B\u00fafer en la Regi\u00f3n Heap de la Memoria en el repositorio de GitHub vim/vim versiones anteriores a 9.0.0044"}], "evaluatorComment": null, "id": "CVE-2022-2343", "lastModified": "2023-05-03T12:15:58.413", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-07-08T18:15:09.820", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/caea66442d86e7bbba3bf3dc202c3c0d549b9853"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/2ecb4345-2fc7-4e7f-adb0-83a20bb458f5"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/43Y3VJPOTTY3NTREDIFUPITM2POG4ZLP/"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/202208-32"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-122"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/caea66442d86e7bbba3bf3dc202c3c0d549b9853"}, "type": "CWE-122"}
172
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n* OpenPBS (Portable Batch System) v2.3 Software License\n*\n* Copyright (c) 1999-2000 Veridian Information Solutions, Inc.\n* All rights reserved.\n*\n* ---------------------------------------------------------------------------\n* For a license to use or redistribute the OpenPBS software under conditions\n* other than those described below, or to purchase support for this software,\n* please contact Veridian Systems, PBS Products Department (\"Licensor\") at:\n*\n* www.OpenPBS.org +1 650 967-4675 sales@OpenPBS.org\n* 877 902-4PBS (US toll-free)\n* ---------------------------------------------------------------------------\n*\n* This license covers use of the OpenPBS v2.3 software (the \"Software\") at\n* your site or location, and, for certain users, redistribution of the\n* Software to other sites and locations. Use and redistribution of\n* OpenPBS v2.3 in source and binary forms, with or without modification,\n* are permitted provided that all of the following conditions are met.\n* After December 31, 2001, only conditions 3-6 must be met:\n*\n* 1. Commercial and/or non-commercial use of the Software is permitted\n* provided a current software registration is on file at www.OpenPBS.org.\n* If use of this software contributes to a publication, product, or\n* service, proper attribution must be given; see www.OpenPBS.org/credit.html\n*\n* 2. Redistribution in any form is only permitted for non-commercial,\n* non-profit purposes. There can be no charge for the Software or any\n* software incorporating the Software. Further, there can be no\n* expectation of revenue generated as a consequence of redistributing\n* the Software.\n*\n* 3. Any Redistribution of source code must retain the above copyright notice\n* and the acknowledgment contained in paragraph 6, this list of conditions\n* and the disclaimer contained in paragraph 7.\n*\n* 4. Any Redistribution in binary form must reproduce the above copyright\n* notice and the acknowledgment contained in paragraph 6, this list of\n* conditions and the disclaimer contained in paragraph 7 in the\n* documentation and/or other materials provided with the distribution.\n*\n* 5. Redistributions in any form must be accompanied by information on how to\n* obtain complete source code for the OpenPBS software and any\n* modifications and/or additions to the OpenPBS software. The source code\n* must either be included in the distribution or be available for no more\n* than the cost of distribution plus a nominal fee, and all modifications\n* and additions to the Software must be freely redistributable by any party\n* (including Licensor) without restriction.\n*\n* 6. All advertising materials mentioning features or use of the Software must\n* display the following acknowledgment:\n*\n* \"This product includes software developed by NASA Ames Research Center,\n* Lawrence Livermore National Laboratory, and Veridian Information\n* Solutions, Inc.\n* Visit www.OpenPBS.org for OpenPBS software support,\n* products, and information.\"\n*\n* 7. DISCLAIMER OF WARRANTY\n*\n* THIS SOFTWARE IS PROVIDED \"AS IS\" WITHOUT WARRANTY OF ANY KIND. ANY EXPRESS\n* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT\n* ARE EXPRESSLY DISCLAIMED.\n*\n* IN NO EVENT SHALL VERIDIAN CORPORATION, ITS AFFILIATED COMPANIES, OR THE\n* U.S. GOVERNMENT OR ANY OF ITS AGENCIES BE LIABLE FOR ANY DIRECT OR INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\n* This license will be governed by the laws of the Commonwealth of Virginia,\n* without reference to its choice of law rules.\n*/\n#include <pbs_config.h> /* the master config generated by configure */", "#include <assert.h>\n#include <stddef.h>", "#include \"dis.h\"\n#include \"dis_.h\"", "", "\nint disrsi_(", " int stream,\n int *negate,\n unsigned *value,\n unsigned count)", " {\n int c;\n unsigned locval;\n unsigned ndigs;\n char *cp;\n char scratch[DIS_BUFSIZ+1];", " assert(negate != NULL);\n assert(value != NULL);\n assert(count);\n assert(stream >= 0);\n assert(dis_getc != NULL);\n assert(dis_gets != NULL);", " memset(scratch, 0, DIS_BUFSIZ+1);\n if (dis_umaxd == 0)\n disiui_();\n", "", " switch (c = (*dis_getc)(stream))\n {", " case '-':", " case '+':", " *negate = c == '-';", " if ((*dis_gets)(stream, scratch, count) != (int)count)\n {\n return(DIS_EOD);\n }", " if (count >= dis_umaxd)\n {\n if (count > dis_umaxd)\n goto overflow;", " if (memcmp(scratch, dis_umax, dis_umaxd) > 0)\n goto overflow;\n }", " cp = scratch;", " locval = 0;", " do\n {\n if (((c = *cp++) < '0') || (c > '9'))\n {\n return(DIS_NONDIGIT);\n }", " locval = 10 * locval + c - '0';\n }\n while (--count);", " *value = locval;", " return (DIS_SUCCESS);", " break;", " case '0':", " return (DIS_LEADZRO);", " break;", " case '1':", " case '2':", " case '3':", " case '4':", " case '5':", " case '6':", " case '7':", " case '8':", " case '9':", " ndigs = c - '0';", " if (count > 1)\n {\n if ((*dis_gets)(stream, scratch + 1, count - 1) != (int)count - 1)\n {\n return(DIS_EOD);\n }", " cp = scratch;", " if (count >= dis_umaxd)\n {\n if (count > dis_umaxd)\n break;", " *cp = c;", " if (memcmp(scratch, dis_umax, dis_umaxd) > 0)\n break;\n }", " while (--count)\n {\n if (((c = *++cp) < '0') || (c > '9'))\n {\n return(DIS_NONDIGIT);\n }", " ndigs = 10 * ndigs + c - '0';\n }\n } /* END if (count > 1) */", " return(disrsi_(stream, negate, value, ndigs));", " /*NOTREACHED*/", " break;", " case - 1:", " return(DIS_EOD);", " /*NOTREACHED*/", " break;", " case -2:", " return(DIS_EOF);", " /*NOTREACHED*/", " break;", " default:", " return(DIS_NONDIGIT);", " /*NOTREACHED*/", " break;\n }", " *negate = FALSE;", "overflow:", " *value = UINT_MAX;", " return(DIS_OVERFLOW);\n } /* END disrsi_() */" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 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, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [114], "buggy_code_start_loc": [114], "filenames": ["src/lib/Libdis/disrsi_.c"], "fixing_code_end_loc": [124], "fixing_code_start_loc": [115], "message": "Stack-based buffer overflow in lib/Libdis/disrsi_.c in Terascale Open-Source Resource and Queue Manager (aka TORQUE Resource Manager) 2.5.x through 2.5.13 allows remote attackers to execute arbitrary code via a large count value.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "682462F9-38E2-4631-8AE2-4ACC2BFDA336", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.1:*:*:*:*:*:*:*", "matchCriteriaId": "F484AC97-0A7C-42D7-8A8A-3F0EE951A7E1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.2:*:*:*:*:*:*:*", "matchCriteriaId": "F929EC66-9E7B-4D8D-AA36-DAE4DF96C01F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "40E5D70B-0965-4794-BD25-42F7C189AD0B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.4:*:*:*:*:*:*:*", "matchCriteriaId": "E3287BE3-DF6B-4C81-9065-50BF91B37664", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.5:*:*:*:*:*:*:*", "matchCriteriaId": "78083338-09F7-4C94-AF55-4998640A5ABE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.6:*:*:*:*:*:*:*", "matchCriteriaId": "A7010B77-6FD0-4A51-81BA-19DA1F2D4881", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.7:*:*:*:*:*:*:*", "matchCriteriaId": "4CA855F9-CAA9-4B65-AAEE-5AA36F8F9538", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.8:*:*:*:*:*:*:*", "matchCriteriaId": "CCBEBC0F-4AE4-4D94-B1E5-503FE2039D43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.9:*:*:*:*:*:*:*", "matchCriteriaId": "1C896A54-9557-4B24-8542-98C025D34B07", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.10:*:*:*:*:*:*:*", "matchCriteriaId": "257109FC-7E26-4EBB-9059-58D418EA4A6D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.11:*:*:*:*:*:*:*", "matchCriteriaId": "956F57CD-314F-41DC-B76D-CC847C3F12DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.12:*:*:*:*:*:*:*", "matchCriteriaId": "CE18F486-1C07-4388-B8E6-A942143A18FC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.13:*:*:*:*:*:*:*", "matchCriteriaId": "E157EA4C-051A-4195-886B-016BC1616A46", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Stack-based buffer overflow in lib/Libdis/disrsi_.c in Terascale Open-Source Resource and Queue Manager (aka TORQUE Resource Manager) 2.5.x through 2.5.13 allows remote attackers to execute arbitrary code via a large count value."}, {"lang": "es", "value": "Desbordamiento de buffer basado en pila en lib/Libdis/disrsi_.c en Terascale Open-Source Resource And Queue Manager (tambi\u00e9n conocido como TORQUE Resource Manager) 2.5.x hasta 2.5.13 permite a atacantes remotos ejecutar c\u00f3digo arbitrario a trav\u00e9s de un valor de contador grande."}], "evaluatorComment": null, "id": "CVE-2014-0749", "lastModified": "2018-10-09T19:42:05.327", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-05-16T14:55:05.547", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://packetstormsecurity.com/files/126651/Torque-2.5.13-Buffer-Overflow.html"}, {"source": "cve@mitre.org", "tags": null, "url": "http://packetstormsecurity.com/files/126855/TORQUE-Resource-Manager-2.5.13-Buffer-Overflow.html"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.debian.org/security/2014/dsa-2936"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.exploit-db.com/exploits/33554"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/archive/1/532110/100/0/threaded"}, {"source": "cve@mitre.org", "tags": ["Exploit"], "url": "http://www.securityfocus.com/bid/67420"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/adaptivecomputing/torque/commit/3ed749263abe3d69fa3626d142a5789dcb5a5684"}, {"source": "cve@mitre.org", "tags": null, "url": "https://github.com/adaptivecomputing/torque/pull/171"}, {"source": "cve@mitre.org", "tags": null, "url": "https://labs.mwrinfosecurity.com/advisories/2014/05/14/torque-buffer-overflow"}, {"source": "cve@mitre.org", "tags": ["Exploit"], "url": "https://labs.mwrinfosecurity.com/system/assets/662/original/torque-buffer-overflow_2014-05-14.pdf"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-119"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/adaptivecomputing/torque/commit/3ed749263abe3d69fa3626d142a5789dcb5a5684"}, "type": "CWE-119"}
173
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n* OpenPBS (Portable Batch System) v2.3 Software License\n*\n* Copyright (c) 1999-2000 Veridian Information Solutions, Inc.\n* All rights reserved.\n*\n* ---------------------------------------------------------------------------\n* For a license to use or redistribute the OpenPBS software under conditions\n* other than those described below, or to purchase support for this software,\n* please contact Veridian Systems, PBS Products Department (\"Licensor\") at:\n*\n* www.OpenPBS.org +1 650 967-4675 sales@OpenPBS.org\n* 877 902-4PBS (US toll-free)\n* ---------------------------------------------------------------------------\n*\n* This license covers use of the OpenPBS v2.3 software (the \"Software\") at\n* your site or location, and, for certain users, redistribution of the\n* Software to other sites and locations. Use and redistribution of\n* OpenPBS v2.3 in source and binary forms, with or without modification,\n* are permitted provided that all of the following conditions are met.\n* After December 31, 2001, only conditions 3-6 must be met:\n*\n* 1. Commercial and/or non-commercial use of the Software is permitted\n* provided a current software registration is on file at www.OpenPBS.org.\n* If use of this software contributes to a publication, product, or\n* service, proper attribution must be given; see www.OpenPBS.org/credit.html\n*\n* 2. Redistribution in any form is only permitted for non-commercial,\n* non-profit purposes. There can be no charge for the Software or any\n* software incorporating the Software. Further, there can be no\n* expectation of revenue generated as a consequence of redistributing\n* the Software.\n*\n* 3. Any Redistribution of source code must retain the above copyright notice\n* and the acknowledgment contained in paragraph 6, this list of conditions\n* and the disclaimer contained in paragraph 7.\n*\n* 4. Any Redistribution in binary form must reproduce the above copyright\n* notice and the acknowledgment contained in paragraph 6, this list of\n* conditions and the disclaimer contained in paragraph 7 in the\n* documentation and/or other materials provided with the distribution.\n*\n* 5. Redistributions in any form must be accompanied by information on how to\n* obtain complete source code for the OpenPBS software and any\n* modifications and/or additions to the OpenPBS software. The source code\n* must either be included in the distribution or be available for no more\n* than the cost of distribution plus a nominal fee, and all modifications\n* and additions to the Software must be freely redistributable by any party\n* (including Licensor) without restriction.\n*\n* 6. All advertising materials mentioning features or use of the Software must\n* display the following acknowledgment:\n*\n* \"This product includes software developed by NASA Ames Research Center,\n* Lawrence Livermore National Laboratory, and Veridian Information\n* Solutions, Inc.\n* Visit www.OpenPBS.org for OpenPBS software support,\n* products, and information.\"\n*\n* 7. DISCLAIMER OF WARRANTY\n*\n* THIS SOFTWARE IS PROVIDED \"AS IS\" WITHOUT WARRANTY OF ANY KIND. ANY EXPRESS\n* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT\n* ARE EXPRESSLY DISCLAIMED.\n*\n* IN NO EVENT SHALL VERIDIAN CORPORATION, ITS AFFILIATED COMPANIES, OR THE\n* U.S. GOVERNMENT OR ANY OF ITS AGENCIES BE LIABLE FOR ANY DIRECT OR INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\n* This license will be governed by the laws of the Commonwealth of Virginia,\n* without reference to its choice of law rules.\n*/\n#include <pbs_config.h> /* the master config generated by configure */", "#include <assert.h>\n#include <stddef.h>", "#include \"dis.h\"\n#include \"dis_.h\"", "", "\nint disrsi_(", " int stream,\n int *negate,\n unsigned *value,\n unsigned count)", " {\n int c;\n unsigned locval;\n unsigned ndigs;\n char *cp;\n char scratch[DIS_BUFSIZ+1];", " assert(negate != NULL);\n assert(value != NULL);\n assert(count);\n assert(stream >= 0);\n assert(dis_getc != NULL);\n assert(dis_gets != NULL);", " memset(scratch, 0, DIS_BUFSIZ+1);\n if (dis_umaxd == 0)\n disiui_();\n", " if (count >= dis_umaxd)\n {\n if (count > dis_umaxd)\n goto overflow;", " if (memcmp(scratch, dis_umax, dis_umaxd) > 0)\n goto overflow;\n }\n", " switch (c = (*dis_getc)(stream))\n {", " case '-':", " case '+':", " *negate = c == '-';", " if ((*dis_gets)(stream, scratch, count) != (int)count)\n {\n return(DIS_EOD);\n }", " if (count >= dis_umaxd)\n {\n if (count > dis_umaxd)\n goto overflow;", " if (memcmp(scratch, dis_umax, dis_umaxd) > 0)\n goto overflow;\n }", " cp = scratch;", " locval = 0;", " do\n {\n if (((c = *cp++) < '0') || (c > '9'))\n {\n return(DIS_NONDIGIT);\n }", " locval = 10 * locval + c - '0';\n }\n while (--count);", " *value = locval;", " return (DIS_SUCCESS);", " break;", " case '0':", " return (DIS_LEADZRO);", " break;", " case '1':", " case '2':", " case '3':", " case '4':", " case '5':", " case '6':", " case '7':", " case '8':", " case '9':", " ndigs = c - '0';", " if (count > 1)\n {\n if ((*dis_gets)(stream, scratch + 1, count - 1) != (int)count - 1)\n {\n return(DIS_EOD);\n }", " cp = scratch;", " if (count >= dis_umaxd)\n {\n if (count > dis_umaxd)\n break;", " *cp = c;", " if (memcmp(scratch, dis_umax, dis_umaxd) > 0)\n break;\n }", " while (--count)\n {\n if (((c = *++cp) < '0') || (c > '9'))\n {\n return(DIS_NONDIGIT);\n }", " ndigs = 10 * ndigs + c - '0';\n }\n } /* END if (count > 1) */", " return(disrsi_(stream, negate, value, ndigs));", " /*NOTREACHED*/", " break;", " case - 1:", " return(DIS_EOD);", " /*NOTREACHED*/", " break;", " case -2:", " return(DIS_EOF);", " /*NOTREACHED*/", " break;", " default:", " return(DIS_NONDIGIT);", " /*NOTREACHED*/", " break;\n }", " *negate = FALSE;", "overflow:", " *value = UINT_MAX;", " return(DIS_OVERFLOW);\n } /* END disrsi_() */" ]
[ 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [114], "buggy_code_start_loc": [114], "filenames": ["src/lib/Libdis/disrsi_.c"], "fixing_code_end_loc": [124], "fixing_code_start_loc": [115], "message": "Stack-based buffer overflow in lib/Libdis/disrsi_.c in Terascale Open-Source Resource and Queue Manager (aka TORQUE Resource Manager) 2.5.x through 2.5.13 allows remote attackers to execute arbitrary code via a large count value.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "682462F9-38E2-4631-8AE2-4ACC2BFDA336", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.1:*:*:*:*:*:*:*", "matchCriteriaId": "F484AC97-0A7C-42D7-8A8A-3F0EE951A7E1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.2:*:*:*:*:*:*:*", "matchCriteriaId": "F929EC66-9E7B-4D8D-AA36-DAE4DF96C01F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "40E5D70B-0965-4794-BD25-42F7C189AD0B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.4:*:*:*:*:*:*:*", "matchCriteriaId": "E3287BE3-DF6B-4C81-9065-50BF91B37664", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.5:*:*:*:*:*:*:*", "matchCriteriaId": "78083338-09F7-4C94-AF55-4998640A5ABE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.6:*:*:*:*:*:*:*", "matchCriteriaId": "A7010B77-6FD0-4A51-81BA-19DA1F2D4881", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.7:*:*:*:*:*:*:*", "matchCriteriaId": "4CA855F9-CAA9-4B65-AAEE-5AA36F8F9538", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.8:*:*:*:*:*:*:*", "matchCriteriaId": "CCBEBC0F-4AE4-4D94-B1E5-503FE2039D43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.9:*:*:*:*:*:*:*", "matchCriteriaId": "1C896A54-9557-4B24-8542-98C025D34B07", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.10:*:*:*:*:*:*:*", "matchCriteriaId": "257109FC-7E26-4EBB-9059-58D418EA4A6D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.11:*:*:*:*:*:*:*", "matchCriteriaId": "956F57CD-314F-41DC-B76D-CC847C3F12DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.12:*:*:*:*:*:*:*", "matchCriteriaId": "CE18F486-1C07-4388-B8E6-A942143A18FC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:adaptivecomputing:torque_resource_manager:2.5.13:*:*:*:*:*:*:*", "matchCriteriaId": "E157EA4C-051A-4195-886B-016BC1616A46", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Stack-based buffer overflow in lib/Libdis/disrsi_.c in Terascale Open-Source Resource and Queue Manager (aka TORQUE Resource Manager) 2.5.x through 2.5.13 allows remote attackers to execute arbitrary code via a large count value."}, {"lang": "es", "value": "Desbordamiento de buffer basado en pila en lib/Libdis/disrsi_.c en Terascale Open-Source Resource And Queue Manager (tambi\u00e9n conocido como TORQUE Resource Manager) 2.5.x hasta 2.5.13 permite a atacantes remotos ejecutar c\u00f3digo arbitrario a trav\u00e9s de un valor de contador grande."}], "evaluatorComment": null, "id": "CVE-2014-0749", "lastModified": "2018-10-09T19:42:05.327", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-05-16T14:55:05.547", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://packetstormsecurity.com/files/126651/Torque-2.5.13-Buffer-Overflow.html"}, {"source": "cve@mitre.org", "tags": null, "url": "http://packetstormsecurity.com/files/126855/TORQUE-Resource-Manager-2.5.13-Buffer-Overflow.html"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.debian.org/security/2014/dsa-2936"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.exploit-db.com/exploits/33554"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/archive/1/532110/100/0/threaded"}, {"source": "cve@mitre.org", "tags": ["Exploit"], "url": "http://www.securityfocus.com/bid/67420"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/adaptivecomputing/torque/commit/3ed749263abe3d69fa3626d142a5789dcb5a5684"}, {"source": "cve@mitre.org", "tags": null, "url": "https://github.com/adaptivecomputing/torque/pull/171"}, {"source": "cve@mitre.org", "tags": null, "url": "https://labs.mwrinfosecurity.com/advisories/2014/05/14/torque-buffer-overflow"}, {"source": "cve@mitre.org", "tags": ["Exploit"], "url": "https://labs.mwrinfosecurity.com/system/assets/662/original/torque-buffer-overflow_2014-05-14.pdf"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-119"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/adaptivecomputing/torque/commit/3ed749263abe3d69fa3626d142a5789dcb5a5684"}, "type": "CWE-119"}
173
Determine whether the {function_name} code is vulnerable or not.
[ "/* Locale-independent implementations of string <-> double conversions. */", "#include \"jsi.h\"", "#if defined(_MSC_VER) && (_MSC_VER < 1700) /* VS2012 has stdint.h */\ntypedef unsigned int uint32_t;\ntypedef unsigned __int64 uint64_t;\n#else\n#include <stdint.h>\n#endif", "#include <errno.h>\n#include <assert.h>", "#ifndef TRUE\n#define TRUE 1\n#define FALSE 0\n#endif", "/*\n * format exponent like sprintf(p, \"e%+d\", e)\n */\nvoid\njs_fmtexp(char *p, int e)\n{\n\tchar se[9];\n\tint i;", "\t*p++ = 'e';\n\tif(e < 0) {\n\t\t*p++ = '-';\n\t\te = -e;\n\t} else\n\t\t*p++ = '+';\n\ti = 0;\n\twhile(e) {\n\t\tse[i++] = e % 10 + '0';\n\t\te /= 10;\n\t}\n\twhile(i < 1)\n\t\tse[i++] = '0';\n\twhile(i > 0)\n\t\t*p++ = se[--i];\n\t*p++ = '\\0';\n}", "/*\n * grisu2_59_56.c\n *\n * Grisu prints the optimal decimal representation of floating-point numbers.\n *\n * Copyright (c) 2009 Florian Loitsch\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */", "typedef struct diy_fp_t {\n\tuint64_t f;\n\tint e;\n} diy_fp_t;", "#define DIY_SIGNIFICAND_SIZE 64\n#define D_1_LOG2_10 0.30102999566398114 /* 1 / lg(10) */", "static const uint64_t powers_ten[] = {\n\t0xbf29dcaba82fdeae, 0xeef453d6923bd65a, 0x9558b4661b6565f8,\n\t0xbaaee17fa23ebf76, 0xe95a99df8ace6f54, 0x91d8a02bb6c10594,\n\t0xb64ec836a47146fa, 0xe3e27a444d8d98b8, 0x8e6d8c6ab0787f73,\n\t0xb208ef855c969f50, 0xde8b2b66b3bc4724, 0x8b16fb203055ac76,\n\t0xaddcb9e83c6b1794, 0xd953e8624b85dd79, 0x87d4713d6f33aa6c,\n\t0xa9c98d8ccb009506, 0xd43bf0effdc0ba48, 0x84a57695fe98746d,\n\t0xa5ced43b7e3e9188, 0xcf42894a5dce35ea, 0x818995ce7aa0e1b2,\n\t0xa1ebfb4219491a1f, 0xca66fa129f9b60a7, 0xfd00b897478238d1,\n\t0x9e20735e8cb16382, 0xc5a890362fddbc63, 0xf712b443bbd52b7c,\n\t0x9a6bb0aa55653b2d, 0xc1069cd4eabe89f9, 0xf148440a256e2c77,\n\t0x96cd2a865764dbca, 0xbc807527ed3e12bd, 0xeba09271e88d976c,\n\t0x93445b8731587ea3, 0xb8157268fdae9e4c, 0xe61acf033d1a45df,\n\t0x8fd0c16206306bac, 0xb3c4f1ba87bc8697, 0xe0b62e2929aba83c,\n\t0x8c71dcd9ba0b4926, 0xaf8e5410288e1b6f, 0xdb71e91432b1a24b,\n\t0x892731ac9faf056f, 0xab70fe17c79ac6ca, 0xd64d3d9db981787d,\n\t0x85f0468293f0eb4e, 0xa76c582338ed2622, 0xd1476e2c07286faa,\n\t0x82cca4db847945ca, 0xa37fce126597973d, 0xcc5fc196fefd7d0c,\n\t0xff77b1fcbebcdc4f, 0x9faacf3df73609b1, 0xc795830d75038c1e,\n\t0xf97ae3d0d2446f25, 0x9becce62836ac577, 0xc2e801fb244576d5,\n\t0xf3a20279ed56d48a, 0x9845418c345644d7, 0xbe5691ef416bd60c,\n\t0xedec366b11c6cb8f, 0x94b3a202eb1c3f39, 0xb9e08a83a5e34f08,\n\t0xe858ad248f5c22ca, 0x91376c36d99995be, 0xb58547448ffffb2e,\n\t0xe2e69915b3fff9f9, 0x8dd01fad907ffc3c, 0xb1442798f49ffb4b,\n\t0xdd95317f31c7fa1d, 0x8a7d3eef7f1cfc52, 0xad1c8eab5ee43b67,\n\t0xd863b256369d4a41, 0x873e4f75e2224e68, 0xa90de3535aaae202,\n\t0xd3515c2831559a83, 0x8412d9991ed58092, 0xa5178fff668ae0b6,\n\t0xce5d73ff402d98e4, 0x80fa687f881c7f8e, 0xa139029f6a239f72,\n\t0xc987434744ac874f, 0xfbe9141915d7a922, 0x9d71ac8fada6c9b5,\n\t0xc4ce17b399107c23, 0xf6019da07f549b2b, 0x99c102844f94e0fb,\n\t0xc0314325637a193a, 0xf03d93eebc589f88, 0x96267c7535b763b5,\n\t0xbbb01b9283253ca3, 0xea9c227723ee8bcb, 0x92a1958a7675175f,\n\t0xb749faed14125d37, 0xe51c79a85916f485, 0x8f31cc0937ae58d3,\n\t0xb2fe3f0b8599ef08, 0xdfbdcece67006ac9, 0x8bd6a141006042be,\n\t0xaecc49914078536d, 0xda7f5bf590966849, 0x888f99797a5e012d,\n\t0xaab37fd7d8f58179, 0xd5605fcdcf32e1d7, 0x855c3be0a17fcd26,\n\t0xa6b34ad8c9dfc070, 0xd0601d8efc57b08c, 0x823c12795db6ce57,\n\t0xa2cb1717b52481ed, 0xcb7ddcdda26da269, 0xfe5d54150b090b03,\n\t0x9efa548d26e5a6e2, 0xc6b8e9b0709f109a, 0xf867241c8cc6d4c1,\n\t0x9b407691d7fc44f8, 0xc21094364dfb5637, 0xf294b943e17a2bc4,\n\t0x979cf3ca6cec5b5b, 0xbd8430bd08277231, 0xece53cec4a314ebe,\n\t0x940f4613ae5ed137, 0xb913179899f68584, 0xe757dd7ec07426e5,\n\t0x9096ea6f3848984f, 0xb4bca50b065abe63, 0xe1ebce4dc7f16dfc,\n\t0x8d3360f09cf6e4bd, 0xb080392cc4349ded, 0xdca04777f541c568,\n\t0x89e42caaf9491b61, 0xac5d37d5b79b6239, 0xd77485cb25823ac7,\n\t0x86a8d39ef77164bd, 0xa8530886b54dbdec, 0xd267caa862a12d67,\n\t0x8380dea93da4bc60, 0xa46116538d0deb78, 0xcd795be870516656,\n\t0x806bd9714632dff6, 0xa086cfcd97bf97f4, 0xc8a883c0fdaf7df0,\n\t0xfad2a4b13d1b5d6c, 0x9cc3a6eec6311a64, 0xc3f490aa77bd60fd,\n\t0xf4f1b4d515acb93c, 0x991711052d8bf3c5, 0xbf5cd54678eef0b7,\n\t0xef340a98172aace5, 0x9580869f0e7aac0f, 0xbae0a846d2195713,\n\t0xe998d258869facd7, 0x91ff83775423cc06, 0xb67f6455292cbf08,\n\t0xe41f3d6a7377eeca, 0x8e938662882af53e, 0xb23867fb2a35b28e,\n\t0xdec681f9f4c31f31, 0x8b3c113c38f9f37f, 0xae0b158b4738705f,\n\t0xd98ddaee19068c76, 0x87f8a8d4cfa417ca, 0xa9f6d30a038d1dbc,\n\t0xd47487cc8470652b, 0x84c8d4dfd2c63f3b, 0xa5fb0a17c777cf0a,\n\t0xcf79cc9db955c2cc, 0x81ac1fe293d599c0, 0xa21727db38cb0030,\n\t0xca9cf1d206fdc03c, 0xfd442e4688bd304b, 0x9e4a9cec15763e2f,\n\t0xc5dd44271ad3cdba, 0xf7549530e188c129, 0x9a94dd3e8cf578ba,\n\t0xc13a148e3032d6e8, 0xf18899b1bc3f8ca2, 0x96f5600f15a7b7e5,\n\t0xbcb2b812db11a5de, 0xebdf661791d60f56, 0x936b9fcebb25c996,\n\t0xb84687c269ef3bfb, 0xe65829b3046b0afa, 0x8ff71a0fe2c2e6dc,\n\t0xb3f4e093db73a093, 0xe0f218b8d25088b8, 0x8c974f7383725573,\n\t0xafbd2350644eead0, 0xdbac6c247d62a584, 0x894bc396ce5da772,\n\t0xab9eb47c81f5114f, 0xd686619ba27255a3, 0x8613fd0145877586,\n\t0xa798fc4196e952e7, 0xd17f3b51fca3a7a1, 0x82ef85133de648c5,\n\t0xa3ab66580d5fdaf6, 0xcc963fee10b7d1b3, 0xffbbcfe994e5c620,\n\t0x9fd561f1fd0f9bd4, 0xc7caba6e7c5382c9, 0xf9bd690a1b68637b,\n\t0x9c1661a651213e2d, 0xc31bfa0fe5698db8, 0xf3e2f893dec3f126,\n\t0x986ddb5c6b3a76b8, 0xbe89523386091466, 0xee2ba6c0678b597f,\n\t0x94db483840b717f0, 0xba121a4650e4ddec, 0xe896a0d7e51e1566,\n\t0x915e2486ef32cd60, 0xb5b5ada8aaff80b8, 0xe3231912d5bf60e6,\n\t0x8df5efabc5979c90, 0xb1736b96b6fd83b4, 0xddd0467c64bce4a1,\n\t0x8aa22c0dbef60ee4, 0xad4ab7112eb3929e, 0xd89d64d57a607745,\n\t0x87625f056c7c4a8b, 0xa93af6c6c79b5d2e, 0xd389b47879823479,\n\t0x843610cb4bf160cc, 0xa54394fe1eedb8ff, 0xce947a3da6a9273e,\n\t0x811ccc668829b887, 0xa163ff802a3426a9, 0xc9bcff6034c13053,\n\t0xfc2c3f3841f17c68, 0x9d9ba7832936edc1, 0xc5029163f384a931,\n\t0xf64335bcf065d37d, 0x99ea0196163fa42e, 0xc06481fb9bcf8d3a,\n\t0xf07da27a82c37088, 0x964e858c91ba2655, 0xbbe226efb628afeb,\n\t0xeadab0aba3b2dbe5, 0x92c8ae6b464fc96f, 0xb77ada0617e3bbcb,\n\t0xe55990879ddcaabe, 0x8f57fa54c2a9eab7, 0xb32df8e9f3546564,\n\t0xdff9772470297ebd, 0x8bfbea76c619ef36, 0xaefae51477a06b04,\n\t0xdab99e59958885c5, 0x88b402f7fd75539b, 0xaae103b5fcd2a882,\n\t0xd59944a37c0752a2, 0x857fcae62d8493a5, 0xa6dfbd9fb8e5b88f,\n\t0xd097ad07a71f26b2, 0x825ecc24c8737830, 0xa2f67f2dfa90563b,\n\t0xcbb41ef979346bca, 0xfea126b7d78186bd, 0x9f24b832e6b0f436,\n\t0xc6ede63fa05d3144, 0xf8a95fcf88747d94, 0x9b69dbe1b548ce7d,\n\t0xc24452da229b021c, 0xf2d56790ab41c2a3, 0x97c560ba6b0919a6,\n\t0xbdb6b8e905cb600f, 0xed246723473e3813, 0x9436c0760c86e30c,\n\t0xb94470938fa89bcf, 0xe7958cb87392c2c3, 0x90bd77f3483bb9ba,\n\t0xb4ecd5f01a4aa828, 0xe2280b6c20dd5232, 0x8d590723948a535f,\n\t0xb0af48ec79ace837, 0xdcdb1b2798182245, 0x8a08f0f8bf0f156b,\n\t0xac8b2d36eed2dac6, 0xd7adf884aa879177, 0x86ccbb52ea94baeb,\n\t0xa87fea27a539e9a5, 0xd29fe4b18e88640f, 0x83a3eeeef9153e89,\n\t0xa48ceaaab75a8e2b, 0xcdb02555653131b6, 0x808e17555f3ebf12,\n\t0xa0b19d2ab70e6ed6, 0xc8de047564d20a8c, 0xfb158592be068d2f,\n\t0x9ced737bb6c4183d, 0xc428d05aa4751e4d, 0xf53304714d9265e0,\n\t0x993fe2c6d07b7fac, 0xbf8fdb78849a5f97, 0xef73d256a5c0f77d,\n\t0x95a8637627989aae, 0xbb127c53b17ec159, 0xe9d71b689dde71b0,\n\t0x9226712162ab070e, 0xb6b00d69bb55c8d1, 0xe45c10c42a2b3b06,\n\t0x8eb98a7a9a5b04e3, 0xb267ed1940f1c61c, 0xdf01e85f912e37a3,\n\t0x8b61313bbabce2c6, 0xae397d8aa96c1b78, 0xd9c7dced53c72256,\n\t0x881cea14545c7575, 0xaa242499697392d3, 0xd4ad2dbfc3d07788,\n\t0x84ec3c97da624ab5, 0xa6274bbdd0fadd62, 0xcfb11ead453994ba,\n\t0x81ceb32c4b43fcf5, 0xa2425ff75e14fc32, 0xcad2f7f5359a3b3e,\n\t0xfd87b5f28300ca0e, 0x9e74d1b791e07e48, 0xc612062576589ddb,\n\t0xf79687aed3eec551, 0x9abe14cd44753b53, 0xc16d9a0095928a27,\n\t0xf1c90080baf72cb1, 0x971da05074da7bef, 0xbce5086492111aeb,\n\t0xec1e4a7db69561a5, 0x9392ee8e921d5d07, 0xb877aa3236a4b449,\n\t0xe69594bec44de15b, 0x901d7cf73ab0acd9, 0xb424dc35095cd80f,\n\t0xe12e13424bb40e13, 0x8cbccc096f5088cc, 0xafebff0bcb24aaff,\n\t0xdbe6fecebdedd5bf, 0x89705f4136b4a597, 0xabcc77118461cefd,\n\t0xd6bf94d5e57a42bc, 0x8637bd05af6c69b6, 0xa7c5ac471b478423,\n\t0xd1b71758e219652c, 0x83126e978d4fdf3b, 0xa3d70a3d70a3d70a,\n\t0xcccccccccccccccd, 0x8000000000000000, 0xa000000000000000,\n\t0xc800000000000000, 0xfa00000000000000, 0x9c40000000000000,\n\t0xc350000000000000, 0xf424000000000000, 0x9896800000000000,\n\t0xbebc200000000000, 0xee6b280000000000, 0x9502f90000000000,\n\t0xba43b74000000000, 0xe8d4a51000000000, 0x9184e72a00000000,\n\t0xb5e620f480000000, 0xe35fa931a0000000, 0x8e1bc9bf04000000,\n\t0xb1a2bc2ec5000000, 0xde0b6b3a76400000, 0x8ac7230489e80000,\n\t0xad78ebc5ac620000, 0xd8d726b7177a8000, 0x878678326eac9000,\n\t0xa968163f0a57b400, 0xd3c21bcecceda100, 0x84595161401484a0,\n\t0xa56fa5b99019a5c8, 0xcecb8f27f4200f3a, 0x813f3978f8940984,\n\t0xa18f07d736b90be5, 0xc9f2c9cd04674edf, 0xfc6f7c4045812296,\n\t0x9dc5ada82b70b59e, 0xc5371912364ce305, 0xf684df56c3e01bc7,\n\t0x9a130b963a6c115c, 0xc097ce7bc90715b3, 0xf0bdc21abb48db20,\n\t0x96769950b50d88f4, 0xbc143fa4e250eb31, 0xeb194f8e1ae525fd,\n\t0x92efd1b8d0cf37be, 0xb7abc627050305ae, 0xe596b7b0c643c719,\n\t0x8f7e32ce7bea5c70, 0xb35dbf821ae4f38c, 0xe0352f62a19e306f,\n\t0x8c213d9da502de45, 0xaf298d050e4395d7, 0xdaf3f04651d47b4c,\n\t0x88d8762bf324cd10, 0xab0e93b6efee0054, 0xd5d238a4abe98068,\n\t0x85a36366eb71f041, 0xa70c3c40a64e6c52, 0xd0cf4b50cfe20766,\n\t0x82818f1281ed44a0, 0xa321f2d7226895c8, 0xcbea6f8ceb02bb3a,\n\t0xfee50b7025c36a08, 0x9f4f2726179a2245, 0xc722f0ef9d80aad6,\n\t0xf8ebad2b84e0d58c, 0x9b934c3b330c8577, 0xc2781f49ffcfa6d5,\n\t0xf316271c7fc3908b, 0x97edd871cfda3a57, 0xbde94e8e43d0c8ec,\n\t0xed63a231d4c4fb27, 0x945e455f24fb1cf9, 0xb975d6b6ee39e437,\n\t0xe7d34c64a9c85d44, 0x90e40fbeea1d3a4b, 0xb51d13aea4a488dd,\n\t0xe264589a4dcdab15, 0x8d7eb76070a08aed, 0xb0de65388cc8ada8,\n\t0xdd15fe86affad912, 0x8a2dbf142dfcc7ab, 0xacb92ed9397bf996,\n\t0xd7e77a8f87daf7fc, 0x86f0ac99b4e8dafd, 0xa8acd7c0222311bd,\n\t0xd2d80db02aabd62c, 0x83c7088e1aab65db, 0xa4b8cab1a1563f52,\n\t0xcde6fd5e09abcf27, 0x80b05e5ac60b6178, 0xa0dc75f1778e39d6,\n\t0xc913936dd571c84c, 0xfb5878494ace3a5f, 0x9d174b2dcec0e47b,\n\t0xc45d1df942711d9a, 0xf5746577930d6501, 0x9968bf6abbe85f20,\n\t0xbfc2ef456ae276e9, 0xefb3ab16c59b14a3, 0x95d04aee3b80ece6,\n\t0xbb445da9ca61281f, 0xea1575143cf97227, 0x924d692ca61be758,\n\t0xb6e0c377cfa2e12e, 0xe498f455c38b997a, 0x8edf98b59a373fec,\n\t0xb2977ee300c50fe7, 0xdf3d5e9bc0f653e1, 0x8b865b215899f46d,\n\t0xae67f1e9aec07188, 0xda01ee641a708dea, 0x884134fe908658b2,\n\t0xaa51823e34a7eedf, 0xd4e5e2cdc1d1ea96, 0x850fadc09923329e,\n\t0xa6539930bf6bff46, 0xcfe87f7cef46ff17, 0x81f14fae158c5f6e,\n\t0xa26da3999aef774a, 0xcb090c8001ab551c, 0xfdcb4fa002162a63,\n\t0x9e9f11c4014dda7e, 0xc646d63501a1511e, 0xf7d88bc24209a565,\n\t0x9ae757596946075f, 0xc1a12d2fc3978937, 0xf209787bb47d6b85,\n\t0x9745eb4d50ce6333, 0xbd176620a501fc00, 0xec5d3fa8ce427b00,\n\t0x93ba47c980e98ce0, 0xb8a8d9bbe123f018, 0xe6d3102ad96cec1e,\n\t0x9043ea1ac7e41393, 0xb454e4a179dd1877, 0xe16a1dc9d8545e95,\n\t0x8ce2529e2734bb1d, 0xb01ae745b101e9e4, 0xdc21a1171d42645d,\n\t0x899504ae72497eba, 0xabfa45da0edbde69, 0xd6f8d7509292d603,\n\t0x865b86925b9bc5c2, 0xa7f26836f282b733, 0xd1ef0244af2364ff,\n\t0x8335616aed761f1f, 0xa402b9c5a8d3a6e7, 0xcd036837130890a1,\n\t0x802221226be55a65, 0xa02aa96b06deb0fe, 0xc83553c5c8965d3d,\n\t0xfa42a8b73abbf48d, 0x9c69a97284b578d8, 0xc38413cf25e2d70e,\n\t0xf46518c2ef5b8cd1, 0x98bf2f79d5993803, 0xbeeefb584aff8604,\n\t0xeeaaba2e5dbf6785, 0x952ab45cfa97a0b3, 0xba756174393d88e0,\n\t0xe912b9d1478ceb17, 0x91abb422ccb812ef, 0xb616a12b7fe617aa,\n\t0xe39c49765fdf9d95, 0x8e41ade9fbebc27d, 0xb1d219647ae6b31c,\n\t0xde469fbd99a05fe3, 0x8aec23d680043bee, 0xada72ccc20054aea,\n\t0xd910f7ff28069da4, 0x87aa9aff79042287, 0xa99541bf57452b28,\n\t0xd3fa922f2d1675f2, 0x847c9b5d7c2e09b7, 0xa59bc234db398c25,\n\t0xcf02b2c21207ef2f, 0x8161afb94b44f57d, 0xa1ba1ba79e1632dc,\n\t0xca28a291859bbf93, 0xfcb2cb35e702af78, 0x9defbf01b061adab,\n\t0xc56baec21c7a1916, 0xf6c69a72a3989f5c, 0x9a3c2087a63f6399,\n\t0xc0cb28a98fcf3c80, 0xf0fdf2d3f3c30b9f, 0x969eb7c47859e744,\n\t0xbc4665b596706115, 0xeb57ff22fc0c795a, 0x9316ff75dd87cbd8,\n\t0xb7dcbf5354e9bece, 0xe5d3ef282a242e82, 0x8fa475791a569d11,\n\t0xb38d92d760ec4455, 0xe070f78d3927556b, 0x8c469ab843b89563,\n\t0xaf58416654a6babb, 0xdb2e51bfe9d0696a, 0x88fcf317f22241e2,\n\t0xab3c2fddeeaad25b, 0xd60b3bd56a5586f2, 0x85c7056562757457,\n\t0xa738c6bebb12d16d, 0xd106f86e69d785c8, 0x82a45b450226b39d,\n\t0xa34d721642b06084, 0xcc20ce9bd35c78a5, 0xff290242c83396ce,\n\t0x9f79a169bd203e41, 0xc75809c42c684dd1, 0xf92e0c3537826146,\n\t0x9bbcc7a142b17ccc, 0xc2abf989935ddbfe, 0xf356f7ebf83552fe,\n\t0x98165af37b2153df, 0xbe1bf1b059e9a8d6, 0xeda2ee1c7064130c,\n\t0x9485d4d1c63e8be8, 0xb9a74a0637ce2ee1, 0xe8111c87c5c1ba9a,\n\t0x910ab1d4db9914a0, 0xb54d5e4a127f59c8, 0xe2a0b5dc971f303a,\n\t0x8da471a9de737e24, 0xb10d8e1456105dad, 0xdd50f1996b947519,\n\t0x8a5296ffe33cc930, 0xace73cbfdc0bfb7b, 0xd8210befd30efa5a,\n\t0x8714a775e3e95c78, 0xa8d9d1535ce3b396, 0xd31045a8341ca07c,\n\t0x83ea2b892091e44e, 0xa4e4b66b68b65d61, 0xce1de40642e3f4b9,\n\t0x80d2ae83e9ce78f4, 0xa1075a24e4421731, 0xc94930ae1d529cfd,\n\t0xfb9b7cd9a4a7443c, 0x9d412e0806e88aa6, 0xc491798a08a2ad4f,\n\t0xf5b5d7ec8acb58a3, 0x9991a6f3d6bf1766, 0xbff610b0cc6edd3f,\n\t0xeff394dcff8a948f, 0x95f83d0a1fb69cd9, 0xbb764c4ca7a44410,\n\t0xea53df5fd18d5514, 0x92746b9be2f8552c, 0xb7118682dbb66a77,\n\t0xe4d5e82392a40515, 0x8f05b1163ba6832d, 0xb2c71d5bca9023f8,\n\t0xdf78e4b2bd342cf7, 0x8bab8eefb6409c1a, 0xae9672aba3d0c321,\n\t0xda3c0f568cc4f3e9, 0x8865899617fb1871, 0xaa7eebfb9df9de8e,\n\t0xd51ea6fa85785631, 0x8533285c936b35df, 0xa67ff273b8460357,\n\t0xd01fef10a657842c, 0x8213f56a67f6b29c, 0xa298f2c501f45f43,\n\t0xcb3f2f7642717713, 0xfe0efb53d30dd4d8, 0x9ec95d1463e8a507,\n\t0xc67bb4597ce2ce49, 0xf81aa16fdc1b81db, 0x9b10a4e5e9913129,\n\t0xc1d4ce1f63f57d73, 0xf24a01a73cf2dcd0, 0x976e41088617ca02,\n\t0xbd49d14aa79dbc82, 0xec9c459d51852ba3, 0x93e1ab8252f33b46,\n\t0xb8da1662e7b00a17, 0xe7109bfba19c0c9d, 0x906a617d450187e2,\n\t0xb484f9dc9641e9db, 0xe1a63853bbd26451, 0x8d07e33455637eb3,\n\t0xb049dc016abc5e60, 0xdc5c5301c56b75f7, 0x89b9b3e11b6329bb,\n\t0xac2820d9623bf429, 0xd732290fbacaf134, 0x867f59a9d4bed6c0,\n\t0xa81f301449ee8c70, 0xd226fc195c6a2f8c, 0x83585d8fd9c25db8,\n\t0xa42e74f3d032f526, 0xcd3a1230c43fb26f, 0x80444b5e7aa7cf85,\n\t0xa0555e361951c367, 0xc86ab5c39fa63441, 0xfa856334878fc151,\n\t0x9c935e00d4b9d8d2, 0xc3b8358109e84f07, 0xf4a642e14c6262c9,\n\t0x98e7e9cccfbd7dbe, 0xbf21e44003acdd2d, 0xeeea5d5004981478,\n\t0x95527a5202df0ccb, 0xbaa718e68396cffe, 0xe950df20247c83fd,\n\t0x91d28b7416cdd27e, 0xb6472e511c81471e, 0xe3d8f9e563a198e5,\n\t0x8e679c2f5e44ff8f, 0xb201833b35d63f73, 0xde81e40a034bcf50,\n\t0x8b112e86420f6192, 0xadd57a27d29339f6, 0xd94ad8b1c7380874,\n\t0x87cec76f1c830549, 0xa9c2794ae3a3c69b, 0xd433179d9c8cb841,\n\t0x849feec281d7f329, 0xa5c7ea73224deff3, 0xcf39e50feae16bf0,\n\t0x81842f29f2cce376, 0xa1e53af46f801c53, 0xca5e89b18b602368,\n\t0xfcf62c1dee382c42, 0x9e19db92b4e31ba9, 0xc5a05277621be294,\n\t0xf70867153aa2db39, 0x9a65406d44a5c903, 0xc0fe908895cf3b44,\n\t0xf13e34aabb430a15, 0x96c6e0eab509e64d, 0xbc789925624c5fe1,\n\t0xeb96bf6ebadf77d9, 0x933e37a534cbaae8, 0xb80dc58e81fe95a1,\n\t0xe61136f2227e3b0a, 0x8fcac257558ee4e6, 0xb3bd72ed2af29e20,\n\t0xe0accfa875af45a8, 0x8c6c01c9498d8b89, 0xaf87023b9bf0ee6b,\n\t0xdb68c2ca82ed2a06, 0x892179be91d43a44, 0xab69d82e364948d4\n};", "static const int powers_ten_e[] = {\n\t-1203, -1200, -1196, -1193, -1190, -1186, -1183, -1180, -1176, -1173,\n\t-1170, -1166, -1163, -1160, -1156, -1153, -1150, -1146, -1143, -1140,\n\t-1136, -1133, -1130, -1127, -1123, -1120, -1117, -1113, -1110, -1107,\n\t-1103, -1100, -1097, -1093, -1090, -1087, -1083, -1080, -1077, -1073,\n\t-1070, -1067, -1063, -1060, -1057, -1053, -1050, -1047, -1043, -1040,\n\t-1037, -1034, -1030, -1027, -1024, -1020, -1017, -1014, -1010, -1007,\n\t-1004, -1000, -997, -994, -990, -987, -984, -980, -977, -974, -970,\n\t-967, -964, -960, -957, -954, -950, -947, -944, -940, -937, -934, -931,\n\t-927, -924, -921, -917, -914, -911, -907, -904, -901, -897, -894, -891,\n\t-887, -884, -881, -877, -874, -871, -867, -864, -861, -857, -854, -851,\n\t-847, -844, -841, -838, -834, -831, -828, -824, -821, -818, -814, -811,\n\t-808, -804, -801, -798, -794, -791, -788, -784, -781, -778, -774, -771,\n\t-768, -764, -761, -758, -754, -751, -748, -744, -741, -738, -735, -731,\n\t-728, -725, -721, -718, -715, -711, -708, -705, -701, -698, -695, -691,\n\t-688, -685, -681, -678, -675, -671, -668, -665, -661, -658, -655, -651,\n\t-648, -645, -642, -638, -635, -632, -628, -625, -622, -618, -615, -612,\n\t-608, -605, -602, -598, -595, -592, -588, -585, -582, -578, -575, -572,\n\t-568, -565, -562, -558, -555, -552, -549, -545, -542, -539, -535, -532,\n\t-529, -525, -522, -519, -515, -512, -509, -505, -502, -499, -495, -492,\n\t-489, -485, -482, -479, -475, -472, -469, -465, -462, -459, -455, -452,\n\t-449, -446, -442, -439, -436, -432, -429, -426, -422, -419, -416, -412,\n\t-409, -406, -402, -399, -396, -392, -389, -386, -382, -379, -376, -372,\n\t-369, -366, -362, -359, -356, -353, -349, -346, -343, -339, -336, -333,\n\t-329, -326, -323, -319, -316, -313, -309, -306, -303, -299, -296, -293,\n\t-289, -286, -283, -279, -276, -273, -269, -266, -263, -259, -256, -253,\n\t-250, -246, -243, -240, -236, -233, -230, -226, -223, -220, -216, -213,\n\t-210, -206, -203, -200, -196, -193, -190, -186, -183, -180, -176, -173,\n\t-170, -166, -163, -160, -157, -153, -150, -147, -143, -140, -137, -133,\n\t-130, -127, -123, -120, -117, -113, -110, -107, -103, -100, -97, -93,\n\t-90, -87, -83, -80, -77, -73, -70, -67, -63, -60, -57, -54, -50, -47,\n\t-44, -40, -37, -34, -30, -27, -24, -20, -17, -14, -10, -7, -4, 0, 3, 6,\n\t10, 13, 16, 20, 23, 26, 30, 33, 36, 39, 43, 46, 49, 53, 56, 59, 63, 66,\n\t69, 73, 76, 79, 83, 86, 89, 93, 96, 99, 103, 106, 109, 113, 116, 119,\n\t123, 126, 129, 132, 136, 139, 142, 146, 149, 152, 156, 159, 162, 166,\n\t169, 172, 176, 179, 182, 186, 189, 192, 196, 199, 202, 206, 209, 212,\n\t216, 219, 222, 226, 229, 232, 235, 239, 242, 245, 249, 252, 255, 259,\n\t262, 265, 269, 272, 275, 279, 282, 285, 289, 292, 295, 299, 302, 305,\n\t309, 312, 315, 319, 322, 325, 328, 332, 335, 338, 342, 345, 348, 352,\n\t355, 358, 362, 365, 368, 372, 375, 378, 382, 385, 388, 392, 395, 398,\n\t402, 405, 408, 412, 415, 418, 422, 425, 428, 431, 435, 438, 441, 445,\n\t448, 451, 455, 458, 461, 465, 468, 471, 475, 478, 481, 485, 488, 491,\n\t495, 498, 501, 505, 508, 511, 515, 518, 521, 524, 528, 531, 534, 538,\n\t541, 544, 548, 551, 554, 558, 561, 564, 568, 571, 574, 578, 581, 584,\n\t588, 591, 594, 598, 601, 604, 608, 611, 614, 617, 621, 624, 627, 631,\n\t634, 637, 641, 644, 647, 651, 654, 657, 661, 664, 667, 671, 674, 677,\n\t681, 684, 687, 691, 694, 697, 701, 704, 707, 711, 714, 717, 720, 724,\n\t727, 730, 734, 737, 740, 744, 747, 750, 754, 757, 760, 764, 767, 770,\n\t774, 777, 780, 784, 787, 790, 794, 797, 800, 804, 807, 810, 813, 817,\n\t820, 823, 827, 830, 833, 837, 840, 843, 847, 850, 853, 857, 860, 863,\n\t867, 870, 873, 877, 880, 883, 887, 890, 893, 897, 900, 903, 907, 910,\n\t913, 916, 920, 923, 926, 930, 933, 936, 940, 943, 946, 950, 953, 956,\n\t960, 963, 966, 970, 973, 976, 980, 983, 986, 990, 993, 996, 1000, 1003,\n\t1006, 1009, 1013, 1016, 1019, 1023, 1026, 1029, 1033, 1036, 1039, 1043,\n\t1046, 1049, 1053, 1056, 1059, 1063, 1066, 1069, 1073, 1076\n};", "static diy_fp_t cached_power(int k)\n{\n\tdiy_fp_t res;\n\tint index = 343 + k;\n\tres.f = powers_ten[index];\n\tres.e = powers_ten_e[index];\n\treturn res;\n}", "static int k_comp(int e, int alpha, int gamma) {\n\treturn ceil((alpha-e+63) * D_1_LOG2_10);\n}", "static diy_fp_t minus(diy_fp_t x, diy_fp_t y)\n{\n\tdiy_fp_t r;\n\tassert(x.e == y.e);\n\tassert(x.f >= y.f);\n\tr.f = x.f - y.f;\n\tr.e = x.e;\n\treturn r;\n}", "static diy_fp_t multiply(diy_fp_t x, diy_fp_t y)\n{\n\tuint64_t a,b,c,d,ac,bc,ad,bd,tmp;\n\tdiy_fp_t r;\n\tuint64_t M32 = 0xFFFFFFFF;\n\ta = x.f >> 32; b = x.f & M32;\n\tc = y.f >> 32; d = y.f & M32;\n\tac = a*c; bc = b*c; ad = a*d; bd = b*d;\n\ttmp = (bd>>32) + (ad&M32) + (bc&M32);\n\ttmp += 1U << 31;\n\tr.f = ac+(ad>>32)+(bc>>32)+(tmp >>32);\n\tr.e = x.e + y.e + 64;\n\treturn r;\n}", "static uint64_t double_to_uint64(double d)\n{\n\tuint64_t n;\n\tmemcpy(&n, &d, 8);\n\treturn n;\n}", "#define DP_SIGNIFICAND_SIZE 52\n#define DP_EXPONENT_BIAS (0x3FF + DP_SIGNIFICAND_SIZE)\n#define DP_MIN_EXPONENT (-DP_EXPONENT_BIAS)\n#define DP_EXPONENT_MASK 0x7FF0000000000000\n#define DP_SIGNIFICAND_MASK 0x000FFFFFFFFFFFFF\n#define DP_HIDDEN_BIT 0x0010000000000000", "static diy_fp_t double2diy_fp(double d)\n{\n\tuint64_t d64 = double_to_uint64(d);\n\tint biased_e = (d64 & DP_EXPONENT_MASK) >> DP_SIGNIFICAND_SIZE;\n\tuint64_t significand = (d64 & DP_SIGNIFICAND_MASK);\n\tdiy_fp_t res;\n\tif (biased_e != 0) {\n\t\tres.f = significand + DP_HIDDEN_BIT;\n\t\tres.e = biased_e - DP_EXPONENT_BIAS;\n\t} else {\n\t\tres.f = significand;\n\t\tres.e = DP_MIN_EXPONENT + 1;\n\t}\n\treturn res;\n}", "static diy_fp_t normalize_boundary(diy_fp_t in)\n{\n\tdiy_fp_t res = in;\n\t/* Normalize now */\n\t/* the original number could have been a denormal. */\n\twhile (! (res.f & (DP_HIDDEN_BIT << 1))) {\n\t\tres.f <<= 1;\n\t\tres.e--;\n\t}\n\t/* do the final shifts in one go. Don't forget the hidden bit (the '-1') */\n\tres.f <<= (DIY_SIGNIFICAND_SIZE - DP_SIGNIFICAND_SIZE - 2);\n\tres.e = res.e - (DIY_SIGNIFICAND_SIZE - DP_SIGNIFICAND_SIZE - 2);\n\treturn res;\n}", "static void normalized_boundaries(double d, diy_fp_t* out_m_minus, diy_fp_t* out_m_plus)\n{\n\tdiy_fp_t v = double2diy_fp(d);\n\tdiy_fp_t pl, mi;\n\tint significand_is_zero = v.f == DP_HIDDEN_BIT;\n\tpl.f = (v.f << 1) + 1; pl.e = v.e - 1;\n\tpl = normalize_boundary(pl);\n\tif (significand_is_zero) {\n\t\tmi.f = (v.f << 2) - 1;\n\t\tmi.e = v.e - 2;\n\t} else {\n\t\tmi.f = (v.f << 1) - 1;\n\t\tmi.e = v.e - 1;\n\t}\n\tmi.f <<= mi.e - pl.e;\n\tmi.e = pl.e;\n\t*out_m_plus = pl;\n\t*out_m_minus = mi;\n}", "#define TEN2 100\nstatic void digit_gen(diy_fp_t Mp, diy_fp_t delta, char* buffer, int* len, int* K)\n{\n\tuint32_t div, p1;\n\tuint64_t p2;\n\tint d,kappa;\n\tdiy_fp_t one;\n\tone.f = ((uint64_t) 1) << -Mp.e; one.e = Mp.e;\n\tp1 = Mp.f >> -one.e;\n\tp2 = Mp.f & (one.f - 1);\n\t*len = 0; kappa = 3; div = TEN2;\n\twhile (kappa > 0) {\n\t\td = p1 / div;\n\t\tif (d || *len) buffer[(*len)++] = '0' + d;\n\t\tp1 %= div; kappa--; div /= 10;\n\t\tif ((((uint64_t)p1)<<-one.e)+p2 <= delta.f) {\n\t\t\t*K += kappa; return;\n\t\t}\n\t}\n\tdo {\n\t\tp2 *= 10;\n\t\td = p2 >> -one.e;\n\t\tif (d || *len) buffer[(*len)++] = '0' + d;\n\t\tp2 &= one.f - 1; kappa--; delta.f *= 10;\n\t} while (p2 > delta.f);\n\t*K += kappa;\n}", "int\njs_grisu2(double v, char *buffer, int *K)\n{\n\tint length, mk;\n\tdiy_fp_t w_m, w_p, c_mk, Wp, Wm, delta;\n\tint q = 64, alpha = -59, gamma = -56;\n\tnormalized_boundaries(v, &w_m, &w_p);\n\tmk = k_comp(w_p.e + q, alpha, gamma);\n\tc_mk = cached_power(mk);\n\tWp = multiply(w_p, c_mk);\n\tWm = multiply(w_m, c_mk);\n\tWm.f++; Wp.f--;\n\tdelta = minus(Wp, Wm);\n\t*K = -mk;\n\tdigit_gen(Wp, delta, buffer, &length, K);\n\treturn length;\n}", "/*\n * strtod.c\n *\n * Copyright (c) 1988-1993 The Regents of the University of California.\n * Copyright (c) 1994 Sun Microsystems, Inc.\n *\n * Permission to use, copy, modify, and distribute this software and its\n * documentation for any purpose and without fee is hereby granted, provided\n * that the above copyright notice appear in all copies. The University of\n * California makes no representations about the suitability of this software\n * for any purpose. It is provided \"as is\" without express or implied warranty.\n */", "/* Largest possible base 10 exponent. Any exponent larger than this will\n * already produce underflow or overflow, so there's no need to worry about\n * additional digits.\n */\nstatic int maxExponent = 511;", "/* Table giving binary powers of 10. Entry\n * is 10^2^i. Used to convert decimal\n * exponents into floating-point numbers.\n */\nstatic double powersOf10[] = {\n\t10.,\n\t100.,\n\t1.0e4,\n\t1.0e8,\n\t1.0e16,\n\t1.0e32,\n\t1.0e64,\n\t1.0e128,\n\t1.0e256\n};", "/* Parse a decimal ASCII floating-point number, optionally preceded by white\n * space. Must have form \"-I.FE-X\", where I is the integer part of the\n * mantissa, F is the fractional part of the mantissa, and X is the exponent.\n * Either of the signs may be \"+\", \"-\", or omitted. Either I or F may be\n * omitted, or both. The decimal point isn't necessary unless F is present.\n * The \"E\" may actually be an \"e\". E and X may both be omitted (but not just\n * one).\n */\ndouble\njs_strtod(const char *string, char **endPtr)\n{\n\tint sign, expSign = FALSE;\n\tdouble fraction, dblExp, *d;\n\tregister const char *p;\n\tregister int c;", "\t/* Exponent read from \"EX\" field. */\n\tint exp = 0;", "\t/* Exponent that derives from the fractional part. Under normal\n\t * circumstances, it is the negative of the number of digits in F.\n\t * However, if I is very long, the last digits of I get dropped\n\t * (otherwise a long I with a large negative exponent could cause an\n\t * unnecessary overflow on I alone). In this case, fracExp is\n\t * incremented one for each dropped digit.\n\t */\n\tint fracExp = 0;", "\t/* Number of digits in mantissa. */\n\tint mantSize;", "\t/* Number of mantissa digits BEFORE decimal point. */\n\tint decPt;", "\t/* Temporarily holds location of exponent in string. */\n\tconst char *pExp;", "\t/*\n\t * Strip off leading blanks and check for a sign.\n\t */", "\tp = string;\n\twhile (*p == ' ' || *p == '\\t' || *p == '\\n' || *p == '\\r') {\n\t\tp += 1;\n\t}\n\tif (*p == '-') {\n\t\tsign = TRUE;\n\t\tp += 1;\n\t} else {\n\t\tif (*p == '+') {\n\t\t\tp += 1;\n\t\t}\n\t\tsign = FALSE;\n\t}", "\t/*\n\t * Count the number of digits in the mantissa (including the decimal\n\t * point), and also locate the decimal point.\n\t */", "\tdecPt = -1;\n\tfor (mantSize = 0; ; mantSize += 1)\n\t{\n\t\tc = *p;\n\t\tif (!(c>='0'&&c<='9')) {\n\t\t\tif ((c != '.') || (decPt >= 0)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdecPt = mantSize;\n\t\t}\n\t\tp += 1;\n\t}", "\t/*\n\t * Now suck up the digits in the mantissa. Use two integers to\n\t * collect 9 digits each (this is faster than using floating-point).\n\t * If the mantissa has more than 18 digits, ignore the extras, since\n\t * they can't affect the value anyway.\n\t */", "\tpExp = p;\n\tp -= mantSize;\n\tif (decPt < 0) {\n\t\tdecPt = mantSize;\n\t} else {\n\t\tmantSize -= 1;\t\t\t/* One of the digits was the point. */\n\t}\n\tif (mantSize > 18) {\n\t\tfracExp = decPt - 18;\n\t\tmantSize = 18;\n\t} else {\n\t\tfracExp = decPt - mantSize;\n\t}\n\tif (mantSize == 0) {\n\t\tfraction = 0.0;\n\t\tp = string;\n\t\tgoto done;\n\t} else {\n\t\tint frac1, frac2;\n\t\tfrac1 = 0;\n\t\tfor ( ; mantSize > 9; mantSize -= 1)\n\t\t{\n\t\t\tc = *p;\n\t\t\tp += 1;\n\t\t\tif (c == '.') {\n\t\t\t\tc = *p;\n\t\t\t\tp += 1;\n\t\t\t}\n\t\t\tfrac1 = 10*frac1 + (c - '0');\n\t\t}\n\t\tfrac2 = 0;\n\t\tfor (; mantSize > 0; mantSize -= 1)\n\t\t{\n\t\t\tc = *p;\n\t\t\tp += 1;\n\t\t\tif (c == '.') {\n\t\t\t\tc = *p;\n\t\t\t\tp += 1;\n\t\t\t}\n\t\t\tfrac2 = 10*frac2 + (c - '0');\n\t\t}\n\t\tfraction = (1.0e9 * frac1) + frac2;\n\t}", "\t/*\n\t * Skim off the exponent.\n\t */", "\tp = pExp;\n\tif ((*p == 'E') || (*p == 'e')) {\n\t\tp += 1;\n\t\tif (*p == '-') {\n\t\t\texpSign = TRUE;\n\t\t\tp += 1;\n\t\t} else {\n\t\t\tif (*p == '+') {\n\t\t\t\tp += 1;\n\t\t\t}\n\t\t\texpSign = FALSE;\n\t\t}", "\t\twhile ((*p >= '0') && (*p <= '9')) {", "\t\t\texp = exp * 10 + (*p - '0');\n\t\t\tp += 1;\n\t\t}", "", "\t}\n\tif (expSign) {\n\t\texp = fracExp - exp;\n\t} else {\n\t\texp = fracExp + exp;\n\t}", "\t/*\n\t * Generate a floating-point number that represents the exponent.\n\t * Do this by processing the exponent one bit at a time to combine\n\t * many powers of 2 of 10. Then combine the exponent with the\n\t * fraction.\n\t */", "\tif (exp < -maxExponent) {\n\t\texp = maxExponent;\n\t\texpSign = TRUE;\n\t\terrno = ERANGE;\n\t} else if (exp > maxExponent) {\n\t\texp = maxExponent;\n\t\texpSign = FALSE;\n\t\terrno = ERANGE;\n\t} else if (exp < 0) {\n\t\texpSign = TRUE;\n\t\texp = -exp;\n\t} else {\n\t\texpSign = FALSE;\n\t}\n\tdblExp = 1.0;\n\tfor (d = powersOf10; exp != 0; exp >>= 1, d += 1) {\n\t\tif (exp & 01) {\n\t\t\tdblExp *= *d;\n\t\t}\n\t}\n\tif (expSign) {\n\t\tfraction /= dblExp;\n\t} else {\n\t\tfraction *= dblExp;\n\t}", "done:\n\tif (endPtr != NULL) {\n\t\t*endPtr = (char *) p;\n\t}", "\tif (sign) {\n\t\treturn -fraction;\n\t}\n\treturn fraction;\n}" ]
[ 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, 0, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [697], "buggy_code_start_loc": [694], "filenames": ["jsdtoa.c"], "fixing_code_end_loc": [700], "fixing_code_start_loc": [694], "message": "Buffer-overflow in jsdtoa.c in Artifex MuJS in versions 1.0.1 to 1.1.1. An integer overflow happens when js_strtod() reads in floating point exponent, which leads to a buffer overflow in the pointer *d.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:artifex:mujs:*:*:*:*:*:*:*:*", "matchCriteriaId": "2D9B97C7-3BAD-48CC-85A1-58BAFDF16DF8", "versionEndExcluding": null, "versionEndIncluding": "1.1.1", "versionStartExcluding": null, "versionStartIncluding": "1.0.1", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Buffer-overflow in jsdtoa.c in Artifex MuJS in versions 1.0.1 to 1.1.1. An integer overflow happens when js_strtod() reads in floating point exponent, which leads to a buffer overflow in the pointer *d."}], "evaluatorComment": null, "id": "CVE-2021-33797", "lastModified": "2023-04-26T23:05:05.003", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-17T22:15:07.677", "references": [{"source": "patrick@puiterwijk.org", "tags": ["Patch"], "url": "https://github.com/ccxvii/mujs/commit/833b6f1672b4f2991a63c4d05318f0b84ef4d550"}, {"source": "patrick@puiterwijk.org", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://github.com/ccxvii/mujs/issues/148"}], "sourceIdentifier": "patrick@puiterwijk.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-190"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-119"}], "source": "patrick@puiterwijk.org", "type": "Secondary"}]}, "github_commit_url": "https://github.com/ccxvii/mujs/commit/833b6f1672b4f2991a63c4d05318f0b84ef4d550"}, "type": "CWE-190"}
174
Determine whether the {function_name} code is vulnerable or not.
[ "/* Locale-independent implementations of string <-> double conversions. */", "#include \"jsi.h\"", "#if defined(_MSC_VER) && (_MSC_VER < 1700) /* VS2012 has stdint.h */\ntypedef unsigned int uint32_t;\ntypedef unsigned __int64 uint64_t;\n#else\n#include <stdint.h>\n#endif", "#include <errno.h>\n#include <assert.h>", "#ifndef TRUE\n#define TRUE 1\n#define FALSE 0\n#endif", "/*\n * format exponent like sprintf(p, \"e%+d\", e)\n */\nvoid\njs_fmtexp(char *p, int e)\n{\n\tchar se[9];\n\tint i;", "\t*p++ = 'e';\n\tif(e < 0) {\n\t\t*p++ = '-';\n\t\te = -e;\n\t} else\n\t\t*p++ = '+';\n\ti = 0;\n\twhile(e) {\n\t\tse[i++] = e % 10 + '0';\n\t\te /= 10;\n\t}\n\twhile(i < 1)\n\t\tse[i++] = '0';\n\twhile(i > 0)\n\t\t*p++ = se[--i];\n\t*p++ = '\\0';\n}", "/*\n * grisu2_59_56.c\n *\n * Grisu prints the optimal decimal representation of floating-point numbers.\n *\n * Copyright (c) 2009 Florian Loitsch\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */", "typedef struct diy_fp_t {\n\tuint64_t f;\n\tint e;\n} diy_fp_t;", "#define DIY_SIGNIFICAND_SIZE 64\n#define D_1_LOG2_10 0.30102999566398114 /* 1 / lg(10) */", "static const uint64_t powers_ten[] = {\n\t0xbf29dcaba82fdeae, 0xeef453d6923bd65a, 0x9558b4661b6565f8,\n\t0xbaaee17fa23ebf76, 0xe95a99df8ace6f54, 0x91d8a02bb6c10594,\n\t0xb64ec836a47146fa, 0xe3e27a444d8d98b8, 0x8e6d8c6ab0787f73,\n\t0xb208ef855c969f50, 0xde8b2b66b3bc4724, 0x8b16fb203055ac76,\n\t0xaddcb9e83c6b1794, 0xd953e8624b85dd79, 0x87d4713d6f33aa6c,\n\t0xa9c98d8ccb009506, 0xd43bf0effdc0ba48, 0x84a57695fe98746d,\n\t0xa5ced43b7e3e9188, 0xcf42894a5dce35ea, 0x818995ce7aa0e1b2,\n\t0xa1ebfb4219491a1f, 0xca66fa129f9b60a7, 0xfd00b897478238d1,\n\t0x9e20735e8cb16382, 0xc5a890362fddbc63, 0xf712b443bbd52b7c,\n\t0x9a6bb0aa55653b2d, 0xc1069cd4eabe89f9, 0xf148440a256e2c77,\n\t0x96cd2a865764dbca, 0xbc807527ed3e12bd, 0xeba09271e88d976c,\n\t0x93445b8731587ea3, 0xb8157268fdae9e4c, 0xe61acf033d1a45df,\n\t0x8fd0c16206306bac, 0xb3c4f1ba87bc8697, 0xe0b62e2929aba83c,\n\t0x8c71dcd9ba0b4926, 0xaf8e5410288e1b6f, 0xdb71e91432b1a24b,\n\t0x892731ac9faf056f, 0xab70fe17c79ac6ca, 0xd64d3d9db981787d,\n\t0x85f0468293f0eb4e, 0xa76c582338ed2622, 0xd1476e2c07286faa,\n\t0x82cca4db847945ca, 0xa37fce126597973d, 0xcc5fc196fefd7d0c,\n\t0xff77b1fcbebcdc4f, 0x9faacf3df73609b1, 0xc795830d75038c1e,\n\t0xf97ae3d0d2446f25, 0x9becce62836ac577, 0xc2e801fb244576d5,\n\t0xf3a20279ed56d48a, 0x9845418c345644d7, 0xbe5691ef416bd60c,\n\t0xedec366b11c6cb8f, 0x94b3a202eb1c3f39, 0xb9e08a83a5e34f08,\n\t0xe858ad248f5c22ca, 0x91376c36d99995be, 0xb58547448ffffb2e,\n\t0xe2e69915b3fff9f9, 0x8dd01fad907ffc3c, 0xb1442798f49ffb4b,\n\t0xdd95317f31c7fa1d, 0x8a7d3eef7f1cfc52, 0xad1c8eab5ee43b67,\n\t0xd863b256369d4a41, 0x873e4f75e2224e68, 0xa90de3535aaae202,\n\t0xd3515c2831559a83, 0x8412d9991ed58092, 0xa5178fff668ae0b6,\n\t0xce5d73ff402d98e4, 0x80fa687f881c7f8e, 0xa139029f6a239f72,\n\t0xc987434744ac874f, 0xfbe9141915d7a922, 0x9d71ac8fada6c9b5,\n\t0xc4ce17b399107c23, 0xf6019da07f549b2b, 0x99c102844f94e0fb,\n\t0xc0314325637a193a, 0xf03d93eebc589f88, 0x96267c7535b763b5,\n\t0xbbb01b9283253ca3, 0xea9c227723ee8bcb, 0x92a1958a7675175f,\n\t0xb749faed14125d37, 0xe51c79a85916f485, 0x8f31cc0937ae58d3,\n\t0xb2fe3f0b8599ef08, 0xdfbdcece67006ac9, 0x8bd6a141006042be,\n\t0xaecc49914078536d, 0xda7f5bf590966849, 0x888f99797a5e012d,\n\t0xaab37fd7d8f58179, 0xd5605fcdcf32e1d7, 0x855c3be0a17fcd26,\n\t0xa6b34ad8c9dfc070, 0xd0601d8efc57b08c, 0x823c12795db6ce57,\n\t0xa2cb1717b52481ed, 0xcb7ddcdda26da269, 0xfe5d54150b090b03,\n\t0x9efa548d26e5a6e2, 0xc6b8e9b0709f109a, 0xf867241c8cc6d4c1,\n\t0x9b407691d7fc44f8, 0xc21094364dfb5637, 0xf294b943e17a2bc4,\n\t0x979cf3ca6cec5b5b, 0xbd8430bd08277231, 0xece53cec4a314ebe,\n\t0x940f4613ae5ed137, 0xb913179899f68584, 0xe757dd7ec07426e5,\n\t0x9096ea6f3848984f, 0xb4bca50b065abe63, 0xe1ebce4dc7f16dfc,\n\t0x8d3360f09cf6e4bd, 0xb080392cc4349ded, 0xdca04777f541c568,\n\t0x89e42caaf9491b61, 0xac5d37d5b79b6239, 0xd77485cb25823ac7,\n\t0x86a8d39ef77164bd, 0xa8530886b54dbdec, 0xd267caa862a12d67,\n\t0x8380dea93da4bc60, 0xa46116538d0deb78, 0xcd795be870516656,\n\t0x806bd9714632dff6, 0xa086cfcd97bf97f4, 0xc8a883c0fdaf7df0,\n\t0xfad2a4b13d1b5d6c, 0x9cc3a6eec6311a64, 0xc3f490aa77bd60fd,\n\t0xf4f1b4d515acb93c, 0x991711052d8bf3c5, 0xbf5cd54678eef0b7,\n\t0xef340a98172aace5, 0x9580869f0e7aac0f, 0xbae0a846d2195713,\n\t0xe998d258869facd7, 0x91ff83775423cc06, 0xb67f6455292cbf08,\n\t0xe41f3d6a7377eeca, 0x8e938662882af53e, 0xb23867fb2a35b28e,\n\t0xdec681f9f4c31f31, 0x8b3c113c38f9f37f, 0xae0b158b4738705f,\n\t0xd98ddaee19068c76, 0x87f8a8d4cfa417ca, 0xa9f6d30a038d1dbc,\n\t0xd47487cc8470652b, 0x84c8d4dfd2c63f3b, 0xa5fb0a17c777cf0a,\n\t0xcf79cc9db955c2cc, 0x81ac1fe293d599c0, 0xa21727db38cb0030,\n\t0xca9cf1d206fdc03c, 0xfd442e4688bd304b, 0x9e4a9cec15763e2f,\n\t0xc5dd44271ad3cdba, 0xf7549530e188c129, 0x9a94dd3e8cf578ba,\n\t0xc13a148e3032d6e8, 0xf18899b1bc3f8ca2, 0x96f5600f15a7b7e5,\n\t0xbcb2b812db11a5de, 0xebdf661791d60f56, 0x936b9fcebb25c996,\n\t0xb84687c269ef3bfb, 0xe65829b3046b0afa, 0x8ff71a0fe2c2e6dc,\n\t0xb3f4e093db73a093, 0xe0f218b8d25088b8, 0x8c974f7383725573,\n\t0xafbd2350644eead0, 0xdbac6c247d62a584, 0x894bc396ce5da772,\n\t0xab9eb47c81f5114f, 0xd686619ba27255a3, 0x8613fd0145877586,\n\t0xa798fc4196e952e7, 0xd17f3b51fca3a7a1, 0x82ef85133de648c5,\n\t0xa3ab66580d5fdaf6, 0xcc963fee10b7d1b3, 0xffbbcfe994e5c620,\n\t0x9fd561f1fd0f9bd4, 0xc7caba6e7c5382c9, 0xf9bd690a1b68637b,\n\t0x9c1661a651213e2d, 0xc31bfa0fe5698db8, 0xf3e2f893dec3f126,\n\t0x986ddb5c6b3a76b8, 0xbe89523386091466, 0xee2ba6c0678b597f,\n\t0x94db483840b717f0, 0xba121a4650e4ddec, 0xe896a0d7e51e1566,\n\t0x915e2486ef32cd60, 0xb5b5ada8aaff80b8, 0xe3231912d5bf60e6,\n\t0x8df5efabc5979c90, 0xb1736b96b6fd83b4, 0xddd0467c64bce4a1,\n\t0x8aa22c0dbef60ee4, 0xad4ab7112eb3929e, 0xd89d64d57a607745,\n\t0x87625f056c7c4a8b, 0xa93af6c6c79b5d2e, 0xd389b47879823479,\n\t0x843610cb4bf160cc, 0xa54394fe1eedb8ff, 0xce947a3da6a9273e,\n\t0x811ccc668829b887, 0xa163ff802a3426a9, 0xc9bcff6034c13053,\n\t0xfc2c3f3841f17c68, 0x9d9ba7832936edc1, 0xc5029163f384a931,\n\t0xf64335bcf065d37d, 0x99ea0196163fa42e, 0xc06481fb9bcf8d3a,\n\t0xf07da27a82c37088, 0x964e858c91ba2655, 0xbbe226efb628afeb,\n\t0xeadab0aba3b2dbe5, 0x92c8ae6b464fc96f, 0xb77ada0617e3bbcb,\n\t0xe55990879ddcaabe, 0x8f57fa54c2a9eab7, 0xb32df8e9f3546564,\n\t0xdff9772470297ebd, 0x8bfbea76c619ef36, 0xaefae51477a06b04,\n\t0xdab99e59958885c5, 0x88b402f7fd75539b, 0xaae103b5fcd2a882,\n\t0xd59944a37c0752a2, 0x857fcae62d8493a5, 0xa6dfbd9fb8e5b88f,\n\t0xd097ad07a71f26b2, 0x825ecc24c8737830, 0xa2f67f2dfa90563b,\n\t0xcbb41ef979346bca, 0xfea126b7d78186bd, 0x9f24b832e6b0f436,\n\t0xc6ede63fa05d3144, 0xf8a95fcf88747d94, 0x9b69dbe1b548ce7d,\n\t0xc24452da229b021c, 0xf2d56790ab41c2a3, 0x97c560ba6b0919a6,\n\t0xbdb6b8e905cb600f, 0xed246723473e3813, 0x9436c0760c86e30c,\n\t0xb94470938fa89bcf, 0xe7958cb87392c2c3, 0x90bd77f3483bb9ba,\n\t0xb4ecd5f01a4aa828, 0xe2280b6c20dd5232, 0x8d590723948a535f,\n\t0xb0af48ec79ace837, 0xdcdb1b2798182245, 0x8a08f0f8bf0f156b,\n\t0xac8b2d36eed2dac6, 0xd7adf884aa879177, 0x86ccbb52ea94baeb,\n\t0xa87fea27a539e9a5, 0xd29fe4b18e88640f, 0x83a3eeeef9153e89,\n\t0xa48ceaaab75a8e2b, 0xcdb02555653131b6, 0x808e17555f3ebf12,\n\t0xa0b19d2ab70e6ed6, 0xc8de047564d20a8c, 0xfb158592be068d2f,\n\t0x9ced737bb6c4183d, 0xc428d05aa4751e4d, 0xf53304714d9265e0,\n\t0x993fe2c6d07b7fac, 0xbf8fdb78849a5f97, 0xef73d256a5c0f77d,\n\t0x95a8637627989aae, 0xbb127c53b17ec159, 0xe9d71b689dde71b0,\n\t0x9226712162ab070e, 0xb6b00d69bb55c8d1, 0xe45c10c42a2b3b06,\n\t0x8eb98a7a9a5b04e3, 0xb267ed1940f1c61c, 0xdf01e85f912e37a3,\n\t0x8b61313bbabce2c6, 0xae397d8aa96c1b78, 0xd9c7dced53c72256,\n\t0x881cea14545c7575, 0xaa242499697392d3, 0xd4ad2dbfc3d07788,\n\t0x84ec3c97da624ab5, 0xa6274bbdd0fadd62, 0xcfb11ead453994ba,\n\t0x81ceb32c4b43fcf5, 0xa2425ff75e14fc32, 0xcad2f7f5359a3b3e,\n\t0xfd87b5f28300ca0e, 0x9e74d1b791e07e48, 0xc612062576589ddb,\n\t0xf79687aed3eec551, 0x9abe14cd44753b53, 0xc16d9a0095928a27,\n\t0xf1c90080baf72cb1, 0x971da05074da7bef, 0xbce5086492111aeb,\n\t0xec1e4a7db69561a5, 0x9392ee8e921d5d07, 0xb877aa3236a4b449,\n\t0xe69594bec44de15b, 0x901d7cf73ab0acd9, 0xb424dc35095cd80f,\n\t0xe12e13424bb40e13, 0x8cbccc096f5088cc, 0xafebff0bcb24aaff,\n\t0xdbe6fecebdedd5bf, 0x89705f4136b4a597, 0xabcc77118461cefd,\n\t0xd6bf94d5e57a42bc, 0x8637bd05af6c69b6, 0xa7c5ac471b478423,\n\t0xd1b71758e219652c, 0x83126e978d4fdf3b, 0xa3d70a3d70a3d70a,\n\t0xcccccccccccccccd, 0x8000000000000000, 0xa000000000000000,\n\t0xc800000000000000, 0xfa00000000000000, 0x9c40000000000000,\n\t0xc350000000000000, 0xf424000000000000, 0x9896800000000000,\n\t0xbebc200000000000, 0xee6b280000000000, 0x9502f90000000000,\n\t0xba43b74000000000, 0xe8d4a51000000000, 0x9184e72a00000000,\n\t0xb5e620f480000000, 0xe35fa931a0000000, 0x8e1bc9bf04000000,\n\t0xb1a2bc2ec5000000, 0xde0b6b3a76400000, 0x8ac7230489e80000,\n\t0xad78ebc5ac620000, 0xd8d726b7177a8000, 0x878678326eac9000,\n\t0xa968163f0a57b400, 0xd3c21bcecceda100, 0x84595161401484a0,\n\t0xa56fa5b99019a5c8, 0xcecb8f27f4200f3a, 0x813f3978f8940984,\n\t0xa18f07d736b90be5, 0xc9f2c9cd04674edf, 0xfc6f7c4045812296,\n\t0x9dc5ada82b70b59e, 0xc5371912364ce305, 0xf684df56c3e01bc7,\n\t0x9a130b963a6c115c, 0xc097ce7bc90715b3, 0xf0bdc21abb48db20,\n\t0x96769950b50d88f4, 0xbc143fa4e250eb31, 0xeb194f8e1ae525fd,\n\t0x92efd1b8d0cf37be, 0xb7abc627050305ae, 0xe596b7b0c643c719,\n\t0x8f7e32ce7bea5c70, 0xb35dbf821ae4f38c, 0xe0352f62a19e306f,\n\t0x8c213d9da502de45, 0xaf298d050e4395d7, 0xdaf3f04651d47b4c,\n\t0x88d8762bf324cd10, 0xab0e93b6efee0054, 0xd5d238a4abe98068,\n\t0x85a36366eb71f041, 0xa70c3c40a64e6c52, 0xd0cf4b50cfe20766,\n\t0x82818f1281ed44a0, 0xa321f2d7226895c8, 0xcbea6f8ceb02bb3a,\n\t0xfee50b7025c36a08, 0x9f4f2726179a2245, 0xc722f0ef9d80aad6,\n\t0xf8ebad2b84e0d58c, 0x9b934c3b330c8577, 0xc2781f49ffcfa6d5,\n\t0xf316271c7fc3908b, 0x97edd871cfda3a57, 0xbde94e8e43d0c8ec,\n\t0xed63a231d4c4fb27, 0x945e455f24fb1cf9, 0xb975d6b6ee39e437,\n\t0xe7d34c64a9c85d44, 0x90e40fbeea1d3a4b, 0xb51d13aea4a488dd,\n\t0xe264589a4dcdab15, 0x8d7eb76070a08aed, 0xb0de65388cc8ada8,\n\t0xdd15fe86affad912, 0x8a2dbf142dfcc7ab, 0xacb92ed9397bf996,\n\t0xd7e77a8f87daf7fc, 0x86f0ac99b4e8dafd, 0xa8acd7c0222311bd,\n\t0xd2d80db02aabd62c, 0x83c7088e1aab65db, 0xa4b8cab1a1563f52,\n\t0xcde6fd5e09abcf27, 0x80b05e5ac60b6178, 0xa0dc75f1778e39d6,\n\t0xc913936dd571c84c, 0xfb5878494ace3a5f, 0x9d174b2dcec0e47b,\n\t0xc45d1df942711d9a, 0xf5746577930d6501, 0x9968bf6abbe85f20,\n\t0xbfc2ef456ae276e9, 0xefb3ab16c59b14a3, 0x95d04aee3b80ece6,\n\t0xbb445da9ca61281f, 0xea1575143cf97227, 0x924d692ca61be758,\n\t0xb6e0c377cfa2e12e, 0xe498f455c38b997a, 0x8edf98b59a373fec,\n\t0xb2977ee300c50fe7, 0xdf3d5e9bc0f653e1, 0x8b865b215899f46d,\n\t0xae67f1e9aec07188, 0xda01ee641a708dea, 0x884134fe908658b2,\n\t0xaa51823e34a7eedf, 0xd4e5e2cdc1d1ea96, 0x850fadc09923329e,\n\t0xa6539930bf6bff46, 0xcfe87f7cef46ff17, 0x81f14fae158c5f6e,\n\t0xa26da3999aef774a, 0xcb090c8001ab551c, 0xfdcb4fa002162a63,\n\t0x9e9f11c4014dda7e, 0xc646d63501a1511e, 0xf7d88bc24209a565,\n\t0x9ae757596946075f, 0xc1a12d2fc3978937, 0xf209787bb47d6b85,\n\t0x9745eb4d50ce6333, 0xbd176620a501fc00, 0xec5d3fa8ce427b00,\n\t0x93ba47c980e98ce0, 0xb8a8d9bbe123f018, 0xe6d3102ad96cec1e,\n\t0x9043ea1ac7e41393, 0xb454e4a179dd1877, 0xe16a1dc9d8545e95,\n\t0x8ce2529e2734bb1d, 0xb01ae745b101e9e4, 0xdc21a1171d42645d,\n\t0x899504ae72497eba, 0xabfa45da0edbde69, 0xd6f8d7509292d603,\n\t0x865b86925b9bc5c2, 0xa7f26836f282b733, 0xd1ef0244af2364ff,\n\t0x8335616aed761f1f, 0xa402b9c5a8d3a6e7, 0xcd036837130890a1,\n\t0x802221226be55a65, 0xa02aa96b06deb0fe, 0xc83553c5c8965d3d,\n\t0xfa42a8b73abbf48d, 0x9c69a97284b578d8, 0xc38413cf25e2d70e,\n\t0xf46518c2ef5b8cd1, 0x98bf2f79d5993803, 0xbeeefb584aff8604,\n\t0xeeaaba2e5dbf6785, 0x952ab45cfa97a0b3, 0xba756174393d88e0,\n\t0xe912b9d1478ceb17, 0x91abb422ccb812ef, 0xb616a12b7fe617aa,\n\t0xe39c49765fdf9d95, 0x8e41ade9fbebc27d, 0xb1d219647ae6b31c,\n\t0xde469fbd99a05fe3, 0x8aec23d680043bee, 0xada72ccc20054aea,\n\t0xd910f7ff28069da4, 0x87aa9aff79042287, 0xa99541bf57452b28,\n\t0xd3fa922f2d1675f2, 0x847c9b5d7c2e09b7, 0xa59bc234db398c25,\n\t0xcf02b2c21207ef2f, 0x8161afb94b44f57d, 0xa1ba1ba79e1632dc,\n\t0xca28a291859bbf93, 0xfcb2cb35e702af78, 0x9defbf01b061adab,\n\t0xc56baec21c7a1916, 0xf6c69a72a3989f5c, 0x9a3c2087a63f6399,\n\t0xc0cb28a98fcf3c80, 0xf0fdf2d3f3c30b9f, 0x969eb7c47859e744,\n\t0xbc4665b596706115, 0xeb57ff22fc0c795a, 0x9316ff75dd87cbd8,\n\t0xb7dcbf5354e9bece, 0xe5d3ef282a242e82, 0x8fa475791a569d11,\n\t0xb38d92d760ec4455, 0xe070f78d3927556b, 0x8c469ab843b89563,\n\t0xaf58416654a6babb, 0xdb2e51bfe9d0696a, 0x88fcf317f22241e2,\n\t0xab3c2fddeeaad25b, 0xd60b3bd56a5586f2, 0x85c7056562757457,\n\t0xa738c6bebb12d16d, 0xd106f86e69d785c8, 0x82a45b450226b39d,\n\t0xa34d721642b06084, 0xcc20ce9bd35c78a5, 0xff290242c83396ce,\n\t0x9f79a169bd203e41, 0xc75809c42c684dd1, 0xf92e0c3537826146,\n\t0x9bbcc7a142b17ccc, 0xc2abf989935ddbfe, 0xf356f7ebf83552fe,\n\t0x98165af37b2153df, 0xbe1bf1b059e9a8d6, 0xeda2ee1c7064130c,\n\t0x9485d4d1c63e8be8, 0xb9a74a0637ce2ee1, 0xe8111c87c5c1ba9a,\n\t0x910ab1d4db9914a0, 0xb54d5e4a127f59c8, 0xe2a0b5dc971f303a,\n\t0x8da471a9de737e24, 0xb10d8e1456105dad, 0xdd50f1996b947519,\n\t0x8a5296ffe33cc930, 0xace73cbfdc0bfb7b, 0xd8210befd30efa5a,\n\t0x8714a775e3e95c78, 0xa8d9d1535ce3b396, 0xd31045a8341ca07c,\n\t0x83ea2b892091e44e, 0xa4e4b66b68b65d61, 0xce1de40642e3f4b9,\n\t0x80d2ae83e9ce78f4, 0xa1075a24e4421731, 0xc94930ae1d529cfd,\n\t0xfb9b7cd9a4a7443c, 0x9d412e0806e88aa6, 0xc491798a08a2ad4f,\n\t0xf5b5d7ec8acb58a3, 0x9991a6f3d6bf1766, 0xbff610b0cc6edd3f,\n\t0xeff394dcff8a948f, 0x95f83d0a1fb69cd9, 0xbb764c4ca7a44410,\n\t0xea53df5fd18d5514, 0x92746b9be2f8552c, 0xb7118682dbb66a77,\n\t0xe4d5e82392a40515, 0x8f05b1163ba6832d, 0xb2c71d5bca9023f8,\n\t0xdf78e4b2bd342cf7, 0x8bab8eefb6409c1a, 0xae9672aba3d0c321,\n\t0xda3c0f568cc4f3e9, 0x8865899617fb1871, 0xaa7eebfb9df9de8e,\n\t0xd51ea6fa85785631, 0x8533285c936b35df, 0xa67ff273b8460357,\n\t0xd01fef10a657842c, 0x8213f56a67f6b29c, 0xa298f2c501f45f43,\n\t0xcb3f2f7642717713, 0xfe0efb53d30dd4d8, 0x9ec95d1463e8a507,\n\t0xc67bb4597ce2ce49, 0xf81aa16fdc1b81db, 0x9b10a4e5e9913129,\n\t0xc1d4ce1f63f57d73, 0xf24a01a73cf2dcd0, 0x976e41088617ca02,\n\t0xbd49d14aa79dbc82, 0xec9c459d51852ba3, 0x93e1ab8252f33b46,\n\t0xb8da1662e7b00a17, 0xe7109bfba19c0c9d, 0x906a617d450187e2,\n\t0xb484f9dc9641e9db, 0xe1a63853bbd26451, 0x8d07e33455637eb3,\n\t0xb049dc016abc5e60, 0xdc5c5301c56b75f7, 0x89b9b3e11b6329bb,\n\t0xac2820d9623bf429, 0xd732290fbacaf134, 0x867f59a9d4bed6c0,\n\t0xa81f301449ee8c70, 0xd226fc195c6a2f8c, 0x83585d8fd9c25db8,\n\t0xa42e74f3d032f526, 0xcd3a1230c43fb26f, 0x80444b5e7aa7cf85,\n\t0xa0555e361951c367, 0xc86ab5c39fa63441, 0xfa856334878fc151,\n\t0x9c935e00d4b9d8d2, 0xc3b8358109e84f07, 0xf4a642e14c6262c9,\n\t0x98e7e9cccfbd7dbe, 0xbf21e44003acdd2d, 0xeeea5d5004981478,\n\t0x95527a5202df0ccb, 0xbaa718e68396cffe, 0xe950df20247c83fd,\n\t0x91d28b7416cdd27e, 0xb6472e511c81471e, 0xe3d8f9e563a198e5,\n\t0x8e679c2f5e44ff8f, 0xb201833b35d63f73, 0xde81e40a034bcf50,\n\t0x8b112e86420f6192, 0xadd57a27d29339f6, 0xd94ad8b1c7380874,\n\t0x87cec76f1c830549, 0xa9c2794ae3a3c69b, 0xd433179d9c8cb841,\n\t0x849feec281d7f329, 0xa5c7ea73224deff3, 0xcf39e50feae16bf0,\n\t0x81842f29f2cce376, 0xa1e53af46f801c53, 0xca5e89b18b602368,\n\t0xfcf62c1dee382c42, 0x9e19db92b4e31ba9, 0xc5a05277621be294,\n\t0xf70867153aa2db39, 0x9a65406d44a5c903, 0xc0fe908895cf3b44,\n\t0xf13e34aabb430a15, 0x96c6e0eab509e64d, 0xbc789925624c5fe1,\n\t0xeb96bf6ebadf77d9, 0x933e37a534cbaae8, 0xb80dc58e81fe95a1,\n\t0xe61136f2227e3b0a, 0x8fcac257558ee4e6, 0xb3bd72ed2af29e20,\n\t0xe0accfa875af45a8, 0x8c6c01c9498d8b89, 0xaf87023b9bf0ee6b,\n\t0xdb68c2ca82ed2a06, 0x892179be91d43a44, 0xab69d82e364948d4\n};", "static const int powers_ten_e[] = {\n\t-1203, -1200, -1196, -1193, -1190, -1186, -1183, -1180, -1176, -1173,\n\t-1170, -1166, -1163, -1160, -1156, -1153, -1150, -1146, -1143, -1140,\n\t-1136, -1133, -1130, -1127, -1123, -1120, -1117, -1113, -1110, -1107,\n\t-1103, -1100, -1097, -1093, -1090, -1087, -1083, -1080, -1077, -1073,\n\t-1070, -1067, -1063, -1060, -1057, -1053, -1050, -1047, -1043, -1040,\n\t-1037, -1034, -1030, -1027, -1024, -1020, -1017, -1014, -1010, -1007,\n\t-1004, -1000, -997, -994, -990, -987, -984, -980, -977, -974, -970,\n\t-967, -964, -960, -957, -954, -950, -947, -944, -940, -937, -934, -931,\n\t-927, -924, -921, -917, -914, -911, -907, -904, -901, -897, -894, -891,\n\t-887, -884, -881, -877, -874, -871, -867, -864, -861, -857, -854, -851,\n\t-847, -844, -841, -838, -834, -831, -828, -824, -821, -818, -814, -811,\n\t-808, -804, -801, -798, -794, -791, -788, -784, -781, -778, -774, -771,\n\t-768, -764, -761, -758, -754, -751, -748, -744, -741, -738, -735, -731,\n\t-728, -725, -721, -718, -715, -711, -708, -705, -701, -698, -695, -691,\n\t-688, -685, -681, -678, -675, -671, -668, -665, -661, -658, -655, -651,\n\t-648, -645, -642, -638, -635, -632, -628, -625, -622, -618, -615, -612,\n\t-608, -605, -602, -598, -595, -592, -588, -585, -582, -578, -575, -572,\n\t-568, -565, -562, -558, -555, -552, -549, -545, -542, -539, -535, -532,\n\t-529, -525, -522, -519, -515, -512, -509, -505, -502, -499, -495, -492,\n\t-489, -485, -482, -479, -475, -472, -469, -465, -462, -459, -455, -452,\n\t-449, -446, -442, -439, -436, -432, -429, -426, -422, -419, -416, -412,\n\t-409, -406, -402, -399, -396, -392, -389, -386, -382, -379, -376, -372,\n\t-369, -366, -362, -359, -356, -353, -349, -346, -343, -339, -336, -333,\n\t-329, -326, -323, -319, -316, -313, -309, -306, -303, -299, -296, -293,\n\t-289, -286, -283, -279, -276, -273, -269, -266, -263, -259, -256, -253,\n\t-250, -246, -243, -240, -236, -233, -230, -226, -223, -220, -216, -213,\n\t-210, -206, -203, -200, -196, -193, -190, -186, -183, -180, -176, -173,\n\t-170, -166, -163, -160, -157, -153, -150, -147, -143, -140, -137, -133,\n\t-130, -127, -123, -120, -117, -113, -110, -107, -103, -100, -97, -93,\n\t-90, -87, -83, -80, -77, -73, -70, -67, -63, -60, -57, -54, -50, -47,\n\t-44, -40, -37, -34, -30, -27, -24, -20, -17, -14, -10, -7, -4, 0, 3, 6,\n\t10, 13, 16, 20, 23, 26, 30, 33, 36, 39, 43, 46, 49, 53, 56, 59, 63, 66,\n\t69, 73, 76, 79, 83, 86, 89, 93, 96, 99, 103, 106, 109, 113, 116, 119,\n\t123, 126, 129, 132, 136, 139, 142, 146, 149, 152, 156, 159, 162, 166,\n\t169, 172, 176, 179, 182, 186, 189, 192, 196, 199, 202, 206, 209, 212,\n\t216, 219, 222, 226, 229, 232, 235, 239, 242, 245, 249, 252, 255, 259,\n\t262, 265, 269, 272, 275, 279, 282, 285, 289, 292, 295, 299, 302, 305,\n\t309, 312, 315, 319, 322, 325, 328, 332, 335, 338, 342, 345, 348, 352,\n\t355, 358, 362, 365, 368, 372, 375, 378, 382, 385, 388, 392, 395, 398,\n\t402, 405, 408, 412, 415, 418, 422, 425, 428, 431, 435, 438, 441, 445,\n\t448, 451, 455, 458, 461, 465, 468, 471, 475, 478, 481, 485, 488, 491,\n\t495, 498, 501, 505, 508, 511, 515, 518, 521, 524, 528, 531, 534, 538,\n\t541, 544, 548, 551, 554, 558, 561, 564, 568, 571, 574, 578, 581, 584,\n\t588, 591, 594, 598, 601, 604, 608, 611, 614, 617, 621, 624, 627, 631,\n\t634, 637, 641, 644, 647, 651, 654, 657, 661, 664, 667, 671, 674, 677,\n\t681, 684, 687, 691, 694, 697, 701, 704, 707, 711, 714, 717, 720, 724,\n\t727, 730, 734, 737, 740, 744, 747, 750, 754, 757, 760, 764, 767, 770,\n\t774, 777, 780, 784, 787, 790, 794, 797, 800, 804, 807, 810, 813, 817,\n\t820, 823, 827, 830, 833, 837, 840, 843, 847, 850, 853, 857, 860, 863,\n\t867, 870, 873, 877, 880, 883, 887, 890, 893, 897, 900, 903, 907, 910,\n\t913, 916, 920, 923, 926, 930, 933, 936, 940, 943, 946, 950, 953, 956,\n\t960, 963, 966, 970, 973, 976, 980, 983, 986, 990, 993, 996, 1000, 1003,\n\t1006, 1009, 1013, 1016, 1019, 1023, 1026, 1029, 1033, 1036, 1039, 1043,\n\t1046, 1049, 1053, 1056, 1059, 1063, 1066, 1069, 1073, 1076\n};", "static diy_fp_t cached_power(int k)\n{\n\tdiy_fp_t res;\n\tint index = 343 + k;\n\tres.f = powers_ten[index];\n\tres.e = powers_ten_e[index];\n\treturn res;\n}", "static int k_comp(int e, int alpha, int gamma) {\n\treturn ceil((alpha-e+63) * D_1_LOG2_10);\n}", "static diy_fp_t minus(diy_fp_t x, diy_fp_t y)\n{\n\tdiy_fp_t r;\n\tassert(x.e == y.e);\n\tassert(x.f >= y.f);\n\tr.f = x.f - y.f;\n\tr.e = x.e;\n\treturn r;\n}", "static diy_fp_t multiply(diy_fp_t x, diy_fp_t y)\n{\n\tuint64_t a,b,c,d,ac,bc,ad,bd,tmp;\n\tdiy_fp_t r;\n\tuint64_t M32 = 0xFFFFFFFF;\n\ta = x.f >> 32; b = x.f & M32;\n\tc = y.f >> 32; d = y.f & M32;\n\tac = a*c; bc = b*c; ad = a*d; bd = b*d;\n\ttmp = (bd>>32) + (ad&M32) + (bc&M32);\n\ttmp += 1U << 31;\n\tr.f = ac+(ad>>32)+(bc>>32)+(tmp >>32);\n\tr.e = x.e + y.e + 64;\n\treturn r;\n}", "static uint64_t double_to_uint64(double d)\n{\n\tuint64_t n;\n\tmemcpy(&n, &d, 8);\n\treturn n;\n}", "#define DP_SIGNIFICAND_SIZE 52\n#define DP_EXPONENT_BIAS (0x3FF + DP_SIGNIFICAND_SIZE)\n#define DP_MIN_EXPONENT (-DP_EXPONENT_BIAS)\n#define DP_EXPONENT_MASK 0x7FF0000000000000\n#define DP_SIGNIFICAND_MASK 0x000FFFFFFFFFFFFF\n#define DP_HIDDEN_BIT 0x0010000000000000", "static diy_fp_t double2diy_fp(double d)\n{\n\tuint64_t d64 = double_to_uint64(d);\n\tint biased_e = (d64 & DP_EXPONENT_MASK) >> DP_SIGNIFICAND_SIZE;\n\tuint64_t significand = (d64 & DP_SIGNIFICAND_MASK);\n\tdiy_fp_t res;\n\tif (biased_e != 0) {\n\t\tres.f = significand + DP_HIDDEN_BIT;\n\t\tres.e = biased_e - DP_EXPONENT_BIAS;\n\t} else {\n\t\tres.f = significand;\n\t\tres.e = DP_MIN_EXPONENT + 1;\n\t}\n\treturn res;\n}", "static diy_fp_t normalize_boundary(diy_fp_t in)\n{\n\tdiy_fp_t res = in;\n\t/* Normalize now */\n\t/* the original number could have been a denormal. */\n\twhile (! (res.f & (DP_HIDDEN_BIT << 1))) {\n\t\tres.f <<= 1;\n\t\tres.e--;\n\t}\n\t/* do the final shifts in one go. Don't forget the hidden bit (the '-1') */\n\tres.f <<= (DIY_SIGNIFICAND_SIZE - DP_SIGNIFICAND_SIZE - 2);\n\tres.e = res.e - (DIY_SIGNIFICAND_SIZE - DP_SIGNIFICAND_SIZE - 2);\n\treturn res;\n}", "static void normalized_boundaries(double d, diy_fp_t* out_m_minus, diy_fp_t* out_m_plus)\n{\n\tdiy_fp_t v = double2diy_fp(d);\n\tdiy_fp_t pl, mi;\n\tint significand_is_zero = v.f == DP_HIDDEN_BIT;\n\tpl.f = (v.f << 1) + 1; pl.e = v.e - 1;\n\tpl = normalize_boundary(pl);\n\tif (significand_is_zero) {\n\t\tmi.f = (v.f << 2) - 1;\n\t\tmi.e = v.e - 2;\n\t} else {\n\t\tmi.f = (v.f << 1) - 1;\n\t\tmi.e = v.e - 1;\n\t}\n\tmi.f <<= mi.e - pl.e;\n\tmi.e = pl.e;\n\t*out_m_plus = pl;\n\t*out_m_minus = mi;\n}", "#define TEN2 100\nstatic void digit_gen(diy_fp_t Mp, diy_fp_t delta, char* buffer, int* len, int* K)\n{\n\tuint32_t div, p1;\n\tuint64_t p2;\n\tint d,kappa;\n\tdiy_fp_t one;\n\tone.f = ((uint64_t) 1) << -Mp.e; one.e = Mp.e;\n\tp1 = Mp.f >> -one.e;\n\tp2 = Mp.f & (one.f - 1);\n\t*len = 0; kappa = 3; div = TEN2;\n\twhile (kappa > 0) {\n\t\td = p1 / div;\n\t\tif (d || *len) buffer[(*len)++] = '0' + d;\n\t\tp1 %= div; kappa--; div /= 10;\n\t\tif ((((uint64_t)p1)<<-one.e)+p2 <= delta.f) {\n\t\t\t*K += kappa; return;\n\t\t}\n\t}\n\tdo {\n\t\tp2 *= 10;\n\t\td = p2 >> -one.e;\n\t\tif (d || *len) buffer[(*len)++] = '0' + d;\n\t\tp2 &= one.f - 1; kappa--; delta.f *= 10;\n\t} while (p2 > delta.f);\n\t*K += kappa;\n}", "int\njs_grisu2(double v, char *buffer, int *K)\n{\n\tint length, mk;\n\tdiy_fp_t w_m, w_p, c_mk, Wp, Wm, delta;\n\tint q = 64, alpha = -59, gamma = -56;\n\tnormalized_boundaries(v, &w_m, &w_p);\n\tmk = k_comp(w_p.e + q, alpha, gamma);\n\tc_mk = cached_power(mk);\n\tWp = multiply(w_p, c_mk);\n\tWm = multiply(w_m, c_mk);\n\tWm.f++; Wp.f--;\n\tdelta = minus(Wp, Wm);\n\t*K = -mk;\n\tdigit_gen(Wp, delta, buffer, &length, K);\n\treturn length;\n}", "/*\n * strtod.c\n *\n * Copyright (c) 1988-1993 The Regents of the University of California.\n * Copyright (c) 1994 Sun Microsystems, Inc.\n *\n * Permission to use, copy, modify, and distribute this software and its\n * documentation for any purpose and without fee is hereby granted, provided\n * that the above copyright notice appear in all copies. The University of\n * California makes no representations about the suitability of this software\n * for any purpose. It is provided \"as is\" without express or implied warranty.\n */", "/* Largest possible base 10 exponent. Any exponent larger than this will\n * already produce underflow or overflow, so there's no need to worry about\n * additional digits.\n */\nstatic int maxExponent = 511;", "/* Table giving binary powers of 10. Entry\n * is 10^2^i. Used to convert decimal\n * exponents into floating-point numbers.\n */\nstatic double powersOf10[] = {\n\t10.,\n\t100.,\n\t1.0e4,\n\t1.0e8,\n\t1.0e16,\n\t1.0e32,\n\t1.0e64,\n\t1.0e128,\n\t1.0e256\n};", "/* Parse a decimal ASCII floating-point number, optionally preceded by white\n * space. Must have form \"-I.FE-X\", where I is the integer part of the\n * mantissa, F is the fractional part of the mantissa, and X is the exponent.\n * Either of the signs may be \"+\", \"-\", or omitted. Either I or F may be\n * omitted, or both. The decimal point isn't necessary unless F is present.\n * The \"E\" may actually be an \"e\". E and X may both be omitted (but not just\n * one).\n */\ndouble\njs_strtod(const char *string, char **endPtr)\n{\n\tint sign, expSign = FALSE;\n\tdouble fraction, dblExp, *d;\n\tregister const char *p;\n\tregister int c;", "\t/* Exponent read from \"EX\" field. */\n\tint exp = 0;", "\t/* Exponent that derives from the fractional part. Under normal\n\t * circumstances, it is the negative of the number of digits in F.\n\t * However, if I is very long, the last digits of I get dropped\n\t * (otherwise a long I with a large negative exponent could cause an\n\t * unnecessary overflow on I alone). In this case, fracExp is\n\t * incremented one for each dropped digit.\n\t */\n\tint fracExp = 0;", "\t/* Number of digits in mantissa. */\n\tint mantSize;", "\t/* Number of mantissa digits BEFORE decimal point. */\n\tint decPt;", "\t/* Temporarily holds location of exponent in string. */\n\tconst char *pExp;", "\t/*\n\t * Strip off leading blanks and check for a sign.\n\t */", "\tp = string;\n\twhile (*p == ' ' || *p == '\\t' || *p == '\\n' || *p == '\\r') {\n\t\tp += 1;\n\t}\n\tif (*p == '-') {\n\t\tsign = TRUE;\n\t\tp += 1;\n\t} else {\n\t\tif (*p == '+') {\n\t\t\tp += 1;\n\t\t}\n\t\tsign = FALSE;\n\t}", "\t/*\n\t * Count the number of digits in the mantissa (including the decimal\n\t * point), and also locate the decimal point.\n\t */", "\tdecPt = -1;\n\tfor (mantSize = 0; ; mantSize += 1)\n\t{\n\t\tc = *p;\n\t\tif (!(c>='0'&&c<='9')) {\n\t\t\tif ((c != '.') || (decPt >= 0)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdecPt = mantSize;\n\t\t}\n\t\tp += 1;\n\t}", "\t/*\n\t * Now suck up the digits in the mantissa. Use two integers to\n\t * collect 9 digits each (this is faster than using floating-point).\n\t * If the mantissa has more than 18 digits, ignore the extras, since\n\t * they can't affect the value anyway.\n\t */", "\tpExp = p;\n\tp -= mantSize;\n\tif (decPt < 0) {\n\t\tdecPt = mantSize;\n\t} else {\n\t\tmantSize -= 1;\t\t\t/* One of the digits was the point. */\n\t}\n\tif (mantSize > 18) {\n\t\tfracExp = decPt - 18;\n\t\tmantSize = 18;\n\t} else {\n\t\tfracExp = decPt - mantSize;\n\t}\n\tif (mantSize == 0) {\n\t\tfraction = 0.0;\n\t\tp = string;\n\t\tgoto done;\n\t} else {\n\t\tint frac1, frac2;\n\t\tfrac1 = 0;\n\t\tfor ( ; mantSize > 9; mantSize -= 1)\n\t\t{\n\t\t\tc = *p;\n\t\t\tp += 1;\n\t\t\tif (c == '.') {\n\t\t\t\tc = *p;\n\t\t\t\tp += 1;\n\t\t\t}\n\t\t\tfrac1 = 10*frac1 + (c - '0');\n\t\t}\n\t\tfrac2 = 0;\n\t\tfor (; mantSize > 0; mantSize -= 1)\n\t\t{\n\t\t\tc = *p;\n\t\t\tp += 1;\n\t\t\tif (c == '.') {\n\t\t\t\tc = *p;\n\t\t\t\tp += 1;\n\t\t\t}\n\t\t\tfrac2 = 10*frac2 + (c - '0');\n\t\t}\n\t\tfraction = (1.0e9 * frac1) + frac2;\n\t}", "\t/*\n\t * Skim off the exponent.\n\t */", "\tp = pExp;\n\tif ((*p == 'E') || (*p == 'e')) {\n\t\tp += 1;\n\t\tif (*p == '-') {\n\t\t\texpSign = TRUE;\n\t\t\tp += 1;\n\t\t} else {\n\t\t\tif (*p == '+') {\n\t\t\t\tp += 1;\n\t\t\t}\n\t\t\texpSign = FALSE;\n\t\t}", "\t\twhile ((*p >= '0') && (*p <= '9') && exp < INT_MAX/10) {", "\t\t\texp = exp * 10 + (*p - '0');\n\t\t\tp += 1;\n\t\t}", "\t\twhile ((*p >= '0') && (*p <= '9'))\n\t\t\tp += 1;", "\t}\n\tif (expSign) {\n\t\texp = fracExp - exp;\n\t} else {\n\t\texp = fracExp + exp;\n\t}", "\t/*\n\t * Generate a floating-point number that represents the exponent.\n\t * Do this by processing the exponent one bit at a time to combine\n\t * many powers of 2 of 10. Then combine the exponent with the\n\t * fraction.\n\t */", "\tif (exp < -maxExponent) {\n\t\texp = maxExponent;\n\t\texpSign = TRUE;\n\t\terrno = ERANGE;\n\t} else if (exp > maxExponent) {\n\t\texp = maxExponent;\n\t\texpSign = FALSE;\n\t\terrno = ERANGE;\n\t} else if (exp < 0) {\n\t\texpSign = TRUE;\n\t\texp = -exp;\n\t} else {\n\t\texpSign = FALSE;\n\t}\n\tdblExp = 1.0;\n\tfor (d = powersOf10; exp != 0; exp >>= 1, d += 1) {\n\t\tif (exp & 01) {\n\t\t\tdblExp *= *d;\n\t\t}\n\t}\n\tif (expSign) {\n\t\tfraction /= dblExp;\n\t} else {\n\t\tfraction *= dblExp;\n\t}", "done:\n\tif (endPtr != NULL) {\n\t\t*endPtr = (char *) p;\n\t}", "\tif (sign) {\n\t\treturn -fraction;\n\t}\n\treturn fraction;\n}" ]
[ 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 ]
PreciseBugs
{"buggy_code_end_loc": [697], "buggy_code_start_loc": [694], "filenames": ["jsdtoa.c"], "fixing_code_end_loc": [700], "fixing_code_start_loc": [694], "message": "Buffer-overflow in jsdtoa.c in Artifex MuJS in versions 1.0.1 to 1.1.1. An integer overflow happens when js_strtod() reads in floating point exponent, which leads to a buffer overflow in the pointer *d.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:artifex:mujs:*:*:*:*:*:*:*:*", "matchCriteriaId": "2D9B97C7-3BAD-48CC-85A1-58BAFDF16DF8", "versionEndExcluding": null, "versionEndIncluding": "1.1.1", "versionStartExcluding": null, "versionStartIncluding": "1.0.1", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Buffer-overflow in jsdtoa.c in Artifex MuJS in versions 1.0.1 to 1.1.1. An integer overflow happens when js_strtod() reads in floating point exponent, which leads to a buffer overflow in the pointer *d."}], "evaluatorComment": null, "id": "CVE-2021-33797", "lastModified": "2023-04-26T23:05:05.003", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-17T22:15:07.677", "references": [{"source": "patrick@puiterwijk.org", "tags": ["Patch"], "url": "https://github.com/ccxvii/mujs/commit/833b6f1672b4f2991a63c4d05318f0b84ef4d550"}, {"source": "patrick@puiterwijk.org", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://github.com/ccxvii/mujs/issues/148"}], "sourceIdentifier": "patrick@puiterwijk.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-190"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-119"}], "source": "patrick@puiterwijk.org", "type": "Secondary"}]}, "github_commit_url": "https://github.com/ccxvii/mujs/commit/833b6f1672b4f2991a63c4d05318f0b84ef4d550"}, "type": "CWE-190"}
174
Determine whether the {function_name} code is vulnerable or not.
[ "/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/* kdc/do_tgs_req.c - KDC Routines to deal with TGS_REQ's */\n/*\n * Copyright 1990,1991,2001,2007,2008,2009 by the Massachusetts Institute of Technology.\n * All Rights Reserved.\n *\n * Export of this software from the United States of America may\n * require a specific license from the United States Government.\n * It is the responsibility of any person or organization contemplating\n * export to obtain such a license before exporting.\n *\n * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and\n * distribute this software and its documentation for any purpose and\n * without fee is hereby granted, provided that the above copyright\n * notice appear in all copies and that both that copyright notice and\n * this permission notice appear in supporting documentation, and that\n * the name of M.I.T. not be used in advertising or publicity pertaining\n * to distribution of the software without specific, written prior\n * permission. Furthermore if you modify this software you must label\n * your software as modified software and not distribute it in such a\n * fashion that it might be confused with the original M.I.T. software.\n * M.I.T. makes no representations about the suitability of\n * this software for any purpose. It is provided \"as is\" without express\n * or implied warranty.\n */\n/*\n * Copyright (c) 2006-2008, Novell, Inc.\n * 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 are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * * The copyright holder's name is not used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */", "#include \"k5-int.h\"", "#include <syslog.h>\n#ifdef HAVE_NETINET_IN_H\n#include <sys/types.h>\n#include <netinet/in.h>\n#ifndef hpux\n#include <arpa/inet.h>\n#endif\n#endif", "#include \"kdc_util.h\"\n#include \"policy.h\"\n#include \"extern.h\"\n#include \"adm_proto.h\"\n#include <ctype.h>", "static krb5_error_code\nfind_alternate_tgs(krb5_kdc_req *,krb5_db_entry **);", "static krb5_error_code\nprepare_error_tgs(struct kdc_request_state *, krb5_kdc_req *,krb5_ticket *,int,\n krb5_principal,krb5_data **,const char *, krb5_pa_data **);", "static krb5_int32\nprep_reprocess_req(krb5_kdc_req *,krb5_principal *);", "/*ARGSUSED*/\nkrb5_error_code\nprocess_tgs_req(krb5_data *pkt, const krb5_fulladdr *from,\n krb5_data **response)\n{\n krb5_keyblock * subkey = 0;\n krb5_keyblock * tgskey = 0;\n krb5_kdc_req *request = 0;\n krb5_db_entry *server = NULL;\n krb5_kdc_rep reply;\n krb5_enc_kdc_rep_part reply_encpart;\n krb5_ticket ticket_reply, *header_ticket = 0;\n int st_idx = 0;\n krb5_enc_tkt_part enc_tkt_reply;\n krb5_transited enc_tkt_transited;\n int newtransited = 0;\n krb5_error_code retval = 0;\n krb5_keyblock encrypting_key;\n krb5_timestamp kdc_time, authtime = 0;\n krb5_keyblock session_key;\n krb5_timestamp rtime;\n krb5_keyblock *reply_key = NULL;\n krb5_key_data *server_key;\n char *cname = 0, *sname = 0, *altcname = 0;\n krb5_last_req_entry *nolrarray[2], nolrentry;\n krb5_enctype useenctype;\n int errcode, errcode2;\n register int i;\n int firstpass = 1;\n const char *status = 0;\n krb5_enc_tkt_part *header_enc_tkt = NULL; /* TGT */\n krb5_enc_tkt_part *subject_tkt = NULL; /* TGT or evidence ticket */\n krb5_db_entry *client = NULL, *krbtgt = NULL;\n krb5_pa_s4u_x509_user *s4u_x509_user = NULL; /* protocol transition request */\n krb5_authdata **kdc_issued_auth_data = NULL; /* auth data issued by KDC */\n unsigned int c_flags = 0, s_flags = 0; /* client/server KDB flags */\n char *s4u_name = NULL;\n krb5_boolean is_referral, db_ref_done = FALSE;\n const char *emsg = NULL;\n krb5_data *tgs_1 =NULL, *server_1 = NULL;\n krb5_principal krbtgt_princ;\n krb5_kvno ticket_kvno = 0;\n struct kdc_request_state *state = NULL;\n krb5_pa_data *pa_tgs_req; /*points into request*/\n krb5_data scratch;\n krb5_pa_data **e_data = NULL;", " reply.padata = 0; /* For cleanup handler */\n reply_encpart.enc_padata = 0;\n enc_tkt_reply.authorization_data = NULL;", " session_key.contents = NULL;", " retval = decode_krb5_tgs_req(pkt, &request);\n if (retval)\n return retval;\n if (request->msg_type != KRB5_TGS_REQ) {\n krb5_free_kdc_req(kdc_context, request);\n return KRB5_BADMSGTYPE;\n }", " /*\n * setup_server_realm() sets up the global realm-specific data pointer.\n */\n if ((retval = setup_server_realm(request->server))) {\n krb5_free_kdc_req(kdc_context, request);\n return retval;\n }\n errcode = kdc_process_tgs_req(request, from, pkt, &header_ticket,\n &krbtgt, &tgskey, &subkey, &pa_tgs_req);\n if (header_ticket && header_ticket->enc_part2 &&\n (errcode2 = krb5_unparse_name(kdc_context,\n header_ticket->enc_part2->client,\n &cname))) {\n status = \"UNPARSING CLIENT\";\n errcode = errcode2;\n goto cleanup;\n }\n limit_string(cname);", " if (errcode) {\n status = \"PROCESS_TGS\";\n goto cleanup;\n }", " if (!header_ticket) {\n errcode = KRB5_NO_TKT_SUPPLIED; /* XXX? */\n status=\"UNEXPECTED NULL in header_ticket\";\n goto cleanup;\n }\n errcode = kdc_make_rstate(&state);\n if (errcode !=0) {\n status = \"making state\";\n goto cleanup;\n }\n scratch.length = pa_tgs_req->length;\n scratch.data = (char *) pa_tgs_req->contents;\n errcode = kdc_find_fast(&request, &scratch, subkey,\n header_ticket->enc_part2->session, state, NULL);\n if (errcode !=0) {\n status = \"kdc_find_fast\";\n goto cleanup;\n }", " /*\n * Pointer to the encrypted part of the header ticket, which may be\n * replaced to point to the encrypted part of the evidence ticket\n * if constrained delegation is used. This simplifies the number of\n * special cases for constrained delegation.\n */\n header_enc_tkt = header_ticket->enc_part2;", " /*\n * We've already dealt with the AP_REQ authentication, so we can\n * use header_ticket freely. The encrypted part (if any) has been\n * decrypted with the session key.\n */", " /* XXX make sure server here has the proper realm...taken from AP_REQ\n header? */", " setflag(s_flags, KRB5_KDB_FLAG_ALIAS_OK);\n if (isflagset(request->kdc_options, KDC_OPT_CANONICALIZE)) {\n setflag(c_flags, KRB5_KDB_FLAG_CANONICALIZE);\n setflag(s_flags, KRB5_KDB_FLAG_CANONICALIZE);\n }", " db_ref_done = FALSE;\nref_tgt_again:\n if ((errcode = krb5_unparse_name(kdc_context, request->server, &sname))) {\n status = \"UNPARSING SERVER\";\n goto cleanup;\n }\n limit_string(sname);", " errcode = krb5_db_get_principal(kdc_context, request->server,\n s_flags, &server);\n if (errcode && errcode != KRB5_KDB_NOENTRY) {\n status = \"LOOKING_UP_SERVER\";\n goto cleanup;\n }\ntgt_again:\n if (errcode == KRB5_KDB_NOENTRY) {\n /*\n * might be a request for a TGT for some other realm; we\n * should do our best to find such a TGS in this db\n */\n if (firstpass ) {", " if ( krb5_is_tgs_principal(request->server) == TRUE) {\n /* Principal is a name of krb ticket service */\n if (krb5_princ_size(kdc_context, request->server) == 2) {", " server_1 = krb5_princ_component(kdc_context,\n request->server, 1);\n tgs_1 = krb5_princ_component(kdc_context, tgs_server, 1);", " if (!tgs_1 || !data_eq(*server_1, *tgs_1)) {\n errcode = find_alternate_tgs(request, &server);\n firstpass = 0;\n if (errcode == 0)\n goto tgt_again;\n }\n }\n status = \"UNKNOWN_SERVER\";\n errcode = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n goto cleanup;", " } else if ( db_ref_done == FALSE) {\n retval = prep_reprocess_req(request, &krbtgt_princ);\n if (!retval) {\n krb5_free_principal(kdc_context, request->server);\n retval = krb5_copy_principal(kdc_context, krbtgt_princ,\n &(request->server));\n if (!retval) {\n db_ref_done = TRUE;\n if (sname != NULL)\n free(sname);\n goto ref_tgt_again;\n }\n }\n }\n }", " status = \"UNKNOWN_SERVER\";\n errcode = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n goto cleanup;\n }", " if ((errcode = krb5_timeofday(kdc_context, &kdc_time))) {\n status = \"TIME_OF_DAY\";\n goto cleanup;\n }", " if ((retval = validate_tgs_request(request, *server, header_ticket,\n kdc_time, &status, &e_data))) {\n if (!status)\n status = \"UNKNOWN_REASON\";\n errcode = retval + ERROR_TABLE_BASE_krb5;\n goto cleanup;\n }", " if (!is_local_principal(header_enc_tkt->client))\n setflag(c_flags, KRB5_KDB_FLAG_CROSS_REALM);", " is_referral = krb5_is_tgs_principal(server->princ) &&\n !krb5_principal_compare(kdc_context, tgs_server, server->princ);", " /* Check for protocol transition */\n errcode = kdc_process_s4u2self_req(kdc_context,\n request,\n header_enc_tkt->client,\n server,\n subkey,\n header_enc_tkt->session,\n kdc_time,\n &s4u_x509_user,\n &client,\n &status);\n if (errcode)\n goto cleanup;\n if (s4u_x509_user != NULL)\n setflag(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION);", " /*\n * We pick the session keytype here....\n *\n * Some special care needs to be taken in the user-to-user\n * case, since we don't know what keytypes the application server\n * which is doing user-to-user authentication can support. We\n * know that it at least must be able to support the encryption\n * type of the session key in the TGT, since otherwise it won't be\n * able to decrypt the U2U ticket! So we use that in preference\n * to anything else.\n */\n useenctype = 0;\n if (isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY |\n KDC_OPT_CNAME_IN_ADDL_TKT)) {\n krb5_keyblock * st_sealing_key;\n krb5_kvno st_srv_kvno;\n krb5_enctype etype;\n krb5_db_entry *st_client;", " /*\n * Get the key for the second ticket, and decrypt it.\n */\n if ((errcode = kdc_get_server_key(request->second_ticket[st_idx],\n c_flags,\n TRUE, /* match_enctype */\n &st_client,\n &st_sealing_key,\n &st_srv_kvno))) {\n status = \"2ND_TKT_SERVER\";\n goto cleanup;\n }\n errcode = krb5_decrypt_tkt_part(kdc_context, st_sealing_key,\n request->second_ticket[st_idx]);\n krb5_free_keyblock(kdc_context, st_sealing_key);\n if (errcode) {\n status = \"2ND_TKT_DECRYPT\";\n krb5_db_free_principal(kdc_context, st_client);\n goto cleanup;\n }", " etype = request->second_ticket[st_idx]->enc_part2->session->enctype;\n if (!krb5_c_valid_enctype(etype)) {\n status = \"BAD_ETYPE_IN_2ND_TKT\";\n errcode = KRB5KDC_ERR_ETYPE_NOSUPP;\n krb5_db_free_principal(kdc_context, st_client);\n goto cleanup;\n }", " for (i = 0; i < request->nktypes; i++) {\n if (request->ktype[i] == etype) {\n useenctype = etype;\n break;\n }\n }", " if (isflagset(request->kdc_options, KDC_OPT_CNAME_IN_ADDL_TKT)) {\n /* Do constrained delegation protocol and authorization checks */\n errcode = kdc_process_s4u2proxy_req(kdc_context,\n request,\n request->second_ticket[st_idx]->enc_part2,\n st_client,\n header_ticket->enc_part2->client,\n request->server,\n &status);\n if (errcode)\n goto cleanup;", " setflag(c_flags, KRB5_KDB_FLAG_CONSTRAINED_DELEGATION);", " assert(krb5_is_tgs_principal(header_ticket->server));", " assert(client == NULL); /* assured by kdc_process_s4u2self_req() */\n client = st_client;\n } else {\n /* \"client\" is not used for user2user */\n krb5_db_free_principal(kdc_context, st_client);\n }\n }", " /*\n * Select the keytype for the ticket session key.\n */\n if ((useenctype == 0) &&\n (useenctype = select_session_keytype(kdc_context, server,\n request->nktypes,\n request->ktype)) == 0) {\n /* unsupported ktype */\n status = \"BAD_ENCRYPTION_TYPE\";\n errcode = KRB5KDC_ERR_ETYPE_NOSUPP;\n goto cleanup;\n }", " errcode = krb5_c_make_random_key(kdc_context, useenctype, &session_key);", " if (errcode) {\n /* random key failed */\n status = \"RANDOM_KEY_FAILED\";\n goto cleanup;\n }", " /*\n * subject_tkt will refer to the evidence ticket (for constrained\n * delegation) or the TGT. The distinction from header_enc_tkt is\n * necessary because the TGS signature only protects some fields:\n * the others could be forged by a malicious server.\n */", " if (isflagset(c_flags, KRB5_KDB_FLAG_CONSTRAINED_DELEGATION))\n subject_tkt = request->second_ticket[st_idx]->enc_part2;\n else\n subject_tkt = header_enc_tkt;\n authtime = subject_tkt->times.authtime;", " if (is_referral)\n ticket_reply.server = server->princ;\n else\n ticket_reply.server = request->server; /* XXX careful for realm... */", " enc_tkt_reply.flags = 0;\n enc_tkt_reply.times.starttime = 0;", " if (isflagset(server->attributes, KRB5_KDB_OK_AS_DELEGATE))\n setflag(enc_tkt_reply.flags, TKT_FLG_OK_AS_DELEGATE);", " /*\n * Fix header_ticket's starttime; if it's zero, fill in the\n * authtime's value.\n */\n if (!(header_enc_tkt->times.starttime))\n header_enc_tkt->times.starttime = authtime;\n setflag(enc_tkt_reply.flags, TKT_FLG_ENC_PA_REP);", " /* don't use new addresses unless forwarded, see below */", " enc_tkt_reply.caddrs = header_enc_tkt->caddrs;\n /* noaddrarray[0] = 0; */\n reply_encpart.caddrs = 0;/* optional...don't put it in */\n reply_encpart.enc_padata = NULL;", " /*\n * It should be noted that local policy may affect the\n * processing of any of these flags. For example, some\n * realms may refuse to issue renewable tickets\n */", " if (isflagset(request->kdc_options, KDC_OPT_FORWARDABLE)) {\n setflag(enc_tkt_reply.flags, TKT_FLG_FORWARDABLE);", " if (isflagset(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION)) {\n /*\n * If S4U2Self principal is not forwardable, then mark ticket as\n * unforwardable. This behaviour matches Windows, but it is\n * different to the MIT AS-REQ path, which returns an error\n * (KDC_ERR_POLICY) if forwardable tickets cannot be issued.\n *\n * Consider this block the S4U2Self equivalent to\n * validate_forwardable().\n */\n if (client != NULL &&\n isflagset(client->attributes, KRB5_KDB_DISALLOW_FORWARDABLE))\n clear(enc_tkt_reply.flags, TKT_FLG_FORWARDABLE);\n /*\n * Forwardable flag is propagated along referral path.\n */\n else if (!isflagset(header_enc_tkt->flags, TKT_FLG_FORWARDABLE))\n clear(enc_tkt_reply.flags, TKT_FLG_FORWARDABLE);\n /*\n * OK_TO_AUTH_AS_DELEGATE must be set on the service requesting\n * S4U2Self in order for forwardable tickets to be returned.\n */\n else if (!is_referral &&\n !isflagset(server->attributes,\n KRB5_KDB_OK_TO_AUTH_AS_DELEGATE))\n clear(enc_tkt_reply.flags, TKT_FLG_FORWARDABLE);\n }\n }", " if (isflagset(request->kdc_options, KDC_OPT_FORWARDED)) {\n setflag(enc_tkt_reply.flags, TKT_FLG_FORWARDED);", " /* include new addresses in ticket & reply */", " enc_tkt_reply.caddrs = request->addresses;\n reply_encpart.caddrs = request->addresses;\n }\n if (isflagset(header_enc_tkt->flags, TKT_FLG_FORWARDED))\n setflag(enc_tkt_reply.flags, TKT_FLG_FORWARDED);", " if (isflagset(request->kdc_options, KDC_OPT_PROXIABLE))\n setflag(enc_tkt_reply.flags, TKT_FLG_PROXIABLE);", " if (isflagset(request->kdc_options, KDC_OPT_PROXY)) {\n setflag(enc_tkt_reply.flags, TKT_FLG_PROXY);", " /* include new addresses in ticket & reply */", " enc_tkt_reply.caddrs = request->addresses;\n reply_encpart.caddrs = request->addresses;\n }", " if (isflagset(request->kdc_options, KDC_OPT_ALLOW_POSTDATE))\n setflag(enc_tkt_reply.flags, TKT_FLG_MAY_POSTDATE);", " if (isflagset(request->kdc_options, KDC_OPT_POSTDATED)) {\n setflag(enc_tkt_reply.flags, TKT_FLG_POSTDATED);\n setflag(enc_tkt_reply.flags, TKT_FLG_INVALID);\n enc_tkt_reply.times.starttime = request->from;\n } else\n enc_tkt_reply.times.starttime = kdc_time;", " if (isflagset(request->kdc_options, KDC_OPT_VALIDATE)) {\n assert(isflagset(c_flags, KRB5_KDB_FLAGS_S4U) == 0);\n /* BEWARE of allocation hanging off of ticket & enc_part2, it belongs\n to the caller */\n ticket_reply = *(header_ticket);\n enc_tkt_reply = *(header_ticket->enc_part2);\n enc_tkt_reply.authorization_data = NULL;\n clear(enc_tkt_reply.flags, TKT_FLG_INVALID);\n }", " if (isflagset(request->kdc_options, KDC_OPT_RENEW)) {\n krb5_deltat old_life;", " assert(isflagset(c_flags, KRB5_KDB_FLAGS_S4U) == 0);\n /* BEWARE of allocation hanging off of ticket & enc_part2, it belongs\n to the caller */\n ticket_reply = *(header_ticket);\n enc_tkt_reply = *(header_ticket->enc_part2);\n enc_tkt_reply.authorization_data = NULL;", " old_life = enc_tkt_reply.times.endtime - enc_tkt_reply.times.starttime;", " enc_tkt_reply.times.starttime = kdc_time;\n enc_tkt_reply.times.endtime =\n min(header_ticket->enc_part2->times.renew_till,\n kdc_time + old_life);\n } else {\n /* not a renew request */\n enc_tkt_reply.times.starttime = kdc_time;", " kdc_get_ticket_endtime(kdc_context, enc_tkt_reply.times.starttime,\n header_enc_tkt->times.endtime, request->till,\n client, server, &enc_tkt_reply.times.endtime);", " if (isflagset(request->kdc_options, KDC_OPT_RENEWABLE_OK) &&\n (enc_tkt_reply.times.endtime < request->till) &&\n isflagset(header_enc_tkt->flags, TKT_FLG_RENEWABLE)) {\n setflag(request->kdc_options, KDC_OPT_RENEWABLE);\n request->rtime =\n min(request->till, header_enc_tkt->times.renew_till);\n }\n }\n rtime = (request->rtime == 0) ? kdc_infinity : request->rtime;", " if (isflagset(request->kdc_options, KDC_OPT_RENEWABLE)) {\n /* already checked above in policy check to reject request for a\n renewable ticket using a non-renewable ticket */\n setflag(enc_tkt_reply.flags, TKT_FLG_RENEWABLE);\n enc_tkt_reply.times.renew_till =\n min(rtime,\n min(header_enc_tkt->times.renew_till,\n enc_tkt_reply.times.starttime +\n min(server->max_renewable_life,\n max_renewable_life_for_realm)));\n } else {\n enc_tkt_reply.times.renew_till = 0;\n }\n if (isflagset(header_enc_tkt->flags, TKT_FLG_ANONYMOUS))\n setflag(enc_tkt_reply.flags, TKT_FLG_ANONYMOUS);\n /*\n * Set authtime to be the same as header or evidence ticket's\n */\n enc_tkt_reply.times.authtime = authtime;", " /*\n * Propagate the preauthentication flags through to the returned ticket.\n */\n if (isflagset(header_enc_tkt->flags, TKT_FLG_PRE_AUTH))\n setflag(enc_tkt_reply.flags, TKT_FLG_PRE_AUTH);", " if (isflagset(header_enc_tkt->flags, TKT_FLG_HW_AUTH))\n setflag(enc_tkt_reply.flags, TKT_FLG_HW_AUTH);", " /* starttime is optional, and treated as authtime if not present.\n so we can nuke it if it matches */\n if (enc_tkt_reply.times.starttime == enc_tkt_reply.times.authtime)\n enc_tkt_reply.times.starttime = 0;", " if (isflagset(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION)) {\n errcode = krb5_unparse_name(kdc_context, s4u_x509_user->user_id.user,\n &s4u_name);\n } else if (isflagset(c_flags, KRB5_KDB_FLAG_CONSTRAINED_DELEGATION)) {\n errcode = krb5_unparse_name(kdc_context, subject_tkt->client,\n &s4u_name);\n } else {\n errcode = 0;\n }\n if (errcode) {\n status = \"UNPARSING S4U CLIENT\";\n goto cleanup;\n }", " if (isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY)) {\n krb5_enc_tkt_part *t2enc = request->second_ticket[st_idx]->enc_part2;\n encrypting_key = *(t2enc->session);\n } else {\n /*\n * Find the server key\n */\n if ((errcode = krb5_dbe_find_enctype(kdc_context, server,\n -1, /* ignore keytype */\n -1, /* Ignore salttype */\n 0, /* Get highest kvno */\n &server_key))) {\n status = \"FINDING_SERVER_KEY\";\n goto cleanup;\n }", " /*\n * Convert server.key into a real key\n * (it may be encrypted in the database)\n */\n if ((errcode = krb5_dbe_decrypt_key_data(kdc_context, NULL,\n server_key, &encrypting_key,\n NULL))) {\n status = \"DECRYPT_SERVER_KEY\";\n goto cleanup;\n }\n }", " if (isflagset(c_flags, KRB5_KDB_FLAG_CONSTRAINED_DELEGATION)) {\n /*\n * Don't allow authorization data to be disabled if constrained\n * delegation is requested. We don't want to deny the server\n * the ability to validate that delegation was used.\n */\n clear(server->attributes, KRB5_KDB_NO_AUTH_DATA_REQUIRED);\n }\n if (isflagset(server->attributes, KRB5_KDB_NO_AUTH_DATA_REQUIRED) == 0) {\n /*\n * If we are not doing protocol transition/constrained delegation\n * try to lookup the client principal so plugins can add additional\n * authorization information.\n *\n * Always validate authorization data for constrained delegation\n * because we must validate the KDC signatures.\n */\n if (!isflagset(c_flags, KRB5_KDB_FLAGS_S4U)) {\n /* Generate authorization data so we can include it in ticket */\n setflag(c_flags, KRB5_KDB_FLAG_INCLUDE_PAC);\n /* Map principals from foreign (possibly non-AD) realms */\n setflag(c_flags, KRB5_KDB_FLAG_MAP_PRINCIPALS);", " assert(client == NULL); /* should not have been set already */", " errcode = krb5_db_get_principal(kdc_context, subject_tkt->client,\n c_flags, &client);\n }\n }", " if (isflagset(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION) &&\n !isflagset(c_flags, KRB5_KDB_FLAG_CROSS_REALM))\n enc_tkt_reply.client = s4u_x509_user->user_id.user;\n else\n enc_tkt_reply.client = subject_tkt->client;", " enc_tkt_reply.session = &session_key;\n enc_tkt_reply.transited.tr_type = KRB5_DOMAIN_X500_COMPRESS;\n enc_tkt_reply.transited.tr_contents = empty_string; /* equivalent of \"\" */", " errcode = handle_authdata(kdc_context, c_flags, client, server, krbtgt,\n subkey != NULL ? subkey :\n header_ticket->enc_part2->session,\n &encrypting_key, /* U2U or server key */\n tgskey,\n pkt,\n request,\n s4u_x509_user ?\n s4u_x509_user->user_id.user : NULL,\n subject_tkt,\n &enc_tkt_reply);\n if (errcode) {\n krb5_klog_syslog(LOG_INFO, _(\"TGS_REQ : handle_authdata (%d)\"),\n errcode);\n status = \"HANDLE_AUTHDATA\";\n goto cleanup;\n }", "\n /*\n * Only add the realm of the presented tgt to the transited list if\n * it is different than the local realm (cross-realm) and it is different\n * than the realm of the client (since the realm of the client is already\n * implicitly part of the transited list and should not be explicitly\n * listed).\n */\n /* realm compare is like strcmp, but knows how to deal with these args */\n if (realm_compare(header_ticket->server, tgs_server) ||\n realm_compare(header_ticket->server, enc_tkt_reply.client)) {\n /* tgt issued by local realm or issued by realm of client */\n enc_tkt_reply.transited = header_enc_tkt->transited;\n } else {\n /* tgt issued by some other realm and not the realm of the client */\n /* assemble new transited field into allocated storage */\n if (header_enc_tkt->transited.tr_type !=\n KRB5_DOMAIN_X500_COMPRESS) {\n status = \"BAD_TRTYPE\";\n errcode = KRB5KDC_ERR_TRTYPE_NOSUPP;\n goto cleanup;\n }\n enc_tkt_transited.tr_type = KRB5_DOMAIN_X500_COMPRESS;\n enc_tkt_transited.magic = 0;\n enc_tkt_transited.tr_contents.magic = 0;\n enc_tkt_transited.tr_contents.data = 0;\n enc_tkt_transited.tr_contents.length = 0;\n enc_tkt_reply.transited = enc_tkt_transited;\n if ((errcode =\n add_to_transited(&header_enc_tkt->transited.tr_contents,\n &enc_tkt_reply.transited.tr_contents,\n header_ticket->server,\n enc_tkt_reply.client,\n request->server))) {\n status = \"ADD_TR_FAIL\";\n goto cleanup;\n }\n newtransited = 1;\n }\n if (isflagset(c_flags, KRB5_KDB_FLAG_CROSS_REALM)) {\n errcode = validate_transit_path(kdc_context, header_enc_tkt->client,\n server, krbtgt);\n if (errcode) {\n status = \"NON_TRANSITIVE\";\n goto cleanup;\n }\n }\n if (!isflagset (request->kdc_options, KDC_OPT_DISABLE_TRANSITED_CHECK)) {\n unsigned int tlen;\n char *tdots;", " errcode = kdc_check_transited_list (kdc_context,\n &enc_tkt_reply.transited.tr_contents,\n krb5_princ_realm (kdc_context, header_enc_tkt->client),\n krb5_princ_realm (kdc_context, request->server));\n tlen = enc_tkt_reply.transited.tr_contents.length;\n tdots = tlen > 125 ? \"...\" : \"\";\n tlen = tlen > 125 ? 125 : tlen;", " if (errcode == 0) {\n setflag (enc_tkt_reply.flags, TKT_FLG_TRANSIT_POLICY_CHECKED);\n } else if (errcode == KRB5KRB_AP_ERR_ILL_CR_TKT)\n krb5_klog_syslog(LOG_INFO, _(\"bad realm transit path from '%s' \"\n \"to '%s' via '%.*s%s'\"),\n cname ? cname : \"<unknown client>\",\n sname ? sname : \"<unknown server>\", tlen,\n enc_tkt_reply.transited.tr_contents.data, tdots);\n else {\n emsg = krb5_get_error_message(kdc_context, errcode);\n krb5_klog_syslog(LOG_ERR, _(\"unexpected error checking transit \"\n \"from '%s' to '%s' via '%.*s%s': %s\"),\n cname ? cname : \"<unknown client>\",\n sname ? sname : \"<unknown server>\", tlen,\n enc_tkt_reply.transited.tr_contents.data, tdots,\n emsg);\n krb5_free_error_message(kdc_context, emsg);\n emsg = NULL;\n }\n } else\n krb5_klog_syslog(LOG_INFO, _(\"not checking transit path\"));\n if (reject_bad_transit\n && !isflagset (enc_tkt_reply.flags, TKT_FLG_TRANSIT_POLICY_CHECKED)) {\n errcode = KRB5KDC_ERR_POLICY;\n status = \"BAD_TRANSIT\";\n goto cleanup;\n }", " ticket_reply.enc_part2 = &enc_tkt_reply;", " /*\n * If we are doing user-to-user authentication, then make sure\n * that the client for the second ticket matches the request\n * server, and then encrypt the ticket using the session key of\n * the second ticket.\n */\n if (isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY)) {\n /*\n * Make sure the client for the second ticket matches\n * requested server.\n */\n krb5_enc_tkt_part *t2enc = request->second_ticket[st_idx]->enc_part2;\n krb5_principal client2 = t2enc->client;\n if (!krb5_principal_compare(kdc_context, request->server, client2)) {\n if ((errcode = krb5_unparse_name(kdc_context, client2, &altcname)))\n altcname = 0;\n if (altcname != NULL)\n limit_string(altcname);", " errcode = KRB5KDC_ERR_SERVER_NOMATCH;\n status = \"2ND_TKT_MISMATCH\";\n goto cleanup;\n }", " ticket_kvno = 0;\n ticket_reply.enc_part.enctype = t2enc->session->enctype;\n st_idx++;\n } else {\n ticket_kvno = server_key->key_data_kvno;\n }", " errcode = krb5_encrypt_tkt_part(kdc_context, &encrypting_key,\n &ticket_reply);\n if (!isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY))\n krb5_free_keyblock_contents(kdc_context, &encrypting_key);\n if (errcode) {\n status = \"TKT_ENCRYPT\";\n goto cleanup;\n }\n ticket_reply.enc_part.kvno = ticket_kvno;\n /* Start assembling the response */\n reply.msg_type = KRB5_TGS_REP;\n if (isflagset(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION) &&\n find_pa_data(request->padata, KRB5_PADATA_S4U_X509_USER) != NULL) {\n errcode = kdc_make_s4u2self_rep(kdc_context,\n subkey,\n header_ticket->enc_part2->session,\n s4u_x509_user,\n &reply,\n &reply_encpart);\n if (errcode) {\n status = \"KDC_RETURN_S4U2SELF_PADATA\";\n goto cleanup;\n }\n }", " reply.client = enc_tkt_reply.client;\n reply.enc_part.kvno = 0;/* We are using the session key */\n reply.ticket = &ticket_reply;", " reply_encpart.session = &session_key;\n reply_encpart.nonce = request->nonce;", " /* copy the time fields */\n reply_encpart.times = enc_tkt_reply.times;", " /* starttime is optional, and treated as authtime if not present.\n so we can nuke it if it matches */\n if (enc_tkt_reply.times.starttime == enc_tkt_reply.times.authtime)\n enc_tkt_reply.times.starttime = 0;", " nolrentry.lr_type = KRB5_LRQ_NONE;\n nolrentry.value = 0;\n nolrarray[0] = &nolrentry;\n nolrarray[1] = 0;\n reply_encpart.last_req = nolrarray; /* not available for TGS reqs */\n reply_encpart.key_exp = 0;/* ditto */\n reply_encpart.flags = enc_tkt_reply.flags;\n reply_encpart.server = ticket_reply.server;", " /* use the session key in the ticket, unless there's a subsession key\n in the AP_REQ */\n reply.enc_part.enctype = subkey ? subkey->enctype :\n header_ticket->enc_part2->session->enctype;\n errcode = kdc_fast_response_handle_padata(state, request, &reply,\n subkey ? subkey->enctype : header_ticket->enc_part2->session->enctype);\n if (errcode !=0 ) {\n status = \"Preparing FAST padata\";\n goto cleanup;\n }\n errcode =kdc_fast_handle_reply_key(state,\n subkey?subkey:header_ticket->enc_part2->session, &reply_key);\n if (errcode) {\n status = \"generating reply key\";\n goto cleanup;\n }\n errcode = return_enc_padata(kdc_context, pkt, request,\n reply_key, server, &reply_encpart,\n is_referral &&\n isflagset(s_flags,\n KRB5_KDB_FLAG_CANONICALIZE));\n if (errcode) {\n status = \"KDC_RETURN_ENC_PADATA\";\n goto cleanup;\n }", " errcode = krb5_encode_kdc_rep(kdc_context, KRB5_TGS_REP, &reply_encpart,\n subkey ? 1 : 0,\n reply_key,\n &reply, response);\n if (errcode) {\n status = \"ENCODE_KDC_REP\";\n } else {\n status = \"ISSUE\";\n }", " memset(ticket_reply.enc_part.ciphertext.data, 0,\n ticket_reply.enc_part.ciphertext.length);\n free(ticket_reply.enc_part.ciphertext.data);\n /* these parts are left on as a courtesy from krb5_encode_kdc_rep so we\n can use them in raw form if needed. But, we don't... */\n memset(reply.enc_part.ciphertext.data, 0,\n reply.enc_part.ciphertext.length);\n free(reply.enc_part.ciphertext.data);", "cleanup:\n assert(status != NULL);\n if (reply_key)\n krb5_free_keyblock(kdc_context, reply_key);\n if (errcode)\n emsg = krb5_get_error_message (kdc_context, errcode);\n log_tgs_req(from, request, &reply, cname, sname, altcname, authtime,\n c_flags, s4u_name, status, errcode, emsg);\n if (errcode) {\n krb5_free_error_message (kdc_context, emsg);\n emsg = NULL;\n }", " if (errcode) {\n int got_err = 0;\n if (status == 0) {\n status = krb5_get_error_message (kdc_context, errcode);\n got_err = 1;\n }\n errcode -= ERROR_TABLE_BASE_krb5;\n if (errcode < 0 || errcode > 128)\n errcode = KRB_ERR_GENERIC;", " retval = prepare_error_tgs(state, request, header_ticket, errcode,\n (server != NULL) ? server->princ : NULL,\n response, status, e_data);\n if (got_err) {\n krb5_free_error_message (kdc_context, status);\n status = 0;\n }\n }", " if (header_ticket != NULL)\n krb5_free_ticket(kdc_context, header_ticket);\n if (request != NULL)\n krb5_free_kdc_req(kdc_context, request);\n if (state)\n kdc_free_rstate(state);\n if (cname != NULL)\n free(cname);\n if (sname != NULL)\n free(sname);\n krb5_db_free_principal(kdc_context, server);\n krb5_db_free_principal(kdc_context, krbtgt);\n krb5_db_free_principal(kdc_context, client);\n if (session_key.contents != NULL)\n krb5_free_keyblock_contents(kdc_context, &session_key);\n if (newtransited)\n free(enc_tkt_reply.transited.tr_contents.data);\n if (s4u_x509_user != NULL)\n krb5_free_pa_s4u_x509_user(kdc_context, s4u_x509_user);\n if (kdc_issued_auth_data != NULL)\n krb5_free_authdata(kdc_context, kdc_issued_auth_data);\n if (s4u_name != NULL)\n free(s4u_name);\n if (subkey != NULL)\n krb5_free_keyblock(kdc_context, subkey);\n if (tgskey != NULL)\n krb5_free_keyblock(kdc_context, tgskey);\n if (reply.padata)\n krb5_free_pa_data(kdc_context, reply.padata);\n if (reply_encpart.enc_padata)\n krb5_free_pa_data(kdc_context, reply_encpart.enc_padata);\n if (enc_tkt_reply.authorization_data != NULL)\n krb5_free_authdata(kdc_context, enc_tkt_reply.authorization_data);\n krb5_free_pa_data(kdc_context, e_data);", " return retval;\n}", "static krb5_error_code\nprepare_error_tgs (struct kdc_request_state *state,\n krb5_kdc_req *request, krb5_ticket *ticket, int error,\n krb5_principal canon_server,\n krb5_data **response, const char *status,\n krb5_pa_data **e_data)\n{\n krb5_error errpkt;\n krb5_error_code retval = 0;\n krb5_data *scratch, *e_data_asn1 = NULL, *fast_edata = NULL;", " errpkt.ctime = request->nonce;\n errpkt.cusec = 0;", " if ((retval = krb5_us_timeofday(kdc_context, &errpkt.stime,\n &errpkt.susec)))\n return(retval);\n errpkt.error = error;\n errpkt.server = request->server;\n if (ticket && ticket->enc_part2)\n errpkt.client = ticket->enc_part2->client;\n else\n errpkt.client = NULL;\n errpkt.text.length = strlen(status);\n if (!(errpkt.text.data = strdup(status)))\n return ENOMEM;", " if (!(scratch = (krb5_data *)malloc(sizeof(*scratch)))) {\n free(errpkt.text.data);\n return ENOMEM;\n }", " if (e_data != NULL) {\n retval = encode_krb5_padata_sequence(e_data, &e_data_asn1);\n if (retval) {\n free(scratch);\n free(errpkt.text.data);\n return retval;\n }\n errpkt.e_data = *e_data_asn1;\n } else\n errpkt.e_data = empty_data();", " if (state) {\n retval = kdc_fast_handle_error(kdc_context, state, request, e_data,\n &errpkt, &fast_edata);\n }\n if (retval) {\n free(scratch);\n free(errpkt.text.data);\n krb5_free_data(kdc_context, e_data_asn1);\n return retval;\n }\n if (fast_edata)\n errpkt.e_data = *fast_edata;\n retval = krb5_mk_error(kdc_context, &errpkt, scratch);\n free(errpkt.text.data);\n krb5_free_data(kdc_context, e_data_asn1);\n krb5_free_data(kdc_context, fast_edata);\n if (retval)\n free(scratch);\n else\n *response = scratch;", " return retval;\n}", "/*\n * The request seems to be for a ticket-granting service somewhere else,\n * but we don't have a ticket for the final TGS. Try to give the requestor\n * some intermediate realm.\n */\nstatic krb5_error_code\nfind_alternate_tgs(krb5_kdc_req *request, krb5_db_entry **server_ptr)\n{\n krb5_error_code retval;\n krb5_principal *plist = NULL, *pl2, tmpprinc;\n krb5_data tmp;\n krb5_db_entry *server = NULL;", " *server_ptr = NULL;", " /*\n * Call to krb5_princ_component is normally not safe but is so\n * here only because find_alternate_tgs() is only called from\n * somewhere that has already checked the number of components in\n * the principal.\n */\n if ((retval = krb5_walk_realm_tree(kdc_context,\n krb5_princ_realm(kdc_context, request->server),\n krb5_princ_component(kdc_context, request->server, 1),\n &plist, KRB5_REALM_BRANCH_CHAR)))\n return retval;", " /* move to the end */\n for (pl2 = plist; *pl2; pl2++);", " /* the first entry in this array is for krbtgt/local@local, so we\n ignore it */\n while (--pl2 > plist) {\n tmp = *krb5_princ_realm(kdc_context, *pl2);\n krb5_princ_set_realm(kdc_context, *pl2,\n krb5_princ_realm(kdc_context, tgs_server));\n retval = krb5_db_get_principal(kdc_context, *pl2, 0, &server);\n krb5_princ_set_realm(kdc_context, *pl2, &tmp);\n if (retval == KRB5_KDB_NOENTRY)\n continue;\n else if (retval)\n goto cleanup;", " /* Found it. */\n tmp = *krb5_princ_realm(kdc_context, *pl2);\n krb5_princ_set_realm(kdc_context, *pl2,\n krb5_princ_realm(kdc_context, tgs_server));\n retval = krb5_copy_principal(kdc_context, *pl2, &tmpprinc);\n if (retval)\n goto cleanup;\n krb5_princ_set_realm(kdc_context, *pl2, &tmp);", " krb5_free_principal(kdc_context, request->server);\n request->server = tmpprinc;\n log_tgs_alt_tgt(request->server);\n *server_ptr = server;\n server = NULL;\n goto cleanup;\n }\n retval = KRB5_KDB_NOENTRY;", "cleanup:\n krb5_free_realm_tree(kdc_context, plist);\n krb5_db_free_principal(kdc_context, server);\n return retval;\n}", "static krb5_int32\nprep_reprocess_req(krb5_kdc_req *request, krb5_principal *krbtgt_princ)\n{\n krb5_error_code retval = KRB5KRB_AP_ERR_BADMATCH;\n char **realms, **cpp, *temp_buf=NULL;\n krb5_data *comp1 = NULL, *comp2 = NULL;\n char *comp1_str = NULL;", " /* By now we know that server principal name is unknown.\n * If CANONICALIZE flag is set in the request\n * If req is not U2U authn. req\n * the requested server princ. has exactly two components\n * either\n * the name type is NT-SRV-HST\n * or name type is NT-UNKNOWN and\n * the 1st component is listed in conf file under host_based_services\n * the 1st component is not in a list in conf under \"no_host_referral\"\n * the 2d component looks like fully-qualified domain name (FQDN)\n * If all of these conditions are satisfied - try mapping the FQDN and\n * re-process the request as if client had asked for cross-realm TGT.\n */\n if (isflagset(request->kdc_options, KDC_OPT_CANONICALIZE) &&\n !isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY) &&\n krb5_princ_size(kdc_context, request->server) == 2) {", " comp1 = krb5_princ_component(kdc_context, request->server, 0);\n comp2 = krb5_princ_component(kdc_context, request->server, 1);", " comp1_str = calloc(1,comp1->length+1);\n if (!comp1_str) {\n retval = ENOMEM;\n goto cleanup;\n }", " strlcpy(comp1_str,comp1->data,comp1->length+1);", "\n if ((krb5_princ_type(kdc_context, request->server) == KRB5_NT_SRV_HST ||\n krb5_princ_type(kdc_context, request->server) == KRB5_NT_SRV_INST ||\n (krb5_princ_type(kdc_context, request->server) == KRB5_NT_UNKNOWN &&\n kdc_active_realm->realm_host_based_services != NULL &&\n (krb5_match_config_pattern(kdc_active_realm->realm_host_based_services,\n comp1_str) == TRUE ||\n krb5_match_config_pattern(kdc_active_realm->realm_host_based_services,\n KRB5_CONF_ASTERISK) == TRUE))) &&\n (kdc_active_realm->realm_no_host_referral == NULL ||\n (krb5_match_config_pattern(kdc_active_realm->realm_no_host_referral,\n KRB5_CONF_ASTERISK) == FALSE &&\n krb5_match_config_pattern(kdc_active_realm->realm_no_host_referral,\n comp1_str) == FALSE))) {", " if (memchr(comp2->data, '.', comp2->length) == NULL)\n goto cleanup;\n temp_buf = calloc(1, comp2->length+1);\n if (!temp_buf) {\n retval = ENOMEM;\n goto cleanup;\n }", " strlcpy(temp_buf, comp2->data,comp2->length+1);", " retval = krb5int_get_domain_realm_mapping(kdc_context, temp_buf, &realms);\n free(temp_buf);\n if (retval) {\n /* no match found */\n kdc_err(kdc_context, retval, \"unable to find realm of host\");\n goto cleanup;\n }\n if (realms == 0) {\n retval = KRB5KRB_AP_ERR_BADMATCH;\n goto cleanup;\n }\n /* Don't return a referral to the null realm or the service\n * realm. */\n if (realms[0] == 0 ||\n data_eq_string(request->server->realm, realms[0])) {\n free(realms[0]);\n free(realms);\n retval = KRB5KRB_AP_ERR_BADMATCH;\n goto cleanup;\n }\n /* Modify request.\n * Construct cross-realm tgt : krbtgt/REMOTE_REALM@LOCAL_REALM\n * and use it as a principal in this req.\n */\n retval = krb5_build_principal(kdc_context, krbtgt_princ,\n (*request->server).realm.length,\n (*request->server).realm.data,\n \"krbtgt\", realms[0], (char *)0);\n for (cpp = realms; *cpp; cpp++)\n free(*cpp);\n }\n }\ncleanup:\n free(comp1_str);", " return retval;\n}" ]
[ 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, 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, 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, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1168], "buggy_code_start_loc": [1144], "filenames": ["src/kdc/do_tgs_req.c"], "fixing_code_end_loc": [1170], "fixing_code_start_loc": [1144], "message": "The prep_reprocess_req function in do_tgs_req.c in the Key Distribution Center (KDC) in MIT Kerberos 5 (aka krb5) before 1.10.5 does not properly perform service-principal realm referral, which allows remote authenticated users to cause a denial of service (NULL pointer dereference and daemon crash) via a crafted TGS-REQ request.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mit:kerberos_5:*:*:*:*:*:*:*:*", "matchCriteriaId": "ADAAA945-792F-419A-9045-01CE94A74320", "versionEndExcluding": "1.10.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:opensuse:11.4:*:*:*:*:*:*:*", "matchCriteriaId": "DE554781-1EB9-446E-911F-6C11970C47F4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:opensuse:opensuse:12.1:*:*:*:*:*:*:*", "matchCriteriaId": "EBB2C482-D2A4-48B3-ACE7-E1DFDCC409B5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:opensuse:opensuse:12.2:*:*:*:*:*:*:*", "matchCriteriaId": "D806A17E-B8F9-466D-807D-3F1E77603DC8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:opensuse:opensuse:12.3:*:*:*:*:*:*:*", "matchCriteriaId": "DFBF430B-0832-44B0-AA0E-BA9E467F7668", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:17:*:*:*:*:*:*:*", "matchCriteriaId": "2DA9D861-3EAF-42F5-B0B6-A4CD7BDD6188", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:18:*:*:*:*:*:*:*", "matchCriteriaId": "E14271AE-1309-48F3-B9C6-D7DEEC488279", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:redhat:enterprise_linux_desktop:6.0:*:*:*:*:*:*:*", "matchCriteriaId": "EE249E1B-A1FD-4E08-AA71-A0E1F10FFE97", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_eus:6.4:*:*:*:*:*:*:*", "matchCriteriaId": "8A8E07B7-3739-4BEB-88F8-C7F62431E889", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_server:6.0:*:*:*:*:*:*:*", "matchCriteriaId": "9BBCD86A-E6C7-4444-9D74-F861084090F0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_server_aus:6.4:*:*:*:*:*:*:*", "matchCriteriaId": "AF83BB87-B203-48F9-9D06-48A5FE399050", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_workstation:6.0:*:*:*:*:*:*:*", "matchCriteriaId": "E5ED5807-55B7-47C5-97A6-03233F4FBC3A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The prep_reprocess_req function in do_tgs_req.c in the Key Distribution Center (KDC) in MIT Kerberos 5 (aka krb5) before 1.10.5 does not properly perform service-principal realm referral, which allows remote authenticated users to cause a denial of service (NULL pointer dereference and daemon crash) via a crafted TGS-REQ request."}, {"lang": "es", "value": "La funci\u00f3n prep_reprocess_req en do_tgs_req.c en el Key Distribution Center (KDC) en MIT Kerberos 5 (aka krb5) antes de v1.10.5 no realiza correctamente el servicio \u00e1mbito de referencia principal, lo que permite a usuarios remotos autenticados causar una denegaci\u00f3n de servicio (desreferencia a un puntero nulo y la ca\u00edda del demonio) a trav\u00e9s de una solicitud TGS-REQ modificada."}], "evaluatorComment": null, "id": "CVE-2013-1416", "lastModified": "2021-02-02T18:40:23.900", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2013-04-19T11:44:26.017", "references": [{"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "http://krbdev.mit.edu/rt/Ticket/Display.html?id=7600"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://lists.fedoraproject.org/pipermail/package-announce/2013-April/102058.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://lists.fedoraproject.org/pipermail/package-announce/2013-April/102074.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-updates/2013-05/msg00011.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-updates/2013-06/msg00041.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-updates/2013-06/msg00102.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://rhn.redhat.com/errata/RHSA-2013-0748.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.mandriva.com/security/advisories?name=MDVSA-2013:157"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.mandriva.com/security/advisories?name=MDVSA-2013:158"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/krb5/krb5/commit/8ee70ec63931d1e38567905387ab9b1d45734d81"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/krb5/krb5/commit/8ee70ec63931d1e38567905387ab9b1d45734d81"}, "type": "CWE-476"}
175
Determine whether the {function_name} code is vulnerable or not.
[ "/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n/* kdc/do_tgs_req.c - KDC Routines to deal with TGS_REQ's */\n/*\n * Copyright 1990,1991,2001,2007,2008,2009 by the Massachusetts Institute of Technology.\n * All Rights Reserved.\n *\n * Export of this software from the United States of America may\n * require a specific license from the United States Government.\n * It is the responsibility of any person or organization contemplating\n * export to obtain such a license before exporting.\n *\n * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and\n * distribute this software and its documentation for any purpose and\n * without fee is hereby granted, provided that the above copyright\n * notice appear in all copies and that both that copyright notice and\n * this permission notice appear in supporting documentation, and that\n * the name of M.I.T. not be used in advertising or publicity pertaining\n * to distribution of the software without specific, written prior\n * permission. Furthermore if you modify this software you must label\n * your software as modified software and not distribute it in such a\n * fashion that it might be confused with the original M.I.T. software.\n * M.I.T. makes no representations about the suitability of\n * this software for any purpose. It is provided \"as is\" without express\n * or implied warranty.\n */\n/*\n * Copyright (c) 2006-2008, Novell, Inc.\n * 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 are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * * The copyright holder's name is not used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */", "#include \"k5-int.h\"", "#include <syslog.h>\n#ifdef HAVE_NETINET_IN_H\n#include <sys/types.h>\n#include <netinet/in.h>\n#ifndef hpux\n#include <arpa/inet.h>\n#endif\n#endif", "#include \"kdc_util.h\"\n#include \"policy.h\"\n#include \"extern.h\"\n#include \"adm_proto.h\"\n#include <ctype.h>", "static krb5_error_code\nfind_alternate_tgs(krb5_kdc_req *,krb5_db_entry **);", "static krb5_error_code\nprepare_error_tgs(struct kdc_request_state *, krb5_kdc_req *,krb5_ticket *,int,\n krb5_principal,krb5_data **,const char *, krb5_pa_data **);", "static krb5_int32\nprep_reprocess_req(krb5_kdc_req *,krb5_principal *);", "/*ARGSUSED*/\nkrb5_error_code\nprocess_tgs_req(krb5_data *pkt, const krb5_fulladdr *from,\n krb5_data **response)\n{\n krb5_keyblock * subkey = 0;\n krb5_keyblock * tgskey = 0;\n krb5_kdc_req *request = 0;\n krb5_db_entry *server = NULL;\n krb5_kdc_rep reply;\n krb5_enc_kdc_rep_part reply_encpart;\n krb5_ticket ticket_reply, *header_ticket = 0;\n int st_idx = 0;\n krb5_enc_tkt_part enc_tkt_reply;\n krb5_transited enc_tkt_transited;\n int newtransited = 0;\n krb5_error_code retval = 0;\n krb5_keyblock encrypting_key;\n krb5_timestamp kdc_time, authtime = 0;\n krb5_keyblock session_key;\n krb5_timestamp rtime;\n krb5_keyblock *reply_key = NULL;\n krb5_key_data *server_key;\n char *cname = 0, *sname = 0, *altcname = 0;\n krb5_last_req_entry *nolrarray[2], nolrentry;\n krb5_enctype useenctype;\n int errcode, errcode2;\n register int i;\n int firstpass = 1;\n const char *status = 0;\n krb5_enc_tkt_part *header_enc_tkt = NULL; /* TGT */\n krb5_enc_tkt_part *subject_tkt = NULL; /* TGT or evidence ticket */\n krb5_db_entry *client = NULL, *krbtgt = NULL;\n krb5_pa_s4u_x509_user *s4u_x509_user = NULL; /* protocol transition request */\n krb5_authdata **kdc_issued_auth_data = NULL; /* auth data issued by KDC */\n unsigned int c_flags = 0, s_flags = 0; /* client/server KDB flags */\n char *s4u_name = NULL;\n krb5_boolean is_referral, db_ref_done = FALSE;\n const char *emsg = NULL;\n krb5_data *tgs_1 =NULL, *server_1 = NULL;\n krb5_principal krbtgt_princ;\n krb5_kvno ticket_kvno = 0;\n struct kdc_request_state *state = NULL;\n krb5_pa_data *pa_tgs_req; /*points into request*/\n krb5_data scratch;\n krb5_pa_data **e_data = NULL;", " reply.padata = 0; /* For cleanup handler */\n reply_encpart.enc_padata = 0;\n enc_tkt_reply.authorization_data = NULL;", " session_key.contents = NULL;", " retval = decode_krb5_tgs_req(pkt, &request);\n if (retval)\n return retval;\n if (request->msg_type != KRB5_TGS_REQ) {\n krb5_free_kdc_req(kdc_context, request);\n return KRB5_BADMSGTYPE;\n }", " /*\n * setup_server_realm() sets up the global realm-specific data pointer.\n */\n if ((retval = setup_server_realm(request->server))) {\n krb5_free_kdc_req(kdc_context, request);\n return retval;\n }\n errcode = kdc_process_tgs_req(request, from, pkt, &header_ticket,\n &krbtgt, &tgskey, &subkey, &pa_tgs_req);\n if (header_ticket && header_ticket->enc_part2 &&\n (errcode2 = krb5_unparse_name(kdc_context,\n header_ticket->enc_part2->client,\n &cname))) {\n status = \"UNPARSING CLIENT\";\n errcode = errcode2;\n goto cleanup;\n }\n limit_string(cname);", " if (errcode) {\n status = \"PROCESS_TGS\";\n goto cleanup;\n }", " if (!header_ticket) {\n errcode = KRB5_NO_TKT_SUPPLIED; /* XXX? */\n status=\"UNEXPECTED NULL in header_ticket\";\n goto cleanup;\n }\n errcode = kdc_make_rstate(&state);\n if (errcode !=0) {\n status = \"making state\";\n goto cleanup;\n }\n scratch.length = pa_tgs_req->length;\n scratch.data = (char *) pa_tgs_req->contents;\n errcode = kdc_find_fast(&request, &scratch, subkey,\n header_ticket->enc_part2->session, state, NULL);\n if (errcode !=0) {\n status = \"kdc_find_fast\";\n goto cleanup;\n }", " /*\n * Pointer to the encrypted part of the header ticket, which may be\n * replaced to point to the encrypted part of the evidence ticket\n * if constrained delegation is used. This simplifies the number of\n * special cases for constrained delegation.\n */\n header_enc_tkt = header_ticket->enc_part2;", " /*\n * We've already dealt with the AP_REQ authentication, so we can\n * use header_ticket freely. The encrypted part (if any) has been\n * decrypted with the session key.\n */", " /* XXX make sure server here has the proper realm...taken from AP_REQ\n header? */", " setflag(s_flags, KRB5_KDB_FLAG_ALIAS_OK);\n if (isflagset(request->kdc_options, KDC_OPT_CANONICALIZE)) {\n setflag(c_flags, KRB5_KDB_FLAG_CANONICALIZE);\n setflag(s_flags, KRB5_KDB_FLAG_CANONICALIZE);\n }", " db_ref_done = FALSE;\nref_tgt_again:\n if ((errcode = krb5_unparse_name(kdc_context, request->server, &sname))) {\n status = \"UNPARSING SERVER\";\n goto cleanup;\n }\n limit_string(sname);", " errcode = krb5_db_get_principal(kdc_context, request->server,\n s_flags, &server);\n if (errcode && errcode != KRB5_KDB_NOENTRY) {\n status = \"LOOKING_UP_SERVER\";\n goto cleanup;\n }\ntgt_again:\n if (errcode == KRB5_KDB_NOENTRY) {\n /*\n * might be a request for a TGT for some other realm; we\n * should do our best to find such a TGS in this db\n */\n if (firstpass ) {", " if ( krb5_is_tgs_principal(request->server) == TRUE) {\n /* Principal is a name of krb ticket service */\n if (krb5_princ_size(kdc_context, request->server) == 2) {", " server_1 = krb5_princ_component(kdc_context,\n request->server, 1);\n tgs_1 = krb5_princ_component(kdc_context, tgs_server, 1);", " if (!tgs_1 || !data_eq(*server_1, *tgs_1)) {\n errcode = find_alternate_tgs(request, &server);\n firstpass = 0;\n if (errcode == 0)\n goto tgt_again;\n }\n }\n status = \"UNKNOWN_SERVER\";\n errcode = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n goto cleanup;", " } else if ( db_ref_done == FALSE) {\n retval = prep_reprocess_req(request, &krbtgt_princ);\n if (!retval) {\n krb5_free_principal(kdc_context, request->server);\n retval = krb5_copy_principal(kdc_context, krbtgt_princ,\n &(request->server));\n if (!retval) {\n db_ref_done = TRUE;\n if (sname != NULL)\n free(sname);\n goto ref_tgt_again;\n }\n }\n }\n }", " status = \"UNKNOWN_SERVER\";\n errcode = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n goto cleanup;\n }", " if ((errcode = krb5_timeofday(kdc_context, &kdc_time))) {\n status = \"TIME_OF_DAY\";\n goto cleanup;\n }", " if ((retval = validate_tgs_request(request, *server, header_ticket,\n kdc_time, &status, &e_data))) {\n if (!status)\n status = \"UNKNOWN_REASON\";\n errcode = retval + ERROR_TABLE_BASE_krb5;\n goto cleanup;\n }", " if (!is_local_principal(header_enc_tkt->client))\n setflag(c_flags, KRB5_KDB_FLAG_CROSS_REALM);", " is_referral = krb5_is_tgs_principal(server->princ) &&\n !krb5_principal_compare(kdc_context, tgs_server, server->princ);", " /* Check for protocol transition */\n errcode = kdc_process_s4u2self_req(kdc_context,\n request,\n header_enc_tkt->client,\n server,\n subkey,\n header_enc_tkt->session,\n kdc_time,\n &s4u_x509_user,\n &client,\n &status);\n if (errcode)\n goto cleanup;\n if (s4u_x509_user != NULL)\n setflag(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION);", " /*\n * We pick the session keytype here....\n *\n * Some special care needs to be taken in the user-to-user\n * case, since we don't know what keytypes the application server\n * which is doing user-to-user authentication can support. We\n * know that it at least must be able to support the encryption\n * type of the session key in the TGT, since otherwise it won't be\n * able to decrypt the U2U ticket! So we use that in preference\n * to anything else.\n */\n useenctype = 0;\n if (isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY |\n KDC_OPT_CNAME_IN_ADDL_TKT)) {\n krb5_keyblock * st_sealing_key;\n krb5_kvno st_srv_kvno;\n krb5_enctype etype;\n krb5_db_entry *st_client;", " /*\n * Get the key for the second ticket, and decrypt it.\n */\n if ((errcode = kdc_get_server_key(request->second_ticket[st_idx],\n c_flags,\n TRUE, /* match_enctype */\n &st_client,\n &st_sealing_key,\n &st_srv_kvno))) {\n status = \"2ND_TKT_SERVER\";\n goto cleanup;\n }\n errcode = krb5_decrypt_tkt_part(kdc_context, st_sealing_key,\n request->second_ticket[st_idx]);\n krb5_free_keyblock(kdc_context, st_sealing_key);\n if (errcode) {\n status = \"2ND_TKT_DECRYPT\";\n krb5_db_free_principal(kdc_context, st_client);\n goto cleanup;\n }", " etype = request->second_ticket[st_idx]->enc_part2->session->enctype;\n if (!krb5_c_valid_enctype(etype)) {\n status = \"BAD_ETYPE_IN_2ND_TKT\";\n errcode = KRB5KDC_ERR_ETYPE_NOSUPP;\n krb5_db_free_principal(kdc_context, st_client);\n goto cleanup;\n }", " for (i = 0; i < request->nktypes; i++) {\n if (request->ktype[i] == etype) {\n useenctype = etype;\n break;\n }\n }", " if (isflagset(request->kdc_options, KDC_OPT_CNAME_IN_ADDL_TKT)) {\n /* Do constrained delegation protocol and authorization checks */\n errcode = kdc_process_s4u2proxy_req(kdc_context,\n request,\n request->second_ticket[st_idx]->enc_part2,\n st_client,\n header_ticket->enc_part2->client,\n request->server,\n &status);\n if (errcode)\n goto cleanup;", " setflag(c_flags, KRB5_KDB_FLAG_CONSTRAINED_DELEGATION);", " assert(krb5_is_tgs_principal(header_ticket->server));", " assert(client == NULL); /* assured by kdc_process_s4u2self_req() */\n client = st_client;\n } else {\n /* \"client\" is not used for user2user */\n krb5_db_free_principal(kdc_context, st_client);\n }\n }", " /*\n * Select the keytype for the ticket session key.\n */\n if ((useenctype == 0) &&\n (useenctype = select_session_keytype(kdc_context, server,\n request->nktypes,\n request->ktype)) == 0) {\n /* unsupported ktype */\n status = \"BAD_ENCRYPTION_TYPE\";\n errcode = KRB5KDC_ERR_ETYPE_NOSUPP;\n goto cleanup;\n }", " errcode = krb5_c_make_random_key(kdc_context, useenctype, &session_key);", " if (errcode) {\n /* random key failed */\n status = \"RANDOM_KEY_FAILED\";\n goto cleanup;\n }", " /*\n * subject_tkt will refer to the evidence ticket (for constrained\n * delegation) or the TGT. The distinction from header_enc_tkt is\n * necessary because the TGS signature only protects some fields:\n * the others could be forged by a malicious server.\n */", " if (isflagset(c_flags, KRB5_KDB_FLAG_CONSTRAINED_DELEGATION))\n subject_tkt = request->second_ticket[st_idx]->enc_part2;\n else\n subject_tkt = header_enc_tkt;\n authtime = subject_tkt->times.authtime;", " if (is_referral)\n ticket_reply.server = server->princ;\n else\n ticket_reply.server = request->server; /* XXX careful for realm... */", " enc_tkt_reply.flags = 0;\n enc_tkt_reply.times.starttime = 0;", " if (isflagset(server->attributes, KRB5_KDB_OK_AS_DELEGATE))\n setflag(enc_tkt_reply.flags, TKT_FLG_OK_AS_DELEGATE);", " /*\n * Fix header_ticket's starttime; if it's zero, fill in the\n * authtime's value.\n */\n if (!(header_enc_tkt->times.starttime))\n header_enc_tkt->times.starttime = authtime;\n setflag(enc_tkt_reply.flags, TKT_FLG_ENC_PA_REP);", " /* don't use new addresses unless forwarded, see below */", " enc_tkt_reply.caddrs = header_enc_tkt->caddrs;\n /* noaddrarray[0] = 0; */\n reply_encpart.caddrs = 0;/* optional...don't put it in */\n reply_encpart.enc_padata = NULL;", " /*\n * It should be noted that local policy may affect the\n * processing of any of these flags. For example, some\n * realms may refuse to issue renewable tickets\n */", " if (isflagset(request->kdc_options, KDC_OPT_FORWARDABLE)) {\n setflag(enc_tkt_reply.flags, TKT_FLG_FORWARDABLE);", " if (isflagset(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION)) {\n /*\n * If S4U2Self principal is not forwardable, then mark ticket as\n * unforwardable. This behaviour matches Windows, but it is\n * different to the MIT AS-REQ path, which returns an error\n * (KDC_ERR_POLICY) if forwardable tickets cannot be issued.\n *\n * Consider this block the S4U2Self equivalent to\n * validate_forwardable().\n */\n if (client != NULL &&\n isflagset(client->attributes, KRB5_KDB_DISALLOW_FORWARDABLE))\n clear(enc_tkt_reply.flags, TKT_FLG_FORWARDABLE);\n /*\n * Forwardable flag is propagated along referral path.\n */\n else if (!isflagset(header_enc_tkt->flags, TKT_FLG_FORWARDABLE))\n clear(enc_tkt_reply.flags, TKT_FLG_FORWARDABLE);\n /*\n * OK_TO_AUTH_AS_DELEGATE must be set on the service requesting\n * S4U2Self in order for forwardable tickets to be returned.\n */\n else if (!is_referral &&\n !isflagset(server->attributes,\n KRB5_KDB_OK_TO_AUTH_AS_DELEGATE))\n clear(enc_tkt_reply.flags, TKT_FLG_FORWARDABLE);\n }\n }", " if (isflagset(request->kdc_options, KDC_OPT_FORWARDED)) {\n setflag(enc_tkt_reply.flags, TKT_FLG_FORWARDED);", " /* include new addresses in ticket & reply */", " enc_tkt_reply.caddrs = request->addresses;\n reply_encpart.caddrs = request->addresses;\n }\n if (isflagset(header_enc_tkt->flags, TKT_FLG_FORWARDED))\n setflag(enc_tkt_reply.flags, TKT_FLG_FORWARDED);", " if (isflagset(request->kdc_options, KDC_OPT_PROXIABLE))\n setflag(enc_tkt_reply.flags, TKT_FLG_PROXIABLE);", " if (isflagset(request->kdc_options, KDC_OPT_PROXY)) {\n setflag(enc_tkt_reply.flags, TKT_FLG_PROXY);", " /* include new addresses in ticket & reply */", " enc_tkt_reply.caddrs = request->addresses;\n reply_encpart.caddrs = request->addresses;\n }", " if (isflagset(request->kdc_options, KDC_OPT_ALLOW_POSTDATE))\n setflag(enc_tkt_reply.flags, TKT_FLG_MAY_POSTDATE);", " if (isflagset(request->kdc_options, KDC_OPT_POSTDATED)) {\n setflag(enc_tkt_reply.flags, TKT_FLG_POSTDATED);\n setflag(enc_tkt_reply.flags, TKT_FLG_INVALID);\n enc_tkt_reply.times.starttime = request->from;\n } else\n enc_tkt_reply.times.starttime = kdc_time;", " if (isflagset(request->kdc_options, KDC_OPT_VALIDATE)) {\n assert(isflagset(c_flags, KRB5_KDB_FLAGS_S4U) == 0);\n /* BEWARE of allocation hanging off of ticket & enc_part2, it belongs\n to the caller */\n ticket_reply = *(header_ticket);\n enc_tkt_reply = *(header_ticket->enc_part2);\n enc_tkt_reply.authorization_data = NULL;\n clear(enc_tkt_reply.flags, TKT_FLG_INVALID);\n }", " if (isflagset(request->kdc_options, KDC_OPT_RENEW)) {\n krb5_deltat old_life;", " assert(isflagset(c_flags, KRB5_KDB_FLAGS_S4U) == 0);\n /* BEWARE of allocation hanging off of ticket & enc_part2, it belongs\n to the caller */\n ticket_reply = *(header_ticket);\n enc_tkt_reply = *(header_ticket->enc_part2);\n enc_tkt_reply.authorization_data = NULL;", " old_life = enc_tkt_reply.times.endtime - enc_tkt_reply.times.starttime;", " enc_tkt_reply.times.starttime = kdc_time;\n enc_tkt_reply.times.endtime =\n min(header_ticket->enc_part2->times.renew_till,\n kdc_time + old_life);\n } else {\n /* not a renew request */\n enc_tkt_reply.times.starttime = kdc_time;", " kdc_get_ticket_endtime(kdc_context, enc_tkt_reply.times.starttime,\n header_enc_tkt->times.endtime, request->till,\n client, server, &enc_tkt_reply.times.endtime);", " if (isflagset(request->kdc_options, KDC_OPT_RENEWABLE_OK) &&\n (enc_tkt_reply.times.endtime < request->till) &&\n isflagset(header_enc_tkt->flags, TKT_FLG_RENEWABLE)) {\n setflag(request->kdc_options, KDC_OPT_RENEWABLE);\n request->rtime =\n min(request->till, header_enc_tkt->times.renew_till);\n }\n }\n rtime = (request->rtime == 0) ? kdc_infinity : request->rtime;", " if (isflagset(request->kdc_options, KDC_OPT_RENEWABLE)) {\n /* already checked above in policy check to reject request for a\n renewable ticket using a non-renewable ticket */\n setflag(enc_tkt_reply.flags, TKT_FLG_RENEWABLE);\n enc_tkt_reply.times.renew_till =\n min(rtime,\n min(header_enc_tkt->times.renew_till,\n enc_tkt_reply.times.starttime +\n min(server->max_renewable_life,\n max_renewable_life_for_realm)));\n } else {\n enc_tkt_reply.times.renew_till = 0;\n }\n if (isflagset(header_enc_tkt->flags, TKT_FLG_ANONYMOUS))\n setflag(enc_tkt_reply.flags, TKT_FLG_ANONYMOUS);\n /*\n * Set authtime to be the same as header or evidence ticket's\n */\n enc_tkt_reply.times.authtime = authtime;", " /*\n * Propagate the preauthentication flags through to the returned ticket.\n */\n if (isflagset(header_enc_tkt->flags, TKT_FLG_PRE_AUTH))\n setflag(enc_tkt_reply.flags, TKT_FLG_PRE_AUTH);", " if (isflagset(header_enc_tkt->flags, TKT_FLG_HW_AUTH))\n setflag(enc_tkt_reply.flags, TKT_FLG_HW_AUTH);", " /* starttime is optional, and treated as authtime if not present.\n so we can nuke it if it matches */\n if (enc_tkt_reply.times.starttime == enc_tkt_reply.times.authtime)\n enc_tkt_reply.times.starttime = 0;", " if (isflagset(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION)) {\n errcode = krb5_unparse_name(kdc_context, s4u_x509_user->user_id.user,\n &s4u_name);\n } else if (isflagset(c_flags, KRB5_KDB_FLAG_CONSTRAINED_DELEGATION)) {\n errcode = krb5_unparse_name(kdc_context, subject_tkt->client,\n &s4u_name);\n } else {\n errcode = 0;\n }\n if (errcode) {\n status = \"UNPARSING S4U CLIENT\";\n goto cleanup;\n }", " if (isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY)) {\n krb5_enc_tkt_part *t2enc = request->second_ticket[st_idx]->enc_part2;\n encrypting_key = *(t2enc->session);\n } else {\n /*\n * Find the server key\n */\n if ((errcode = krb5_dbe_find_enctype(kdc_context, server,\n -1, /* ignore keytype */\n -1, /* Ignore salttype */\n 0, /* Get highest kvno */\n &server_key))) {\n status = \"FINDING_SERVER_KEY\";\n goto cleanup;\n }", " /*\n * Convert server.key into a real key\n * (it may be encrypted in the database)\n */\n if ((errcode = krb5_dbe_decrypt_key_data(kdc_context, NULL,\n server_key, &encrypting_key,\n NULL))) {\n status = \"DECRYPT_SERVER_KEY\";\n goto cleanup;\n }\n }", " if (isflagset(c_flags, KRB5_KDB_FLAG_CONSTRAINED_DELEGATION)) {\n /*\n * Don't allow authorization data to be disabled if constrained\n * delegation is requested. We don't want to deny the server\n * the ability to validate that delegation was used.\n */\n clear(server->attributes, KRB5_KDB_NO_AUTH_DATA_REQUIRED);\n }\n if (isflagset(server->attributes, KRB5_KDB_NO_AUTH_DATA_REQUIRED) == 0) {\n /*\n * If we are not doing protocol transition/constrained delegation\n * try to lookup the client principal so plugins can add additional\n * authorization information.\n *\n * Always validate authorization data for constrained delegation\n * because we must validate the KDC signatures.\n */\n if (!isflagset(c_flags, KRB5_KDB_FLAGS_S4U)) {\n /* Generate authorization data so we can include it in ticket */\n setflag(c_flags, KRB5_KDB_FLAG_INCLUDE_PAC);\n /* Map principals from foreign (possibly non-AD) realms */\n setflag(c_flags, KRB5_KDB_FLAG_MAP_PRINCIPALS);", " assert(client == NULL); /* should not have been set already */", " errcode = krb5_db_get_principal(kdc_context, subject_tkt->client,\n c_flags, &client);\n }\n }", " if (isflagset(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION) &&\n !isflagset(c_flags, KRB5_KDB_FLAG_CROSS_REALM))\n enc_tkt_reply.client = s4u_x509_user->user_id.user;\n else\n enc_tkt_reply.client = subject_tkt->client;", " enc_tkt_reply.session = &session_key;\n enc_tkt_reply.transited.tr_type = KRB5_DOMAIN_X500_COMPRESS;\n enc_tkt_reply.transited.tr_contents = empty_string; /* equivalent of \"\" */", " errcode = handle_authdata(kdc_context, c_flags, client, server, krbtgt,\n subkey != NULL ? subkey :\n header_ticket->enc_part2->session,\n &encrypting_key, /* U2U or server key */\n tgskey,\n pkt,\n request,\n s4u_x509_user ?\n s4u_x509_user->user_id.user : NULL,\n subject_tkt,\n &enc_tkt_reply);\n if (errcode) {\n krb5_klog_syslog(LOG_INFO, _(\"TGS_REQ : handle_authdata (%d)\"),\n errcode);\n status = \"HANDLE_AUTHDATA\";\n goto cleanup;\n }", "\n /*\n * Only add the realm of the presented tgt to the transited list if\n * it is different than the local realm (cross-realm) and it is different\n * than the realm of the client (since the realm of the client is already\n * implicitly part of the transited list and should not be explicitly\n * listed).\n */\n /* realm compare is like strcmp, but knows how to deal with these args */\n if (realm_compare(header_ticket->server, tgs_server) ||\n realm_compare(header_ticket->server, enc_tkt_reply.client)) {\n /* tgt issued by local realm or issued by realm of client */\n enc_tkt_reply.transited = header_enc_tkt->transited;\n } else {\n /* tgt issued by some other realm and not the realm of the client */\n /* assemble new transited field into allocated storage */\n if (header_enc_tkt->transited.tr_type !=\n KRB5_DOMAIN_X500_COMPRESS) {\n status = \"BAD_TRTYPE\";\n errcode = KRB5KDC_ERR_TRTYPE_NOSUPP;\n goto cleanup;\n }\n enc_tkt_transited.tr_type = KRB5_DOMAIN_X500_COMPRESS;\n enc_tkt_transited.magic = 0;\n enc_tkt_transited.tr_contents.magic = 0;\n enc_tkt_transited.tr_contents.data = 0;\n enc_tkt_transited.tr_contents.length = 0;\n enc_tkt_reply.transited = enc_tkt_transited;\n if ((errcode =\n add_to_transited(&header_enc_tkt->transited.tr_contents,\n &enc_tkt_reply.transited.tr_contents,\n header_ticket->server,\n enc_tkt_reply.client,\n request->server))) {\n status = \"ADD_TR_FAIL\";\n goto cleanup;\n }\n newtransited = 1;\n }\n if (isflagset(c_flags, KRB5_KDB_FLAG_CROSS_REALM)) {\n errcode = validate_transit_path(kdc_context, header_enc_tkt->client,\n server, krbtgt);\n if (errcode) {\n status = \"NON_TRANSITIVE\";\n goto cleanup;\n }\n }\n if (!isflagset (request->kdc_options, KDC_OPT_DISABLE_TRANSITED_CHECK)) {\n unsigned int tlen;\n char *tdots;", " errcode = kdc_check_transited_list (kdc_context,\n &enc_tkt_reply.transited.tr_contents,\n krb5_princ_realm (kdc_context, header_enc_tkt->client),\n krb5_princ_realm (kdc_context, request->server));\n tlen = enc_tkt_reply.transited.tr_contents.length;\n tdots = tlen > 125 ? \"...\" : \"\";\n tlen = tlen > 125 ? 125 : tlen;", " if (errcode == 0) {\n setflag (enc_tkt_reply.flags, TKT_FLG_TRANSIT_POLICY_CHECKED);\n } else if (errcode == KRB5KRB_AP_ERR_ILL_CR_TKT)\n krb5_klog_syslog(LOG_INFO, _(\"bad realm transit path from '%s' \"\n \"to '%s' via '%.*s%s'\"),\n cname ? cname : \"<unknown client>\",\n sname ? sname : \"<unknown server>\", tlen,\n enc_tkt_reply.transited.tr_contents.data, tdots);\n else {\n emsg = krb5_get_error_message(kdc_context, errcode);\n krb5_klog_syslog(LOG_ERR, _(\"unexpected error checking transit \"\n \"from '%s' to '%s' via '%.*s%s': %s\"),\n cname ? cname : \"<unknown client>\",\n sname ? sname : \"<unknown server>\", tlen,\n enc_tkt_reply.transited.tr_contents.data, tdots,\n emsg);\n krb5_free_error_message(kdc_context, emsg);\n emsg = NULL;\n }\n } else\n krb5_klog_syslog(LOG_INFO, _(\"not checking transit path\"));\n if (reject_bad_transit\n && !isflagset (enc_tkt_reply.flags, TKT_FLG_TRANSIT_POLICY_CHECKED)) {\n errcode = KRB5KDC_ERR_POLICY;\n status = \"BAD_TRANSIT\";\n goto cleanup;\n }", " ticket_reply.enc_part2 = &enc_tkt_reply;", " /*\n * If we are doing user-to-user authentication, then make sure\n * that the client for the second ticket matches the request\n * server, and then encrypt the ticket using the session key of\n * the second ticket.\n */\n if (isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY)) {\n /*\n * Make sure the client for the second ticket matches\n * requested server.\n */\n krb5_enc_tkt_part *t2enc = request->second_ticket[st_idx]->enc_part2;\n krb5_principal client2 = t2enc->client;\n if (!krb5_principal_compare(kdc_context, request->server, client2)) {\n if ((errcode = krb5_unparse_name(kdc_context, client2, &altcname)))\n altcname = 0;\n if (altcname != NULL)\n limit_string(altcname);", " errcode = KRB5KDC_ERR_SERVER_NOMATCH;\n status = \"2ND_TKT_MISMATCH\";\n goto cleanup;\n }", " ticket_kvno = 0;\n ticket_reply.enc_part.enctype = t2enc->session->enctype;\n st_idx++;\n } else {\n ticket_kvno = server_key->key_data_kvno;\n }", " errcode = krb5_encrypt_tkt_part(kdc_context, &encrypting_key,\n &ticket_reply);\n if (!isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY))\n krb5_free_keyblock_contents(kdc_context, &encrypting_key);\n if (errcode) {\n status = \"TKT_ENCRYPT\";\n goto cleanup;\n }\n ticket_reply.enc_part.kvno = ticket_kvno;\n /* Start assembling the response */\n reply.msg_type = KRB5_TGS_REP;\n if (isflagset(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION) &&\n find_pa_data(request->padata, KRB5_PADATA_S4U_X509_USER) != NULL) {\n errcode = kdc_make_s4u2self_rep(kdc_context,\n subkey,\n header_ticket->enc_part2->session,\n s4u_x509_user,\n &reply,\n &reply_encpart);\n if (errcode) {\n status = \"KDC_RETURN_S4U2SELF_PADATA\";\n goto cleanup;\n }\n }", " reply.client = enc_tkt_reply.client;\n reply.enc_part.kvno = 0;/* We are using the session key */\n reply.ticket = &ticket_reply;", " reply_encpart.session = &session_key;\n reply_encpart.nonce = request->nonce;", " /* copy the time fields */\n reply_encpart.times = enc_tkt_reply.times;", " /* starttime is optional, and treated as authtime if not present.\n so we can nuke it if it matches */\n if (enc_tkt_reply.times.starttime == enc_tkt_reply.times.authtime)\n enc_tkt_reply.times.starttime = 0;", " nolrentry.lr_type = KRB5_LRQ_NONE;\n nolrentry.value = 0;\n nolrarray[0] = &nolrentry;\n nolrarray[1] = 0;\n reply_encpart.last_req = nolrarray; /* not available for TGS reqs */\n reply_encpart.key_exp = 0;/* ditto */\n reply_encpart.flags = enc_tkt_reply.flags;\n reply_encpart.server = ticket_reply.server;", " /* use the session key in the ticket, unless there's a subsession key\n in the AP_REQ */\n reply.enc_part.enctype = subkey ? subkey->enctype :\n header_ticket->enc_part2->session->enctype;\n errcode = kdc_fast_response_handle_padata(state, request, &reply,\n subkey ? subkey->enctype : header_ticket->enc_part2->session->enctype);\n if (errcode !=0 ) {\n status = \"Preparing FAST padata\";\n goto cleanup;\n }\n errcode =kdc_fast_handle_reply_key(state,\n subkey?subkey:header_ticket->enc_part2->session, &reply_key);\n if (errcode) {\n status = \"generating reply key\";\n goto cleanup;\n }\n errcode = return_enc_padata(kdc_context, pkt, request,\n reply_key, server, &reply_encpart,\n is_referral &&\n isflagset(s_flags,\n KRB5_KDB_FLAG_CANONICALIZE));\n if (errcode) {\n status = \"KDC_RETURN_ENC_PADATA\";\n goto cleanup;\n }", " errcode = krb5_encode_kdc_rep(kdc_context, KRB5_TGS_REP, &reply_encpart,\n subkey ? 1 : 0,\n reply_key,\n &reply, response);\n if (errcode) {\n status = \"ENCODE_KDC_REP\";\n } else {\n status = \"ISSUE\";\n }", " memset(ticket_reply.enc_part.ciphertext.data, 0,\n ticket_reply.enc_part.ciphertext.length);\n free(ticket_reply.enc_part.ciphertext.data);\n /* these parts are left on as a courtesy from krb5_encode_kdc_rep so we\n can use them in raw form if needed. But, we don't... */\n memset(reply.enc_part.ciphertext.data, 0,\n reply.enc_part.ciphertext.length);\n free(reply.enc_part.ciphertext.data);", "cleanup:\n assert(status != NULL);\n if (reply_key)\n krb5_free_keyblock(kdc_context, reply_key);\n if (errcode)\n emsg = krb5_get_error_message (kdc_context, errcode);\n log_tgs_req(from, request, &reply, cname, sname, altcname, authtime,\n c_flags, s4u_name, status, errcode, emsg);\n if (errcode) {\n krb5_free_error_message (kdc_context, emsg);\n emsg = NULL;\n }", " if (errcode) {\n int got_err = 0;\n if (status == 0) {\n status = krb5_get_error_message (kdc_context, errcode);\n got_err = 1;\n }\n errcode -= ERROR_TABLE_BASE_krb5;\n if (errcode < 0 || errcode > 128)\n errcode = KRB_ERR_GENERIC;", " retval = prepare_error_tgs(state, request, header_ticket, errcode,\n (server != NULL) ? server->princ : NULL,\n response, status, e_data);\n if (got_err) {\n krb5_free_error_message (kdc_context, status);\n status = 0;\n }\n }", " if (header_ticket != NULL)\n krb5_free_ticket(kdc_context, header_ticket);\n if (request != NULL)\n krb5_free_kdc_req(kdc_context, request);\n if (state)\n kdc_free_rstate(state);\n if (cname != NULL)\n free(cname);\n if (sname != NULL)\n free(sname);\n krb5_db_free_principal(kdc_context, server);\n krb5_db_free_principal(kdc_context, krbtgt);\n krb5_db_free_principal(kdc_context, client);\n if (session_key.contents != NULL)\n krb5_free_keyblock_contents(kdc_context, &session_key);\n if (newtransited)\n free(enc_tkt_reply.transited.tr_contents.data);\n if (s4u_x509_user != NULL)\n krb5_free_pa_s4u_x509_user(kdc_context, s4u_x509_user);\n if (kdc_issued_auth_data != NULL)\n krb5_free_authdata(kdc_context, kdc_issued_auth_data);\n if (s4u_name != NULL)\n free(s4u_name);\n if (subkey != NULL)\n krb5_free_keyblock(kdc_context, subkey);\n if (tgskey != NULL)\n krb5_free_keyblock(kdc_context, tgskey);\n if (reply.padata)\n krb5_free_pa_data(kdc_context, reply.padata);\n if (reply_encpart.enc_padata)\n krb5_free_pa_data(kdc_context, reply_encpart.enc_padata);\n if (enc_tkt_reply.authorization_data != NULL)\n krb5_free_authdata(kdc_context, enc_tkt_reply.authorization_data);\n krb5_free_pa_data(kdc_context, e_data);", " return retval;\n}", "static krb5_error_code\nprepare_error_tgs (struct kdc_request_state *state,\n krb5_kdc_req *request, krb5_ticket *ticket, int error,\n krb5_principal canon_server,\n krb5_data **response, const char *status,\n krb5_pa_data **e_data)\n{\n krb5_error errpkt;\n krb5_error_code retval = 0;\n krb5_data *scratch, *e_data_asn1 = NULL, *fast_edata = NULL;", " errpkt.ctime = request->nonce;\n errpkt.cusec = 0;", " if ((retval = krb5_us_timeofday(kdc_context, &errpkt.stime,\n &errpkt.susec)))\n return(retval);\n errpkt.error = error;\n errpkt.server = request->server;\n if (ticket && ticket->enc_part2)\n errpkt.client = ticket->enc_part2->client;\n else\n errpkt.client = NULL;\n errpkt.text.length = strlen(status);\n if (!(errpkt.text.data = strdup(status)))\n return ENOMEM;", " if (!(scratch = (krb5_data *)malloc(sizeof(*scratch)))) {\n free(errpkt.text.data);\n return ENOMEM;\n }", " if (e_data != NULL) {\n retval = encode_krb5_padata_sequence(e_data, &e_data_asn1);\n if (retval) {\n free(scratch);\n free(errpkt.text.data);\n return retval;\n }\n errpkt.e_data = *e_data_asn1;\n } else\n errpkt.e_data = empty_data();", " if (state) {\n retval = kdc_fast_handle_error(kdc_context, state, request, e_data,\n &errpkt, &fast_edata);\n }\n if (retval) {\n free(scratch);\n free(errpkt.text.data);\n krb5_free_data(kdc_context, e_data_asn1);\n return retval;\n }\n if (fast_edata)\n errpkt.e_data = *fast_edata;\n retval = krb5_mk_error(kdc_context, &errpkt, scratch);\n free(errpkt.text.data);\n krb5_free_data(kdc_context, e_data_asn1);\n krb5_free_data(kdc_context, fast_edata);\n if (retval)\n free(scratch);\n else\n *response = scratch;", " return retval;\n}", "/*\n * The request seems to be for a ticket-granting service somewhere else,\n * but we don't have a ticket for the final TGS. Try to give the requestor\n * some intermediate realm.\n */\nstatic krb5_error_code\nfind_alternate_tgs(krb5_kdc_req *request, krb5_db_entry **server_ptr)\n{\n krb5_error_code retval;\n krb5_principal *plist = NULL, *pl2, tmpprinc;\n krb5_data tmp;\n krb5_db_entry *server = NULL;", " *server_ptr = NULL;", " /*\n * Call to krb5_princ_component is normally not safe but is so\n * here only because find_alternate_tgs() is only called from\n * somewhere that has already checked the number of components in\n * the principal.\n */\n if ((retval = krb5_walk_realm_tree(kdc_context,\n krb5_princ_realm(kdc_context, request->server),\n krb5_princ_component(kdc_context, request->server, 1),\n &plist, KRB5_REALM_BRANCH_CHAR)))\n return retval;", " /* move to the end */\n for (pl2 = plist; *pl2; pl2++);", " /* the first entry in this array is for krbtgt/local@local, so we\n ignore it */\n while (--pl2 > plist) {\n tmp = *krb5_princ_realm(kdc_context, *pl2);\n krb5_princ_set_realm(kdc_context, *pl2,\n krb5_princ_realm(kdc_context, tgs_server));\n retval = krb5_db_get_principal(kdc_context, *pl2, 0, &server);\n krb5_princ_set_realm(kdc_context, *pl2, &tmp);\n if (retval == KRB5_KDB_NOENTRY)\n continue;\n else if (retval)\n goto cleanup;", " /* Found it. */\n tmp = *krb5_princ_realm(kdc_context, *pl2);\n krb5_princ_set_realm(kdc_context, *pl2,\n krb5_princ_realm(kdc_context, tgs_server));\n retval = krb5_copy_principal(kdc_context, *pl2, &tmpprinc);\n if (retval)\n goto cleanup;\n krb5_princ_set_realm(kdc_context, *pl2, &tmp);", " krb5_free_principal(kdc_context, request->server);\n request->server = tmpprinc;\n log_tgs_alt_tgt(request->server);\n *server_ptr = server;\n server = NULL;\n goto cleanup;\n }\n retval = KRB5_KDB_NOENTRY;", "cleanup:\n krb5_free_realm_tree(kdc_context, plist);\n krb5_db_free_principal(kdc_context, server);\n return retval;\n}", "static krb5_int32\nprep_reprocess_req(krb5_kdc_req *request, krb5_principal *krbtgt_princ)\n{\n krb5_error_code retval = KRB5KRB_AP_ERR_BADMATCH;\n char **realms, **cpp, *temp_buf=NULL;\n krb5_data *comp1 = NULL, *comp2 = NULL;\n char *comp1_str = NULL;", " /* By now we know that server principal name is unknown.\n * If CANONICALIZE flag is set in the request\n * If req is not U2U authn. req\n * the requested server princ. has exactly two components\n * either\n * the name type is NT-SRV-HST\n * or name type is NT-UNKNOWN and\n * the 1st component is listed in conf file under host_based_services\n * the 1st component is not in a list in conf under \"no_host_referral\"\n * the 2d component looks like fully-qualified domain name (FQDN)\n * If all of these conditions are satisfied - try mapping the FQDN and\n * re-process the request as if client had asked for cross-realm TGT.\n */\n if (isflagset(request->kdc_options, KDC_OPT_CANONICALIZE) &&\n !isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY) &&\n krb5_princ_size(kdc_context, request->server) == 2) {", " comp1 = krb5_princ_component(kdc_context, request->server, 0);\n comp2 = krb5_princ_component(kdc_context, request->server, 1);", " comp1_str = calloc(1,comp1->length+1);\n if (!comp1_str) {\n retval = ENOMEM;\n goto cleanup;\n }", " if (comp1->data != NULL)\n memcpy(comp1_str, comp1->data, comp1->length);", "\n if ((krb5_princ_type(kdc_context, request->server) == KRB5_NT_SRV_HST ||\n krb5_princ_type(kdc_context, request->server) == KRB5_NT_SRV_INST ||\n (krb5_princ_type(kdc_context, request->server) == KRB5_NT_UNKNOWN &&\n kdc_active_realm->realm_host_based_services != NULL &&\n (krb5_match_config_pattern(kdc_active_realm->realm_host_based_services,\n comp1_str) == TRUE ||\n krb5_match_config_pattern(kdc_active_realm->realm_host_based_services,\n KRB5_CONF_ASTERISK) == TRUE))) &&\n (kdc_active_realm->realm_no_host_referral == NULL ||\n (krb5_match_config_pattern(kdc_active_realm->realm_no_host_referral,\n KRB5_CONF_ASTERISK) == FALSE &&\n krb5_match_config_pattern(kdc_active_realm->realm_no_host_referral,\n comp1_str) == FALSE))) {", " if (memchr(comp2->data, '.', comp2->length) == NULL)\n goto cleanup;\n temp_buf = calloc(1, comp2->length+1);\n if (!temp_buf) {\n retval = ENOMEM;\n goto cleanup;\n }", " if (comp2->data != NULL)\n memcpy(temp_buf, comp2->data, comp2->length);", " retval = krb5int_get_domain_realm_mapping(kdc_context, temp_buf, &realms);\n free(temp_buf);\n if (retval) {\n /* no match found */\n kdc_err(kdc_context, retval, \"unable to find realm of host\");\n goto cleanup;\n }\n if (realms == 0) {\n retval = KRB5KRB_AP_ERR_BADMATCH;\n goto cleanup;\n }\n /* Don't return a referral to the null realm or the service\n * realm. */\n if (realms[0] == 0 ||\n data_eq_string(request->server->realm, realms[0])) {\n free(realms[0]);\n free(realms);\n retval = KRB5KRB_AP_ERR_BADMATCH;\n goto cleanup;\n }\n /* Modify request.\n * Construct cross-realm tgt : krbtgt/REMOTE_REALM@LOCAL_REALM\n * and use it as a principal in this req.\n */\n retval = krb5_build_principal(kdc_context, krbtgt_princ,\n (*request->server).realm.length,\n (*request->server).realm.data,\n \"krbtgt\", realms[0], (char *)0);\n for (cpp = realms; *cpp; cpp++)\n free(*cpp);\n }\n }\ncleanup:\n free(comp1_str);", " return retval;\n}" ]
[ 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, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [1168], "buggy_code_start_loc": [1144], "filenames": ["src/kdc/do_tgs_req.c"], "fixing_code_end_loc": [1170], "fixing_code_start_loc": [1144], "message": "The prep_reprocess_req function in do_tgs_req.c in the Key Distribution Center (KDC) in MIT Kerberos 5 (aka krb5) before 1.10.5 does not properly perform service-principal realm referral, which allows remote authenticated users to cause a denial of service (NULL pointer dereference and daemon crash) via a crafted TGS-REQ request.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mit:kerberos_5:*:*:*:*:*:*:*:*", "matchCriteriaId": "ADAAA945-792F-419A-9045-01CE94A74320", "versionEndExcluding": "1.10.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:opensuse:11.4:*:*:*:*:*:*:*", "matchCriteriaId": "DE554781-1EB9-446E-911F-6C11970C47F4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:opensuse:opensuse:12.1:*:*:*:*:*:*:*", "matchCriteriaId": "EBB2C482-D2A4-48B3-ACE7-E1DFDCC409B5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:opensuse:opensuse:12.2:*:*:*:*:*:*:*", "matchCriteriaId": "D806A17E-B8F9-466D-807D-3F1E77603DC8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:opensuse:opensuse:12.3:*:*:*:*:*:*:*", "matchCriteriaId": "DFBF430B-0832-44B0-AA0E-BA9E467F7668", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:17:*:*:*:*:*:*:*", "matchCriteriaId": "2DA9D861-3EAF-42F5-B0B6-A4CD7BDD6188", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:18:*:*:*:*:*:*:*", "matchCriteriaId": "E14271AE-1309-48F3-B9C6-D7DEEC488279", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:redhat:enterprise_linux_desktop:6.0:*:*:*:*:*:*:*", "matchCriteriaId": "EE249E1B-A1FD-4E08-AA71-A0E1F10FFE97", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_eus:6.4:*:*:*:*:*:*:*", "matchCriteriaId": "8A8E07B7-3739-4BEB-88F8-C7F62431E889", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_server:6.0:*:*:*:*:*:*:*", "matchCriteriaId": "9BBCD86A-E6C7-4444-9D74-F861084090F0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_server_aus:6.4:*:*:*:*:*:*:*", "matchCriteriaId": "AF83BB87-B203-48F9-9D06-48A5FE399050", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_workstation:6.0:*:*:*:*:*:*:*", "matchCriteriaId": "E5ED5807-55B7-47C5-97A6-03233F4FBC3A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The prep_reprocess_req function in do_tgs_req.c in the Key Distribution Center (KDC) in MIT Kerberos 5 (aka krb5) before 1.10.5 does not properly perform service-principal realm referral, which allows remote authenticated users to cause a denial of service (NULL pointer dereference and daemon crash) via a crafted TGS-REQ request."}, {"lang": "es", "value": "La funci\u00f3n prep_reprocess_req en do_tgs_req.c en el Key Distribution Center (KDC) en MIT Kerberos 5 (aka krb5) antes de v1.10.5 no realiza correctamente el servicio \u00e1mbito de referencia principal, lo que permite a usuarios remotos autenticados causar una denegaci\u00f3n de servicio (desreferencia a un puntero nulo y la ca\u00edda del demonio) a trav\u00e9s de una solicitud TGS-REQ modificada."}], "evaluatorComment": null, "id": "CVE-2013-1416", "lastModified": "2021-02-02T18:40:23.900", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2013-04-19T11:44:26.017", "references": [{"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "http://krbdev.mit.edu/rt/Ticket/Display.html?id=7600"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://lists.fedoraproject.org/pipermail/package-announce/2013-April/102058.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://lists.fedoraproject.org/pipermail/package-announce/2013-April/102074.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-updates/2013-05/msg00011.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-updates/2013-06/msg00041.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-updates/2013-06/msg00102.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://rhn.redhat.com/errata/RHSA-2013-0748.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.mandriva.com/security/advisories?name=MDVSA-2013:157"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.mandriva.com/security/advisories?name=MDVSA-2013:158"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/krb5/krb5/commit/8ee70ec63931d1e38567905387ab9b1d45734d81"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/krb5/krb5/commit/8ee70ec63931d1e38567905387ab9b1d45734d81"}, "type": "CWE-476"}
175
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n *\t\t\tGPAC - Multimedia Framework C SDK\n *\n *\t\t\tAuthors: Jean Le Feuvre\n *\t\t\tCopyright (c) Telecom ParisTech 2000-2021\n *\t\t\t\t\tAll rights reserved\n *\n * This file is part of GPAC / NALU (AVC, HEVC, VVC) reframer filter\n *\n * GPAC is free software; you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2, or (at your option)\n * any later version.\n *\n * GPAC is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; see the file COPYING. If not, write to\n * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.\n *\n */", "#include <gpac/avparse.h>\n#include <gpac/constants.h>\n#include <gpac/filters.h>\n#include <gpac/internal/media_dev.h>\n//for oinf stuff\n#include <gpac/internal/isomedia_dev.h>", "#ifndef GPAC_DISABLE_AV_PARSERS", "#define CTS_POC_OFFSET_SAFETY\t1000", "GF_Err gf_bs_set_logger(GF_BitStream *bs, void (*on_bs_log)(void *udta, const char *field_name, u32 nb_bits, u64 field_val, s32 idx1, s32 idx2, s32 idx3), void *udta);", "typedef struct\n{\n\tu64 pos;\n\tDouble duration;\n} NALUIdx;", "\ntypedef struct\n{\n\tu32 layer_id_plus_one;\n\tu32 min_temporal_id, max_temporal_id;\n} LHVCLayerInfo;", "enum {\n\tSTRICT_POC_OFF = 0,\n\tSTRICT_POC_ON,\n\tSTRICT_POC_ERROR,\n};", "typedef struct\n{\n\t//filter args\n\tGF_Fraction fps;\n\tDouble index;\n\tBool explicit, force_sync, nosei, importer, subsamples, nosvc, novpsext, deps, seirw, audelim, analyze;\n\tu32 nal_length;\n\tu32 strict_poc;\n\tu32 bsdbg;\n\tGF_Fraction idur;", "\t//only one input pid declared\n\tGF_FilterPid *ipid;\n\t//only one output pid declared\n\tGF_FilterPid *opid;", "\t//read bitstream for AVC/HEVC parsing\n\tGF_BitStream *bs_r;\n\t//write bitstream for nalus size length rewrite\n\tGF_BitStream *bs_w;\n\t//current CTS/DTS of the stream, may be overridden by input packet if not file (eg TS PES)\n\tu64 cts, dts, prev_dts, prev_cts;\n\tu32 pck_duration;\n\t//basic config stored here: with, height CRC of base and enh layer decoder config, sample aspect ratio\n\t//when changing, a new pid config will be emitted\n\tu32 width, height;\n\tu32 crc_cfg, crc_cfg_enh;\n\tGF_Fraction sar;\n\tGF_Fraction cur_fps;", "\t//duration of the file if known\n\tGF_Fraction64 duration;\n\t//playback start range\n\tDouble start_range;\n\t//indicates we are in seek, packets before start range should be marked\n\tBool in_seek;\n\t//set once we play something\n\tBool is_playing;\n\t//is a file, is a file fully loaded on disk (local or download done)\n\tBool is_file, file_loaded;\n\t//initial PLAY command found\n\tBool initial_play_done;", "\t//list of RAP entry points\n\tNALUIdx *indexes;\n\tu32 index_alloc_size, index_size;", "\n\t//timescale of the input pid if any, 0 otherwise\n\tu32 timescale;\n\t//framing flag of input packet when input pid has timing (eg is not a file)\n\tBool input_is_au_start;", "\tGF_FilterPacket *src_pck;", "\tBool full_au_source;", "\t//total delay in frames between decode and presentation\n\ts32 max_total_delay;\n\t//max size codable with our nal_length setting\n\tu32 max_nalu_size_allowed;", "\t//position in input packet from which we resume parsing\n\tu32 resume_from;\n\t//prevents message about possible NAL size optimizaion at finalization\n\tBool nal_adjusted;", "\t//avc/hevc switch\n\tu32 codecid;\n\t//name of the logger\n\tconst char *log_name;", "\t//list of packet (in decode order !!) not yet dispatched.\n\t//Dispatch depends on the mode:\n\t//strict_poc=0: we wait after each IDR until we find a stable poc diff between pictures, controled by poc_probe_done\n\t//strict_poc>=1: we dispatch only after IDR or at the end (huge delay)\n\tGF_List *pck_queue;\n\t//dts of the last IDR found\n\tu64 dts_last_IDR;\n\t//max size of NALUs in the bitstream\n\tu32 max_nalu_size;", "\n\tu8 *nal_store;\n\tu32 nal_store_size, nal_store_alloc;", "\t//list of param sets found\n\tGF_List *sps, *pps, *vps, *sps_ext, *pps_svc, *vvc_aps_pre, *vvc_dci;\n\t//set to true if one of the PS has been modified, will potentially trigger a PID reconfigure\n\tBool ps_modified;", "\t//stats\n\tu32 nb_idr, nb_i, nb_p, nb_b, nb_sp, nb_si, nb_sei, nb_nalus, nb_aud;", "\t//frame has intra slice\n\tBool has_islice;\n\t//AU is rap\n\tGF_FilterSAPType au_sap;\n\t//frame first slice\n\tBool first_slice_in_au;\n\t//paff used - NEED FURTHER CHECKING\n\tBool is_paff;\n\tBool bottom_field_flag;\n\t//SEI recovery count - if 0 and I slice only frame, openGOP detection (avc)\n\ts32 sei_recovery_frame_count;\n\tu32 use_opengop_gdr;\n\t//poc compute variables\n\ts32 last_poc, max_last_poc, max_last_b_poc, poc_diff, prev_last_poc, min_poc, poc_shift;\n\t//set to TRUE once 3 frames with same min poc diff are found, enabling dispatch of the frames\n\tBool poc_probe_done;\n\t//pointer to the first packet of the current frame (the one holding timing info)\n\t//this packet is in the packet queue\n\tGF_FilterPacket *first_pck_in_au;\n\t//frame has slices used as reference\n\tBool has_ref_slices;\n\t//frame has redundant coding\n\tBool has_redundant;", "\tBool last_frame_is_idr;", "\t//buffer to store SEI messages\n\t//for AVC: we have to rewrite the SEI to remove some of the messages according to the spec\n\t//for HEVC: we store prefix SEI here and dispatch them once the first VCL is found\n\tchar *sei_buffer;\n\tu32 sei_buffer_size, sei_buffer_alloc;", "\t//subsample buffer, only used for SVC for now\n\tu32 subsamp_buffer_alloc, subsamp_buffer_size, subs_mapped_bytes;\n\tchar *subsamp_buffer;", "\t//AVC specific\n\t//avc bitstream state\n\tAVCState *avc_state;", "\t//SVC specific\n\tchar *svc_prefix_buffer;\n\tu32 svc_prefix_buffer_size, svc_prefix_buffer_alloc;\n\tu32 svc_nalu_prefix_reserved;\n\tu8 svc_nalu_prefix_priority;", "\t//HEVC specific\n\tHEVCState *hevc_state;\n\t//shvc stats\n\tu32 nb_e_idr, nb_e_i, nb_e_p, nb_e_b;\n\tBool vvc_no_stats;", "\tLHVCLayerInfo linf[64];\n\tu8 max_temporal_id[64];\n\tu8 min_layer_id;", "\t//VVC specific\n\tVVCState *vvc_state;", "\tBool has_initial_aud;\n\tchar init_aud[3];", "\tBool interlaced;", "\tBool is_mvc;", "\tu32 bitrate;\n\tu32 nb_frames;\n} GF_NALUDmxCtx;", "static void naludmx_enqueue_or_dispatch(GF_NALUDmxCtx *ctx, GF_FilterPacket *n_pck, Bool flush_ref);\nstatic void naludmx_finalize_au_flags(GF_NALUDmxCtx *ctx);", "\nGF_Err naludmx_configure_pid(GF_Filter *filter, GF_FilterPid *pid, Bool is_remove)\n{\n\tconst GF_PropertyValue *p;\n\tGF_NALUDmxCtx *ctx = gf_filter_get_udta(filter);", "\tif (is_remove) {\n\t\tctx->ipid = NULL;\n\t\tif (ctx->opid) {\n\t\t\tgf_filter_pid_remove(ctx->opid);\n\t\t\tctx->opid = NULL;\n\t\t}\n\t\treturn GF_OK;\n\t}\n\tif (! gf_filter_pid_check_caps(pid))\n\t\treturn GF_NOT_SUPPORTED;", "\tctx->ipid = pid;\n\tp = gf_filter_pid_get_property(pid, GF_PROP_PID_TIMESCALE);\n\tif (p) {\n\t\tctx->timescale = p->value.uint;\n\t\t//if we have a FPS prop, use it\n\t\tp = gf_filter_pid_get_property(pid, GF_PROP_PID_FPS);\n\t\tif (p) {\n\t\t\tctx->cur_fps = p->value.frac;\n\t\t} else {\n\t\t\tctx->cur_fps.den = 0;\n\t\t\tctx->cur_fps.num = ctx->timescale;\n\t\t}\n\t}", "\tp = gf_filter_pid_get_property(pid, GF_PROP_PID_CODECID);\n\tif (p) {\n\t\tswitch (p->value.uint) {\n\t\tcase GF_CODECID_HEVC:\n\t\tcase GF_CODECID_LHVC:\n\t\t\tctx->codecid = GF_CODECID_HEVC;\n\t\t\tbreak;\n\t\tcase GF_CODECID_VVC:\n\t\t\tctx->codecid = GF_CODECID_VVC;\n\t\t\tbreak;\n\t\tcase GF_CODECID_AVC:\n\t\tcase GF_CODECID_AVC_PS:\n\t\tcase GF_CODECID_SVC:\n\t\tcase GF_CODECID_MVC:\n\t\t\tctx->codecid = GF_CODECID_AVC;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn GF_NOT_SUPPORTED;\n\t\t}\n\t}\n\telse {\n\t\tp = gf_filter_pid_get_property(pid, GF_PROP_PID_MIME);\n\t\tif (p && p->value.string && (\n\t\t\tstrstr(p->value.string, \"hvc\")\n\t\t\t|| strstr(p->value.string, \"hevc\")\n\t\t\t|| strstr(p->value.string, \"265\")\n\t\t\t|| strstr(p->value.string, \"shvc\")\n\t\t\t|| strstr(p->value.string, \"mhvc\")\n\t\t\t|| strstr(p->value.string, \"lhvc\")\n\t\t) )\n\t\t\tctx->codecid = GF_CODECID_HEVC;\n\t\telse if (p && p->value.string && (\n\t\t\tstrstr(p->value.string, \"vvc\")\n\t\t) )\n\t\t\tctx->codecid = GF_CODECID_VVC;\n\t\telse {\n\t\t\tp = gf_filter_pid_get_property(pid, GF_PROP_PID_FILE_EXT);\n\t\t\tif (p && p->value.string && (\n\t\t\t\t strstr(p->value.string, \"hvc\")\n\t\t\t\t || strstr(p->value.string, \"hevc\")\n\t\t\t\t || strstr(p->value.string, \"265\")\n\t\t\t\t || strstr(p->value.string, \"shvc\")\n\t\t\t\t || strstr(p->value.string, \"mhvc\")\n\t\t\t\t || strstr(p->value.string, \"lhvc\")\n\t\t\t ) )\n\t\t\t\tctx->codecid = GF_CODECID_HEVC;\n\t\t\telse if (p && p->value.string && (\n\t\t\t\t strstr(p->value.string, \"vvc\")\n\t\t\t\t || strstr(p->value.string, \"266\")\n\t\t\t\t || strstr(p->value.string, \"lvvc\")\n\t\t\t ) )\n\t\t\t\tctx->codecid = GF_CODECID_VVC;\n\t\t\telse\n\t\t\t\tctx->codecid = GF_CODECID_AVC;\n\t\t}\n\t}\n\tif (ctx->codecid==GF_CODECID_HEVC) {\n#ifdef GPAC_DISABLE_HEVC\n\t\treturn GF_NOT_SUPPORTED;\n#else\n\t\tctx->log_name = \"HEVC\";\n\t\tif (ctx->avc_state) gf_free(ctx->avc_state);\n\t\tif (ctx->vvc_state) gf_free(ctx->vvc_state);\n\t\tif (!ctx->hevc_state) GF_SAFEALLOC(ctx->hevc_state, HEVCState);\n\t\tctx->min_layer_id = 0xFF;\n#endif\n\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\tctx->log_name = \"VVC\";\n\t\tif (ctx->hevc_state) gf_free(ctx->hevc_state);\n\t\tif (ctx->avc_state) gf_free(ctx->avc_state);\n\t\tif (!ctx->vvc_state) GF_SAFEALLOC(ctx->vvc_state, VVCState);\n\t} else {\n\t\tctx->log_name = \"AVC|H264\";\n\t\tif (ctx->hevc_state) gf_free(ctx->hevc_state);\n\t\tif (ctx->vvc_state) gf_free(ctx->vvc_state);\n\t\tif (!ctx->avc_state) GF_SAFEALLOC(ctx->avc_state, AVCState);\n\t}\n\tif (ctx->timescale && !ctx->opid) {\n\t\tctx->opid = gf_filter_pid_new(filter);\n\t\tctx->first_slice_in_au = GF_TRUE;\n\t}\n\tctx->full_au_source = GF_FALSE;\n\tp = gf_filter_pid_get_property(pid, GF_PROP_PID_UNFRAMED_FULL_AU);\n\tif (p && p->value.boolean) {\n\t\tGF_FilterEvent fevt;\n\t\t//this is a reframer used after an encoder, we want to make sure we have enough frames to compute POC otherwise we might block the chain\n\t\t//by holding input packets - ask 1s by default\n\t\tGF_FEVT_INIT(fevt, GF_FEVT_BUFFER_REQ, ctx->ipid);\n\t\tfevt.buffer_req.pid_only = GF_TRUE;\n\t\tfevt.buffer_req.max_buffer_us = 1000000;\n\t\tgf_filter_pid_send_event(ctx->ipid, &fevt);\n\t\tctx->full_au_source = GF_TRUE;\n\t}", "\t//copy properties at init or reconfig\n\tif (ctx->opid) {\n\t\tif (ctx->poc_probe_done) {\n\t\t\t//full frame mode, flush everything before signaling discontinuity\n\t\t\t//for other modes discontinuity we signal disconntinuity before the current AU being reconstructed\n\t\t\tif (ctx->full_au_source && ctx->first_pck_in_au)\n\t\t\t\tnaludmx_finalize_au_flags(ctx);", "\t\t\tnaludmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE);\n\t\t}\n\t\tgf_filter_pid_copy_properties(ctx->opid, ctx->ipid);\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_STREAM_TYPE, & PROP_UINT(GF_STREAM_VISUAL));\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_CODECID, & PROP_UINT(ctx->codecid));", "\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_UNFRAMED, NULL);\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_UNFRAMED_FULL_AU, NULL);\n\t\tif (!gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_ID))\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_ID, &PROP_UINT(1));", "\t\tctx->ps_modified = GF_TRUE;\n\t\tctx->crc_cfg = ctx->crc_cfg_enh = 0;\n\t}", "\treturn GF_OK;\n}", "\nstatic void naludmx_check_dur(GF_Filter *filter, GF_NALUDmxCtx *ctx)\n{\n\tFILE *stream;\n\tGF_BitStream *bs;\n\tu64 duration, cur_dur, nal_start, start_code_pos, rate;\n\tAVCState *avc_state = NULL;\n\tHEVCState *hevc_state = NULL;\n\tVVCState *vvc_state = NULL;\n\tBool first_slice_in_pic = GF_TRUE;\n\tconst GF_PropertyValue *p;\n\tconst char *filepath = NULL;\n\tif (!ctx->opid || ctx->timescale || ctx->file_loaded) return;", "\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_FILEPATH);\n\tif (!p || !p->value.string || !strncmp(p->value.string, \"gmem://\", 7)) {\n\t\tctx->is_file = GF_FALSE;\n\t\tctx->file_loaded = GF_TRUE;\n\t\treturn;\n\t}\n\tfilepath = p->value.string;\n\tctx->is_file = GF_TRUE;", "\tif (ctx->index<0) {\n\t\tif (gf_opts_get_bool(\"temp\", \"force_indexing\")) {\n\t\t\tctx->index = 1.0;\n\t\t} else {\n\t\t\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_DOWN_SIZE);\n\t\t\tif (!p || (p->value.longuint > 20000000)) {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_PARSER, (\"[%s] Source file larger than 20M, skipping indexing\\n\", ctx->log_name));\n\t\t\t} else {\n\t\t\t\tctx->index = -ctx->index;\n\t\t\t}\n\t\t}\n\t}\n\tif (ctx->index<=0) {\n\t\tctx->duration.num = 1;\n\t\tctx->file_loaded = GF_TRUE;\n\t\treturn;\n\t}", "\tif (ctx->codecid==GF_CODECID_HEVC) {\n\t\tGF_SAFEALLOC(hevc_state, HEVCState);\n\t\tif (!hevc_state) return;\n\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\tGF_SAFEALLOC(vvc_state, VVCState);\n\t\tif (!vvc_state) return;\n\t} else {\n\t\tGF_SAFEALLOC(avc_state, AVCState);\n\t\tif (!avc_state) return;\n\t}", "\tstream = gf_fopen(filepath, \"rb\");\n\tif (!stream) {\n\t\tif (hevc_state) gf_free(hevc_state);\n\t\tif (vvc_state) gf_free(vvc_state);\n\t\tif (avc_state) gf_free(avc_state);\n\t\treturn;\n\t}\n\tctx->index_size = 0;\n\tduration = 0;\n\tcur_dur = 0;", "\tbs = gf_bs_from_file(stream, GF_BITSTREAM_READ);\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);", "\tstart_code_pos = gf_bs_get_position(bs);\n\tif (!gf_media_nalu_is_start_code(bs)) {\n\t\tif (hevc_state) gf_free(hevc_state);\n\t\tif (avc_state) gf_free(avc_state);\n\t\tgf_bs_del(bs);\n\t\tgf_fclose(stream);\n\t\tctx->duration.num = 1;\n\t\tctx->file_loaded = GF_TRUE;\n\t\treturn;\n\t}", "\tnal_start = gf_bs_get_position(bs);", "\twhile (gf_bs_available(bs)) {\n\t\tu32 nal_size;\n\t\ts32 res;\n\t\tBool is_rap = GF_FALSE;\n\t\tBool is_slice = GF_FALSE;\n\t\tnal_size = gf_media_nalu_next_start_code_bs(bs);", "\t\tgf_bs_seek(bs, nal_start);\n\t\tif (hevc_state) {\n#ifndef GPAC_DISABLE_HEVC\n\t\t\tu8 temporal_id, layer_id, nal_type;", "\t\t\tres = gf_hevc_parse_nalu_bs(bs, hevc_state, &nal_type, &temporal_id, &layer_id);\n\t\t\tif (res>0) first_slice_in_pic = GF_TRUE;\n\t\t\tswitch (nal_type) {\n\t\t\tcase GF_HEVC_NALU_SLICE_IDR_N_LP:\n\t\t\tcase GF_HEVC_NALU_SLICE_IDR_W_DLP:\n\t\t\tcase GF_HEVC_NALU_SLICE_CRA:\n\t\t\tcase GF_HEVC_NALU_SLICE_BLA_N_LP:\n\t\t\tcase GF_HEVC_NALU_SLICE_BLA_W_LP:\n\t\t\tcase GF_HEVC_NALU_SLICE_BLA_W_DLP:\n\t\t\t\tis_rap = GF_TRUE;\n\t\t\t\tis_slice = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tcase GF_HEVC_NALU_SLICE_STSA_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_STSA_R:\n\t\t\tcase GF_HEVC_NALU_SLICE_RADL_R:\n\t\t\tcase GF_HEVC_NALU_SLICE_RASL_R:\n\t\t\tcase GF_HEVC_NALU_SLICE_RADL_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_RASL_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_TRAIL_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_TRAIL_R:\n\t\t\tcase GF_HEVC_NALU_SLICE_TSA_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_TSA_R:\n\t\t\t\tis_slice = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n#endif // GPAC_DISABLE_HEVC\n\t\t} else if (vvc_state) {", "\t\t} else {\n\t\t\tu32 nal_type;\n\t\t\tu64 pos = gf_bs_get_position(bs);\n\t\t\tres = gf_avc_parse_nalu(bs, avc_state);\n\t\t\tif (res>0) first_slice_in_pic = GF_TRUE;", "\t\t\tnal_type = avc_state->last_nal_type_parsed;", "\t\t\tswitch (nal_type) {\n\t\t\tcase GF_AVC_NALU_SEQ_PARAM:\n\t\t\t\tgf_bs_seek(bs, pos);\n\t\t\t\tgf_avc_read_sps_bs(bs, avc_state, GF_FALSE, NULL);\n\t\t\t\tbreak;\n\t\t\tcase GF_AVC_NALU_PIC_PARAM:\n\t\t\t\tgf_bs_seek(bs, pos);\n\t\t\t\tgf_avc_read_pps_bs(bs, avc_state);\n\t\t\t\tbreak;\n\t\t\tcase GF_AVC_NALU_IDR_SLICE:\n\t\t\t\tis_rap = GF_TRUE;\n\t\t\t\tis_slice = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tcase GF_AVC_NALU_NON_IDR_SLICE:\n\t\t\tcase GF_AVC_NALU_DP_A_SLICE:\n\t\t\tcase GF_AVC_NALU_DP_B_SLICE:\n\t\t\tcase GF_AVC_NALU_DP_C_SLICE:\n\t\t\t\tis_slice = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "\t\tif (is_rap && first_slice_in_pic && (cur_dur >= ctx->index * ctx->cur_fps.num) ) {\n\t\t\tif (!ctx->index_alloc_size) ctx->index_alloc_size = 10;\n\t\t\telse if (ctx->index_alloc_size == ctx->index_size) ctx->index_alloc_size *= 2;\n\t\t\tctx->indexes = gf_realloc(ctx->indexes, sizeof(NALUIdx)*ctx->index_alloc_size);\n\t\t\tctx->indexes[ctx->index_size].pos = start_code_pos;\n\t\t\tctx->indexes[ctx->index_size].duration = (Double) duration;\n\t\t\tctx->indexes[ctx->index_size].duration /= ctx->cur_fps.num;\n\t\t\tctx->index_size ++;\n\t\t\tcur_dur = 0;\n\t\t}", "\t\tif (is_slice && first_slice_in_pic) {\n\t\t\tduration += ctx->cur_fps.den;\n\t\t\tcur_dur += ctx->cur_fps.den;\n\t\t\tfirst_slice_in_pic = GF_FALSE;\n\t\t}", "\t\tgf_bs_seek(bs, nal_start + nal_size);\n/*\t\tnal_start = gf_media_nalu_next_start_code_bs(bs);\n\t\tif (nal_start) gf_bs_skip_bytes(bs, nal_start);\n*/\n\t\tif (gf_bs_available(bs)<4)\n\t\t\tbreak;", "\t\tstart_code_pos = gf_bs_get_position(bs);\n\t\tnal_start = gf_media_nalu_is_start_code(bs);\n\t\tif (!nal_start) {\n\t\t\tbreak;\n\t\t}\n\t\tnal_start = gf_bs_get_position(bs);\n\t}", "\trate = gf_bs_get_position(bs);\n\tgf_bs_del(bs);\n\tgf_fclose(stream);\n\tif (hevc_state) gf_free(hevc_state);\n\tif (vvc_state) gf_free(vvc_state);\n\tif (avc_state) gf_free(avc_state);", "\tif (!ctx->duration.num || (ctx->duration.num * ctx->cur_fps.num != duration * ctx->duration.den)) {\n\t\tctx->duration.num = (s32) duration;\n\t\tctx->duration.den = ctx->cur_fps.num;", "\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_DURATION, & PROP_FRAC64(ctx->duration));", "\t\tif (duration && (!gf_sys_is_test_mode() || gf_opts_get_bool(\"temp\", \"force_indexing\"))) {\n\t\t\trate *= 8 * ctx->duration.den;\n\t\t\trate /= ctx->duration.num;\n\t\t\tctx->bitrate = (u32) rate;\n\t\t}\n\t}", "\n\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_FILE_CACHED);\n\tif (p && p->value.boolean) ctx->file_loaded = GF_TRUE;\n\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_CAN_DATAREF, & PROP_BOOL(GF_TRUE ) );\n}", "\nstatic void naludmx_enqueue_or_dispatch(GF_NALUDmxCtx *ctx, GF_FilterPacket *n_pck, Bool flush_ref)\n{\n\t//TODO: we are dispatching frames in \"negctts mode\", ie we may have DTS>CTS\n\t//need to signal this for consumers using DTS (eg MPEG-2 TS)\n\tif (flush_ref && ctx->pck_queue && ctx->poc_diff) {\n\t\tu32 dts_inc=0;\n\t\ts32 last_poc = 0;\n\t\tBool patch_missing_frame = GF_FALSE;\n\t\t//send all reference packet queued\n\t\tif (ctx->strict_poc==STRICT_POC_ERROR) {\n\t\t\tu32 i;\n\t\t\tu32 nb_bframes = 0;\n\t\t\tfor (i=0; i<gf_list_count(ctx->pck_queue); i++) {\n\t\t\t\ts32 poc;\n\t\t\t\tu64 poc_ts, dts;\n\t\t\t\tGF_FilterPacket *q_pck = gf_list_get(ctx->pck_queue, i);", "\t\t\t\tif (q_pck == ctx->first_pck_in_au) break;", "\t\t\t\tdts = gf_filter_pck_get_dts(q_pck);\n\t\t\t\tif (dts == GF_FILTER_NO_TS) continue;\n\t\t\t\tpoc_ts = gf_filter_pck_get_cts(q_pck);\n\t\t\t\tassert(poc_ts != GF_FILTER_NO_TS);\n\t\t\t\tpoc = (s32) ((s64) poc_ts - CTS_POC_OFFSET_SAFETY);", "\t\t\t\tif (i) {\n\t\t\t\t\tif (last_poc>poc) nb_bframes ++;\n\t\t\t\t\telse if (last_poc + ctx->poc_diff<poc)\n\t\t\t\t\t\tpatch_missing_frame = GF_TRUE;\n\t\t\t\t}\n\t\t\t\tlast_poc = poc;\n\t\t\t}\n\t\t\tif (nb_bframes>1)\n\t\t\t\tpatch_missing_frame = GF_FALSE;\n\t\t\telse if (nb_bframes)\n\t\t\t\tpatch_missing_frame = GF_TRUE;\n\t\t}\n\t\tlast_poc = GF_INT_MIN;", "\t\twhile (gf_list_count(ctx->pck_queue) ) {\n\t\t\tu64 dts;\n\t\t\tGF_FilterPacket *q_pck = gf_list_get(ctx->pck_queue, 0);", "\t\t\tif (q_pck == ctx->first_pck_in_au) break;", "\t\t\tdts = gf_filter_pck_get_dts(q_pck);\n\t\t\tif (dts != GF_FILTER_NO_TS) {\n\t\t\t\ts32 poc;\n\t\t\t\tu64 poc_ts, cts;\n\t\t\t\tu8 carousel_info = gf_filter_pck_get_carousel_version(q_pck);", "\t\t\t\t//we reused timing from source packets\n\t\t\t\tif (!carousel_info) {\n\t\t\t\t\tassert(ctx->timescale);\n\t\t\t\t\tgf_list_rem(ctx->pck_queue, 0);\n\t\t\t\t\tgf_filter_pck_send(q_pck);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tgf_filter_pck_set_carousel_version(q_pck, 0);", "\n\t\t\t\tpoc_ts = gf_filter_pck_get_cts(q_pck);\n\t\t\t\tassert(poc_ts != GF_FILTER_NO_TS);\n\t\t\t\tpoc = (s32) ((s64) poc_ts - CTS_POC_OFFSET_SAFETY);", "\t\t\t\tif (patch_missing_frame) {\n\t\t\t\t\tif (last_poc!=GF_INT_MIN) {\n\t\t\t\t\t\t//check if we missed an IDR (poc reset)\n\t\t\t\t\t\tif (poc && (last_poc > poc) ) {\n\t\t\t\t\t\t\tlast_poc = 0;\n\t\t\t\t\t\t\tdts_inc += ctx->cur_fps.den;\n\t\t\t\t\t\t\tctx->dts_last_IDR = dts;\n\t\t\t\t\t\t\tctx->dts += ctx->cur_fps.den;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//check if we miss a frame\n\t\t\t\t\t\twhile (last_poc + ctx->poc_diff < poc) {\n\t\t\t\t\t\t\tlast_poc += ctx->poc_diff;\n\t\t\t\t\t\t\tdts_inc += ctx->cur_fps.den;\n\t\t\t\t\t\t\tctx->dts += ctx->cur_fps.den;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlast_poc = poc;\n\t\t\t\t\tdts += dts_inc;\n\t\t\t\t}\n\t\t\t\t//poc is stored as diff since last IDR which has min_poc\n\t\t\t\tcts = ( (ctx->min_poc + (s32) poc) * ctx->cur_fps.den ) / ctx->poc_diff + ctx->dts_last_IDR;", "\t\t\t\t/*if PAFF, 2 pictures (eg poc) <=> 1 aggregated frame (eg sample), divide by 2*/\n\t\t\t\tif (ctx->is_paff) {\n\t\t\t\t\tcts /= 2;\n\t\t\t\t\t/*in some cases the poc is not on the top field - if that is the case, round up*/\n\t\t\t\t\tif (cts % ctx->cur_fps.den) {\n\t\t\t\t\t\tcts = ((cts/ctx->cur_fps.den)+1) * ctx->cur_fps.den;\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\tgf_filter_pck_set_cts(q_pck, cts);\n\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"[%s] Frame timestamps computed dts \"LLU\" cts \"LLU\" (poc %d min poc %d poc_diff %d last IDR DTS \"LLU\")\\n\", ctx->log_name, dts, cts, poc, ctx->min_poc, ctx->poc_diff, ctx->dts_last_IDR));", "\t\t\t\tif (ctx->importer && ctx->cur_fps.den) {\n\t\t\t\t\tpoc = (s32) ( (s64) cts - (s64) dts);\n\t\t\t\t\tif (poc<0) poc = -poc;\n\t\t\t\t\tpoc /= ctx->cur_fps.den;\n\t\t\t\t\tif (poc > ctx->max_total_delay)\n\t\t\t\t\t\tctx->max_total_delay = poc;\n\t\t\t\t}\n\t\t\t}\n\t\t\tgf_list_rem(ctx->pck_queue, 0);\n\t\t\tgf_filter_pck_send(q_pck);\n\t\t}\n\t}\n\tif (!n_pck) return;", "\tif (!ctx->pck_queue) ctx->pck_queue = gf_list_new();\n\tgf_list_add(ctx->pck_queue, n_pck);\n}", "static void naludmx_add_param_nalu(GF_List *param_list, GF_NALUFFParam *sl, u8 nal_type)\n{\n\tGF_NALUFFParamArray *pa = NULL;\n\tu32 i, count;\n\tcount = gf_list_count(param_list);\n\tfor (i=0; i<count; i++) {\n\t\tpa = gf_list_get(param_list, i);\n\t\tif (pa->type == nal_type) break;\n\t\tpa = NULL;\n\t}\n\tif (!pa) {\n\t\tGF_SAFEALLOC(pa, GF_NALUFFParamArray);\n\t\tif (!pa) return;", "\t\tpa->array_completeness = 1;\n\t\tpa->type = nal_type;\n\t\tpa->nalus = gf_list_new();\n\t\tgf_list_add(param_list, pa);\n\t}\n\tgf_list_add(pa->nalus, sl);\n}", "#ifndef GPAC_DISABLE_HEVC", "static void naludmx_hevc_set_parall_type(GF_NALUDmxCtx *ctx, GF_HEVCConfig *hevc_cfg)\n{\n\tu32 use_tiles, use_wpp, nb_pps, i, count;\n\tHEVCState hevc;", "\tcount = gf_list_count(ctx->pps);", "\tmemset(&hevc, 0, sizeof(HEVCState));\n\thevc.sps_active_idx = -1;", "\tuse_tiles = 0;\n\tuse_wpp = 0;\n\tnb_pps = 0;", "\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *slc = (GF_NALUFFParam*)gf_list_get(ctx->pps, i);\n\t\ts32 idx = gf_hevc_read_pps(slc->data, slc->size, &hevc);", "\t\tif (idx>=0) {\n\t\t\tHEVC_PPS *pps;\n\t\t\tnb_pps++;\n\t\t\tpps = &hevc.pps[idx];\n\t\t\tif (!pps->entropy_coding_sync_enabled_flag && pps->tiles_enabled_flag)\n\t\t\t\tuse_tiles++;\n\t\t\telse if (pps->entropy_coding_sync_enabled_flag && !pps->tiles_enabled_flag)\n\t\t\t\tuse_wpp++;\n\t\t}\n\t}\n\tif (!use_tiles && !use_wpp) hevc_cfg->parallelismType = 1;\n\telse if (!use_wpp && (use_tiles==nb_pps) ) hevc_cfg->parallelismType = 2;\n\telse if (!use_tiles && (use_wpp==nb_pps) ) hevc_cfg->parallelismType = 3;\n\telse hevc_cfg->parallelismType = 0;\n}\n#endif // GPAC_DISABLE_HEVC", "GF_Err naludmx_set_hevc_oinf(GF_NALUDmxCtx *ctx, u8 *max_temporal_id)\n{\n\tGF_OperatingPointsInformation *oinf;\n\tGF_BitStream *bs;\n\tu8 *data;\n\tu32 data_size;\n\tu32 i;\n\tHEVC_VPS *vps;\n\tGF_NALUFFParam *vps_sl = gf_list_get(ctx->vps, 0);\n\tif (!vps_sl) return GF_SERVICE_ERROR;", "\tvps = &ctx->hevc_state->vps[vps_sl->id];", "\tif (!vps->vps_extension_found) return GF_OK;\n\tif (vps->max_layers<2) return GF_OK;", "\toinf = gf_isom_oinf_new_entry();\n\tif (!oinf) return GF_OUT_OF_MEM;", "\toinf->scalability_mask = 0;\n\tfor (i = 0; i < 16; i++) {\n\t\tif (vps->scalability_mask[i])\n\t\t\toinf->scalability_mask |= 1 << i;\n\t}", "\tfor (i = 0; i < vps->num_profile_tier_level; i++) {\n\t\tHEVC_ProfileTierLevel ptl = (i == 0) ? vps->ptl : vps->ext_ptl[i-1];\n\t\tLHEVC_ProfileTierLevel *lhevc_ptl;\n\t\tGF_SAFEALLOC(lhevc_ptl, LHEVC_ProfileTierLevel);\n\t\tif (!lhevc_ptl) return GF_OUT_OF_MEM;", "\t\tlhevc_ptl->general_profile_space = ptl.profile_space;\n\t\tlhevc_ptl->general_tier_flag = ptl.tier_flag;\n\t\tlhevc_ptl->general_profile_idc = ptl.profile_idc;\n\t\tlhevc_ptl->general_profile_compatibility_flags = ptl.profile_compatibility_flag;\n\t\tlhevc_ptl->general_constraint_indicator_flags = 0;\n\t\tif (ptl.general_progressive_source_flag)\n\t\t\tlhevc_ptl->general_constraint_indicator_flags |= ((u64)1) << 47;\n\t\tif (ptl.general_interlaced_source_flag)\n\t\t\tlhevc_ptl->general_constraint_indicator_flags |= ((u64)1) << 46;\n\t\tif (ptl.general_non_packed_constraint_flag)\n\t\t\tlhevc_ptl->general_constraint_indicator_flags |= ((u64)1) << 45;\n\t\tif (ptl.general_frame_only_constraint_flag)\n\t\t\tlhevc_ptl->general_constraint_indicator_flags |= ((u64)1) << 44;\n\t\tlhevc_ptl->general_constraint_indicator_flags |= ptl.general_reserved_44bits;\n\t\tlhevc_ptl->general_level_idc = ptl.level_idc;\n\t\tgf_list_add(oinf->profile_tier_levels, lhevc_ptl);\n\t}", "\tfor (i = 0; i < vps->num_output_layer_sets; i++) {\n\t\tLHEVC_OperatingPoint *op;\n\t\tu32 j;\n\t\tu16 minPicWidth, minPicHeight, maxPicWidth, maxPicHeight;\n\t\tu8 maxChromaFormat, maxBitDepth;\n\t\tu8 maxTemporalId;\n\t\tGF_SAFEALLOC(op, LHEVC_OperatingPoint);\n\t\tif (!op) return GF_OUT_OF_MEM;", "\t\top->output_layer_set_idx = i;\n\t\top->layer_count = vps->num_necessary_layers[i];\n\t\tminPicWidth = minPicHeight = maxPicWidth = maxPicHeight = maxTemporalId = 0;\n\t\tmaxChromaFormat = maxBitDepth = 0;\n\t\tfor (j = 0; j < op->layer_count; j++) {\n\t\t\tu32 format_idx;\n\t\t\tu32 bitDepth;\n\t\t\top->layers_info[j].ptl_idx = vps->profile_tier_level_idx[i][j];\n\t\t\top->layers_info[j].layer_id = j;\n\t\t\top->layers_info[j].is_outputlayer = vps->output_layer_flag[i][j];\n\t\t\t//FIXME: we consider that this flag is never set\n\t\t\top->layers_info[j].is_alternate_outputlayer = GF_FALSE;", "\t\t\tif (max_temporal_id) {\n\t\t\t\tif (!maxTemporalId || (maxTemporalId < max_temporal_id[op->layers_info[j].layer_id]))\n\t\t\t\t\tmaxTemporalId = max_temporal_id[op->layers_info[j].layer_id];\n\t\t\t} else {\n\t\t\t\tmaxTemporalId = vps->max_sub_layers;\n\t\t\t}", "\t\t\tformat_idx = vps->rep_format_idx[op->layers_info[j].layer_id];\n\t\t\tif (!minPicWidth || (minPicWidth > vps->rep_formats[format_idx].pic_width_luma_samples))\n\t\t\t\tminPicWidth = vps->rep_formats[format_idx].pic_width_luma_samples;\n\t\t\tif (!minPicHeight || (minPicHeight > vps->rep_formats[format_idx].pic_height_luma_samples))\n\t\t\t\tminPicHeight = vps->rep_formats[format_idx].pic_height_luma_samples;\n\t\t\tif (!maxPicWidth || (maxPicWidth < vps->rep_formats[format_idx].pic_width_luma_samples))\n\t\t\t\tmaxPicWidth = vps->rep_formats[format_idx].pic_width_luma_samples;\n\t\t\tif (!maxPicHeight || (maxPicHeight < vps->rep_formats[format_idx].pic_height_luma_samples))\n\t\t\t\tmaxPicHeight = vps->rep_formats[format_idx].pic_height_luma_samples;\n\t\t\tif (!maxChromaFormat || (maxChromaFormat < vps->rep_formats[format_idx].chroma_format_idc))\n\t\t\t\tmaxChromaFormat = vps->rep_formats[format_idx].chroma_format_idc;\n\t\t\tbitDepth = vps->rep_formats[format_idx].bit_depth_chroma > vps->rep_formats[format_idx].bit_depth_luma ? vps->rep_formats[format_idx].bit_depth_chroma : vps->rep_formats[format_idx].bit_depth_luma;\n\t\t\tif (!maxChromaFormat || (maxChromaFormat < bitDepth))\n\t\t\t\tmaxChromaFormat = bitDepth;\n\t\t}\n\t\top->max_temporal_id = maxTemporalId;\n\t\top->minPicWidth = minPicWidth;\n\t\top->minPicHeight = minPicHeight;\n\t\top->maxPicWidth = maxPicWidth;\n\t\top->maxPicHeight = maxPicHeight;\n\t\top->maxChromaFormat = maxChromaFormat;\n\t\top->maxBitDepth = maxBitDepth;\n\t\top->frame_rate_info_flag = GF_FALSE; //FIXME: should fetch this info from VUI\n\t\top->bit_rate_info_flag = GF_FALSE; //we don't use it\n\t\tgf_list_add(oinf->operating_points, op);\n\t}", "\tfor (i = 0; i < vps->max_layers; i++) {\n\t\tLHEVC_DependentLayer *dep;\n\t\tu32 j, k;\n\t\tGF_SAFEALLOC(dep, LHEVC_DependentLayer);\n\t\tif (!dep) return GF_OUT_OF_MEM;", "\t\tdep->dependent_layerID = vps->layer_id_in_nuh[i];\n\t\tfor (j = 0; j < vps->max_layers; j++) {\n\t\t\tif (vps->direct_dependency_flag[dep->dependent_layerID][j]) {\n\t\t\t\tdep->dependent_on_layerID[dep->num_layers_dependent_on] = j;\n\t\t\t\tdep->num_layers_dependent_on ++;\n\t\t\t}\n\t\t}\n\t\tk = 0;\n\t\tfor (j = 0; j < 16; j++) {\n\t\t\tif (oinf->scalability_mask & (1 << j)) {\n\t\t\t\tdep->dimension_identifier[j] = vps->dimension_id[i][k];\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tgf_list_add(oinf->dependency_layers, dep);\n\t}", "\t//write Operating Points Information Sample Group\n\tbs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);\n\tgf_isom_oinf_write_entry(oinf, bs);\n\tgf_bs_get_content(bs, &data, &data_size);\n\tgf_bs_del(bs);\n\tgf_isom_oinf_del_entry(oinf);", "\tgf_filter_pid_set_info_str(ctx->opid, \"hevc:oinf\", &PROP_DATA_NO_COPY(data, data_size) );\n\treturn GF_OK;\n}", "static void naludmx_set_hevc_linf(GF_NALUDmxCtx *ctx)\n{\n\tu32 i, nb_layers=0, nb_sublayers=0;\n\tu8 *data;\n\tu32 data_size;\n\tGF_BitStream *bs;", "\tfor (i=0; i<64; i++) {\n\t\tif (ctx->linf[i].layer_id_plus_one) nb_layers++;\n\t\tif (ctx->linf[i].min_temporal_id != ctx->linf[i].max_temporal_id) nb_sublayers++;\n\t}\n\tif (!nb_layers && !nb_sublayers)\n\t\treturn;", "\tbs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);", "\tgf_bs_write_int(bs, 0, 2);\n\tgf_bs_write_int(bs, nb_layers, 6);\n\tfor (i=0; i<nb_layers; i++) {\n\t\tif (! ctx->linf[i].layer_id_plus_one) continue;\n\t\tgf_bs_write_int(bs, 0, 4);\n\t\tgf_bs_write_int(bs, ctx->linf[i].layer_id_plus_one - 1, 6);\n\t\tgf_bs_write_int(bs, ctx->linf[i].min_temporal_id, 3);\n\t\tgf_bs_write_int(bs, ctx->linf[i].max_temporal_id, 3);\n\t\tgf_bs_write_int(bs, 0, 1);\n\t\tgf_bs_write_int(bs, 0xFF, 7);", "\t}\n\tgf_bs_get_content(bs, &data, &data_size);\n\tgf_bs_del(bs);\n\tgf_filter_pid_set_info_str(ctx->opid, \"hevc:linf\", &PROP_DATA_NO_COPY(data, data_size) );\n}", "static void naludmx_create_hevc_decoder_config(GF_NALUDmxCtx *ctx, u8 **dsi, u32 *dsi_size, u8 **dsi_enh, u32 *dsi_enh_size, u32 *max_width, u32 *max_height, u32 *max_enh_width, u32 *max_enh_height, GF_Fraction *sar, Bool *has_hevc_base)\n{\n#ifndef GPAC_DISABLE_HEVC\n\tu32 i, count;\n\tu8 layer_id;\n\tBool first = GF_TRUE;\n\tBool first_lhvc = GF_TRUE;\n\tGF_HEVCConfig *cfg;\n\tGF_HEVCConfig *hvcc;\n\tGF_HEVCConfig *lvcc;\n\tu32 max_w, max_h, max_ew, max_eh;", "\t*has_hevc_base = GF_FALSE;", "\n\tmax_w = max_h = 0;\n\tmax_ew = max_eh = 0;\n\tsar->num = sar->den = 0;", "\thvcc = gf_odf_hevc_cfg_new();\n\tlvcc = gf_odf_hevc_cfg_new();\n\thvcc->nal_unit_size = ctx->nal_length;\n\tlvcc->nal_unit_size = ctx->nal_length;\n\tlvcc->is_lhvc = GF_TRUE;\n\t//check we have one pps or sps in base layer\n\tcount = gf_list_count(ctx->sps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->sps, i);\n\t\tlayer_id = ((sl->data[0] & 0x1) << 5) | (sl->data[1] >> 3);\n\t\tif (!layer_id) {\n\t\t\t*has_hevc_base = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t}\n\tcount = gf_list_count(ctx->pps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->pps, i);\n\t\tlayer_id = ((sl->data[0] & 0x1) << 5) | (sl->data[1] >> 3);\n\t\tif (!layer_id) {\n\t\t\t*has_hevc_base = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t}\n\t//assign vps first so that they are serialized first\n\tcount = gf_list_count(ctx->vps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->vps, i);\n\t\tHEVC_VPS *vps = &ctx->hevc_state->vps[sl->id];", "\t\tif (!i) {\n\t\t\thvcc->avgFrameRate = lvcc->avgFrameRate = vps->rates[0].avg_pic_rate;\n\t\t\thvcc->constantFrameRate = lvcc->constantFrameRate = vps->rates[0].constand_pic_rate_idc;\n\t\t\thvcc->numTemporalLayers = lvcc->numTemporalLayers = vps->max_sub_layers;\n\t\t\thvcc->temporalIdNested = lvcc->temporalIdNested = vps->temporal_id_nesting;\n\t\t}\n\t\t//TODO set scalability mask\n\t\tif (!ctx->analyze)\n\t\t\tnaludmx_add_param_nalu((ctx->explicit || ! (*has_hevc_base) ) ? lvcc->param_array : hvcc->param_array, sl, GF_HEVC_NALU_VID_PARAM);\n\t}", "\tcount = gf_list_count(ctx->sps);\n\tfor (i=0; i<count; i++) {\n\t\tBool is_lhvc = GF_FALSE;\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->sps, i);\n\t\tHEVC_SPS *sps = &ctx->hevc_state->sps[sl->id];\n\t\tlayer_id = ((sl->data[0] & 0x1) << 5) | (sl->data[1] >> 3);\n\t\tif (!layer_id) *has_hevc_base = GF_TRUE;", "\t\tif (ctx->explicit || layer_id) {\n\t\t\tcfg = lvcc;\n\t\t\tis_lhvc = GF_TRUE;\n\t\t} else {\n\t\t\tcfg = hvcc;\n\t\t}", "\t\tif (first || (is_lhvc && first_lhvc) ) {\n\t\t\tcfg->configurationVersion = 1;\n\t\t\tcfg->profile_space = sps->ptl.profile_space;\n\t\t\tcfg->tier_flag = sps->ptl.tier_flag;\n\t\t\tcfg->profile_idc = sps->ptl.profile_idc;\n\t\t\tcfg->general_profile_compatibility_flags = sps->ptl.profile_compatibility_flag;\n\t\t\tcfg->progressive_source_flag = sps->ptl.general_progressive_source_flag;\n\t\t\tcfg->interlaced_source_flag = sps->ptl.general_interlaced_source_flag;\n\t\t\tcfg->non_packed_constraint_flag = sps->ptl.general_non_packed_constraint_flag;\n\t\t\tcfg->frame_only_constraint_flag = sps->ptl.general_frame_only_constraint_flag;\n\t\t\tcfg->constraint_indicator_flags = sps->ptl.general_reserved_44bits;\n\t\t\tcfg->level_idc = sps->ptl.level_idc;\n\t\t\tcfg->chromaFormat = sps->chroma_format_idc;\n\t\t\tcfg->luma_bit_depth = sps->bit_depth_luma;\n\t\t\tcfg->chroma_bit_depth = sps->bit_depth_chroma;\n\t\t\tctx->interlaced = cfg->interlaced_source_flag ? GF_TRUE : GF_FALSE;", "\t\t\tif (sps->aspect_ratio_info_present_flag && sps->sar_width && sps->sar_height) {\n\t\t\t\tsar->num = sps->sar_width;\n\t\t\t\tsar->den = sps->sar_height;\n\t\t\t}", "\t\t\t/*disable frame rate scan, most bitstreams have wrong values there*/\n\t\t\tif (!ctx->timescale && first && (!ctx->fps.num || !ctx->fps.den) && sps->has_timing_info\n\t\t\t\t/*if detected FPS is greater than 1000, assume wrong timing info*/\n\t\t\t\t&& (sps->time_scale <= 1000*sps->num_units_in_tick)\n\t\t\t) {\n\t\t\t\tctx->cur_fps.num = sps->time_scale;\n\t\t\t\tctx->cur_fps.den = sps->num_units_in_tick;", "\t\t\t\tif (!ctx->fps.num && ctx->dts==ctx->fps.den)\n\t\t\t\t\tctx->dts = ctx->cur_fps.den;\n\t\t\t}\n\t\t\tctx->fps = ctx->cur_fps;\n\t\t}\n\t\tfirst = GF_FALSE;\n\t\tif (is_lhvc) {\n\t\t\tfirst_lhvc = GF_FALSE;\n\t\t\tif (sps->width > max_ew) max_ew = sps->width;\n\t\t\tif (sps->height > max_eh) max_eh = sps->height;\n\t\t} else {\n\t\t\tif (sps->width > max_w) max_w = sps->width;\n\t\t\tif (sps->height > max_h) max_h = sps->height;\n\t\t}\n\t\tif (!ctx->analyze)\n\t\t\tnaludmx_add_param_nalu(cfg->param_array, sl, GF_HEVC_NALU_SEQ_PARAM);\n\t}", "\tcfg = ctx->explicit ? lvcc : hvcc;\n\tcount = gf_list_count(ctx->pps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->pps, i);\n\t\tlayer_id = ((sl->data[0] & 0x1) << 5) | (sl->data[1] >> 3);\n\t\tif (!layer_id) *has_hevc_base = GF_TRUE;\n\t\tif (!ctx->analyze)\n\t\t\tnaludmx_add_param_nalu(layer_id ? lvcc->param_array : cfg->param_array, sl, GF_HEVC_NALU_PIC_PARAM);\n\t}", "\t*dsi = *dsi_enh = NULL;\n\t*dsi_size = *dsi_enh_size = 0;", "\tif (ctx->explicit || ! (*has_hevc_base) ) {\n\t\tnaludmx_hevc_set_parall_type(ctx, lvcc);\n\t\tgf_odf_hevc_cfg_write(lvcc, dsi, dsi_size);\n\t\t*max_width = *max_enh_width = max_ew;\n\t\t*max_height = *max_enh_height = max_eh;\n\t} else {\n\t\tnaludmx_hevc_set_parall_type(ctx, hvcc);\n\t\tgf_odf_hevc_cfg_write(hvcc, dsi, dsi_size);\n\t\tif (gf_list_count(lvcc->param_array) ) {\n\t\t\tnaludmx_hevc_set_parall_type(ctx, lvcc);\n\t\t\tgf_odf_hevc_cfg_write(lvcc, dsi_enh, dsi_enh_size);\n\t\t}\n\t\t*max_width = max_w;\n\t\t*max_height = max_h;\n\t\t*max_enh_width = max_ew;\n\t\t*max_enh_height = max_eh;\n\t}\n\tcount = gf_list_count(hvcc->param_array);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParamArray *pa = gf_list_get(hvcc->param_array, i);\n\t\tgf_list_reset(pa->nalus);\n\t}\n\tcount = gf_list_count(lvcc->param_array);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParamArray *pa = gf_list_get(lvcc->param_array, i);\n\t\tgf_list_reset(pa->nalus);\n\t}\n\tgf_odf_hevc_cfg_del(hvcc);\n\tgf_odf_hevc_cfg_del(lvcc);\n#endif // GPAC_DISABLE_HEVC\n}", "\nstatic void naludmx_create_vvc_decoder_config(GF_NALUDmxCtx *ctx, u8 **dsi, u32 *dsi_size, u8 **dsi_enh, u32 *dsi_enh_size, u32 *max_width, u32 *max_height, u32 *max_enh_width, u32 *max_enh_height, GF_Fraction *sar, Bool *has_vvc_base)\n{\n\tu32 i, count;\n\tu8 layer_id;\n\tBool first = GF_TRUE;\n\tBool first_lvvc = GF_TRUE;\n\tGF_VVCConfig *cfg;\n\tu32 max_w, max_h, max_ew, max_eh;", "\t*has_vvc_base = GF_FALSE;", "\tmax_w = max_h = 0;\n\tmax_ew = max_eh = 0;\n\tsar->num = sar->den = 0;", "\tcfg = gf_odf_vvc_cfg_new();\n\tcfg->nal_unit_size = ctx->nal_length;", "\t//check we have one pps or sps in base layer\n\tcount = gf_list_count(ctx->sps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->sps, i);\n\t\tlayer_id = (sl->data[0] & 0x3f);\n\t\t//todo, base is not always 0 !\n\t\tif (!layer_id) {\n\t\t\t*has_vvc_base = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t}\n\tcount = gf_list_count(ctx->pps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->pps, i);\n\t\tlayer_id = (sl->data[0] & 0x3f);\n\t\t//todo, base is not always 0 !\n\t\tif (!layer_id) {\n\t\t\t*has_vvc_base = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t}\n\t//assign vps first so that they are serialized first\n\tcount = gf_list_count(ctx->vps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->vps, i);\n\t\tVVC_VPS *vps = &ctx->vvc_state->vps[sl->id];", "\t\tif (!i) {\n\t\t\tcfg->avgFrameRate = vps->rates[0].avg_pic_rate;\n\t\t\tcfg->constantFrameRate = vps->rates[0].constand_pic_rate_idc;\n\t\t\tcfg->numTemporalLayers = vps->max_sub_layers;\n\t\t}\n\t\tif (!ctx->analyze)\n\t\t\tnaludmx_add_param_nalu(cfg->param_array, sl, GF_VVC_NALU_VID_PARAM);\n\t}", "\tcount = gf_list_count(ctx->sps);\n\tfor (i=0; i<count; i++) {\n\t\tBool is_lvvc = GF_FALSE;\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->sps, i);\n\t\tVVC_SPS *sps = &ctx->vvc_state->sps[sl->id];\n\t\tlayer_id = sl->data[0] & 0x3f;\n\t\tif (!layer_id) *has_vvc_base = GF_TRUE;", "\t\tif (ctx->explicit || layer_id) {\n\t\t\tis_lvvc = GF_TRUE;\n\t\t}", "\t\tif (first || (is_lvvc && first_lvvc) ) {\n\t\t\tVVC_VPS *vps = &ctx->vvc_state->vps[sps->vps_id];\n\t\t\tcfg->avgFrameRate = 0;\n\t\t\tcfg->constantFrameRate = 1;\n\t\t\tcfg->numTemporalLayers = sps->max_sublayers;\n\t\t\tcfg->nal_unit_size = ctx->nal_length;\n\t\t\tcfg->ptl_present = vps->num_ptl ? 1 : 0;", "\t\t\tif (vps->num_ptl) {\n\t\t\t\tcfg->num_constraint_info = vps->ptl[0].gci_present ? 1 : 12;\n\t\t\t\tcfg->general_profile_idc = vps->ptl[0].general_profile_idc;\n\t\t\t\tcfg->general_tier_flag = vps->ptl[0].general_tier_flag;\n\t\t\t\tcfg->general_level_idc = vps->ptl[0].general_level_idc;\n\t\t\t\tcfg->ptl_frame_only_constraint = vps->ptl[0].frame_only_constraint;\n\t\t\t\tcfg->ptl_multilayer_enabled = vps->ptl[0].multilayer_enabled;", "\t\t\t\tcfg->general_constraint_info = gf_malloc(sizeof(u8) * cfg-> num_constraint_info);\n\t\t\t\tif (cfg->general_constraint_info)\n\t\t\t\t\tmemcpy(cfg->general_constraint_info, vps->ptl[0].gci, cfg->num_constraint_info);", "\t\t\t\t//todo set temporal sublayers\n\t\t\t\tcfg->ptl_sublayer_present_mask = 0;\n\t\t\t\tcfg->num_sub_profiles = 0;\n\t\t\t\tcfg->ols_idx = 0;\n\t\t\t}\n\t\t\tcfg->chroma_format = sps->chroma_format_idc;\n\t\t\tcfg->bit_depth = sps->bitdepth;\n\t\t\tcfg->maxPictureWidth = sps->width;\n\t\t\tcfg->maxPictureHeight = sps->height;", "\t\t\tif (sps->aspect_ratio_info_present_flag && sps->sar_width && sps->sar_height) {\n\t\t\t\tsar->num = sps->sar_width;\n\t\t\t\tsar->den = sps->sar_height;\n\t\t\t}", "\t\t\t/*disable frame rate scan, most bitstreams have wrong values there*/\n\t\t\tif (!ctx->timescale && first && (!ctx->fps.num || !ctx->fps.den) && sps->has_timing_info\n\t\t\t\t/*if detected FPS is greater than 1000, assume wrong timing info*/\n\t\t\t\t&& (sps->time_scale <= 1000*sps->num_units_in_tick)\n\t\t\t) {\n\t\t\t\tctx->cur_fps.num = sps->time_scale;\n\t\t\t\tctx->cur_fps.den = sps->num_units_in_tick;", "\t\t\t\tif (!ctx->fps.num && ctx->dts==ctx->fps.den)\n\t\t\t\t\tctx->dts = ctx->cur_fps.den;\n\t\t\t}\n\t\t\tctx->fps = ctx->cur_fps;\n\t\t}\n\t\tfirst = GF_FALSE;\n\t\tif (is_lvvc) {\n\t\t\tfirst_lvvc = GF_FALSE;\n\t\t\tif (sps->width > max_ew) max_ew = sps->width;\n\t\t\tif (sps->height > max_eh) max_eh = sps->height;\n\t\t} else {\n\t\t\tif (sps->width > max_w) max_w = sps->width;\n\t\t\tif (sps->height > max_h) max_h = sps->height;\n\t\t}\n\t\tif (!ctx->analyze)\n\t\t\tnaludmx_add_param_nalu(cfg->param_array, sl, GF_VVC_NALU_SEQ_PARAM);\n\t}", "\tcount = gf_list_count(ctx->pps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->pps, i);\n\t\tlayer_id = sl->data[0] & 0x3F;\n\t\tif (!layer_id) *has_vvc_base = GF_TRUE;\n\t\tif (!ctx->analyze)\n\t\t\tnaludmx_add_param_nalu(cfg->param_array, sl, GF_VVC_NALU_PIC_PARAM);\n\t}", "\tcount = gf_list_count(ctx->vvc_dci);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->vvc_dci, i);\n\t\tlayer_id = sl->data[0] & 0x3F;\n\t\tif (!layer_id) *has_vvc_base = GF_TRUE;\n\t\tif (!ctx->analyze)\n\t\t\tnaludmx_add_param_nalu(cfg->param_array, sl, GF_VVC_NALU_DEC_PARAM);\n\t}", "\tcount = gf_list_count(ctx->vvc_aps_pre);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->vvc_aps_pre, i);\n\t\tlayer_id = sl->data[0] & 0x3F;\n\t\tif (!layer_id) *has_vvc_base = GF_TRUE;\n\t\tif (!ctx->analyze)\n\t\t\tnaludmx_add_param_nalu(cfg->param_array, sl, GF_VVC_NALU_APS_PREFIX);\n\t}", "\t*dsi = *dsi_enh = NULL;\n\t*dsi_size = *dsi_enh_size = 0;", "\tgf_odf_vvc_cfg_write(cfg, dsi, dsi_size);\n\t*max_width = max_w;\n\t*max_height = max_h;\n\t*max_enh_width = max_ew;\n\t*max_enh_height = max_eh;", "\tcount = gf_list_count(cfg->param_array);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParamArray *pa = gf_list_get(cfg->param_array, i);\n\t\tgf_list_reset(pa->nalus);\n\t}\n\tgf_odf_vvc_cfg_del(cfg);\n}", "void naludmx_create_avc_decoder_config(GF_NALUDmxCtx *ctx, u8 **dsi, u32 *dsi_size, u8 **dsi_enh, u32 *dsi_enh_size, u32 *max_width, u32 *max_height, u32 *max_enh_width, u32 *max_enh_height, GF_Fraction *sar)\n{\n\tu32 i, count;\n\tBool first = GF_TRUE;\n\tBool first_svc = GF_TRUE;\n\tGF_AVCConfig *cfg;\n\tGF_AVCConfig *avcc;\n\tGF_AVCConfig *svcc;\n\tu32 max_w, max_h, max_ew, max_eh;", "\n\tmax_w = max_h = max_ew = max_eh = 0;\n\tsar->num = sar->den = 0;", "\tavcc = gf_odf_avc_cfg_new();\n\tsvcc = gf_odf_avc_cfg_new();\n\tavcc->nal_unit_size = ctx->nal_length;\n\tsvcc->nal_unit_size = ctx->nal_length;", "\tctx->is_mvc = GF_FALSE;\n\tcount = gf_list_count(ctx->sps);\n\tfor (i=0; i<count; i++) {\n\t\tBool is_svc = GF_FALSE;\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->sps, i);\n\t\tAVC_SPS *sps = &ctx->avc_state->sps[sl->id];\n\t\tu32 nal_type = sl->data[0] & 0x1F;", "\t\tif ((sps->profile_idc == 118) || (sps->profile_idc == 128)) {\n\t\t\tctx->is_mvc = GF_TRUE;\n\t\t}", "\t\tif (ctx->explicit) {\n\t\t\tcfg = svcc;\n\t\t} else if (nal_type == GF_AVC_NALU_SVC_SUBSEQ_PARAM) {\n\t\t\tcfg = svcc;\n\t\t\tis_svc = GF_TRUE;\n\t\t} else {\n\t\t\tcfg = avcc;\n\t\t}", "\t\tif (first || (is_svc && first_svc) ) {\n\t\t\tcfg->configurationVersion = 1;\n\t\t\tcfg->profile_compatibility = sps->prof_compat;\n\t\t\tcfg->AVCProfileIndication = sps->profile_idc;\n\t\t\tcfg->AVCLevelIndication = sps->level_idc;\n\t\t\tcfg->chroma_format = sps->chroma_format;\n\t\t\tcfg->luma_bit_depth = 8 + sps->luma_bit_depth_m8;\n\t\t\tcfg->chroma_bit_depth = 8 + sps->chroma_bit_depth_m8;\n\t\t\t/*try to patch ?*/\n\t\t\tif (!gf_avc_is_rext_profile(cfg->AVCProfileIndication)\n\t\t\t\t&& ((cfg->chroma_format>1) || (cfg->luma_bit_depth>8) || (cfg->chroma_bit_depth>8))\n\t\t\t) {\n\t\t\t\tif ((cfg->luma_bit_depth>8) || (cfg->chroma_bit_depth>8)) {\n\t\t\t\t\tcfg->AVCProfileIndication = 110;\n\t\t\t\t} else {\n\t\t\t\t\tcfg->AVCProfileIndication = (cfg->chroma_format==3) ? 244 : 122;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (sps->vui_parameters_present_flag && sps->vui.par_num && sps->vui.par_den) {\n\t\t\t\tsar->num = sps->vui.par_num;\n\t\t\t\tsar->den = sps->vui.par_den;\n\t\t\t}\n\t\t\tctx->interlaced = sps->frame_mbs_only_flag ? GF_FALSE : GF_TRUE;", "\n\t\t\t/*disable frame rate scan, most bitstreams have wrong values there*/\n\t\t\tif (first && (!ctx->fps.num || !ctx->fps.den) && sps->vui.timing_info_present_flag\n\t\t\t\t/*if detected FPS is greater than 1000, assume wrong timing info*/\n\t\t\t\t&& (sps->vui.time_scale <= 1000*sps->vui.num_units_in_tick)\n\t\t\t) {\n\t\t\t\t/*ISO/IEC 14496-10 n11084 Table E-6*/\n\t\t\t\t/* not used :\t\t\t\tu8 DeltaTfiDivisorTable[] = {1,1,1,2,2,2,2,3,3,4,6}; */\n\t\t\t\tu8 DeltaTfiDivisorIdx;\n\t\t\t\tif (!sps->vui.pic_struct_present_flag) {\n\t\t\t\t\tDeltaTfiDivisorIdx = 1 + (1 - ctx->avc_state->s_info.field_pic_flag);\n\t\t\t\t} else {\n\t\t\t\t\tif (!ctx->avc_state->sei.pic_timing.pic_struct)\n\t\t\t\t\t\tDeltaTfiDivisorIdx = 2;\n\t\t\t\t\telse if (ctx->avc_state->sei.pic_timing.pic_struct == 8)\n\t\t\t\t\t\tDeltaTfiDivisorIdx = 6;\n\t\t\t\t\telse\n\t\t\t\t\t\tDeltaTfiDivisorIdx = (ctx->avc_state->sei.pic_timing.pic_struct+1) / 2;\n\t\t\t\t}\n\t\t\t\tif (!ctx->timescale) {\n\t\t\t\t\tctx->cur_fps.num = 2 * sps->vui.time_scale;\n\t\t\t\t\tctx->cur_fps.den = 2 * sps->vui.num_units_in_tick * DeltaTfiDivisorIdx;", "\t\t\t\t\tif (!ctx->fps.num && ctx->dts==ctx->fps.den)\n\t\t\t\t\t\tctx->dts = ctx->cur_fps.den;\n\t\t\t\t}\n\t\t\t\tif (! sps->vui.fixed_frame_rate_flag)\n\t\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_PARSER, (\"[%s] Possible Variable Frame Rate: VUI \\\"fixed_frame_rate_flag\\\" absent\\n\", ctx->log_name));\n\t\t\t}\n\t\t\tctx->fps = ctx->cur_fps;\n\t\t}\n\t\tfirst = GF_FALSE;\n\t\tif (is_svc) {\n\t\t\tfirst_svc = GF_FALSE;\n\t\t\tif (sps->width > max_ew) max_ew = sps->width;\n\t\t\tif (sps->height > max_eh) max_eh = sps->height;\n\t\t} else {\n\t\t\tif (sps->width > max_w) max_w = sps->width;\n\t\t\tif (sps->height > max_h) max_h = sps->height;\n\t\t}\n\t\tif (!ctx->analyze)\n\t\t\tgf_list_add(cfg->sequenceParameterSets, sl);\n\t}", "\tcfg = ctx->explicit ? svcc : avcc;\n\tcount = gf_list_count(ctx->sps_ext);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->sps_ext, i);\n\t\tif (!cfg->sequenceParameterSetExtensions) cfg->sequenceParameterSetExtensions = gf_list_new();\n\t\tif (!ctx->analyze)\n\t\t\tgf_list_add(cfg->sequenceParameterSetExtensions, sl);\n\t}", "\tcfg = ctx->explicit ? svcc : avcc;\n\tcount = gf_list_count(ctx->pps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->pps, i);\n\t\tif (!ctx->analyze)\n\t\t\tgf_list_add(cfg->pictureParameterSets, sl);\n\t}", "\tcfg = svcc;\n\tcount = gf_list_count(ctx->pps_svc);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->pps_svc, i);\n\t\tif (!ctx->analyze)\n\t\t\tgf_list_add(cfg->pictureParameterSets, sl);\n\t}", "\t*dsi = *dsi_enh = NULL;\n\t*dsi_size = *dsi_enh_size = 0;", "\tif (ctx->explicit) {\n\t\tgf_odf_avc_cfg_write(svcc, dsi, dsi_size);\n\t} else {\n\t\tgf_odf_avc_cfg_write(avcc, dsi, dsi_size);\n\t\tif (gf_list_count(svcc->sequenceParameterSets) || svcc->sequenceParameterSetExtensions) {\n\t\t\tgf_odf_avc_cfg_write(svcc, dsi_enh, dsi_enh_size);\n\t\t}\n\t}\n\tgf_list_reset(avcc->sequenceParameterSets);\n\tgf_list_reset(avcc->sequenceParameterSetExtensions);\n\tgf_list_reset(avcc->pictureParameterSets);\n\tgf_list_reset(svcc->sequenceParameterSets);\n\tgf_list_reset(svcc->sequenceParameterSetExtensions);\n\tgf_list_reset(svcc->pictureParameterSets);\n\tgf_odf_avc_cfg_del(avcc);\n\tgf_odf_avc_cfg_del(svcc);\n\t*max_width = max_w;\n\t*max_height = max_h;\n\t*max_enh_width = max_ew;\n\t*max_enh_height = max_eh;\n}", "static void naludmx_check_pid(GF_Filter *filter, GF_NALUDmxCtx *ctx)\n{\n\tu32 w, h, ew, eh;\n\tu8 *dsi, *dsi_enh;\n\tu32 dsi_size, dsi_enh_size;\n\tu32 crc_cfg, crc_cfg_enh;\n\tGF_Fraction sar;\n\tBool has_hevc_base = GF_TRUE;\n\tBool has_colr_info = GF_FALSE;", "\tif (ctx->analyze) {\n\t\tif (ctx->opid && !ctx->ps_modified) return;\n\t} else {\n\t\tif (!ctx->ps_modified) return;\n\t}\n\tctx->ps_modified = GF_FALSE;", "\tdsi = dsi_enh = NULL;", "\tif (!ctx->timescale) {\n\t\tctx->cur_fps = ctx->fps;\n\t\tif (!ctx->cur_fps.num || !ctx->cur_fps.den) {\n\t\t\tctx->cur_fps.num = 25000;\n\t\t\tctx->cur_fps.den = 1000;\n\t\t}\n\t}", "\tif (ctx->codecid==GF_CODECID_HEVC) {\n\t\tnaludmx_create_hevc_decoder_config(ctx, &dsi, &dsi_size, &dsi_enh, &dsi_enh_size, &w, &h, &ew, &eh, &sar, &has_hevc_base);\n\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\tnaludmx_create_vvc_decoder_config(ctx, &dsi, &dsi_size, &dsi_enh, &dsi_enh_size, &w, &h, &ew, &eh, &sar, &has_hevc_base);\n\t} else {\n\t\tnaludmx_create_avc_decoder_config(ctx, &dsi, &dsi_size, &dsi_enh, &dsi_enh_size, &w, &h, &ew, &eh, &sar);\n\t}\n\tcrc_cfg = crc_cfg_enh = 0;\n\tif (dsi) crc_cfg = gf_crc_32(dsi, dsi_size);\n\tif (dsi_enh) crc_cfg_enh = gf_crc_32(dsi_enh, dsi_enh_size);", "\tif (!ctx->opid) {\n\t\tctx->opid = gf_filter_pid_new(filter);", "\t\tnaludmx_check_dur(filter, ctx);\n\t\tctx->first_slice_in_au = GF_TRUE;\n\t}", "\tif ((ctx->crc_cfg == crc_cfg) && (ctx->crc_cfg_enh == crc_cfg_enh)\n\t\t&& (ctx->width==w) && (ctx->height==h)\n\t\t&& (ctx->sar.num * sar.den == ctx->sar.den * sar.num)\n\t) {\n\t\tif (dsi) gf_free(dsi);\n\t\tif (dsi_enh) gf_free(dsi_enh);\n\t\treturn;\n\t}", "\tnaludmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE);\n\tif (!ctx->analyze && (gf_list_count(ctx->pck_queue)>1)) {\n\t\tGF_LOG(dsi_enh ? GF_LOG_DEBUG : GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] xPS changed but could not flush frames before signaling state change %s\\n\", ctx->log_name, dsi_enh ? \"- likely scalable xPS update\" : \"!\"));\n\t}", "\t//copy properties at init or reconfig\n\tgf_filter_pid_copy_properties(ctx->opid, ctx->ipid);\n\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_STREAM_TYPE, & PROP_UINT(GF_STREAM_VISUAL));\n\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_UNFRAMED, NULL);\n\tif (!gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_ID))\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_ID, &PROP_UINT(1));", "\tctx->width = w;\n\tctx->height = h;\n\tctx->sar = sar;\n\tctx->crc_cfg = crc_cfg;\n\tctx->crc_cfg_enh = crc_cfg_enh;", "\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_WIDTH, & PROP_UINT( ctx->width));\n\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_HEIGHT, & PROP_UINT( ctx->height));\n\tif (ew && eh) {\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_WIDTH_MAX, & PROP_UINT( ew ));\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_HEIGHT_MAX, & PROP_UINT( eh ));\n\t}\n\tif (ctx->sar.den)\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_SAR, & PROP_FRAC(ctx->sar));\n\telse\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_SAR, NULL);", "\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_FPS, & PROP_FRAC(ctx->cur_fps));\n\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_TIMESCALE, & PROP_UINT(ctx->timescale ? ctx->timescale : ctx->cur_fps.num));", "\tif (ctx->explicit || !has_hevc_base) {\n\t\tu32 enh_cid = GF_CODECID_SVC;\n\t\tif (ctx->codecid==GF_CODECID_HEVC) enh_cid = GF_CODECID_LHVC;\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_CODECID, & PROP_UINT(enh_cid));\n\t\tif (dsi) gf_filter_pid_set_property(ctx->opid, GF_PROP_PID_DECODER_CONFIG, &PROP_DATA_NO_COPY(dsi, dsi_size) );\n\t} else {\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_CODECID, & PROP_UINT(ctx->codecid));\n\t\tif (dsi) gf_filter_pid_set_property(ctx->opid, GF_PROP_PID_DECODER_CONFIG, &PROP_DATA_NO_COPY(dsi, dsi_size) );\n\t\tif (dsi_enh) gf_filter_pid_set_property(ctx->opid, GF_PROP_PID_DECODER_CONFIG_ENHANCEMENT, &PROP_DATA_NO_COPY(dsi_enh, dsi_enh_size) );\n\t}", "\tif (ctx->bitrate) {\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_BITRATE, & PROP_UINT(ctx->bitrate));\n\t}", "\tif ((ctx->codecid==GF_CODECID_HEVC) && gf_list_count(ctx->vps) ) {\n\t\tGF_Err e = naludmx_set_hevc_oinf(ctx, NULL);\n\t\tif (e) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, (\"[%s] Failed to create OINF chunk\\n\", ctx->log_name));\n\t\t}\n\t\tnaludmx_set_hevc_linf(ctx);\n\t}\n\tif (ctx->duration.num)\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_DURATION, & PROP_FRAC64(ctx->duration));", "\tif (ctx->is_file /* && ctx->index*/) {\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_PLAYBACK_MODE, & PROP_UINT(GF_PLAYBACK_MODE_FASTFORWARD) );\n\t}\n\t//set interlaced or remove interlaced property\n\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_INTERLACED, ctx->interlaced ? & PROP_UINT(GF_TRUE) : NULL);", "\tif (ctx->codecid==GF_CODECID_HEVC) {\n\t\tHEVC_SPS *sps = &ctx->hevc_state->sps[ctx->hevc_state->sps_active_idx];\n\t\tif (sps->colour_description_present_flag) {\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_PRIMARIES, & PROP_UINT(sps->colour_primaries) );\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_TRANSFER, & PROP_UINT(sps->transfer_characteristic) );\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_MX, & PROP_UINT(sps->matrix_coeffs) );\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_RANGE, & PROP_BOOL(sps->video_full_range_flag) );\n\t\t\thas_colr_info = GF_TRUE;\n\t\t}\n\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t} else {\n\t\t/*use the last active SPS*/\n\t\tif (ctx->avc_state->sps[ctx->avc_state->sps_active_idx].vui_parameters_present_flag\n\t\t&& ctx->avc_state->sps[ctx->avc_state->sps_active_idx].vui.colour_description_present_flag) {\n\t\t\tAVC_VUI *vui = &ctx->avc_state->sps[ctx->avc_state->sps_active_idx].vui;", "\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_PRIMARIES, & PROP_UINT(vui->colour_primaries) );\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_TRANSFER, & PROP_UINT(vui->transfer_characteristics) );\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_MX, & PROP_UINT(vui->matrix_coefficients) );\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_RANGE, & PROP_BOOL(vui->video_full_range_flag) );\n\t\t\thas_colr_info = GF_TRUE;\n\t\t}\n\t}", "\tif (!has_colr_info) {\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_PRIMARIES, NULL);\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_TRANSFER, NULL);\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_MX, NULL);\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_RANGE, NULL);\n\t}\n}", "static Bool naludmx_process_event(GF_Filter *filter, const GF_FilterEvent *evt)\n{\n\tu32 i;\n\tu64 file_pos = 0;\n\tGF_FilterEvent fevt;\n\tGF_NALUDmxCtx *ctx = gf_filter_get_udta(filter);", "\tswitch (evt->base.type) {\n\tcase GF_FEVT_PLAY:\n\t\tif (!ctx->is_playing) {\n\t\t\tctx->is_playing = GF_TRUE;\n\t\t\tctx->cts = ctx->dts = 0;\n\t\t}\n\t\tif (! ctx->is_file) {\n\t\t\tif (!ctx->initial_play_done) {\n\t\t\t\tctx->initial_play_done = GF_TRUE;\n\t\t\t\tif (evt->play.start_range<0.1)\n\t\t\t\t\treturn GF_FALSE;\n\t\t\t}\n\t\t\tctx->resume_from = 0;\n\t\t\tctx->nal_store_size = 0;\n\t\t\treturn GF_FALSE;\n\t\t}\n\t\tif (ctx->start_range && (ctx->index<0)) {\n\t\t\tctx->index = -ctx->index;\n\t\t\tctx->file_loaded = GF_FALSE;\n\t\t\tctx->duration.den = ctx->duration.num = 0;\n\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_PARSER, (\"[%s] Play request from %d, building index\\n\", ctx->log_name, ctx->start_range));\n\t\t\tnaludmx_check_dur(filter, ctx);\n\t\t}\n\t\tctx->start_range = evt->play.start_range;\n\t\tctx->in_seek = GF_TRUE;", "\t\tif (ctx->start_range) {\n\t\t\tctx->nb_nalus = ctx->nb_i = ctx->nb_p = ctx->nb_b = ctx->nb_sp = ctx->nb_si = ctx->nb_sei = ctx->nb_idr = 0;\n\t\t\tfor (i=1; i<ctx->index_size; i++) {\n\t\t\t\tif (ctx->indexes[i].duration>ctx->start_range) {\n\t\t\t\t\tctx->cts = ctx->dts = (u64) (ctx->indexes[i-1].duration * ctx->cur_fps.num);\n\t\t\t\t\tfile_pos = ctx->indexes[i-1].pos;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!ctx->initial_play_done) {\n\t\t\tctx->initial_play_done = GF_TRUE;\n\t\t\t//seek will not change the current source state, don't send a seek\n\t\t\tif (!file_pos) {\n\t\t\t\t//very short streams, input is done before we get notified for play and everything stored in memory: flush\n\t\t\t\tif (gf_filter_pid_is_eos(ctx->ipid) && (ctx->nal_store_size)) {\n\t\t\t\t\tgf_filter_post_process_task(filter);\n\t\t\t\t}\n\t\t\t\treturn GF_TRUE;\n\t\t\t}\n\t\t}\n\t\tctx->nb_frames = 0;\n\t\tctx->nb_nalus = 0;\n\t\tctx->resume_from = 0;\n\t\tctx->nal_store_size = 0;", "\t\t//post a seek\n\t\tGF_FEVT_INIT(fevt, GF_FEVT_SOURCE_SEEK, ctx->ipid);\n\t\tfevt.seek.start_offset = file_pos;\n\t\tgf_filter_pid_send_event(ctx->ipid, &fevt);", "\t\t//cancel event\n\t\treturn GF_TRUE;", "\tcase GF_FEVT_STOP:\n\t\t//don't cancel event\n\t\tctx->is_playing = GF_FALSE;\n\t\tctx->nal_store_size = 0;\n\t\tctx->resume_from = 0;\n\t\treturn GF_FALSE;", "\tcase GF_FEVT_SET_SPEED:\n\t\t//cancel event\n\t\treturn GF_TRUE;\n\tdefault:\n\t\tbreak;\n\t}\n\t//by default don't cancel event - to rework once we have downloading in place\n\treturn GF_FALSE;\n}", "static GFINLINE void naludmx_update_time(GF_NALUDmxCtx *ctx)\n{\n\tassert(ctx->cur_fps.num);", "\tif (ctx->timescale) {\n\t\t//very first frame, no dts diff, assume 3000/90k. It should only hurt if we have several frames packet in the first packet sent\n\t\tu64 dts_inc = ctx->cur_fps.den ? ctx->cur_fps.den : 3000;\n\t\tctx->cts += dts_inc;\n\t\tctx->dts += dts_inc;\n\t} else {\n\t\tassert(ctx->cur_fps.den);\n\t\tctx->cts += ctx->cur_fps.den;\n\t\tctx->dts += ctx->cur_fps.den;\n\t}\n}", "static void naludmx_queue_param_set(GF_NALUDmxCtx *ctx, char *data, u32 size, u32 ps_type, s32 ps_id)\n{\n\tGF_List *list = NULL, *alt_list = NULL;\n\tGF_NALUFFParam *sl;", "\tu32 i, count;\n\tu32 crc = gf_crc_32(data, size);", "\n\tif (ctx->codecid==GF_CODECID_HEVC) {\n\t\tswitch (ps_type) {\n\t\tcase GF_HEVC_NALU_VID_PARAM:\n\t\t\tif (!ctx->vps) ctx->vps = gf_list_new();\n\t\t\tlist = ctx->vps;\n\t\t\tbreak;\n\t\tcase GF_HEVC_NALU_SEQ_PARAM:\n\t\t\tlist = ctx->sps;\n\t\t\tbreak;\n\t\tcase GF_HEVC_NALU_PIC_PARAM:\n\t\t\tlist = ctx->pps;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tassert(0);\n\t\t\treturn;\n\t\t}\n\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\tswitch (ps_type) {\n\t\tcase GF_VVC_NALU_VID_PARAM:\n\t\t\tif (!ctx->vps) ctx->vps = gf_list_new();\n\t\t\tlist = ctx->vps;\n\t\t\tbreak;\n\t\tcase GF_VVC_NALU_SEQ_PARAM:\n\t\t\tlist = ctx->sps;\n\t\t\tbreak;\n\t\tcase GF_VVC_NALU_PIC_PARAM:\n\t\t\tlist = ctx->pps;\n\t\t\tbreak;\n\t\tcase GF_VVC_NALU_DEC_PARAM:\n\t\t\tif (!ctx->vvc_dci) ctx->vvc_dci = gf_list_new();\n\t\t\tlist = ctx->vvc_dci;\n\t\t\tbreak;\n\t\tcase GF_VVC_NALU_APS_PREFIX:\n\t\t\tif (!ctx->vvc_aps_pre) ctx->vvc_aps_pre = gf_list_new();\n\t\t\tlist = ctx->vvc_aps_pre;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tassert(0);\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tswitch (ps_type) {\n\t\tcase GF_AVC_NALU_SVC_SUBSEQ_PARAM:\n\t\tcase GF_AVC_NALU_SEQ_PARAM:\n\t\t\tlist = ctx->sps;\n\t\t\tbreak;\n\t\tcase GF_AVC_NALU_PIC_PARAM:\n\t\t\tlist = ctx->pps;\n\t\t\talt_list = ctx->pps_svc;\n\t\t\tbreak;\n\t\tcase GF_AVC_NALU_SEQ_PARAM_EXT:\n\t\t\tif (!ctx->sps_ext) ctx->sps_ext = gf_list_new();\n\t\t\tlist = ctx->sps_ext;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tassert(0);\n\t\t\treturn;\n\t\t}\n\t}\n\tsl = NULL;\n\tcount = gf_list_count(list);\n\tfor (i=0; i<count; i++) {\n\t\tsl = gf_list_get(list, i);\n\t\tif (sl->id != ps_id) {\n\t\t\tsl = NULL;\n\t\t\tcontinue;\n\t\t}\n\t\t//same ID, same CRC, we don't change our state\n\t\tif (sl->crc == crc) return;\n\t\tbreak;\n\t}\n\t//handle alt PPS list for SVC\n\tif (!sl && alt_list) {\n\t\tcount = gf_list_count(alt_list);\n\t\tfor (i=0; i<count; i++) {\n\t\t\tsl = gf_list_get(alt_list, i);\n\t\t\tif (sl->id != ps_id) {\n\t\t\t\tsl = NULL;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t//same ID, same CRC, we don't change our state\n\t\t\tif (sl->crc == crc) return;\n\t\t\tbreak;\n\t\t}\n\t}", "\tif (sl) {\n\t\t//otherwise we keep this new param set\n\t\tsl->data = gf_realloc(sl->data, size);\n\t\tmemcpy(sl->data, data, size);\n\t\tsl->size = size;\n\t\tsl->crc = crc;\n\t\tctx->ps_modified = GF_TRUE;\n\t\treturn;\n\t}\n\t//TODO we might want to purge the list after a while !!", "\tGF_SAFEALLOC(sl, GF_NALUFFParam);\n\tif (!sl) return;\n\tsl->data = gf_malloc(sizeof(char) * size);\n\tif (!sl->data) {\n\t\tgf_free(sl);\n\t\treturn;\n\t}\n\tmemcpy(sl->data, data, size);\n\tsl->size = size;\n\tsl->id = ps_id;\n\tsl->crc = crc;", "\tctx->ps_modified = GF_TRUE;\n\tgf_list_add(list, sl);\n}", "static void naludmx_finalize_au_flags(GF_NALUDmxCtx *ctx)\n{\n\tu64 ts;\n\tBool is_rap = GF_FALSE;", "\tif (!ctx->first_pck_in_au)\n\t\treturn;\n\tif (ctx->au_sap) {\n\t\tgf_filter_pck_set_sap(ctx->first_pck_in_au, ctx->au_sap);\n\t\tif (ctx->au_sap == GF_FILTER_SAP_1) {\n\t\t\tctx->dts_last_IDR = gf_filter_pck_get_dts(ctx->first_pck_in_au);\n\t\t\tif (ctx->is_paff)\n\t\t\t\tctx->dts_last_IDR *= 2;\n\t\t}\n\t\tif (ctx->au_sap <= GF_FILTER_SAP_3) {\n\t\t\tis_rap = GF_TRUE;\n\t\t}\n\t}\n\telse if (ctx->has_islice && ctx->force_sync && (ctx->sei_recovery_frame_count==0)) {\n\t\tgf_filter_pck_set_sap(ctx->first_pck_in_au, GF_FILTER_SAP_1);\n\t\tif (!ctx->use_opengop_gdr) {\n\t\t\tctx->use_opengop_gdr = 1;\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[%s] Forcing non-IDR samples with I slices to be marked as sync points - resulting file will not be ISOBMFF conformant\\n\", ctx->log_name));\n\t\t}\n\t\tis_rap = GF_TRUE;\n\t}\n\t/*set roll info sampleGroups info*/\n\telse if (!ctx->au_sap && ( (ctx->sei_recovery_frame_count >= 0) || ctx->has_islice) ) {\n\t\t/*generic GDR*/\n\t\tif (ctx->sei_recovery_frame_count > 0) {\n\t\t\tif (!ctx->use_opengop_gdr) ctx->use_opengop_gdr = 1;\n\t\t\tgf_filter_pck_set_sap(ctx->first_pck_in_au, GF_FILTER_SAP_4);\n\t\t\tgf_filter_pck_set_roll_info(ctx->first_pck_in_au, ctx->sei_recovery_frame_count);\n\t\t}\n\t\t/*open-GOP*/\n\t\telse if ((ctx->sei_recovery_frame_count == 0) && ctx->has_islice) {\n\t\t\tif (!ctx->use_opengop_gdr) ctx->use_opengop_gdr = 2;\n\t\t\tgf_filter_pck_set_sap(ctx->first_pck_in_au, GF_FILTER_SAP_3);\n\t\t\tis_rap = GF_TRUE;\n\t\t}\n\t}\n\tif (ctx->is_paff) {\n\t\tgf_filter_pck_set_interlaced(ctx->first_pck_in_au, ctx->bottom_field_flag ? 2 : 1);\n\t}", "\t//if TS is set, the packet was the first in AU in the input timed packet (eg PES), we reuse the input timing\n\tts = gf_filter_pck_get_cts(ctx->first_pck_in_au);\n\tif (ts == GF_FILTER_NO_TS) {\n\t\t/*we store the POC (last POC minus the poc shift) as the CTS offset and re-update the CTS when dispatching*/\n\t\tassert(ctx->last_poc >= ctx->poc_shift);\n\t\tgf_filter_pck_set_cts(ctx->first_pck_in_au, CTS_POC_OFFSET_SAFETY + ctx->last_poc - ctx->poc_shift);\n\t\t//we use the carousel flag temporarly to indicate the cts must be recomputed\n\t\tgf_filter_pck_set_carousel_version(ctx->first_pck_in_au, 1);\n\t}", "\tif (ctx->subsamp_buffer_size) {\n\t\tgf_filter_pck_set_property(ctx->first_pck_in_au, GF_PROP_PCK_SUBS, &PROP_DATA(ctx->subsamp_buffer, ctx->subsamp_buffer_size) );\n\t\tctx->subsamp_buffer_size = 0;\n\t\tctx->subs_mapped_bytes = 0;\n\t}\n\tif (ctx->deps) {\n\t\tu8 flags = 0;\n\t\t//dependsOn\n\t\tflags = (is_rap) ? 2 : 1;\n\t\tflags <<= 2;\n\t\t//dependedOn\n\t \tflags |= ctx->has_ref_slices ? 1 : 2;\n\t\tflags <<= 2;\n\t\t//hasRedundant\n\t \tflags |= ctx->has_redundant ? 1 : 2;\n\t \tgf_filter_pck_set_dependency_flags(ctx->first_pck_in_au, flags);\n\t}\n\tctx->has_ref_slices = GF_FALSE;\n\tctx->has_redundant = GF_FALSE;", "\t//if we reuse input packets timing, we can dispatch asap.\n\t//otherwise if poc probe is done (we know the min_poc_diff between images) and we are not in strict mode, dispatch asap\n\t//otherwise we will need to wait for the next ref frame to make sure we know all pocs ...\n\tif (ctx->timescale || (!ctx->strict_poc && ctx->poc_probe_done) )\n\t\tnaludmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE);", "\tctx->first_pck_in_au = NULL;\n}", "static void naludmx_update_nalu_maxsize(GF_NALUDmxCtx *ctx, u32 size)\n{\n\tif (ctx->max_nalu_size < size) {\n\t\tctx->max_nalu_size = size;\n\t\tif (size > ctx->max_nalu_size_allowed) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] nal size %d larger than max allowed size %d - change import settings\\n\", ctx->log_name, size, ctx->max_nalu_size_allowed ));\n\t\t}\n\t}\n}", "\nGF_Err naludmx_realloc_last_pck(GF_NALUDmxCtx *ctx, u32 nb_bytes_to_add, u8 **data_ptr)\n{\n\tGF_Err e;\n\tu8 *pck_data;\n\tu32 full_size;\n\tGF_FilterPacket *pck = gf_list_last(ctx->pck_queue);\n\t*data_ptr = NULL;\n\tif (!pck) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] attempt to reallocate a non-existing packet!\\n\", ctx->log_name));\n\t\treturn GF_SERVICE_ERROR;\n\t}\n\te = gf_filter_pck_expand(pck, nb_bytes_to_add, &pck_data, data_ptr, &full_size);\n\tif (e) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Failed to reallocate packet buffer: %s\\n\", ctx->log_name, gf_error_to_string(e) ));\n\t\treturn e;\n\t}\n\tassert(ctx->bs_w);\n\t//rewrite NALU size length\n\tfull_size -= ctx->nal_length;\n\tgf_bs_reassign_buffer(ctx->bs_w, pck_data, ctx->nal_length);\n\tgf_bs_write_int(ctx->bs_w, full_size, 8*ctx->nal_length);\n\tnaludmx_update_nalu_maxsize(ctx, full_size);\n\t//rewrite subsample size\n\tif (ctx->subsamples) {\n\t\tassert(ctx->subsamp_buffer_size>=14);\n\t\t//reassign to beginning of size field (after first u32 flags)\n\t\tgf_bs_reassign_buffer(ctx->bs_w, ctx->subsamp_buffer + ctx->subsamp_buffer_size-14 + 4, 14 - 4);\n\t\tgf_bs_write_u32(ctx->bs_w, full_size + ctx->nal_length);\n\t}\n\treturn GF_OK;\n}", "GF_FilterPacket *naludmx_start_nalu(GF_NALUDmxCtx *ctx, u32 nal_size, Bool skip_nal_field, Bool *au_start, u8 **pck_data)\n{\n\tGF_FilterPacket *dst_pck = gf_filter_pck_new_alloc(ctx->opid, nal_size + (skip_nal_field ? 0 : ctx->nal_length), pck_data);\n\tif (!dst_pck) return NULL;", "\tif (!skip_nal_field) {\n\t\tif (!ctx->bs_w) ctx->bs_w = gf_bs_new(*pck_data, ctx->nal_length, GF_BITSTREAM_WRITE);\n\t\telse gf_bs_reassign_buffer(ctx->bs_w, *pck_data, ctx->nal_length);\n\t\tgf_bs_write_int(ctx->bs_w, nal_size, 8*ctx->nal_length);\n\t}", "\tif (*au_start) {\n\t\tctx->first_pck_in_au = dst_pck;\n\t\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck);", "\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_FALSE);\n\t\t//we reuse the timing of the input packet for the first nal of the first frame starting in this packet\n\t\tif (ctx->input_is_au_start) {\n\t\t\tctx->input_is_au_start = GF_FALSE;\n\t\t\tgf_filter_pck_set_dts(dst_pck, ctx->dts);\n\t\t\tgf_filter_pck_set_cts(dst_pck, ctx->cts);\n\t\t} else {\n\t\t\t//we don't set the CTS, it will be set once we detect frame end\n\t\t\tgf_filter_pck_set_dts(dst_pck, ctx->dts);\n\t\t}\n\t\t//we use the carousel flag temporarly to indicate the cts must be recomputed\n\t\tgf_filter_pck_set_carousel_version(dst_pck, ctx->timescale ? 0 : 1);", "\t\tgf_filter_pck_set_duration(dst_pck, ctx->pck_duration ? ctx->pck_duration : ctx->cur_fps.den);\n\t\tif (ctx->in_seek) gf_filter_pck_set_seek_flag(dst_pck, GF_TRUE);", "\t\tnaludmx_update_time(ctx);\n\t\t*au_start = GF_FALSE;\n\t\tctx->nb_frames++;\n\t} else {\n\t\tgf_filter_pck_set_framing(dst_pck, GF_FALSE, GF_FALSE);\n\t}\n\tnaludmx_update_nalu_maxsize(ctx, nal_size);", "\tnaludmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE);", "\treturn dst_pck;\n}", "void naludmx_add_subsample(GF_NALUDmxCtx *ctx, u32 subs_size, u8 subs_priority, u32 subs_reserved)\n{\n\tif (ctx->subsamp_buffer_alloc < ctx->subsamp_buffer_size+14 ) {\n\t\tctx->subsamp_buffer_alloc = ctx->subsamp_buffer_size+14;\n\t\tctx->subsamp_buffer = gf_realloc(ctx->subsamp_buffer, ctx->subsamp_buffer_alloc);\n\t}\n\tassert(ctx->subsamp_buffer);\n\tgf_bs_reassign_buffer(ctx->bs_w, ctx->subsamp_buffer + ctx->subsamp_buffer_size, 14);\n\tgf_bs_write_u32(ctx->bs_w, 0); //flags\n\tgf_bs_write_u32(ctx->bs_w, subs_size + ctx->nal_length);\n\tgf_bs_write_u32(ctx->bs_w, subs_reserved); //reserved\n\tgf_bs_write_u8(ctx->bs_w, subs_priority); //priority\n\tgf_bs_write_u8(ctx->bs_w, 0); //discardable - todo\n\tctx->subsamp_buffer_size += 14;\n\tctx->subs_mapped_bytes += subs_size + ctx->nal_length;\n}", "static s32 naludmx_parse_nal_hevc(GF_NALUDmxCtx *ctx, char *data, u32 size, Bool *skip_nal, Bool *is_slice, Bool *is_islice)\n{\n#ifdef GPAC_DISABLE_HEVC\n\treturn -1;\n#else\n\ts32 ps_idx = 0;\n\ts32 res;\n\tu8 nal_unit_type, temporal_id, layer_id;\n\t*skip_nal = GF_FALSE;", "\tgf_bs_reassign_buffer(ctx->bs_r, data, size);\n\tres = gf_hevc_parse_nalu_bs(ctx->bs_r, ctx->hevc_state, &nal_unit_type, &temporal_id, &layer_id);\n\tctx->nb_nalus++;", "\tif (res < 0) {\n\t\tif (res == -1) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Warning: Error parsing NAL unit\\n\", ctx->log_name));\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t}", "\tif (layer_id && ctx->nosvc) {\n\t\t*skip_nal = GF_TRUE;\n\t\treturn 0;\n\t}", "\tswitch (nal_unit_type) {\n\tcase GF_HEVC_NALU_VID_PARAM:\n\t\tif (ctx->novpsext) {\n\t\t\t//this may modify nal_size, but we don't use it for bitstream reading\n\t\t\tps_idx = gf_hevc_read_vps_ex(data, &size, ctx->hevc_state, GF_TRUE);\n\t\t} else {\n\t\t\tps_idx = ctx->hevc_state->last_parsed_vps_id;\n\t\t}\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Video Param Set\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_HEVC_NALU_VID_PARAM, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_HEVC_NALU_SEQ_PARAM:\n\t\tps_idx = ctx->hevc_state->last_parsed_sps_id;\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Sequence Param Set\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_HEVC_NALU_SEQ_PARAM, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_HEVC_NALU_PIC_PARAM:\n\t\tps_idx = ctx->hevc_state->last_parsed_pps_id;\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Picture Param Set\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_HEVC_NALU_PIC_PARAM, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_HEVC_NALU_SEI_PREFIX:\n\t\tgf_hevc_parse_sei(data, size, ctx->hevc_state);\n\t\tif (!ctx->nosei) {\n\t\t\tctx->nb_sei++;", "\t\t\tif (ctx->sei_buffer_alloc < ctx->sei_buffer_size + size + ctx->nal_length) {\n\t\t\t\tctx->sei_buffer_alloc = ctx->sei_buffer_size + size + ctx->nal_length;\n\t\t\t\tctx->sei_buffer = gf_realloc(ctx->sei_buffer, ctx->sei_buffer_alloc);\n\t\t\t}", "\t\t\tif (!ctx->bs_w) ctx->bs_w = gf_bs_new(ctx->sei_buffer + ctx->sei_buffer_size, ctx->nal_length + size, GF_BITSTREAM_WRITE);\n\t\t\telse gf_bs_reassign_buffer(ctx->bs_w, ctx->sei_buffer + ctx->sei_buffer_size, ctx->nal_length + size);\n\t\t\tgf_bs_write_int(ctx->bs_w, size, 8*ctx->nal_length);\n\t\t\tmemcpy(ctx->sei_buffer + ctx->sei_buffer_size + ctx->nal_length, data, size);\n\t\t\tctx->sei_buffer_size += size + ctx->nal_length;\n\t\t} else {\n\t\t\tctx->nb_nalus--;\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_HEVC_NALU_SEI_SUFFIX:\n\t\tif (! ctx->is_playing) return 0;\n\t\tif (ctx->nosei) {\n\t\t\t*skip_nal = GF_TRUE;\n\t\t\tctx->nb_nalus--;\n\t\t} else {\n\t\t\tctx->nb_sei++;\n\t\t}\n\t\tbreak;", "\t/*slice_segment_layer_rbsp*/\n\tcase GF_HEVC_NALU_SLICE_STSA_N:\n\tcase GF_HEVC_NALU_SLICE_STSA_R:\n\tcase GF_HEVC_NALU_SLICE_RADL_R:\n\tcase GF_HEVC_NALU_SLICE_RASL_R:\n\tcase GF_HEVC_NALU_SLICE_RADL_N:\n\tcase GF_HEVC_NALU_SLICE_RASL_N:\n\tcase GF_HEVC_NALU_SLICE_TRAIL_N:\n\tcase GF_HEVC_NALU_SLICE_TRAIL_R:\n\tcase GF_HEVC_NALU_SLICE_TSA_N:\n\tcase GF_HEVC_NALU_SLICE_TSA_R:\n\tcase GF_HEVC_NALU_SLICE_BLA_W_LP:\n\tcase GF_HEVC_NALU_SLICE_BLA_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_BLA_N_LP:\n\tcase GF_HEVC_NALU_SLICE_IDR_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_IDR_N_LP:\n\tcase GF_HEVC_NALU_SLICE_CRA:\n\t\tif (! ctx->is_playing) return 0;\n\t\t*is_slice = GF_TRUE;\n\t\tif (! *skip_nal) {\n\t\t\tswitch (ctx->hevc_state->s_info.slice_type) {\n\t\t\tcase GF_HEVC_SLICE_TYPE_P:\n\t\t\t\tif (layer_id) ctx->nb_e_p++;\n\t\t\t\telse ctx->nb_p++;\n\t\t\t\tbreak;\n\t\t\tcase GF_HEVC_SLICE_TYPE_I:\n\t\t\t\tif (layer_id) ctx->nb_e_i++;\n\t\t\t\telse ctx->nb_i++;\n\t\t\t\t*is_islice = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tcase GF_HEVC_SLICE_TYPE_B:\n\t\t\t\tif (layer_id) ctx->nb_e_b++;\n\t\t\t\telse ctx->nb_b++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;", "\tcase GF_HEVC_NALU_ACCESS_UNIT:\n\t\tctx->nb_aud++;\n\t\tif (!ctx->audelim) {\n\t\t\t*skip_nal = GF_TRUE;\n\t\t} else if (!ctx->opid) {\n\t\t\tctx->has_initial_aud = GF_TRUE;\n\t\t\tmemcpy(ctx->init_aud, data, 3);\n\t\t}\n\t\tbreak;\n\t/*remove*/\n\tcase GF_HEVC_NALU_FILLER_DATA:\n\tcase GF_HEVC_NALU_END_OF_SEQ:\n\tcase GF_HEVC_NALU_END_OF_STREAM:\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;", "\t//parsing is partial, see https://github.com/DolbyLaboratories/dlb_mp4base/blob/70a2e1d4d99a8439b7b8087bf50dd503eeea2291/src/esparser/parser_hevc.c#L1233\n\tcase GF_HEVC_NALU_DV_RPU:\n\t\tctx->hevc_state->dv_rpu = GF_TRUE;\n\t\tbreak;\n\tcase GF_HEVC_NALU_DV_EL:\n\t\tctx->hevc_state->dv_el = GF_TRUE;\n\t\tbreak;", "\tdefault:\n\t\tif (! ctx->is_playing) return 0;\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, (\"[%s] NAL Unit type %d not handled - adding\\n\", ctx->log_name, nal_unit_type));\n\t\tbreak;\n\t}\n\tif (*skip_nal) return res;", "\tctx->linf[layer_id].layer_id_plus_one = layer_id + 1;\n\tif (! ctx->linf[layer_id].max_temporal_id ) ctx->linf[layer_id].max_temporal_id = temporal_id;\n\telse if (ctx->linf[layer_id].max_temporal_id < temporal_id) ctx->linf[layer_id].max_temporal_id = temporal_id;", "\tif (! ctx->linf[layer_id].min_temporal_id ) ctx->linf[layer_id].min_temporal_id = temporal_id;\n\telse if (ctx->linf[layer_id].min_temporal_id > temporal_id) ctx->linf[layer_id].min_temporal_id = temporal_id;", "\tif (ctx->max_temporal_id[layer_id] < temporal_id)\n\t\tctx->max_temporal_id[layer_id] = temporal_id;\n\tif (ctx->min_layer_id > layer_id) ctx->min_layer_id = layer_id;\n\treturn res;\n#endif // GPAC_DISABLE_HEVC\n}", "\nstatic s32 naludmx_parse_nal_vvc(GF_NALUDmxCtx *ctx, char *data, u32 size, Bool *skip_nal, Bool *is_slice, Bool *is_islice)\n{\n\ts32 ps_idx = 0;\n\ts32 res;\n\tu8 nal_unit_type, temporal_id, layer_id;\n\t*skip_nal = GF_FALSE;", "\tgf_bs_reassign_buffer(ctx->bs_r, data, size);\n\tres = gf_media_vvc_parse_nalu_bs(ctx->bs_r, ctx->vvc_state, &nal_unit_type, &temporal_id, &layer_id);\n\tctx->nb_nalus++;", "\tif (res < 0) {\n\t\tif (res == -1) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Warning: Error parsing NAL unit\\n\", ctx->log_name));\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t}", "\tif (layer_id && ctx->nosvc) {\n\t\t*skip_nal = GF_TRUE;\n\t\treturn 0;\n\t}", "\tswitch (nal_unit_type) {\n\tcase GF_VVC_NALU_VID_PARAM:\n\t\tif (ctx->novpsext) {\n\t\t\t//this may modify nal_size, but we don't use it for bitstream reading\n//\t\t\tps_idx = gf_hevc_read_vps_ex(data, &size, ctx->hevc_state, GF_TRUE);\n\t\t\tps_idx = ctx->vvc_state->last_parsed_vps_id;\n\t\t} else {\n\t\t\tps_idx = ctx->vvc_state->last_parsed_vps_id;\n\t\t}\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Video Param Set\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_VVC_NALU_VID_PARAM, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_VVC_NALU_SEQ_PARAM:\n\t\tps_idx = ctx->vvc_state->last_parsed_sps_id;\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Sequence Param Set\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_VVC_NALU_SEQ_PARAM, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_VVC_NALU_PIC_PARAM:\n\t\tps_idx = ctx->vvc_state->last_parsed_pps_id;\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Picture Param Set\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_VVC_NALU_PIC_PARAM, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_VVC_NALU_DEC_PARAM:\n\t\tps_idx = 0;\n\t\tnaludmx_queue_param_set(ctx, data, size, GF_VVC_NALU_DEC_PARAM, ps_idx);\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_VVC_NALU_APS_PREFIX:\n\t\t//for now we keep APS in the stream\n#if 0\n\t\tps_idx = ctx->vvc_state->last_parsed_aps_id;\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Decoder Param Set\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_VVC_NALU_APS_PREFIX, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n#endif\n\t\tbreak;\n\tcase GF_VVC_NALU_SEI_PREFIX:\n\t\tgf_media_vvc_parse_sei(data, size, ctx->vvc_state);\n\t\tif (!ctx->nosei) {\n\t\t\tctx->nb_sei++;", "\t\t\tif (ctx->sei_buffer_alloc < ctx->sei_buffer_size + size + ctx->nal_length) {\n\t\t\t\tctx->sei_buffer_alloc = ctx->sei_buffer_size + size + ctx->nal_length;\n\t\t\t\tctx->sei_buffer = gf_realloc(ctx->sei_buffer, ctx->sei_buffer_alloc);\n\t\t\t}", "\t\t\tif (!ctx->bs_w) ctx->bs_w = gf_bs_new(ctx->sei_buffer + ctx->sei_buffer_size, ctx->nal_length + size, GF_BITSTREAM_WRITE);\n\t\t\telse gf_bs_reassign_buffer(ctx->bs_w, ctx->sei_buffer + ctx->sei_buffer_size, ctx->nal_length + size);\n\t\t\tgf_bs_write_int(ctx->bs_w, size, 8*ctx->nal_length);\n\t\t\tmemcpy(ctx->sei_buffer + ctx->sei_buffer_size + ctx->nal_length, data, size);\n\t\t\tctx->sei_buffer_size += size + ctx->nal_length;\n\t\t} else {\n\t\t\tctx->nb_nalus--;\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_VVC_NALU_SEI_SUFFIX:\n\t\tif (! ctx->is_playing) return 0;\n\t\tif (ctx->nosei) {\n\t\t\t*skip_nal = GF_TRUE;\n\t\t\tctx->nb_nalus--;\n\t\t} else {\n\t\t\tctx->nb_sei++;\n\t\t}\n\t\tbreak;", "\tcase GF_VVC_NALU_PIC_HEADER:\n\t\tif (! ctx->is_playing) return 0;\n\t\tbreak;", "\t/*slice_segment_layer_rbsp*/\n\tcase GF_VVC_NALU_SLICE_TRAIL:\n\tcase GF_VVC_NALU_SLICE_STSA:\n\tcase GF_VVC_NALU_SLICE_RADL:\n\tcase GF_VVC_NALU_SLICE_RASL:\n\tcase GF_VVC_NALU_SLICE_IDR_W_RADL:\n\tcase GF_VVC_NALU_SLICE_IDR_N_LP:\n\tcase GF_VVC_NALU_SLICE_CRA:\n\tcase GF_VVC_NALU_SLICE_GDR:\n\t\tif (! ctx->is_playing) return 0;\n\t\t*is_slice = GF_TRUE;\n\t\tif (! *skip_nal) {\n\t\t\tswitch (ctx->vvc_state->s_info.slice_type) {\n\t\t\tcase GF_VVC_SLICE_TYPE_P:\n\t\t\t\tif (layer_id) ctx->nb_e_p++;\n\t\t\t\telse ctx->nb_p++;\n\t\t\t\tbreak;\n\t\t\tcase GF_VVC_SLICE_TYPE_I:\n\t\t\t\tif (layer_id) ctx->nb_e_i++;\n\t\t\t\telse ctx->nb_i++;\n\t\t\t\t*is_islice = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tcase GF_VVC_SLICE_TYPE_B:\n\t\t\t\tif (layer_id) ctx->nb_e_b++;\n\t\t\t\telse ctx->nb_b++;\n\t\t\t\tbreak;\n\t\t\tcase GF_VVC_SLICE_TYPE_UNKNOWN:\n\t\t\t\tctx->vvc_no_stats = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;", "\tcase GF_VVC_NALU_ACCESS_UNIT:\n\t\tctx->nb_aud++;\n\t\t//no skip AUD in VVC", "\t\tif (!ctx->opid) {\n\t\t\tctx->has_initial_aud = GF_TRUE;\n\t\t\tmemcpy(ctx->init_aud, data, 3);\n\t\t}\n\t\tbreak;\n\t/*remove*/\n\tcase GF_VVC_NALU_FILLER_DATA:\n\tcase GF_VVC_NALU_END_OF_SEQ:\n\tcase GF_VVC_NALU_END_OF_STREAM:\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;", "\tcase GF_VVC_NALU_OPI:\n\t\tif (! ctx->is_playing) return 0;\n\t\tbreak;", "\tdefault:\n\t\tif (! ctx->is_playing) return 0;\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, (\"[%s] NAL Unit type %d not handled - adding\\n\", ctx->log_name, nal_unit_type));\n\t\tbreak;\n\t}\n\tif (*skip_nal) return res;", "\tctx->linf[layer_id].layer_id_plus_one = layer_id + 1;\n\tif (! ctx->linf[layer_id].max_temporal_id ) ctx->linf[layer_id].max_temporal_id = temporal_id;\n\telse if (ctx->linf[layer_id].max_temporal_id < temporal_id) ctx->linf[layer_id].max_temporal_id = temporal_id;", "\tif (! ctx->linf[layer_id].min_temporal_id ) ctx->linf[layer_id].min_temporal_id = temporal_id;\n\telse if (ctx->linf[layer_id].min_temporal_id > temporal_id) ctx->linf[layer_id].min_temporal_id = temporal_id;", "\tif (ctx->max_temporal_id[layer_id] < temporal_id)\n\t\tctx->max_temporal_id[layer_id] = temporal_id;\n\tif (ctx->min_layer_id > layer_id) ctx->min_layer_id = layer_id;\n\treturn res;\n}", "static s32 naludmx_parse_nal_avc(GF_NALUDmxCtx *ctx, char *data, u32 size, u32 nal_type, Bool *skip_nal, Bool *is_slice, Bool *is_islice)\n{\n\ts32 ps_idx = 0;\n\ts32 res = 0;", "\tgf_bs_reassign_buffer(ctx->bs_r, data, size);\n\t*skip_nal = GF_FALSE;\n\tres = gf_avc_parse_nalu(ctx->bs_r, ctx->avc_state);\n\tif (res < 0) {\n\t\tif (res == -1) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Warning: Error parsing NAL unit\\n\", ctx->log_name));\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t}\n\tctx->nb_nalus++;", "\tswitch (nal_type) {\n\tcase GF_AVC_NALU_SVC_SUBSEQ_PARAM:\n\tcase GF_AVC_NALU_SEQ_PARAM:\n\t\tps_idx = ctx->avc_state->last_ps_idx;\n\t\tif (ps_idx<0) {\n\t\t\tif (ctx->avc_state->sps[0].profile_idc) {\n\t\t\t\tGF_LOG(ctx->avc_state->sps[0].profile_idc ? GF_LOG_WARNING : GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Sequence Param Set\\n\", ctx->log_name));\n\t\t\t}\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_AVC_NALU_SEQ_PARAM, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\treturn 0;", "\tcase GF_AVC_NALU_PIC_PARAM:\n\t\tps_idx = ctx->avc_state->last_ps_idx;\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Picture Param Set\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_AVC_NALU_PIC_PARAM, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\treturn 0;", "\tcase GF_AVC_NALU_SEQ_PARAM_EXT:\n\t\tps_idx = ctx->avc_state->last_ps_idx;\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Sequence Param Set Extension\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_AVC_NALU_SEQ_PARAM_EXT, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\treturn 0;", "\tcase GF_AVC_NALU_SEI:\n\t\tif (ctx->avc_state->sps_active_idx != -1) {\n\t\t\tu32 rw_sei_size, sei_size = size;\n\t\t\tif (ctx->sei_buffer_alloc < ctx->sei_buffer_size + sei_size + ctx->nal_length) {\n\t\t\t\tctx->sei_buffer_alloc = ctx->sei_buffer_size + sei_size + ctx->nal_length;\n\t\t\t\tctx->sei_buffer = gf_realloc(ctx->sei_buffer, ctx->sei_buffer_alloc);\n\t\t\t}", "\t\t\tif (!ctx->bs_w) ctx->bs_w = gf_bs_new(ctx->sei_buffer + ctx->sei_buffer_size, ctx->nal_length + sei_size, GF_BITSTREAM_WRITE);\n\t\t\telse gf_bs_reassign_buffer(ctx->bs_w, ctx->sei_buffer + ctx->sei_buffer_size, ctx->nal_length + sei_size);\n\t\t\tgf_bs_write_int(ctx->bs_w, sei_size, 8*ctx->nal_length);", "\t\t\tmemcpy(ctx->sei_buffer + ctx->sei_buffer_size + ctx->nal_length, data, sei_size);\n\t\t\trw_sei_size = gf_media_avc_reformat_sei(ctx->sei_buffer + ctx->sei_buffer_size + ctx->nal_length, sei_size, ctx->seirw, ctx->avc_state);\n\t\t\tif (rw_sei_size < sei_size) {\n\t\t\t\tgf_bs_seek(ctx->bs_w, 0);\n\t\t\t\tgf_bs_write_int(ctx->bs_w, rw_sei_size, 8*ctx->nal_length);\n\t\t\t}", "\t\t\t*skip_nal = GF_TRUE;\n\t\t\tctx->sei_buffer_size += rw_sei_size + ctx->nal_length;", "\t\t\tif (ctx->nosei) {\n\t\t\t\tctx->sei_buffer_size = 0;\n\t\t\t} else {\n\t\t\t\tctx->nb_sei++;\n\t\t\t}\n\t\t}\n\t\treturn 0;", "\tcase GF_AVC_NALU_ACCESS_UNIT:\n\t\tctx->nb_aud++;\n\t\tif (!ctx->audelim) {\n\t\t\t*skip_nal = GF_TRUE;\n\t\t} else if (!ctx->opid) {\n\t\t\tctx->has_initial_aud = GF_TRUE;\n\t\t\tmemcpy(ctx->init_aud, data, 2);\n\t\t}\n\t\treturn 1;\n\t/*remove*/\n\tcase GF_AVC_NALU_FILLER_DATA:\n\tcase GF_AVC_NALU_END_OF_SEQ:\n\tcase GF_AVC_NALU_END_OF_STREAM:\n\t\t*skip_nal = GF_TRUE;\n\t\treturn 0;", "\t//update stats\n\tcase GF_AVC_NALU_NON_IDR_SLICE:\n\tcase GF_AVC_NALU_DP_A_SLICE:\n\tcase GF_AVC_NALU_DP_B_SLICE:\n\tcase GF_AVC_NALU_DP_C_SLICE:\n\tcase GF_AVC_NALU_IDR_SLICE:\n\t\t*is_slice = GF_TRUE;\n\t\tswitch (ctx->avc_state->s_info.slice_type) {\n\t\tcase GF_AVC_TYPE_P:\n\t\tcase GF_AVC_TYPE2_P:\n\t\t\tctx->nb_p++;\n\t\t\tbreak;\n\t\tcase GF_AVC_TYPE_I:\n\t\tcase GF_AVC_TYPE2_I:\n\t\t\tctx->nb_i++;\n\t\t\t*is_islice = GF_TRUE;\n\t\t\tbreak;\n\t\tcase GF_AVC_TYPE_B:\n\t\tcase GF_AVC_TYPE2_B:\n\t\t\tctx->nb_b++;\n\t\t\tbreak;\n\t\tcase GF_AVC_TYPE_SP:\n\t\tcase GF_AVC_TYPE2_SP:\n\t\t\tctx->nb_sp++;\n\t\t\tbreak;\n\t\tcase GF_AVC_TYPE_SI:\n\t\tcase GF_AVC_TYPE2_SI:\n\t\t\tctx->nb_si++;\n\t\t\tbreak;\n\t\t}\n\t\tbreak;", "\tcase GF_AVC_NALU_SVC_SLICE:\n\t\tif (!ctx->explicit) {\n\t\t\tu32 i;\n\t\t\tfor (i = 0; i < gf_list_count(ctx->pps); i ++) {\n\t\t\t\tGF_NALUFFParam *slc = (GF_NALUFFParam*)gf_list_get(ctx->pps, i);\n\t\t\t\tif (ctx->avc_state->s_info.pps && ctx->avc_state->s_info.pps->id == slc->id) {\n\t\t\t\t\t/* This PPS is used by an SVC NAL unit, it should be moved to the SVC Config Record) */\n\t\t\t\t\tgf_list_rem(ctx->pps, i);\n\t\t\t\t\ti--;\n\t\t\t\t\tif (!ctx->pps_svc) ctx->pps_svc = gf_list_new(ctx->pps_svc);\n\t\t\t\t\tgf_list_add(ctx->pps_svc, slc);\n\t\t\t\t\tctx->ps_modified = GF_TRUE;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t*is_slice = GF_TRUE;\n\t\t//we disable temporal scalability when parsing mvc - never used and many encoders screw up POC in enhancemen\n\t\tif (ctx->is_mvc && (res>=0)) {\n\t\t\tres=0;\n\t\t\tctx->avc_state->s_info.poc = ctx->last_poc;\n\t\t}\n if (ctx->avc_state->s_info.sps) {\n switch (ctx->avc_state->s_info.slice_type) {\n case GF_AVC_TYPE_P:\n case GF_AVC_TYPE2_P:\n ctx->avc_state->s_info.sps->nb_ep++;\n break;\n case GF_AVC_TYPE_I:\n case GF_AVC_TYPE2_I:\n ctx->avc_state->s_info.sps->nb_ei++;\n break;\n case GF_AVC_TYPE_B:\n case GF_AVC_TYPE2_B:\n ctx->avc_state->s_info.sps->nb_eb++;\n break;\n }\n }\n break;\n\tcase GF_AVC_NALU_SLICE_AUX:\n\t\t*is_slice = GF_TRUE;\n\t\tbreak;\n\t}\n\treturn res;\n}", "static void naldmx_switch_timestamps(GF_NALUDmxCtx *ctx, GF_FilterPacket *pck)\n{\n\t//input pid sets some timescale - we flushed pending data , update cts\n\tif (ctx->timescale) {\n\t\tu64 ts = gf_filter_pck_get_cts(pck);\n\t\tif (ts != GF_FILTER_NO_TS) {\n\t\t\tctx->prev_cts = ctx->cts;\n\t\t\tctx->cts = ts;\n\t\t}\n\t\tts = gf_filter_pck_get_dts(pck);\n\t\tif (ts != GF_FILTER_NO_TS) {\n\t\t\tif (ctx->full_au_source) {\n\t\t\t\tctx->prev_dts = ctx->dts;\n\t\t\t\tctx->dts = ts;\n\t\t\t} else {\n\t\t\t\tGF_FilterClockType ck_type = gf_filter_pid_get_clock_info(ctx->ipid, NULL, NULL);\n\t\t\t\tif (ck_type==GF_FILTER_CLOCK_PCR_DISC)\n\t\t\t\t\tctx->dts = ts;\n\t\t\t\telse if (ctx->dts<ts)\n\t\t\t\t\tctx->dts=ts;", "\t\t\t\tif (!ctx->prev_dts) ctx->prev_dts = ts;\n\t\t\t\telse if (ctx->prev_dts != ts) {\n\t\t\t\t\tu64 diff = ts;\n\t\t\t\t\tdiff -= ctx->prev_dts;\n\t\t\t\t\tif (!ctx->cur_fps.den)\n\t\t\t\t\t\tctx->cur_fps.den = (u32) diff;\n\t\t\t\t\telse if (ctx->cur_fps.den > diff)\n\t\t\t\t\t\tctx->cur_fps.den = (u32) diff;", "\t\t\t\t\tctx->prev_dts = ts;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tctx->pck_duration = gf_filter_pck_get_duration(pck);\n\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\tctx->src_pck = pck;\n\t\tgf_filter_pck_ref_props(&ctx->src_pck);\n\t\t//store framing flags. If input_is_au_start, the first NAL of the first frame beginning in this packet will\n\t\t//use the DTS/CTS of the input packet, otherwise we will use our internal POC recompute\n\t\tgf_filter_pck_get_framing(pck, &ctx->input_is_au_start, NULL);\n\t}\n}", "static void naldmx_check_timestamp_switch(GF_NALUDmxCtx *ctx, u32 *nalu_store_before, u32 bytes_drop, Bool *drop_packet, GF_FilterPacket *pck)\n{\n\tif (*nalu_store_before) {\n\t\tif (*nalu_store_before > bytes_drop) {\n\t\t\t*nalu_store_before -= bytes_drop;\n\t\t} else {\n\t\t\t//all data from previous frame consumed, update timestamps with info from current packet\n\t\t\t*nalu_store_before = 0;\n\t\t\tnaldmx_switch_timestamps(ctx, pck);\n\t\t\tif (*drop_packet) {\n\t\t\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\t\t\t*drop_packet = GF_FALSE;\n\t\t\t}\n\t\t}\n\t}\n}", "static void naldmx_bs_log(void *udta, const char *field_name, u32 nb_bits, u64 field_val, s32 idx1, s32 idx2, s32 idx3)\n{\n\tGF_NALUDmxCtx *ctx = (GF_NALUDmxCtx *) udta;\n\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\" %s\", field_name));\n\tif (idx1>=0) {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"_%d\", idx1));\n\t\tif (idx2>=0) {\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"_%d\", idx2));\n\t\t\tif (idx3>=0) {\n\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"_%d\", idx3));\n\t\t\t}\n\t\t}\n\t}\n\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"=\\\"\"LLD, field_val));\n\tif ((ctx->bsdbg==2) && ((s32) nb_bits > 1) )\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"(%u)\", nb_bits));", "\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"\\\" \"));\n}", "GF_Err naludmx_process(GF_Filter *filter)\n{\n\tGF_NALUDmxCtx *ctx = gf_filter_get_udta(filter);\n\tGF_FilterPacket *pck;\n\tGF_Err e;\n\tu8 *start;\n\tu32 nalu_before = ctx->nb_nalus;\n\tu32 nalu_store_before = 0;\n\ts32 remain;\n\tBool is_eos = GF_FALSE;\n\tBool drop_packet = GF_FALSE;\n\tu64 byte_offset = GF_FILTER_NO_BO;", "\t//always reparse duration\n\tif (!ctx->file_loaded)\n\t\tnaludmx_check_dur(filter, ctx);", "\tpck = gf_filter_pid_get_packet(ctx->ipid);\n\tif (!ctx->resume_from && !pck) {\n\t\tif (gf_filter_pid_is_eos(ctx->ipid)) {\n\t\t\tif (ctx->nal_store_size) {\n\t\t\t\tif (!ctx->is_playing)\n\t\t\t\t\treturn GF_OK;", "\t\t\t\tstart = ctx->nal_store;\n\t\t\t\tremain = ctx->nal_store_size;\n\t\t\t\tis_eos = GF_TRUE;\n\t\t\t\tgoto naldmx_flush;\n\t\t\t}\n\t\t\tif (ctx->first_pck_in_au) {\n\t\t\t\tnaludmx_finalize_au_flags(ctx);\n\t\t\t}\n\t\t\t//single-frame stream\n\t\t\tif (!ctx->poc_diff) ctx->poc_diff = 1;\n\t\t\tctx->strict_poc = STRICT_POC_OFF;\n\t\t\tnaludmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE);\n\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\tctx->src_pck = NULL;\n\t\t\tif (!ctx->opid) return GF_EOS;", "\t\t\tgf_filter_pid_set_info(ctx->opid, GF_PROP_PID_MAX_NALU_SIZE, &PROP_UINT(ctx->max_nalu_size) );\n\t\t\tif (ctx->codecid==GF_CODECID_HEVC) {\n\t\t\t\tnaludmx_set_hevc_oinf(ctx, ctx->max_temporal_id);\n\t\t\t\tnaludmx_set_hevc_linf(ctx);\n\t\t\t\tgf_filter_pid_set_info_str(ctx->opid, \"hevc:min_lid\", &PROP_UINT(ctx->min_layer_id) );\n\t\t\t}\n\t\t\tif (ctx->opid)\n\t\t\t\tgf_filter_pid_set_eos(ctx->opid);\n\t\t\treturn GF_EOS;\n\t\t}\n\t\treturn GF_OK;\n\t}", "\tif (!ctx->is_playing && ctx->opid)\n\t\treturn GF_OK;", "\t//if we have bytes from previous packet in the header, we cannot switch timing until we know what these bytes are\n\tif (!ctx->nal_store_size)\n\t\tnaldmx_switch_timestamps(ctx, pck);", "\tnalu_store_before = ctx->nal_store_size;\n\tif (!ctx->resume_from && pck) {\n\t\tu32 pck_size;\n\t\tconst u8 *data = gf_filter_pck_get_data(pck, &pck_size);\n\t\tif (ctx->nal_store_alloc < ctx->nal_store_size + pck_size) {\n\t\t\tctx->nal_store_alloc = ctx->nal_store_size + pck_size;\n\t\t\tctx->nal_store = gf_realloc(ctx->nal_store, sizeof(char)*ctx->nal_store_alloc);\n\t\t\tif (!ctx->nal_store) {\n\t\t\t\tctx->nal_store_alloc = 0;\n\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t}\n\t\t}\n\t\tbyte_offset = gf_filter_pck_get_byte_offset(pck);\n\t\tif (byte_offset != GF_FILTER_NO_BO)\n\t\t\tbyte_offset -= ctx->nal_store_size;\n\t\tmemcpy(ctx->nal_store + ctx->nal_store_size, data, sizeof(char)*pck_size);\n\t\tctx->nal_store_size += pck_size;\n\t\tdrop_packet = GF_TRUE;\n\t}\n\tstart = ctx->nal_store;\n\tremain = ctx->nal_store_size;", "\tif (ctx->resume_from) {\n\t\tif (ctx->opid && gf_filter_pid_would_block(ctx->opid))\n\t\t\treturn GF_OK;", "\t\tassert(ctx->resume_from < ctx->nal_store_size);\n\t\tstart += ctx->resume_from;\n\t\tremain -= ctx->resume_from;\n\t\tctx->resume_from = 0;", "\t\tif (!pck && gf_filter_pid_is_eos(ctx->ipid))\n\t\t\tis_eos = GF_TRUE;\n\t}", "naldmx_flush:\n\tif (!ctx->bs_r) {\n\t\tctx->bs_r = gf_bs_new(start, remain, GF_BITSTREAM_READ);", "#ifndef GPAC_DISABLE_LOG\n\t\tif (ctx->bsdbg && gf_log_tool_level_on(GF_LOG_PARSER, GF_LOG_DEBUG))\n\t\t\tgf_bs_set_logger(ctx->bs_r, naldmx_bs_log, ctx);\n#endif", "\t} else {\n\t\tgf_bs_reassign_buffer(ctx->bs_r, start, remain);\n\t}", " assert(remain>=0);", "\twhile (remain) {\n\t\tu8 *pck_data;\n\t\tu8 *nal_data;\n\t\tu32 nal_size;\n\t\ts32 current;\n\t\tBool skip_nal = GF_FALSE;\n\t\tu32 sc_size=0;\n\t\tu32 nal_type = 0;\n\t\tu32 nal_ref_idc = 0;\n\t\ts32 next=0;\n\t\tu32 next_sc_size=0;\n\t\ts32 nal_parse_result;\n\t\tBool slice_is_ref, slice_force_ref;\n\t\tBool is_slice = GF_FALSE;\n\t\tBool is_islice = GF_FALSE;\n\t\tBool bottom_field_flag = GF_FALSE;\n\t\tBool au_start;\n\t\tu32 avc_svc_subs_reserved = 0;\n\t\tu8 avc_svc_subs_priority = 0;\n\t\tBool recovery_point_valid = GF_FALSE;\n\t\tu32 recovery_point_frame_cnt = 0;\n\t\tBool bIntraSlice = GF_FALSE;\n\t\tGF_FilterSAPType au_sap_type = GF_FILTER_SAP_NONE;\n\t\tBool slice_is_b = GF_FALSE;\n\t\tBool check_dep = GF_FALSE;\n\t\ts32 slice_poc = 0;", "\t\t//not enough bytes to parse start code + nal hdr\n\t\tif (!is_eos && (remain<6)) {\n\t\t\tbreak;\n\t\t}", "\t\t//locate next start code\n\t\tcurrent = gf_media_nalu_next_start_code(start, remain, &sc_size);\n\t\tif (current == remain)\n\t\t\tcurrent = -1;", "\t\t//no start code: if eos or full AU dispatch mode, send remaining otherwise gather\n\t\tif (current<0) {\n\t\t\tif (!is_eos && !ctx->full_au_source) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\te = naludmx_realloc_last_pck(ctx, (u32) remain, &pck_data);\n\t\t\tif (e==GF_OK)\n\t\t\t\tmemcpy(pck_data, start, (size_t) remain);\n\t\t\tremain = 0;\n\t\t\tbreak;\n\t\t}", "\t\tassert(current>=0);", "\t\t//skip if no output pid\n\t\tif (!ctx->opid && current) {\n\t\t\tassert(remain>=current);\n assert((s32) current >= 0);", "\t\t\tstart += current;\n\t\t\tremain -= current;\n\t\t\tcurrent = 0;\n\t\t}", "\t\t//dispatch remaining bytes\n\t\tif (current>0) {\n\t\t\t//flush remaining bytes in NAL\n\t\t\tif (gf_list_count(ctx->pck_queue)) {\n\t\t\t\te = naludmx_realloc_last_pck(ctx, current, &pck_data);\n\t\t\t\tif (e==GF_OK) {\n\t\t\t\t\tmemcpy(pck_data, start, current);\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert(remain>=current);\n\t\t\tstart += current;\n\t\t\tremain -= current;\n\t\t\tnaldmx_check_timestamp_switch(ctx, &nalu_store_before, current, &drop_packet, pck);\n\t\t}\n\t\tif (!remain)\n\t\t\tbreak;", "\t\t//not enough bytes to parse start code + nal hdr\n\t\tif (!is_eos && (remain<6)) {\n\t\t\tbreak;\n\t\t}", "\t\tnal_data = start + sc_size;\n\t\tnal_size = remain - sc_size;", "\t\t//figure out which nal we need to completely load\n\t\tif (ctx->codecid==GF_CODECID_HEVC) {\n\t\t\tnal_type = nal_data[0];\n\t\t\tnal_type = (nal_type & 0x7E) >> 1;", "\t\t\tswitch (nal_type) {\n\t\t\tcase GF_HEVC_NALU_VID_PARAM:\n\t\t\tcase GF_HEVC_NALU_SEQ_PARAM:\n\t\t\tcase GF_HEVC_NALU_PIC_PARAM:\n\t\t\tcase GF_HEVC_NALU_SEI_PREFIX:\n\t\t\tcase GF_HEVC_NALU_SEI_SUFFIX:\n\t\t\t\tbreak;\n\t\t\tcase GF_HEVC_NALU_SLICE_TRAIL_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_TSA_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_STSA_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_RADL_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_RASL_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_RSV_VCL_N10:\n\t\t\tcase GF_HEVC_NALU_SLICE_RSV_VCL_N12:\n\t\t\tcase GF_HEVC_NALU_SLICE_RSV_VCL_N14:\n\t\t\t\tcheck_dep = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (nal_type<GF_HEVC_NALU_VID_PARAM)\n\t\t\t\t\tnal_ref_idc = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\t\tnal_type = nal_data[1]>>3;\n\t\t\tswitch (nal_type) {\n\t\t\tcase GF_VVC_NALU_OPI:\n\t\t\tcase GF_VVC_NALU_DEC_PARAM:\n\t\t\tcase GF_VVC_NALU_VID_PARAM:\n\t\t\tcase GF_VVC_NALU_SEQ_PARAM:\n\t\t\tcase GF_VVC_NALU_PIC_PARAM:\n\t\t\tcase GF_VVC_NALU_SEI_PREFIX:\n\t\t\tcase GF_VVC_NALU_SEI_SUFFIX:\n\t\t\tcase GF_VVC_NALU_APS_PREFIX:\n\t\t\tcase GF_VVC_NALU_APS_SUFFIX:\n\t\t\tcase GF_VVC_NALU_PIC_HEADER:\n\t\t\t\tbreak;", "\t\t\tcase GF_VVC_NALU_SLICE_TRAIL:\n\t\t\tcase GF_VVC_NALU_SLICE_STSA:\n\t\t\tcase GF_VVC_NALU_SLICE_RADL:\n\t\t\tcase GF_VVC_NALU_SLICE_RASL:\n\t\t\tcase GF_VVC_NALU_SLICE_IDR_W_RADL:\n\t\t\tcase GF_VVC_NALU_SLICE_IDR_N_LP:\n\t\t\tcase GF_VVC_NALU_SLICE_CRA:\n\t\t\tcase GF_VVC_NALU_SLICE_GDR:\n\t\t\t\tif (ctx->deps) {\n\t\t\t\t\tcheck_dep = GF_TRUE;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (nal_type<GF_HEVC_NALU_VID_PARAM)\n\t\t\t\t\tnal_ref_idc = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tnal_type = nal_data[0] & 0x1F;\n\t\t\tnal_ref_idc = (nal_data[0] & 0x60) >> 5;\n\t\t}", "\t\t//locate next NAL start\n\t\tnext = gf_media_nalu_next_start_code(nal_data, nal_size, &next_sc_size);\n\t\tif (!is_eos && (next == nal_size) && !ctx->full_au_source) {\n\t\t\tnext = -1;\n\t\t}", "\t\t//next nal start not found, wait\n\t\tif (next<0) {\n\t\t\tbreak;\n\t\t}", "\t\t//this is our exact NAL size, without start code\n\t\tnal_size = next;", "\t\tif (ctx->codecid==GF_CODECID_HEVC) {\n\t\t\tnal_parse_result = naludmx_parse_nal_hevc(ctx, nal_data, nal_size, &skip_nal, &is_slice, &is_islice);\n\t\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\t\tnal_parse_result = naludmx_parse_nal_vvc(ctx, nal_data, nal_size, &skip_nal, &is_slice, &is_islice);\n\t\t} else {\n\t\t\tnal_parse_result = naludmx_parse_nal_avc(ctx, nal_data, nal_size, nal_type, &skip_nal, &is_slice, &is_islice);\n\t\t}", "\t\t//dispatch right away if analyze\n\t\tif (ctx->analyze) {\n\t\t\tskip_nal = GF_FALSE;\n\t\t\tctx->sei_buffer_size = 0;\n\t\t}", "\t\t//new frame - if no slices, we detected the new frame on AU delimiter, don't flush new frame !\n\t\tif ((nal_parse_result>0) && !ctx->first_slice_in_au) {\n\t\t\t//new frame - we flush later on\n\t\t\tnaludmx_finalize_au_flags(ctx);", "\t\t\tctx->has_islice = GF_FALSE;\n\t\t\tctx->first_slice_in_au = GF_TRUE;\n\t\t\tctx->sei_recovery_frame_count = -1;\n\t\t\tctx->au_sap = GF_FILTER_SAP_NONE;\n\t\t\tctx->bottom_field_flag = GF_FALSE;\n\t\t}", "\t\tnaludmx_check_pid(filter, ctx);\n\t\tif (!ctx->opid) skip_nal = GF_TRUE;", "\t\tif (skip_nal) {\n\t\t\tnal_size += sc_size;\n\t\t\tassert((u32) remain >= nal_size);\n\t\t\tstart += nal_size;\n\t\t\tremain -= nal_size;\n\t\t\tnaldmx_check_timestamp_switch(ctx, &nalu_store_before, nal_size, &drop_packet, pck);\n\t\t\tcontinue;\n\t\t}", "\t\tif (!ctx->is_playing) {\n\t\t\tctx->resume_from = (u32) (start - ctx->nal_store);\n assert(ctx->resume_from<=ctx->nal_store_size);\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"[%s] not yet playing\\n\", ctx->log_name));", "\t\t\tif (drop_packet)\n\t\t\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\t\treturn GF_OK;\n\t\t}\n\t\tif (ctx->in_seek) {\n\t\t\tu64 nb_frames_at_seek = (u64) (ctx->start_range * ctx->cur_fps.num);\n\t\t\tif (ctx->cts + ctx->cur_fps.den >= nb_frames_at_seek) {\n\t\t\t\t//u32 samples_to_discard = (ctx->cts + ctx->dts_inc) - nb_samples_at_seek;\n\t\t\t\tctx->in_seek = GF_FALSE;\n\t\t\t}\n\t\t}", "\t\tif (nal_parse_result<0) {\n\t\t\tif (byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\tu64 bo = byte_offset;\n\t\t\t\tbo += (start - ctx->nal_store);", "\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing NAL Unit %d (byte offset \"LLU\" size %d type %d frame %d last POC %d) - skipping\\n\", ctx->log_name, ctx->nb_nalus, bo, nal_size, nal_type, ctx->nb_frames, ctx->last_poc));\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing NAL Unit %d (size %d type %d frame %d last POC %d) - skipping\\n\", ctx->log_name, ctx->nb_nalus, nal_size, nal_type, ctx->nb_frames, ctx->last_poc));\n\t\t\t}\n\t\t\tnal_size += sc_size;\n\t\t\tassert((u32) remain >= nal_size);\n\t\t\tstart += nal_size;\n\t\t\tremain -= nal_size;\n\t\t\tnaldmx_check_timestamp_switch(ctx, &nalu_store_before, nal_size, &drop_packet, pck);\n\t\t\tcontinue;\n\t\t}", "\t\tif (check_dep) {\n\t\t\tif ((ctx->codecid==GF_CODECID_HEVC) && ctx->hevc_state->s_info.sps) {\n\t\t\t\tHEVC_VPS *vps;\n\t\t\t\tu32 temporal_id = nal_data[1] & 0x7;\n\t\t\t\tvps = & ctx->hevc_state->vps[ctx->hevc_state->s_info.sps->vps_id];\n\t\t\t\tif (temporal_id + 1 < vps->max_sub_layers) {\n\t\t\t\t\tnal_ref_idc = GF_TRUE;\n\t\t\t\t}\n\t\t\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\t\t\tif (ctx->vvc_state->s_info.non_ref_pic) {\n\t\t\t\t\tnal_ref_idc = GF_FALSE;\n\t\t\t\t} else {\n\t\t\t\t\t//todo\n\t\t\t\t\tnal_ref_idc = GF_TRUE;\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\n\t\tif (is_islice) ctx->has_islice = GF_TRUE;", "\t\t//store all variables needed to compute POC/CTS and sample SAP and recovery info\n\t\tif (ctx->codecid==GF_CODECID_HEVC) {\n#ifndef GPAC_DISABLE_HEVC\n\t\t\tslice_is_ref = gf_hevc_slice_is_IDR(ctx->hevc_state);", "\t\t\trecovery_point_valid = ctx->hevc_state->sei.recovery_point.valid;\n\t\t\trecovery_point_frame_cnt = ctx->hevc_state->sei.recovery_point.frame_cnt;\n\t\t\tbIntraSlice = gf_hevc_slice_is_intra(ctx->hevc_state);", "\t\t\tau_sap_type = GF_FILTER_SAP_NONE;\n\t\t\tif (gf_hevc_slice_is_IDR(ctx->hevc_state)) {\n\t\t\t\tau_sap_type = GF_FILTER_SAP_1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tswitch (ctx->hevc_state->s_info.nal_unit_type) {\n\t\t\t\tcase GF_HEVC_NALU_SLICE_BLA_W_LP:\n\t\t\t\tcase GF_HEVC_NALU_SLICE_BLA_W_DLP:\n\t\t\t\t\tau_sap_type = GF_FILTER_SAP_3;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_HEVC_NALU_SLICE_BLA_N_LP:\n\t\t\t\t\tau_sap_type = GF_FILTER_SAP_1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_HEVC_NALU_SLICE_CRA:\n\t\t\t\t\tau_sap_type = GF_FILTER_SAP_3;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}", "\t\t\tslice_poc = ctx->hevc_state->s_info.poc;", "\t\t\t/*need to store TS offsets*/\n\t\t\tswitch (ctx->hevc_state->s_info.slice_type) {\n\t\t\tcase GF_AVC_TYPE_B:\n\t\t\tcase GF_AVC_TYPE2_B:\n\t\t\t\tslice_is_b = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n#endif // GPAC_DISABLE_HEVC\n\t\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\t\tslice_is_ref = gf_media_vvc_slice_is_ref(ctx->vvc_state);\n\t\t\trecovery_point_valid = ctx->vvc_state->s_info.recovery_point_valid;\n\t\t\trecovery_point_frame_cnt = ctx->vvc_state->s_info.gdr_recovery_count;", "//\t\t\tcommented, set below\n//\t\t\tif (ctx->vvc_state->s_info.irap_or_gdr_pic && !ctx->vvc_state->s_info.gdr_pic)\n//\t\t\t\tbIntraSlice = GF_TRUE; //gf_hevc_slice_is_intra(ctx->hevc_state);", "\t\t\tau_sap_type = GF_FILTER_SAP_NONE;\n\t\t\tif (ctx->vvc_state->s_info.irap_or_gdr_pic && !ctx->vvc_state->s_info.gdr_pic) {\n\t\t\t\tau_sap_type = GF_FILTER_SAP_1;\n\t\t\t\tbIntraSlice = GF_TRUE;\n\t\t\t\tslice_is_ref = 1;\n\t\t\t} else {\n\t\t\t\tswitch (ctx->vvc_state->s_info.nal_unit_type) {\n\t\t\t\tcase GF_VVC_NALU_SLICE_IDR_N_LP:\n\t\t\t\t\tau_sap_type = GF_FILTER_SAP_1;\n\t\t\t\t\tslice_is_ref = 1;\n\t\t\t\t\tbIntraSlice = GF_TRUE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_VVC_NALU_SLICE_CRA:\n\t\t\t\t\tau_sap_type = GF_FILTER_SAP_3;\n\t\t\t\t\tbIntraSlice = GF_TRUE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_VVC_NALU_SLICE_IDR_W_RADL:\n\t\t\t\t\tbIntraSlice = GF_TRUE;\n\t\t\t\t\tif (ctx->vvc_state->s_info.gdr_pic) {\n\t\t\t\t\t\tau_sap_type = GF_FILTER_SAP_3;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tau_sap_type = GF_FILTER_SAP_1;\n\t\t\t\t\t\tslice_is_ref = 1;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}", "\t\t\tslice_poc = ctx->vvc_state->s_info.poc;", "\t\t\t/*need to store TS offsets*/\n\t\t\tswitch (ctx->vvc_state->s_info.slice_type) {\n\t\t\tcase GF_AVC_TYPE_B:\n\t\t\tcase GF_AVC_TYPE2_B:\n\t\t\t\tslice_is_b = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {", "\t\t\t/*fixme - we need finer grain for priority*/\n\t\t\tif ((nal_type==GF_AVC_NALU_SVC_PREFIX_NALU) || (nal_type==GF_AVC_NALU_SVC_SLICE)) {\n\t\t\t\tif (!ctx->is_mvc) {\n\t\t\t\t\tunsigned char *p = (unsigned char *) start;\n\t\t\t\t\t// RefPicFlag\n\t\t\t\t\tavc_svc_subs_reserved |= (p[0] & 0x60) ? 0x80000000 : 0;\n\t\t\t\t\t// RedPicFlag TODO: not supported, would require to parse NAL unit payload\n\t\t\t\t\tavc_svc_subs_reserved |= (0) ? 0x40000000 : 0;\n\t\t\t\t\t// VclNALUnitFlag\n\t\t\t\t\tavc_svc_subs_reserved |= (1<=nal_type && nal_type<=5) || (nal_type==GF_AVC_NALU_SVC_PREFIX_NALU) || (nal_type==GF_AVC_NALU_SVC_SLICE) ? 0x20000000 : 0;\n\t\t\t\t\t// use values of IdrFlag and PriorityId directly from SVC extension header\n\t\t\t\t\tavc_svc_subs_reserved |= p[1] << 16;\n\t\t\t\t\t// use values of DependencyId and QualityId directly from SVC extension header\n\t\t\t\t\tavc_svc_subs_reserved |= p[2] << 8;\n\t\t\t\t\t// use values of TemporalId and UseRefBasePicFlag directly from SVC extension header\n\t\t\t\t\tavc_svc_subs_reserved |= p[3] & 0xFC;\n\t\t\t\t\t// StoreBaseRepFlag TODO: SVC FF mentions a store_base_rep_flag which cannot be found in SVC spec\n\t\t\t\t\tavc_svc_subs_reserved |= (0) ? 0x00000002 : 0;", "\t\t\t\t\t// priority_id (6 bits) in SVC has inverse meaning -> lower value means higher priority - invert it and scale it to 8 bits\n\t\t\t\t\tavc_svc_subs_priority = (63 - (p[1] & 0x3F)) << 2;\n\t\t\t\t}\n\t\t\t\tif (nal_type==GF_AVC_NALU_SVC_PREFIX_NALU) {\n if (ctx->svc_prefix_buffer_size) {\n GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[%s] broken bitstream, two consecutive SVC prefix NALU without SVC slice in-between\\n\", ctx->log_name));\n ctx->svc_prefix_buffer_size = 0;\n }", "\t\t\t\t\t/* remember reserved and priority value */\n\t\t\t\t\tctx->svc_nalu_prefix_reserved = avc_svc_subs_reserved;\n\t\t\t\t\tctx->svc_nalu_prefix_priority = avc_svc_subs_priority;", "\t\t\t\t\tctx->svc_prefix_buffer_size = nal_size;\n\t\t\t\t\tif (ctx->svc_prefix_buffer_size > ctx->svc_prefix_buffer_alloc) {\n\t\t\t\t\t\tctx->svc_prefix_buffer_alloc = ctx->svc_prefix_buffer_size;\n\t\t\t\t\t\tctx->svc_prefix_buffer = gf_realloc(ctx->svc_prefix_buffer, ctx->svc_prefix_buffer_size);\n\t\t\t\t\t}\n\t\t\t\t\tmemcpy(ctx->svc_prefix_buffer, start+sc_size, ctx->svc_prefix_buffer_size);", "\t\t\t\t\tassert( (u32) remain >= sc_size + nal_size);\n\t\t\t\t\tstart += sc_size + nal_size;\n\t\t\t\t\tremain -= sc_size + nal_size;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else if (is_slice) {\n\t\t\t\t// RefPicFlag\n\t\t\t\tavc_svc_subs_reserved |= (start[0] & 0x60) ? 0x80000000 : 0;\n\t\t\t\t// VclNALUnitFlag\n\t\t\t\tavc_svc_subs_reserved |= (1<=nal_type && nal_type<=5) || (nal_type==GF_AVC_NALU_SVC_PREFIX_NALU) || (nal_type==GF_AVC_NALU_SVC_SLICE) ? 0x20000000 : 0;\n\t\t\t\tavc_svc_subs_priority = 0;\n\t\t\t}", "\t\t\tif (is_slice && ctx->avc_state->s_info.field_pic_flag) {\n\t\t\t\tctx->is_paff = GF_TRUE;\n\t\t\t\tbottom_field_flag = ctx->avc_state->s_info.bottom_field_flag;\n\t\t\t}", "\t\t\tslice_is_ref = (ctx->avc_state->s_info.nal_unit_type==GF_AVC_NALU_IDR_SLICE) ? GF_TRUE : GF_FALSE;", "\t\t\trecovery_point_valid = ctx->avc_state->sei.recovery_point.valid;\n\t\t\trecovery_point_frame_cnt = ctx->avc_state->sei.recovery_point.frame_cnt;\n\t\t\tbIntraSlice = gf_media_avc_slice_is_intra(ctx->avc_state);", "\t\t\tau_sap_type = GF_FILTER_SAP_NONE;\n\t\t\tif (ctx->avc_state->s_info.nal_unit_type == GF_AVC_NALU_IDR_SLICE)\n\t\t\t\tau_sap_type = GF_FILTER_SAP_1;", "\t\t\tslice_poc = ctx->avc_state->s_info.poc;\n\t\t\t/*need to store TS offsets*/\n\t\t\tswitch (ctx->avc_state->s_info.slice_type) {\n\t\t\tcase GF_AVC_TYPE_B:\n\t\t\tcase GF_AVC_TYPE2_B:\n\t\t\t\tslice_is_b = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "\t\tif (is_slice) {\n\t\t\tBool first_in_au = ctx->first_slice_in_au;", "\t\t\tif (slice_is_ref)\n\t\t\t\tctx->nb_idr++;\n\t\t\tslice_force_ref = GF_FALSE;", "\t\t\t/*we only indicate TRUE IDRs for sync samples (cf AVC file format spec).\n\t\t\tSEI recovery should be used to build sampleToGroup & RollRecovery tables*/\n\t\t\tif (ctx->first_slice_in_au) {\n\t\t\t\tctx->first_slice_in_au = GF_FALSE;\n\t\t\t\tif (recovery_point_valid) {\n\t\t\t\t\tctx->sei_recovery_frame_count = recovery_point_frame_cnt;", "\t\t\t\t\t/*we allow to mark I-frames as sync on open-GOPs (with sei_recovery_frame_count=0) when forcing sync even when the SEI RP is not available*/\n\t\t\t\t\tif (!recovery_point_frame_cnt && bIntraSlice) {\n\t\t\t\t\t\tctx->has_islice = 1;\n\t\t\t\t\t\tif (ctx->use_opengop_gdr == 1) {\n\t\t\t\t\t\t\tctx->use_opengop_gdr = 2; /*avoid message flooding*/\n\t\t\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[%s] No valid SEI Recovery Point found although needed - forcing\\n\", ctx->log_name));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (ctx->codecid==GF_CODECID_HEVC) {\n\t\t\t\t\t\tctx->hevc_state->sei.recovery_point.valid = 0;\n\t\t\t\t\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\t\t\t\t\tctx->vvc_state->s_info.recovery_point_valid = 0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tctx->avc_state->sei.recovery_point.valid = 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (bIntraSlice && ctx->force_sync && (ctx->sei_recovery_frame_count==0))\n\t\t\t\t\t\tslice_force_ref = GF_TRUE;\n\t\t\t\t}\n\t\t\t\tctx->au_sap = au_sap_type;\n\t\t\t\tctx->bottom_field_flag = bottom_field_flag;\n\t\t\t}", "\t\t\tif (slice_poc < ctx->poc_shift) {", "\t\t\t\tu32 i, count = gf_list_count(ctx->pck_queue);\n\t\t\t\tfor (i=0; i<count; i++) {\n\t\t\t\t\tu64 dts, cts;\n\t\t\t\t\tGF_FilterPacket *q_pck = gf_list_get(ctx->pck_queue, i);\n\t\t\t\t\tassert(q_pck);\n\t\t\t\t\tdts = gf_filter_pck_get_dts(q_pck);\n\t\t\t\t\tif (dts == GF_FILTER_NO_TS) continue;\n\t\t\t\t\tcts = gf_filter_pck_get_cts(q_pck);\n\t\t\t\t\tcts += ctx->poc_shift;\n\t\t\t\t\tcts -= slice_poc;\n\t\t\t\t\tgf_filter_pck_set_cts(q_pck, cts);\n\t\t\t\t}", "\t\t\t\tctx->poc_shift = slice_poc;\n\t\t\t}", "\t\t\t/*if #pics, compute smallest POC increase*/\n\t\t\tif (slice_poc != ctx->last_poc) {\n\t\t\t\ts32 pdiff = ABS(ctx->last_poc - slice_poc);", "\t\t\t\tif ((slice_poc < 0) && !ctx->last_poc)\n\t\t\t\t\tctx->poc_diff = 0;", "\t\t\t\tif (!ctx->poc_diff || (ctx->poc_diff > (s32) pdiff ) ) {\n\t\t\t\t\tctx->poc_diff = pdiff;\n\t\t\t\t\tctx->poc_probe_done = GF_FALSE;\n\t\t\t\t} else if (first_in_au) {\n\t\t\t\t\t//second frame with the same poc diff, we should be able to properly recompute CTSs\n\t\t\t\t\tctx->poc_probe_done = GF_TRUE;\n\t\t\t\t}\n\t\t\t\tctx->last_poc = slice_poc;\n\t\t\t}\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"[%s] POC is %d - min poc diff %d - slice is ref %d\\n\", ctx->log_name, slice_poc, ctx->poc_diff, slice_is_ref));", "\t\t\t/*ref slice, reset poc*/\n\t\t\tif (slice_is_ref) {\n\t\t\t\tif (first_in_au) {\n\t\t\t\t\tBool temp_poc_diff = GF_FALSE;\n\t\t\t\t\t//two consecutive IDRs, force poc_diff to 1 if 0 (when we have intra-only) to force frame dispatch\n\t\t\t\t\tif (ctx->last_frame_is_idr && !ctx->poc_diff) {\n\t\t\t\t\t\ttemp_poc_diff = GF_TRUE;\n\t\t\t\t\t\tctx->poc_diff = 1;\n\t\t\t\t\t}\n\t\t\t\t\t//new ref frame, dispatch all pending packets\n\t\t\t\t\tnaludmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE);", "\t\t\t\t\tctx->max_last_poc = ctx->last_poc = ctx->max_last_b_poc = 0;\n\t\t\t\t\tctx->poc_shift = 0;\n\t\t\t\t\t//force probing of POC diff, this will prevent dispatching frames with wrong CTS until we have a clue of min poc_diff used\n\t\t\t\t\tctx->poc_probe_done = 0;\n\t\t\t\t\tctx->last_frame_is_idr = GF_TRUE;\n\t\t\t\t\tif (temp_poc_diff)\n\t\t\t\t\t\tctx->poc_diff = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*forced ref slice*/\n\t\t\telse if (slice_force_ref) {\n\t\t\t\tctx->last_frame_is_idr = GF_FALSE;\n\t\t\t\tif (first_in_au) {\n\t\t\t\t\t//new ref frame, dispatch all pending packets\n\t\t\t\t\tnaludmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE);", "\t\t\t\t\t/*adjust POC shift as sample will now be marked as sync, so we must store poc as if IDR (eg POC=0) for our CTS offset computing to be correct*/\n\t\t\t\t\tctx->poc_shift = slice_poc;", "\t\t\t\t\t//force probing of POC diff, this will prevent dispatching frames with wrong CTS until we have a clue of min poc_diff used\n\t\t\t\t\tctx->poc_probe_done = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*strictly less - this is a new P slice*/\n\t\t\telse if (ctx->max_last_poc < ctx->last_poc) {\n\t\t\t\tctx->max_last_b_poc = 0;\n\t\t\t\tctx->max_last_poc = ctx->last_poc;\n\t\t\t\tctx->last_frame_is_idr = GF_FALSE;\n\t\t\t}\n\t\t\t/*stricly greater*/\n\t\t\telse if (slice_is_b && (ctx->max_last_poc > ctx->last_poc)) {\n\t\t\t\tctx->last_frame_is_idr = GF_FALSE;\n\t\t\t\tif (!ctx->max_last_b_poc) {\n\t\t\t\t\tctx->max_last_b_poc = ctx->last_poc;\n\t\t\t\t}\n\t\t\t\t/*if same poc than last max, this is a B-slice*/\n\t\t\t\telse if (ctx->last_poc > ctx->max_last_b_poc) {\n\t\t\t\t\tctx->max_last_b_poc = ctx->last_poc;\n\t\t\t\t}\n\t\t\t\t/*otherwise we had a B-slice reference: do nothing*/\n\t\t\t} else {\n\t\t\t\tctx->last_frame_is_idr = GF_FALSE;\n\t\t\t}", "\n\t\t\tif (ctx->deps) {\n\t\t\t\tif (nal_ref_idc) {\n\t\t\t\t\tctx->has_ref_slices = GF_TRUE;\n\t\t\t\t}\n\t\t\t\tif ((ctx->codecid==GF_CODECID_AVC) && (ctx->avc_state->s_info.redundant_pic_cnt) ) {\n\t\t\t\t\tctx->has_redundant = GF_TRUE;\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\n\t\tau_start = ctx->first_pck_in_au ? GF_FALSE : GF_TRUE;", "\t\tif (ctx->has_initial_aud) {\n\t\t\tu32 audelim_size = (ctx->codecid!=GF_CODECID_AVC) ? 3 : 2;\n\t\t\t/*dst_pck = */naludmx_start_nalu(ctx, audelim_size, GF_FALSE, &au_start, &pck_data);\n\t\t\tmemcpy(pck_data + ctx->nal_length , ctx->init_aud, audelim_size);\n\t\t\tctx->has_initial_aud = GF_FALSE;\n\t\t\tif (ctx->subsamples) {\n\t\t\t\tnaludmx_add_subsample(ctx, audelim_size, avc_svc_subs_priority, avc_svc_subs_reserved);\n\t\t\t}\n\t\t}\n\t\tif (ctx->sei_buffer_size) {\n\t\t\t//sei buffer is already nal size prefixed\n\t\t\t/*dst_pck = */naludmx_start_nalu(ctx, ctx->sei_buffer_size, GF_TRUE, &au_start, &pck_data);\n\t\t\tmemcpy(pck_data, ctx->sei_buffer, ctx->sei_buffer_size);\n\t\t\tif (ctx->subsamples) {\n\t\t\t\tnaludmx_add_subsample(ctx, ctx->sei_buffer_size - ctx->nal_length, avc_svc_subs_priority, avc_svc_subs_reserved);\n\t\t\t}\n\t\t\tctx->sei_buffer_size = 0;\n\t\t}", "\t\tif (ctx->svc_prefix_buffer_size) {\n\t\t\t/*dst_pck = */naludmx_start_nalu(ctx, ctx->svc_prefix_buffer_size, GF_FALSE, &au_start, &pck_data);\n\t\t\tmemcpy(pck_data + ctx->nal_length, ctx->svc_prefix_buffer, ctx->svc_prefix_buffer_size);\n\t\t\tif (ctx->subsamples) {\n\t\t\t\tnaludmx_add_subsample(ctx, ctx->svc_prefix_buffer_size, ctx->svc_nalu_prefix_priority, ctx->svc_nalu_prefix_reserved);\n\t\t\t}\n\t\t\tctx->svc_prefix_buffer_size = 0;\n\t\t}", "\t\t//nalu size field\n\t\t/*dst_pck = */naludmx_start_nalu(ctx, (u32) nal_size, GF_FALSE, &au_start, &pck_data);\n\t\tpck_data += ctx->nal_length;", "\t\t//add subsample info before touching the size\n\t\tif (ctx->subsamples) {\n\t\t\tnaludmx_add_subsample(ctx, (u32) nal_size, avc_svc_subs_priority, avc_svc_subs_reserved);\n\t\t}", "\n\t\t//bytes only come from the data packet\n\t\tmemcpy(pck_data, nal_data, (size_t) nal_size);", "\t\tnal_size += sc_size;\n\t\tstart += nal_size;\n\t\tremain -= nal_size;\n\t\tnaldmx_check_timestamp_switch(ctx, &nalu_store_before, nal_size, &drop_packet, pck);", "\t\t//don't demux too much of input, abort when we would block. This avoid dispatching\n\t\t//a huge number of frames in a single call\n\t\tif (remain && gf_filter_pid_would_block(ctx->opid)) {\n\t\t\tctx->resume_from = (u32) (start - ctx->nal_store);\n\t\t\tassert(ctx->resume_from <= ctx->nal_store_size);\n\t\t\tassert(ctx->resume_from == ctx->nal_store_size - remain);\n\t\t\tif (drop_packet)\n\t\t\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\t\treturn GF_OK;\n\t\t}\n\t}", "\tif (remain) {\n\t\tif (is_eos && (remain == ctx->nal_store_size)) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, (\"[%s] Incomplete last NAL and eos, discarding\\n\", ctx->log_name));\n\t\t\tremain = 0;\n\t\t} else {\n\t\t\tassert((u32) remain<=ctx->nal_store_size);\n\t\t\tmemmove(ctx->nal_store, start, remain);\n\t\t}\n\t}\n\tctx->nal_store_size = remain;", "\tif (drop_packet)\n\t\tgf_filter_pid_drop_packet(ctx->ipid);", "\tif (is_eos)\n\t\treturn naludmx_process(filter);", "\tif ((ctx->nb_nalus>nalu_before) && gf_filter_reporting_enabled(filter)) {\n\t\tchar szStatus[1024];", "\t\tsprintf(szStatus, \"%s %dx%d % 10d NALU % 8d I % 8d P % 8d B % 8d SEI\", ctx->log_name, ctx->width, ctx->height, ctx->nb_nalus, ctx->nb_i, ctx->nb_p, ctx->nb_b, ctx->nb_sei);\n\t\tgf_filter_update_status(filter, -1, szStatus);\n\t}\n\tif (ctx->full_au_source && ctx->poc_probe_done) {\n\t\tif (ctx->first_pck_in_au)\n\t\t\tnaludmx_finalize_au_flags(ctx);", "\t\tnaludmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE);\n\t}\n\treturn GF_OK;\n}", "static GF_Err naludmx_initialize(GF_Filter *filter)\n{\n\tGF_NALUDmxCtx *ctx = gf_filter_get_udta(filter);\n\tctx->sps = gf_list_new();\n\tctx->pps = gf_list_new();\n\tswitch (ctx->nal_length) {\n\tcase 1:\n\t\tctx->max_nalu_size_allowed = 0xFF;\n\t\tbreak;\n\tcase 2:\n\t\tctx->max_nalu_size_allowed = 0xFFFF;\n\t\tbreak;\n\tcase 4:\n\t\tctx->max_nalu_size_allowed = 0xFFFFFFFF;\n\t\tbreak;\n\tcase 0:\n\t\tctx->max_nalu_size_allowed = 0xFFFFFFFF;\n\t\tctx->nal_length = 4;\n\t\tctx->nal_adjusted = GF_TRUE;\n\t\tbreak;\n\tdefault:\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[%s] NAL size length %d is not allowed, defaulting to 4 bytes\\n\", ctx->log_name));\n\t\tctx->max_nalu_size_allowed = 0xFFFFFFFF;\n\t\tctx->nal_length = 4;\n\t\tbreak;\n\t}\n\treturn GF_OK;\n}", "static void naludmx_del_param_list(GF_List *ps)\n{\n\tif (!ps) return;\n\twhile (gf_list_count(ps)) {\n\t\tGF_NALUFFParam *sl = gf_list_pop_back(ps);\n\t\tif (sl->data) gf_free(sl->data);\n\t\tgf_free(sl);\n\t}\n\tgf_list_del(ps);\n}", "static void naludmx_log_stats(GF_NALUDmxCtx *ctx)\n{\n\tu32 i, count;\n\tconst char *msg_import;\n\tu32 nb_frames = 0;\n\tif (ctx->cur_fps.den)\n\t\tnb_frames = (u32) (ctx->dts / ctx->cur_fps.den);", "\tif (ctx->idur.den && ctx->idur.num) {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s duration specified at import time, may have parsed more frames than imported\\n\", ctx->log_name));\n\t\tmsg_import = \"parsed\";\n\t} else {\n\t\tmsg_import = \"Import results:\";\n\t}", "\tif (ctx->nb_si || ctx->nb_sp) {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s %s %d frames (%d NALUs) - Slices: %d I %d P %d B %d SP %d SI - %d SEI - %d IDR\\n\", ctx->log_name, msg_import, nb_frames, ctx->nb_nalus, ctx->nb_i, ctx->nb_p, ctx->nb_b, ctx->nb_sp, ctx->nb_si, ctx->nb_sei, ctx->nb_idr ));\n\t} else if (ctx->vvc_no_stats) {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s %s %d samples (%d NALUs) - %d SEI - %d IDR\\n\",\n\t\t\t ctx->log_name, msg_import, nb_frames, ctx->nb_nalus, ctx->nb_sei, ctx->nb_idr));\n\t} else {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s %s %d samples (%d NALUs) - Slices: %d I %d P %d B - %d SEI - %d IDR\\n\",\n\t\t\t ctx->log_name, msg_import, nb_frames, ctx->nb_nalus, ctx->nb_i, ctx->nb_p, ctx->nb_b, ctx->nb_sei, ctx->nb_idr));\n\t}", "\tif (ctx->codecid==GF_CODECID_AVC) {\n\t\tcount = gf_list_count(ctx->sps);\n\t\tfor (i=0; i<count; i++) {\n\t\t\tAVC_SPS *sps;\n\t\t\tGF_NALUFFParam *svcc = (GF_NALUFFParam*)gf_list_get(ctx->sps, i);\n\t\t\tsps = & ctx->avc_state->sps[svcc->id];\n\t\t\tif (sps->nb_ei || sps->nb_ep) {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s SVC (SSPS ID %d, %dx%d) %s Slices: %d I %d P %d B\\n\", ctx->log_name, svcc->id - GF_SVC_SSPS_ID_SHIFT, sps->width, sps->height, msg_import, sps->nb_ei, sps->nb_ep, sps->nb_eb ));\n\t\t\t}\n\t\t}\n\t} else if (ctx->nb_e_i || ctx->nb_e_p || ctx->nb_e_b) {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s L-HEVC %s Slices: %d I %d P %d B\\n\", ctx->log_name, msg_import, ctx->nb_e_i, ctx->nb_e_p, ctx->nb_e_b ));\n\t}", "\tif (ctx->max_total_delay>1) {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s Stream uses forward prediction - stream CTS offset: %d frames\\n\", ctx->log_name, ctx->max_total_delay));\n\t}", "\tif (!ctx->nal_adjusted) {\n\t\tif ((ctx->max_nalu_size < 0xFF) && (ctx->nal_length>1) ){\n\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s Max NALU size is %d - stream could be optimized by setting nal_length=1\\n\", ctx->log_name, ctx->max_nalu_size));\n\t\t} else if ((ctx->max_nalu_size < 0xFFFF) && (ctx->nal_length>2) ){\n\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s Max NALU size is %d - stream could be optimized by setting nal_length=2\\n\", ctx->log_name, ctx->max_nalu_size));\n\t\t}\n\t}\n}", "static void naludmx_finalize(GF_Filter *filter)\n{\n\tGF_NALUDmxCtx *ctx = gf_filter_get_udta(filter);", "\tif (ctx->importer) naludmx_log_stats(ctx);", "\tif (ctx->bs_r) gf_bs_del(ctx->bs_r);\n\tif (ctx->bs_w) gf_bs_del(ctx->bs_w);\n\tif (ctx->indexes) gf_free(ctx->indexes);\n\tif (ctx->nal_store) gf_free(ctx->nal_store);\n\tif (ctx->pck_queue) {\n\t\twhile (gf_list_count(ctx->pck_queue)) {\n\t\t\tGF_FilterPacket *pck = gf_list_pop_back(ctx->pck_queue);\n\t\t\tgf_filter_pck_discard(pck);\n\t\t}\n\t\tgf_list_del(ctx->pck_queue);\n\t}\n\tif (ctx->sei_buffer) gf_free(ctx->sei_buffer);\n\tif (ctx->svc_prefix_buffer) gf_free(ctx->svc_prefix_buffer);\n\tif (ctx->subsamp_buffer) gf_free(ctx->subsamp_buffer);", "\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\tctx->src_pck = NULL;", "\tnaludmx_del_param_list(ctx->sps);\n\tnaludmx_del_param_list(ctx->pps);\n\tnaludmx_del_param_list(ctx->vps);\n\tnaludmx_del_param_list(ctx->sps_ext);\n\tnaludmx_del_param_list(ctx->pps_svc);\n\tnaludmx_del_param_list(ctx->vvc_aps_pre);\n\tnaludmx_del_param_list(ctx->vvc_dci);", "\tif (ctx->avc_state) gf_free(ctx->avc_state);\n\tif (ctx->hevc_state) gf_free(ctx->hevc_state);\n\tif (ctx->vvc_state) gf_free(ctx->vvc_state);\n}", "\nstatic const char *naludmx_probe_data(const u8 *data, u32 size, GF_FilterProbeScore *score)\n{\n\tu32 sc, sc_size;\n\tu32 not_hevc=0;\n\tu32 not_avc=0;\n\tu32 not_vvc=0;\n\tu32 nb_hevc=0;\n\tu32 nb_avc=0;\n\tu32 nb_vvc=0;\n\tu32 nb_nalus=0;\n\tu32 nb_hevc_zero=0;\n\tu32 nb_avc_zero=0;\n\tu32 nb_vvc_zero=0;\n\tu32 nb_sps_hevc=0,nb_pps_hevc=0,nb_vps_hevc=0;\n\tu32 nb_sps_avc=0,nb_pps_avc=0;\n\tu32 nb_sps_vvc=0,nb_pps_vvc=0,nb_vps_vvc=0;", "\twhile (size>3) {\n\t\tu32 nal_type=0;\n\t\tsc = gf_media_nalu_next_start_code(data, size, &sc_size);\n\t\tif (!sc_size) break;", "\t\tdata += sc + sc_size;\n\t\tif (size <= sc + sc_size) break;\n\t\tsize -= sc + sc_size;", "\t\tif (data[0] & 0x80) {\n\t\t\tnot_avc++;\n\t\t\tnot_hevc++;\n\t\t\tnot_vvc++;\n\t\t\tcontinue;\n\t\t}\n\t\tnb_nalus++;", "\t\tnal_type = (data[0] & 0x7E) >> 1;\n\t\tif (nal_type<=40) {\n\t\t\tnb_hevc++;\n\t\t\tswitch (nal_type) {\n\t\t\tcase GF_HEVC_NALU_PIC_PARAM:\n\t\t\t\tif (nb_sps_hevc)\n\t\t\t\t\tnb_pps_hevc++;\n\t\t\t\tbreak;\n\t\t\tcase GF_HEVC_NALU_SEQ_PARAM:\n\t\t\t\tnb_sps_hevc++;\n\t\t\t\tbreak;\n\t\t\tcase GF_HEVC_NALU_VID_PARAM:\n\t\t\t\tnb_vps_hevc++;\n\t\t\t\tbreak;\n\t\t\tcase 0:\n\t\t\t\tnb_hevc_zero++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tnot_hevc++;\n\t\t}", "\t\tnal_type = data[0] & 0x1F;\n\t\tif (nal_type && nal_type<=24) {\n\t\t\tnb_avc++;\n\t\t\tswitch (nal_type) {\n\t\t\tcase GF_AVC_NALU_PIC_PARAM:\n\t\t\t\tif (nb_sps_avc)\n\t\t\t\t\tnb_pps_avc++;\n\t\t\t\tbreak;\n\t\t\tcase GF_AVC_NALU_SEQ_PARAM:\n\t\t\t\tnb_sps_avc++;\n\t\t\t\tbreak;\n\t\t\tcase 0:\n\t\t\t\tnb_avc_zero++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tnot_avc++;\n\t\t}", "\t\t//check vvc - 2nd bit reserved to 0\n\t\tif (data[0] & 0x40) {\n\t\t\tnot_vvc++;\n\t\t\tcontinue;\n\t\t}\n\t\tnal_type = data[1] >> 3;\n\t\tif (nal_type>31) {\n\t\t\tnot_vvc++;\n\t\t\tcontinue;\n\t\t}\n\t\tnb_vvc++;\n\t\tswitch (nal_type) {\n\t\tcase GF_VVC_NALU_PIC_PARAM:\n\t\t\tif (nb_sps_vvc)\n\t\t\t\tnb_pps_vvc++;\n\t\t\tbreak;\n\t\tcase GF_VVC_NALU_SEQ_PARAM:\n\t\t\tnb_sps_vvc++;\n\t\t\tbreak;\n\t\tcase GF_VVC_NALU_VID_PARAM:\n\t\t\tnb_vps_vvc++;\n\t\t\tbreak;\n\t\tcase 0:\n\t\t\tnb_vvc_zero++;\n\t\t\tbreak;\n\t\t}\n\t}", "\tif (!nb_sps_avc || !nb_pps_avc) nb_avc=0;\n\tif (!nb_sps_hevc || !nb_pps_hevc || !nb_vps_hevc) nb_hevc=0;\n\tif (!nb_sps_vvc || !nb_pps_vvc || !nb_vps_vvc) nb_vvc=0;\n\tif (not_avc) nb_avc=0;\n\tif (not_hevc) nb_hevc=0;\n\tif (not_vvc) nb_vvc=0;", "\tif (not_avc && not_hevc && not_vvc) return NULL;\n\tif (nb_avc==nb_avc_zero) nb_avc=0;\n\tif (nb_hevc==nb_hevc_zero) nb_hevc=0;\n\tif (nb_vvc==nb_vvc_zero) nb_vvc=0;", "\tif (!nb_hevc && !nb_avc && !nb_vvc) return NULL;\n\t*score = GF_FPROBE_SUPPORTED;\n\tif (!nb_hevc) return (nb_vvc>nb_avc) ? \"video/vvc\" : \"video/avc\";\n\tif (!nb_avc) return (nb_vvc>nb_hevc) ? \"video/vvc\" : \"video/hevc\";\n\tif (!nb_vvc) return (nb_avc>nb_hevc) ? \"video/avc\" : \"video/hevc\";", "\tif ((nb_hevc>nb_avc) && (nb_hevc>nb_vvc)) return \"video/hevc\";\n\tif ((nb_vvc>nb_avc) && (nb_vvc>nb_hevc)) return \"video/vvc\";\n\treturn \"video/avc\";\n}", "static const GF_FilterCapability NALUDmxCaps[] =\n{\n\tCAP_UINT(GF_CAPS_INPUT, GF_PROP_PID_STREAM_TYPE, GF_STREAM_FILE),\n\tCAP_STRING(GF_CAPS_INPUT, GF_PROP_PID_FILE_EXT, \"264|h264|26L|h26L|h26l|avc|svc|mvc|hevc|hvc|265|h265|shvc|lvhc|mhvc|266|vvc|lvvc\"),\n\tCAP_STRING(GF_CAPS_INPUT, GF_PROP_PID_MIME, \"video/avc|video/h264|video/svc|video/mvc|video/hevc|video/lhvc|video/shvc|video/mhvc|video/vvc\"),\n\tCAP_UINT(GF_CAPS_OUTPUT_STATIC, GF_PROP_PID_STREAM_TYPE, GF_STREAM_VISUAL),\n\tCAP_UINT(GF_CAPS_OUTPUT_STATIC, GF_PROP_PID_CODECID, GF_CODECID_AVC),\n\tCAP_UINT(GF_CAPS_OUTPUT_STATIC, GF_PROP_PID_CODECID, GF_CODECID_AVC_PS),\n\tCAP_UINT(GF_CAPS_OUTPUT_STATIC, GF_PROP_PID_CODECID, GF_CODECID_SVC),\n\tCAP_UINT(GF_CAPS_OUTPUT_STATIC, GF_PROP_PID_CODECID, GF_CODECID_MVC),\n\tCAP_UINT(GF_CAPS_OUTPUT_STATIC, GF_PROP_PID_CODECID, GF_CODECID_HEVC),\n\tCAP_UINT(GF_CAPS_OUTPUT_STATIC, GF_PROP_PID_CODECID, GF_CODECID_LHVC),\n\tCAP_UINT(GF_CAPS_OUTPUT_STATIC, GF_PROP_PID_CODECID, GF_CODECID_VVC),\n\tCAP_BOOL(GF_CAPS_OUTPUT_STATIC_EXCLUDED, GF_PROP_PID_UNFRAMED, GF_TRUE),\n\tCAP_BOOL(GF_CAPS_OUTPUT_STATIC_EXCLUDED, GF_PROP_PID_TILE_BASE, GF_TRUE),\n\t{0},\n\tCAP_UINT(GF_CAPS_INPUT,GF_PROP_PID_STREAM_TYPE, GF_STREAM_VISUAL),\n\tCAP_UINT(GF_CAPS_INPUT,GF_PROP_PID_CODECID, GF_CODECID_AVC),\n\tCAP_UINT(GF_CAPS_INPUT,GF_PROP_PID_CODECID, GF_CODECID_AVC_PS),\n\tCAP_UINT(GF_CAPS_INPUT,GF_PROP_PID_CODECID, GF_CODECID_SVC),\n\tCAP_UINT(GF_CAPS_INPUT,GF_PROP_PID_CODECID, GF_CODECID_MVC),\n\tCAP_UINT(GF_CAPS_INPUT,GF_PROP_PID_CODECID, GF_CODECID_HEVC),\n\tCAP_UINT(GF_CAPS_INPUT,GF_PROP_PID_CODECID, GF_CODECID_LHVC),\n\tCAP_UINT(GF_CAPS_INPUT,GF_PROP_PID_CODECID, GF_CODECID_VVC),\n\tCAP_BOOL(GF_CAPS_INPUT,GF_PROP_PID_UNFRAMED, GF_TRUE),\n\tCAP_BOOL(GF_CAPS_INPUT_EXCLUDED, GF_PROP_PID_TILE_BASE, GF_TRUE),\n};", "#define OFFS(_n)\t#_n, offsetof(GF_NALUDmxCtx, _n)\nstatic const GF_FilterArgs NALUDmxArgs[] =\n{\n\t{ OFFS(fps), \"import frame rate (0 default to FPS from bitstream or 25 Hz)\", GF_PROP_FRACTION, \"0/1000\", NULL, 0},\n\t{ OFFS(index), \"indexing window length. If 0, bitstream is not probed for duration. A negative value skips the indexing if the source file is larger than 100M (slows down importers) unless a play with start range > 0 is issued, otherwise uses the positive value\", GF_PROP_DOUBLE, \"-1.0\", NULL, 0},\n\t{ OFFS(explicit), \"use explicit layered (SVC/LHVC) import\", GF_PROP_BOOL, \"false\", NULL, GF_FS_ARG_HINT_ADVANCED},\n\t{ OFFS(strict_poc), \"delay frame output of an entire GOP to ensure CTS info is correct when POC suddenly changes\\n\"\n\t\t\"- off: disable GOP buffering\\n\"\n\t\t\"- on: enable GOP buffering, assuming no error in POC\\n\"\n\t\t\"- error: enable GOP buffering and try to detect lost frames\", GF_PROP_UINT, \"off\", \"off|on|error\", GF_FS_ARG_HINT_ADVANCED},\n\t{ OFFS(nosei), \"remove all sei messages\", GF_PROP_BOOL, \"false\", NULL, GF_FS_ARG_HINT_ADVANCED},\n\t{ OFFS(nosvc), \"remove all SVC/MVC/LHVC data\", GF_PROP_BOOL, \"false\", NULL, GF_FS_ARG_HINT_ADVANCED},\n\t{ OFFS(novpsext), \"remove all VPS extensions\", GF_PROP_BOOL, \"false\", NULL, GF_FS_ARG_HINT_ADVANCED},\n\t{ OFFS(importer), \"compatibility with old importer, displays import results\", GF_PROP_BOOL, \"false\", NULL, GF_FS_ARG_HINT_ADVANCED},\n\t{ OFFS(idur), \"compatibility with old importer to log imported frames only\", GF_PROP_FRACTION, \"0\", NULL, GF_FS_ARG_HINT_HIDE},\n\t{ OFFS(nal_length), \"set number of bytes used to code length field: 1, 2 or 4\", GF_PROP_UINT, \"4\", NULL, GF_FS_ARG_HINT_EXPERT},\n\t{ OFFS(subsamples), \"import subsamples information\", GF_PROP_BOOL, \"false\", NULL, GF_FS_ARG_HINT_EXPERT},\n\t{ OFFS(deps), \"import samples dependencies information\", GF_PROP_BOOL, \"false\", NULL, GF_FS_ARG_HINT_EXPERT},\n\t{ OFFS(seirw), \"rewrite AVC sei messages for ISOBMFF constraints\", GF_PROP_BOOL, \"true\", NULL, GF_FS_ARG_HINT_EXPERT},\n\t{ OFFS(audelim), \"keep Access Unit delimiter in payload\", GF_PROP_BOOL, \"false\", NULL, GF_FS_ARG_HINT_EXPERT},\n\t{ OFFS(analyze), \"skip reformat of decoder config and SEI and dispatch all NAL in input order - shall only be used with inspect filter analyze mode!\", GF_PROP_UINT, \"off\", \"off|on|bs|full\", GF_FS_ARG_HINT_HIDE},", "\t{ OFFS(bsdbg), \"debug NAL parsing in parser@debug logs\\n\"\n\t\t\"- off: not enabled\\n\"\n\t\t\"- on: enabled\\n\"\n\t\t\"- full: enable with number of bits dumped\", GF_PROP_UINT, \"off\", \"off|on|full\", GF_FS_ARG_HINT_EXPERT},\n\t{0}\n};", "\nGF_FilterRegister NALUDmxRegister = {\n\t.name = \"rfnalu\",\n\tGF_FS_SET_DESCRIPTION(\"AVC/HEVC reframer\")\n\tGF_FS_SET_HELP(\"This filter parses AVC|H264 and HEVC files/data and outputs corresponding video PID and frames.\\n\"\n\t\"This demuxer only produces ISOBMFF-compatible output: start codes are removed, NALU length field added and avcC/hvcC config created.\\nNote: The demux uses negative CTS offsets: CTS is corrrect, but some frames may have DTS greater than CTS.\")\n\t.private_size = sizeof(GF_NALUDmxCtx),\n\t.args = NALUDmxArgs,\n\t.initialize = naludmx_initialize,\n\t.finalize = naludmx_finalize,\n\tSETCAPS(NALUDmxCaps),\n\t.configure_pid = naludmx_configure_pid,\n\t.process = naludmx_process,\n\t.process_event = naludmx_process_event,\n\t.probe_data = naludmx_probe_data,\n};", "\nconst GF_FilterRegister *naludmx_register(GF_FilterSession *session)\n{\n\treturn &NALUDmxRegister;\n}", "#else\nconst GF_FilterRegister *naludmx_register(GF_FilterSession *session)\n{\n\treturn NULL;\n}\n#endif //GPAC_DISABLE_AV_PARSERS" ]
[ 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, 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, 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, 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, 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, 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, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [1685], "buggy_code_start_loc": [1683], "filenames": ["src/filters/reframe_nalu.c"], "fixing_code_end_loc": [1687], "fixing_code_start_loc": [1683], "message": "A Segmentation fault exists casued by null pointer dereference exists in Gpac through 1.0.1 via the naludmx_create_avc_decoder_config function in reframe_nalu.c when using mp4box, which causes a denial of service.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gpac:gpac:*:*:*:*:*:*:*:*", "matchCriteriaId": "72EEF01B-F945-4AEF-B5C2-6F84A51311C9", "versionEndExcluding": null, "versionEndIncluding": "1.0.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A Segmentation fault exists casued by null pointer dereference exists in Gpac through 1.0.1 via the naludmx_create_avc_decoder_config function in reframe_nalu.c when using mp4box, which causes a denial of service."}, {"lang": "es", "value": "Se presenta un fallo de segmentaci\u00f3n causado por una desreferencia de puntero null en Gpac versiones hasta 1.0.1, por medio de la funci\u00f3n naludmx_create_avc_decoder_config en el archivo reframe_nalu.c cuando es usado mp4box, que causa una denegaci\u00f3n de servicio"}], "evaluatorComment": null, "id": "CVE-2021-40563", "lastModified": "2023-05-27T04:15:16.293", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-01-12T22:15:07.807", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gpac/gpac/commit/5ce0c906ed8599d218036b18b78e8126a496f137"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/gpac/gpac/issues/1892"}, {"source": "cve@mitre.org", "tags": null, "url": "https://www.debian.org/security/2023/dsa-5411"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gpac/gpac/commit/5ce0c906ed8599d218036b18b78e8126a496f137"}, "type": "CWE-476"}
176
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n *\t\t\tGPAC - Multimedia Framework C SDK\n *\n *\t\t\tAuthors: Jean Le Feuvre\n *\t\t\tCopyright (c) Telecom ParisTech 2000-2021\n *\t\t\t\t\tAll rights reserved\n *\n * This file is part of GPAC / NALU (AVC, HEVC, VVC) reframer filter\n *\n * GPAC is free software; you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2, or (at your option)\n * any later version.\n *\n * GPAC is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; see the file COPYING. If not, write to\n * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.\n *\n */", "#include <gpac/avparse.h>\n#include <gpac/constants.h>\n#include <gpac/filters.h>\n#include <gpac/internal/media_dev.h>\n//for oinf stuff\n#include <gpac/internal/isomedia_dev.h>", "#ifndef GPAC_DISABLE_AV_PARSERS", "#define CTS_POC_OFFSET_SAFETY\t1000", "GF_Err gf_bs_set_logger(GF_BitStream *bs, void (*on_bs_log)(void *udta, const char *field_name, u32 nb_bits, u64 field_val, s32 idx1, s32 idx2, s32 idx3), void *udta);", "typedef struct\n{\n\tu64 pos;\n\tDouble duration;\n} NALUIdx;", "\ntypedef struct\n{\n\tu32 layer_id_plus_one;\n\tu32 min_temporal_id, max_temporal_id;\n} LHVCLayerInfo;", "enum {\n\tSTRICT_POC_OFF = 0,\n\tSTRICT_POC_ON,\n\tSTRICT_POC_ERROR,\n};", "typedef struct\n{\n\t//filter args\n\tGF_Fraction fps;\n\tDouble index;\n\tBool explicit, force_sync, nosei, importer, subsamples, nosvc, novpsext, deps, seirw, audelim, analyze;\n\tu32 nal_length;\n\tu32 strict_poc;\n\tu32 bsdbg;\n\tGF_Fraction idur;", "\t//only one input pid declared\n\tGF_FilterPid *ipid;\n\t//only one output pid declared\n\tGF_FilterPid *opid;", "\t//read bitstream for AVC/HEVC parsing\n\tGF_BitStream *bs_r;\n\t//write bitstream for nalus size length rewrite\n\tGF_BitStream *bs_w;\n\t//current CTS/DTS of the stream, may be overridden by input packet if not file (eg TS PES)\n\tu64 cts, dts, prev_dts, prev_cts;\n\tu32 pck_duration;\n\t//basic config stored here: with, height CRC of base and enh layer decoder config, sample aspect ratio\n\t//when changing, a new pid config will be emitted\n\tu32 width, height;\n\tu32 crc_cfg, crc_cfg_enh;\n\tGF_Fraction sar;\n\tGF_Fraction cur_fps;", "\t//duration of the file if known\n\tGF_Fraction64 duration;\n\t//playback start range\n\tDouble start_range;\n\t//indicates we are in seek, packets before start range should be marked\n\tBool in_seek;\n\t//set once we play something\n\tBool is_playing;\n\t//is a file, is a file fully loaded on disk (local or download done)\n\tBool is_file, file_loaded;\n\t//initial PLAY command found\n\tBool initial_play_done;", "\t//list of RAP entry points\n\tNALUIdx *indexes;\n\tu32 index_alloc_size, index_size;", "\n\t//timescale of the input pid if any, 0 otherwise\n\tu32 timescale;\n\t//framing flag of input packet when input pid has timing (eg is not a file)\n\tBool input_is_au_start;", "\tGF_FilterPacket *src_pck;", "\tBool full_au_source;", "\t//total delay in frames between decode and presentation\n\ts32 max_total_delay;\n\t//max size codable with our nal_length setting\n\tu32 max_nalu_size_allowed;", "\t//position in input packet from which we resume parsing\n\tu32 resume_from;\n\t//prevents message about possible NAL size optimizaion at finalization\n\tBool nal_adjusted;", "\t//avc/hevc switch\n\tu32 codecid;\n\t//name of the logger\n\tconst char *log_name;", "\t//list of packet (in decode order !!) not yet dispatched.\n\t//Dispatch depends on the mode:\n\t//strict_poc=0: we wait after each IDR until we find a stable poc diff between pictures, controled by poc_probe_done\n\t//strict_poc>=1: we dispatch only after IDR or at the end (huge delay)\n\tGF_List *pck_queue;\n\t//dts of the last IDR found\n\tu64 dts_last_IDR;\n\t//max size of NALUs in the bitstream\n\tu32 max_nalu_size;", "\n\tu8 *nal_store;\n\tu32 nal_store_size, nal_store_alloc;", "\t//list of param sets found\n\tGF_List *sps, *pps, *vps, *sps_ext, *pps_svc, *vvc_aps_pre, *vvc_dci;\n\t//set to true if one of the PS has been modified, will potentially trigger a PID reconfigure\n\tBool ps_modified;", "\t//stats\n\tu32 nb_idr, nb_i, nb_p, nb_b, nb_sp, nb_si, nb_sei, nb_nalus, nb_aud;", "\t//frame has intra slice\n\tBool has_islice;\n\t//AU is rap\n\tGF_FilterSAPType au_sap;\n\t//frame first slice\n\tBool first_slice_in_au;\n\t//paff used - NEED FURTHER CHECKING\n\tBool is_paff;\n\tBool bottom_field_flag;\n\t//SEI recovery count - if 0 and I slice only frame, openGOP detection (avc)\n\ts32 sei_recovery_frame_count;\n\tu32 use_opengop_gdr;\n\t//poc compute variables\n\ts32 last_poc, max_last_poc, max_last_b_poc, poc_diff, prev_last_poc, min_poc, poc_shift;\n\t//set to TRUE once 3 frames with same min poc diff are found, enabling dispatch of the frames\n\tBool poc_probe_done;\n\t//pointer to the first packet of the current frame (the one holding timing info)\n\t//this packet is in the packet queue\n\tGF_FilterPacket *first_pck_in_au;\n\t//frame has slices used as reference\n\tBool has_ref_slices;\n\t//frame has redundant coding\n\tBool has_redundant;", "\tBool last_frame_is_idr;", "\t//buffer to store SEI messages\n\t//for AVC: we have to rewrite the SEI to remove some of the messages according to the spec\n\t//for HEVC: we store prefix SEI here and dispatch them once the first VCL is found\n\tchar *sei_buffer;\n\tu32 sei_buffer_size, sei_buffer_alloc;", "\t//subsample buffer, only used for SVC for now\n\tu32 subsamp_buffer_alloc, subsamp_buffer_size, subs_mapped_bytes;\n\tchar *subsamp_buffer;", "\t//AVC specific\n\t//avc bitstream state\n\tAVCState *avc_state;", "\t//SVC specific\n\tchar *svc_prefix_buffer;\n\tu32 svc_prefix_buffer_size, svc_prefix_buffer_alloc;\n\tu32 svc_nalu_prefix_reserved;\n\tu8 svc_nalu_prefix_priority;", "\t//HEVC specific\n\tHEVCState *hevc_state;\n\t//shvc stats\n\tu32 nb_e_idr, nb_e_i, nb_e_p, nb_e_b;\n\tBool vvc_no_stats;", "\tLHVCLayerInfo linf[64];\n\tu8 max_temporal_id[64];\n\tu8 min_layer_id;", "\t//VVC specific\n\tVVCState *vvc_state;", "\tBool has_initial_aud;\n\tchar init_aud[3];", "\tBool interlaced;", "\tBool is_mvc;", "\tu32 bitrate;\n\tu32 nb_frames;\n} GF_NALUDmxCtx;", "static void naludmx_enqueue_or_dispatch(GF_NALUDmxCtx *ctx, GF_FilterPacket *n_pck, Bool flush_ref);\nstatic void naludmx_finalize_au_flags(GF_NALUDmxCtx *ctx);", "\nGF_Err naludmx_configure_pid(GF_Filter *filter, GF_FilterPid *pid, Bool is_remove)\n{\n\tconst GF_PropertyValue *p;\n\tGF_NALUDmxCtx *ctx = gf_filter_get_udta(filter);", "\tif (is_remove) {\n\t\tctx->ipid = NULL;\n\t\tif (ctx->opid) {\n\t\t\tgf_filter_pid_remove(ctx->opid);\n\t\t\tctx->opid = NULL;\n\t\t}\n\t\treturn GF_OK;\n\t}\n\tif (! gf_filter_pid_check_caps(pid))\n\t\treturn GF_NOT_SUPPORTED;", "\tctx->ipid = pid;\n\tp = gf_filter_pid_get_property(pid, GF_PROP_PID_TIMESCALE);\n\tif (p) {\n\t\tctx->timescale = p->value.uint;\n\t\t//if we have a FPS prop, use it\n\t\tp = gf_filter_pid_get_property(pid, GF_PROP_PID_FPS);\n\t\tif (p) {\n\t\t\tctx->cur_fps = p->value.frac;\n\t\t} else {\n\t\t\tctx->cur_fps.den = 0;\n\t\t\tctx->cur_fps.num = ctx->timescale;\n\t\t}\n\t}", "\tp = gf_filter_pid_get_property(pid, GF_PROP_PID_CODECID);\n\tif (p) {\n\t\tswitch (p->value.uint) {\n\t\tcase GF_CODECID_HEVC:\n\t\tcase GF_CODECID_LHVC:\n\t\t\tctx->codecid = GF_CODECID_HEVC;\n\t\t\tbreak;\n\t\tcase GF_CODECID_VVC:\n\t\t\tctx->codecid = GF_CODECID_VVC;\n\t\t\tbreak;\n\t\tcase GF_CODECID_AVC:\n\t\tcase GF_CODECID_AVC_PS:\n\t\tcase GF_CODECID_SVC:\n\t\tcase GF_CODECID_MVC:\n\t\t\tctx->codecid = GF_CODECID_AVC;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn GF_NOT_SUPPORTED;\n\t\t}\n\t}\n\telse {\n\t\tp = gf_filter_pid_get_property(pid, GF_PROP_PID_MIME);\n\t\tif (p && p->value.string && (\n\t\t\tstrstr(p->value.string, \"hvc\")\n\t\t\t|| strstr(p->value.string, \"hevc\")\n\t\t\t|| strstr(p->value.string, \"265\")\n\t\t\t|| strstr(p->value.string, \"shvc\")\n\t\t\t|| strstr(p->value.string, \"mhvc\")\n\t\t\t|| strstr(p->value.string, \"lhvc\")\n\t\t) )\n\t\t\tctx->codecid = GF_CODECID_HEVC;\n\t\telse if (p && p->value.string && (\n\t\t\tstrstr(p->value.string, \"vvc\")\n\t\t) )\n\t\t\tctx->codecid = GF_CODECID_VVC;\n\t\telse {\n\t\t\tp = gf_filter_pid_get_property(pid, GF_PROP_PID_FILE_EXT);\n\t\t\tif (p && p->value.string && (\n\t\t\t\t strstr(p->value.string, \"hvc\")\n\t\t\t\t || strstr(p->value.string, \"hevc\")\n\t\t\t\t || strstr(p->value.string, \"265\")\n\t\t\t\t || strstr(p->value.string, \"shvc\")\n\t\t\t\t || strstr(p->value.string, \"mhvc\")\n\t\t\t\t || strstr(p->value.string, \"lhvc\")\n\t\t\t ) )\n\t\t\t\tctx->codecid = GF_CODECID_HEVC;\n\t\t\telse if (p && p->value.string && (\n\t\t\t\t strstr(p->value.string, \"vvc\")\n\t\t\t\t || strstr(p->value.string, \"266\")\n\t\t\t\t || strstr(p->value.string, \"lvvc\")\n\t\t\t ) )\n\t\t\t\tctx->codecid = GF_CODECID_VVC;\n\t\t\telse\n\t\t\t\tctx->codecid = GF_CODECID_AVC;\n\t\t}\n\t}\n\tif (ctx->codecid==GF_CODECID_HEVC) {\n#ifdef GPAC_DISABLE_HEVC\n\t\treturn GF_NOT_SUPPORTED;\n#else\n\t\tctx->log_name = \"HEVC\";\n\t\tif (ctx->avc_state) gf_free(ctx->avc_state);\n\t\tif (ctx->vvc_state) gf_free(ctx->vvc_state);\n\t\tif (!ctx->hevc_state) GF_SAFEALLOC(ctx->hevc_state, HEVCState);\n\t\tctx->min_layer_id = 0xFF;\n#endif\n\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\tctx->log_name = \"VVC\";\n\t\tif (ctx->hevc_state) gf_free(ctx->hevc_state);\n\t\tif (ctx->avc_state) gf_free(ctx->avc_state);\n\t\tif (!ctx->vvc_state) GF_SAFEALLOC(ctx->vvc_state, VVCState);\n\t} else {\n\t\tctx->log_name = \"AVC|H264\";\n\t\tif (ctx->hevc_state) gf_free(ctx->hevc_state);\n\t\tif (ctx->vvc_state) gf_free(ctx->vvc_state);\n\t\tif (!ctx->avc_state) GF_SAFEALLOC(ctx->avc_state, AVCState);\n\t}\n\tif (ctx->timescale && !ctx->opid) {\n\t\tctx->opid = gf_filter_pid_new(filter);\n\t\tctx->first_slice_in_au = GF_TRUE;\n\t}\n\tctx->full_au_source = GF_FALSE;\n\tp = gf_filter_pid_get_property(pid, GF_PROP_PID_UNFRAMED_FULL_AU);\n\tif (p && p->value.boolean) {\n\t\tGF_FilterEvent fevt;\n\t\t//this is a reframer used after an encoder, we want to make sure we have enough frames to compute POC otherwise we might block the chain\n\t\t//by holding input packets - ask 1s by default\n\t\tGF_FEVT_INIT(fevt, GF_FEVT_BUFFER_REQ, ctx->ipid);\n\t\tfevt.buffer_req.pid_only = GF_TRUE;\n\t\tfevt.buffer_req.max_buffer_us = 1000000;\n\t\tgf_filter_pid_send_event(ctx->ipid, &fevt);\n\t\tctx->full_au_source = GF_TRUE;\n\t}", "\t//copy properties at init or reconfig\n\tif (ctx->opid) {\n\t\tif (ctx->poc_probe_done) {\n\t\t\t//full frame mode, flush everything before signaling discontinuity\n\t\t\t//for other modes discontinuity we signal disconntinuity before the current AU being reconstructed\n\t\t\tif (ctx->full_au_source && ctx->first_pck_in_au)\n\t\t\t\tnaludmx_finalize_au_flags(ctx);", "\t\t\tnaludmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE);\n\t\t}\n\t\tgf_filter_pid_copy_properties(ctx->opid, ctx->ipid);\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_STREAM_TYPE, & PROP_UINT(GF_STREAM_VISUAL));\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_CODECID, & PROP_UINT(ctx->codecid));", "\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_UNFRAMED, NULL);\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_UNFRAMED_FULL_AU, NULL);\n\t\tif (!gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_ID))\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_ID, &PROP_UINT(1));", "\t\tctx->ps_modified = GF_TRUE;\n\t\tctx->crc_cfg = ctx->crc_cfg_enh = 0;\n\t}", "\treturn GF_OK;\n}", "\nstatic void naludmx_check_dur(GF_Filter *filter, GF_NALUDmxCtx *ctx)\n{\n\tFILE *stream;\n\tGF_BitStream *bs;\n\tu64 duration, cur_dur, nal_start, start_code_pos, rate;\n\tAVCState *avc_state = NULL;\n\tHEVCState *hevc_state = NULL;\n\tVVCState *vvc_state = NULL;\n\tBool first_slice_in_pic = GF_TRUE;\n\tconst GF_PropertyValue *p;\n\tconst char *filepath = NULL;\n\tif (!ctx->opid || ctx->timescale || ctx->file_loaded) return;", "\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_FILEPATH);\n\tif (!p || !p->value.string || !strncmp(p->value.string, \"gmem://\", 7)) {\n\t\tctx->is_file = GF_FALSE;\n\t\tctx->file_loaded = GF_TRUE;\n\t\treturn;\n\t}\n\tfilepath = p->value.string;\n\tctx->is_file = GF_TRUE;", "\tif (ctx->index<0) {\n\t\tif (gf_opts_get_bool(\"temp\", \"force_indexing\")) {\n\t\t\tctx->index = 1.0;\n\t\t} else {\n\t\t\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_DOWN_SIZE);\n\t\t\tif (!p || (p->value.longuint > 20000000)) {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_PARSER, (\"[%s] Source file larger than 20M, skipping indexing\\n\", ctx->log_name));\n\t\t\t} else {\n\t\t\t\tctx->index = -ctx->index;\n\t\t\t}\n\t\t}\n\t}\n\tif (ctx->index<=0) {\n\t\tctx->duration.num = 1;\n\t\tctx->file_loaded = GF_TRUE;\n\t\treturn;\n\t}", "\tif (ctx->codecid==GF_CODECID_HEVC) {\n\t\tGF_SAFEALLOC(hevc_state, HEVCState);\n\t\tif (!hevc_state) return;\n\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\tGF_SAFEALLOC(vvc_state, VVCState);\n\t\tif (!vvc_state) return;\n\t} else {\n\t\tGF_SAFEALLOC(avc_state, AVCState);\n\t\tif (!avc_state) return;\n\t}", "\tstream = gf_fopen(filepath, \"rb\");\n\tif (!stream) {\n\t\tif (hevc_state) gf_free(hevc_state);\n\t\tif (vvc_state) gf_free(vvc_state);\n\t\tif (avc_state) gf_free(avc_state);\n\t\treturn;\n\t}\n\tctx->index_size = 0;\n\tduration = 0;\n\tcur_dur = 0;", "\tbs = gf_bs_from_file(stream, GF_BITSTREAM_READ);\n\tgf_bs_enable_emulation_byte_removal(bs, GF_TRUE);", "\tstart_code_pos = gf_bs_get_position(bs);\n\tif (!gf_media_nalu_is_start_code(bs)) {\n\t\tif (hevc_state) gf_free(hevc_state);\n\t\tif (avc_state) gf_free(avc_state);\n\t\tgf_bs_del(bs);\n\t\tgf_fclose(stream);\n\t\tctx->duration.num = 1;\n\t\tctx->file_loaded = GF_TRUE;\n\t\treturn;\n\t}", "\tnal_start = gf_bs_get_position(bs);", "\twhile (gf_bs_available(bs)) {\n\t\tu32 nal_size;\n\t\ts32 res;\n\t\tBool is_rap = GF_FALSE;\n\t\tBool is_slice = GF_FALSE;\n\t\tnal_size = gf_media_nalu_next_start_code_bs(bs);", "\t\tgf_bs_seek(bs, nal_start);\n\t\tif (hevc_state) {\n#ifndef GPAC_DISABLE_HEVC\n\t\t\tu8 temporal_id, layer_id, nal_type;", "\t\t\tres = gf_hevc_parse_nalu_bs(bs, hevc_state, &nal_type, &temporal_id, &layer_id);\n\t\t\tif (res>0) first_slice_in_pic = GF_TRUE;\n\t\t\tswitch (nal_type) {\n\t\t\tcase GF_HEVC_NALU_SLICE_IDR_N_LP:\n\t\t\tcase GF_HEVC_NALU_SLICE_IDR_W_DLP:\n\t\t\tcase GF_HEVC_NALU_SLICE_CRA:\n\t\t\tcase GF_HEVC_NALU_SLICE_BLA_N_LP:\n\t\t\tcase GF_HEVC_NALU_SLICE_BLA_W_LP:\n\t\t\tcase GF_HEVC_NALU_SLICE_BLA_W_DLP:\n\t\t\t\tis_rap = GF_TRUE;\n\t\t\t\tis_slice = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tcase GF_HEVC_NALU_SLICE_STSA_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_STSA_R:\n\t\t\tcase GF_HEVC_NALU_SLICE_RADL_R:\n\t\t\tcase GF_HEVC_NALU_SLICE_RASL_R:\n\t\t\tcase GF_HEVC_NALU_SLICE_RADL_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_RASL_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_TRAIL_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_TRAIL_R:\n\t\t\tcase GF_HEVC_NALU_SLICE_TSA_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_TSA_R:\n\t\t\t\tis_slice = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n#endif // GPAC_DISABLE_HEVC\n\t\t} else if (vvc_state) {", "\t\t} else {\n\t\t\tu32 nal_type;\n\t\t\tu64 pos = gf_bs_get_position(bs);\n\t\t\tres = gf_avc_parse_nalu(bs, avc_state);\n\t\t\tif (res>0) first_slice_in_pic = GF_TRUE;", "\t\t\tnal_type = avc_state->last_nal_type_parsed;", "\t\t\tswitch (nal_type) {\n\t\t\tcase GF_AVC_NALU_SEQ_PARAM:\n\t\t\t\tgf_bs_seek(bs, pos);\n\t\t\t\tgf_avc_read_sps_bs(bs, avc_state, GF_FALSE, NULL);\n\t\t\t\tbreak;\n\t\t\tcase GF_AVC_NALU_PIC_PARAM:\n\t\t\t\tgf_bs_seek(bs, pos);\n\t\t\t\tgf_avc_read_pps_bs(bs, avc_state);\n\t\t\t\tbreak;\n\t\t\tcase GF_AVC_NALU_IDR_SLICE:\n\t\t\t\tis_rap = GF_TRUE;\n\t\t\t\tis_slice = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tcase GF_AVC_NALU_NON_IDR_SLICE:\n\t\t\tcase GF_AVC_NALU_DP_A_SLICE:\n\t\t\tcase GF_AVC_NALU_DP_B_SLICE:\n\t\t\tcase GF_AVC_NALU_DP_C_SLICE:\n\t\t\t\tis_slice = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "\t\tif (is_rap && first_slice_in_pic && (cur_dur >= ctx->index * ctx->cur_fps.num) ) {\n\t\t\tif (!ctx->index_alloc_size) ctx->index_alloc_size = 10;\n\t\t\telse if (ctx->index_alloc_size == ctx->index_size) ctx->index_alloc_size *= 2;\n\t\t\tctx->indexes = gf_realloc(ctx->indexes, sizeof(NALUIdx)*ctx->index_alloc_size);\n\t\t\tctx->indexes[ctx->index_size].pos = start_code_pos;\n\t\t\tctx->indexes[ctx->index_size].duration = (Double) duration;\n\t\t\tctx->indexes[ctx->index_size].duration /= ctx->cur_fps.num;\n\t\t\tctx->index_size ++;\n\t\t\tcur_dur = 0;\n\t\t}", "\t\tif (is_slice && first_slice_in_pic) {\n\t\t\tduration += ctx->cur_fps.den;\n\t\t\tcur_dur += ctx->cur_fps.den;\n\t\t\tfirst_slice_in_pic = GF_FALSE;\n\t\t}", "\t\tgf_bs_seek(bs, nal_start + nal_size);\n/*\t\tnal_start = gf_media_nalu_next_start_code_bs(bs);\n\t\tif (nal_start) gf_bs_skip_bytes(bs, nal_start);\n*/\n\t\tif (gf_bs_available(bs)<4)\n\t\t\tbreak;", "\t\tstart_code_pos = gf_bs_get_position(bs);\n\t\tnal_start = gf_media_nalu_is_start_code(bs);\n\t\tif (!nal_start) {\n\t\t\tbreak;\n\t\t}\n\t\tnal_start = gf_bs_get_position(bs);\n\t}", "\trate = gf_bs_get_position(bs);\n\tgf_bs_del(bs);\n\tgf_fclose(stream);\n\tif (hevc_state) gf_free(hevc_state);\n\tif (vvc_state) gf_free(vvc_state);\n\tif (avc_state) gf_free(avc_state);", "\tif (!ctx->duration.num || (ctx->duration.num * ctx->cur_fps.num != duration * ctx->duration.den)) {\n\t\tctx->duration.num = (s32) duration;\n\t\tctx->duration.den = ctx->cur_fps.num;", "\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_DURATION, & PROP_FRAC64(ctx->duration));", "\t\tif (duration && (!gf_sys_is_test_mode() || gf_opts_get_bool(\"temp\", \"force_indexing\"))) {\n\t\t\trate *= 8 * ctx->duration.den;\n\t\t\trate /= ctx->duration.num;\n\t\t\tctx->bitrate = (u32) rate;\n\t\t}\n\t}", "\n\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_FILE_CACHED);\n\tif (p && p->value.boolean) ctx->file_loaded = GF_TRUE;\n\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_CAN_DATAREF, & PROP_BOOL(GF_TRUE ) );\n}", "\nstatic void naludmx_enqueue_or_dispatch(GF_NALUDmxCtx *ctx, GF_FilterPacket *n_pck, Bool flush_ref)\n{\n\t//TODO: we are dispatching frames in \"negctts mode\", ie we may have DTS>CTS\n\t//need to signal this for consumers using DTS (eg MPEG-2 TS)\n\tif (flush_ref && ctx->pck_queue && ctx->poc_diff) {\n\t\tu32 dts_inc=0;\n\t\ts32 last_poc = 0;\n\t\tBool patch_missing_frame = GF_FALSE;\n\t\t//send all reference packet queued\n\t\tif (ctx->strict_poc==STRICT_POC_ERROR) {\n\t\t\tu32 i;\n\t\t\tu32 nb_bframes = 0;\n\t\t\tfor (i=0; i<gf_list_count(ctx->pck_queue); i++) {\n\t\t\t\ts32 poc;\n\t\t\t\tu64 poc_ts, dts;\n\t\t\t\tGF_FilterPacket *q_pck = gf_list_get(ctx->pck_queue, i);", "\t\t\t\tif (q_pck == ctx->first_pck_in_au) break;", "\t\t\t\tdts = gf_filter_pck_get_dts(q_pck);\n\t\t\t\tif (dts == GF_FILTER_NO_TS) continue;\n\t\t\t\tpoc_ts = gf_filter_pck_get_cts(q_pck);\n\t\t\t\tassert(poc_ts != GF_FILTER_NO_TS);\n\t\t\t\tpoc = (s32) ((s64) poc_ts - CTS_POC_OFFSET_SAFETY);", "\t\t\t\tif (i) {\n\t\t\t\t\tif (last_poc>poc) nb_bframes ++;\n\t\t\t\t\telse if (last_poc + ctx->poc_diff<poc)\n\t\t\t\t\t\tpatch_missing_frame = GF_TRUE;\n\t\t\t\t}\n\t\t\t\tlast_poc = poc;\n\t\t\t}\n\t\t\tif (nb_bframes>1)\n\t\t\t\tpatch_missing_frame = GF_FALSE;\n\t\t\telse if (nb_bframes)\n\t\t\t\tpatch_missing_frame = GF_TRUE;\n\t\t}\n\t\tlast_poc = GF_INT_MIN;", "\t\twhile (gf_list_count(ctx->pck_queue) ) {\n\t\t\tu64 dts;\n\t\t\tGF_FilterPacket *q_pck = gf_list_get(ctx->pck_queue, 0);", "\t\t\tif (q_pck == ctx->first_pck_in_au) break;", "\t\t\tdts = gf_filter_pck_get_dts(q_pck);\n\t\t\tif (dts != GF_FILTER_NO_TS) {\n\t\t\t\ts32 poc;\n\t\t\t\tu64 poc_ts, cts;\n\t\t\t\tu8 carousel_info = gf_filter_pck_get_carousel_version(q_pck);", "\t\t\t\t//we reused timing from source packets\n\t\t\t\tif (!carousel_info) {\n\t\t\t\t\tassert(ctx->timescale);\n\t\t\t\t\tgf_list_rem(ctx->pck_queue, 0);\n\t\t\t\t\tgf_filter_pck_send(q_pck);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tgf_filter_pck_set_carousel_version(q_pck, 0);", "\n\t\t\t\tpoc_ts = gf_filter_pck_get_cts(q_pck);\n\t\t\t\tassert(poc_ts != GF_FILTER_NO_TS);\n\t\t\t\tpoc = (s32) ((s64) poc_ts - CTS_POC_OFFSET_SAFETY);", "\t\t\t\tif (patch_missing_frame) {\n\t\t\t\t\tif (last_poc!=GF_INT_MIN) {\n\t\t\t\t\t\t//check if we missed an IDR (poc reset)\n\t\t\t\t\t\tif (poc && (last_poc > poc) ) {\n\t\t\t\t\t\t\tlast_poc = 0;\n\t\t\t\t\t\t\tdts_inc += ctx->cur_fps.den;\n\t\t\t\t\t\t\tctx->dts_last_IDR = dts;\n\t\t\t\t\t\t\tctx->dts += ctx->cur_fps.den;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//check if we miss a frame\n\t\t\t\t\t\twhile (last_poc + ctx->poc_diff < poc) {\n\t\t\t\t\t\t\tlast_poc += ctx->poc_diff;\n\t\t\t\t\t\t\tdts_inc += ctx->cur_fps.den;\n\t\t\t\t\t\t\tctx->dts += ctx->cur_fps.den;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlast_poc = poc;\n\t\t\t\t\tdts += dts_inc;\n\t\t\t\t}\n\t\t\t\t//poc is stored as diff since last IDR which has min_poc\n\t\t\t\tcts = ( (ctx->min_poc + (s32) poc) * ctx->cur_fps.den ) / ctx->poc_diff + ctx->dts_last_IDR;", "\t\t\t\t/*if PAFF, 2 pictures (eg poc) <=> 1 aggregated frame (eg sample), divide by 2*/\n\t\t\t\tif (ctx->is_paff) {\n\t\t\t\t\tcts /= 2;\n\t\t\t\t\t/*in some cases the poc is not on the top field - if that is the case, round up*/\n\t\t\t\t\tif (cts % ctx->cur_fps.den) {\n\t\t\t\t\t\tcts = ((cts/ctx->cur_fps.den)+1) * ctx->cur_fps.den;\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\tgf_filter_pck_set_cts(q_pck, cts);\n\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"[%s] Frame timestamps computed dts \"LLU\" cts \"LLU\" (poc %d min poc %d poc_diff %d last IDR DTS \"LLU\")\\n\", ctx->log_name, dts, cts, poc, ctx->min_poc, ctx->poc_diff, ctx->dts_last_IDR));", "\t\t\t\tif (ctx->importer && ctx->cur_fps.den) {\n\t\t\t\t\tpoc = (s32) ( (s64) cts - (s64) dts);\n\t\t\t\t\tif (poc<0) poc = -poc;\n\t\t\t\t\tpoc /= ctx->cur_fps.den;\n\t\t\t\t\tif (poc > ctx->max_total_delay)\n\t\t\t\t\t\tctx->max_total_delay = poc;\n\t\t\t\t}\n\t\t\t}\n\t\t\tgf_list_rem(ctx->pck_queue, 0);\n\t\t\tgf_filter_pck_send(q_pck);\n\t\t}\n\t}\n\tif (!n_pck) return;", "\tif (!ctx->pck_queue) ctx->pck_queue = gf_list_new();\n\tgf_list_add(ctx->pck_queue, n_pck);\n}", "static void naludmx_add_param_nalu(GF_List *param_list, GF_NALUFFParam *sl, u8 nal_type)\n{\n\tGF_NALUFFParamArray *pa = NULL;\n\tu32 i, count;\n\tcount = gf_list_count(param_list);\n\tfor (i=0; i<count; i++) {\n\t\tpa = gf_list_get(param_list, i);\n\t\tif (pa->type == nal_type) break;\n\t\tpa = NULL;\n\t}\n\tif (!pa) {\n\t\tGF_SAFEALLOC(pa, GF_NALUFFParamArray);\n\t\tif (!pa) return;", "\t\tpa->array_completeness = 1;\n\t\tpa->type = nal_type;\n\t\tpa->nalus = gf_list_new();\n\t\tgf_list_add(param_list, pa);\n\t}\n\tgf_list_add(pa->nalus, sl);\n}", "#ifndef GPAC_DISABLE_HEVC", "static void naludmx_hevc_set_parall_type(GF_NALUDmxCtx *ctx, GF_HEVCConfig *hevc_cfg)\n{\n\tu32 use_tiles, use_wpp, nb_pps, i, count;\n\tHEVCState hevc;", "\tcount = gf_list_count(ctx->pps);", "\tmemset(&hevc, 0, sizeof(HEVCState));\n\thevc.sps_active_idx = -1;", "\tuse_tiles = 0;\n\tuse_wpp = 0;\n\tnb_pps = 0;", "\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *slc = (GF_NALUFFParam*)gf_list_get(ctx->pps, i);\n\t\ts32 idx = gf_hevc_read_pps(slc->data, slc->size, &hevc);", "\t\tif (idx>=0) {\n\t\t\tHEVC_PPS *pps;\n\t\t\tnb_pps++;\n\t\t\tpps = &hevc.pps[idx];\n\t\t\tif (!pps->entropy_coding_sync_enabled_flag && pps->tiles_enabled_flag)\n\t\t\t\tuse_tiles++;\n\t\t\telse if (pps->entropy_coding_sync_enabled_flag && !pps->tiles_enabled_flag)\n\t\t\t\tuse_wpp++;\n\t\t}\n\t}\n\tif (!use_tiles && !use_wpp) hevc_cfg->parallelismType = 1;\n\telse if (!use_wpp && (use_tiles==nb_pps) ) hevc_cfg->parallelismType = 2;\n\telse if (!use_tiles && (use_wpp==nb_pps) ) hevc_cfg->parallelismType = 3;\n\telse hevc_cfg->parallelismType = 0;\n}\n#endif // GPAC_DISABLE_HEVC", "GF_Err naludmx_set_hevc_oinf(GF_NALUDmxCtx *ctx, u8 *max_temporal_id)\n{\n\tGF_OperatingPointsInformation *oinf;\n\tGF_BitStream *bs;\n\tu8 *data;\n\tu32 data_size;\n\tu32 i;\n\tHEVC_VPS *vps;\n\tGF_NALUFFParam *vps_sl = gf_list_get(ctx->vps, 0);\n\tif (!vps_sl) return GF_SERVICE_ERROR;", "\tvps = &ctx->hevc_state->vps[vps_sl->id];", "\tif (!vps->vps_extension_found) return GF_OK;\n\tif (vps->max_layers<2) return GF_OK;", "\toinf = gf_isom_oinf_new_entry();\n\tif (!oinf) return GF_OUT_OF_MEM;", "\toinf->scalability_mask = 0;\n\tfor (i = 0; i < 16; i++) {\n\t\tif (vps->scalability_mask[i])\n\t\t\toinf->scalability_mask |= 1 << i;\n\t}", "\tfor (i = 0; i < vps->num_profile_tier_level; i++) {\n\t\tHEVC_ProfileTierLevel ptl = (i == 0) ? vps->ptl : vps->ext_ptl[i-1];\n\t\tLHEVC_ProfileTierLevel *lhevc_ptl;\n\t\tGF_SAFEALLOC(lhevc_ptl, LHEVC_ProfileTierLevel);\n\t\tif (!lhevc_ptl) return GF_OUT_OF_MEM;", "\t\tlhevc_ptl->general_profile_space = ptl.profile_space;\n\t\tlhevc_ptl->general_tier_flag = ptl.tier_flag;\n\t\tlhevc_ptl->general_profile_idc = ptl.profile_idc;\n\t\tlhevc_ptl->general_profile_compatibility_flags = ptl.profile_compatibility_flag;\n\t\tlhevc_ptl->general_constraint_indicator_flags = 0;\n\t\tif (ptl.general_progressive_source_flag)\n\t\t\tlhevc_ptl->general_constraint_indicator_flags |= ((u64)1) << 47;\n\t\tif (ptl.general_interlaced_source_flag)\n\t\t\tlhevc_ptl->general_constraint_indicator_flags |= ((u64)1) << 46;\n\t\tif (ptl.general_non_packed_constraint_flag)\n\t\t\tlhevc_ptl->general_constraint_indicator_flags |= ((u64)1) << 45;\n\t\tif (ptl.general_frame_only_constraint_flag)\n\t\t\tlhevc_ptl->general_constraint_indicator_flags |= ((u64)1) << 44;\n\t\tlhevc_ptl->general_constraint_indicator_flags |= ptl.general_reserved_44bits;\n\t\tlhevc_ptl->general_level_idc = ptl.level_idc;\n\t\tgf_list_add(oinf->profile_tier_levels, lhevc_ptl);\n\t}", "\tfor (i = 0; i < vps->num_output_layer_sets; i++) {\n\t\tLHEVC_OperatingPoint *op;\n\t\tu32 j;\n\t\tu16 minPicWidth, minPicHeight, maxPicWidth, maxPicHeight;\n\t\tu8 maxChromaFormat, maxBitDepth;\n\t\tu8 maxTemporalId;\n\t\tGF_SAFEALLOC(op, LHEVC_OperatingPoint);\n\t\tif (!op) return GF_OUT_OF_MEM;", "\t\top->output_layer_set_idx = i;\n\t\top->layer_count = vps->num_necessary_layers[i];\n\t\tminPicWidth = minPicHeight = maxPicWidth = maxPicHeight = maxTemporalId = 0;\n\t\tmaxChromaFormat = maxBitDepth = 0;\n\t\tfor (j = 0; j < op->layer_count; j++) {\n\t\t\tu32 format_idx;\n\t\t\tu32 bitDepth;\n\t\t\top->layers_info[j].ptl_idx = vps->profile_tier_level_idx[i][j];\n\t\t\top->layers_info[j].layer_id = j;\n\t\t\top->layers_info[j].is_outputlayer = vps->output_layer_flag[i][j];\n\t\t\t//FIXME: we consider that this flag is never set\n\t\t\top->layers_info[j].is_alternate_outputlayer = GF_FALSE;", "\t\t\tif (max_temporal_id) {\n\t\t\t\tif (!maxTemporalId || (maxTemporalId < max_temporal_id[op->layers_info[j].layer_id]))\n\t\t\t\t\tmaxTemporalId = max_temporal_id[op->layers_info[j].layer_id];\n\t\t\t} else {\n\t\t\t\tmaxTemporalId = vps->max_sub_layers;\n\t\t\t}", "\t\t\tformat_idx = vps->rep_format_idx[op->layers_info[j].layer_id];\n\t\t\tif (!minPicWidth || (minPicWidth > vps->rep_formats[format_idx].pic_width_luma_samples))\n\t\t\t\tminPicWidth = vps->rep_formats[format_idx].pic_width_luma_samples;\n\t\t\tif (!minPicHeight || (minPicHeight > vps->rep_formats[format_idx].pic_height_luma_samples))\n\t\t\t\tminPicHeight = vps->rep_formats[format_idx].pic_height_luma_samples;\n\t\t\tif (!maxPicWidth || (maxPicWidth < vps->rep_formats[format_idx].pic_width_luma_samples))\n\t\t\t\tmaxPicWidth = vps->rep_formats[format_idx].pic_width_luma_samples;\n\t\t\tif (!maxPicHeight || (maxPicHeight < vps->rep_formats[format_idx].pic_height_luma_samples))\n\t\t\t\tmaxPicHeight = vps->rep_formats[format_idx].pic_height_luma_samples;\n\t\t\tif (!maxChromaFormat || (maxChromaFormat < vps->rep_formats[format_idx].chroma_format_idc))\n\t\t\t\tmaxChromaFormat = vps->rep_formats[format_idx].chroma_format_idc;\n\t\t\tbitDepth = vps->rep_formats[format_idx].bit_depth_chroma > vps->rep_formats[format_idx].bit_depth_luma ? vps->rep_formats[format_idx].bit_depth_chroma : vps->rep_formats[format_idx].bit_depth_luma;\n\t\t\tif (!maxChromaFormat || (maxChromaFormat < bitDepth))\n\t\t\t\tmaxChromaFormat = bitDepth;\n\t\t}\n\t\top->max_temporal_id = maxTemporalId;\n\t\top->minPicWidth = minPicWidth;\n\t\top->minPicHeight = minPicHeight;\n\t\top->maxPicWidth = maxPicWidth;\n\t\top->maxPicHeight = maxPicHeight;\n\t\top->maxChromaFormat = maxChromaFormat;\n\t\top->maxBitDepth = maxBitDepth;\n\t\top->frame_rate_info_flag = GF_FALSE; //FIXME: should fetch this info from VUI\n\t\top->bit_rate_info_flag = GF_FALSE; //we don't use it\n\t\tgf_list_add(oinf->operating_points, op);\n\t}", "\tfor (i = 0; i < vps->max_layers; i++) {\n\t\tLHEVC_DependentLayer *dep;\n\t\tu32 j, k;\n\t\tGF_SAFEALLOC(dep, LHEVC_DependentLayer);\n\t\tif (!dep) return GF_OUT_OF_MEM;", "\t\tdep->dependent_layerID = vps->layer_id_in_nuh[i];\n\t\tfor (j = 0; j < vps->max_layers; j++) {\n\t\t\tif (vps->direct_dependency_flag[dep->dependent_layerID][j]) {\n\t\t\t\tdep->dependent_on_layerID[dep->num_layers_dependent_on] = j;\n\t\t\t\tdep->num_layers_dependent_on ++;\n\t\t\t}\n\t\t}\n\t\tk = 0;\n\t\tfor (j = 0; j < 16; j++) {\n\t\t\tif (oinf->scalability_mask & (1 << j)) {\n\t\t\t\tdep->dimension_identifier[j] = vps->dimension_id[i][k];\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\tgf_list_add(oinf->dependency_layers, dep);\n\t}", "\t//write Operating Points Information Sample Group\n\tbs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);\n\tgf_isom_oinf_write_entry(oinf, bs);\n\tgf_bs_get_content(bs, &data, &data_size);\n\tgf_bs_del(bs);\n\tgf_isom_oinf_del_entry(oinf);", "\tgf_filter_pid_set_info_str(ctx->opid, \"hevc:oinf\", &PROP_DATA_NO_COPY(data, data_size) );\n\treturn GF_OK;\n}", "static void naludmx_set_hevc_linf(GF_NALUDmxCtx *ctx)\n{\n\tu32 i, nb_layers=0, nb_sublayers=0;\n\tu8 *data;\n\tu32 data_size;\n\tGF_BitStream *bs;", "\tfor (i=0; i<64; i++) {\n\t\tif (ctx->linf[i].layer_id_plus_one) nb_layers++;\n\t\tif (ctx->linf[i].min_temporal_id != ctx->linf[i].max_temporal_id) nb_sublayers++;\n\t}\n\tif (!nb_layers && !nb_sublayers)\n\t\treturn;", "\tbs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);", "\tgf_bs_write_int(bs, 0, 2);\n\tgf_bs_write_int(bs, nb_layers, 6);\n\tfor (i=0; i<nb_layers; i++) {\n\t\tif (! ctx->linf[i].layer_id_plus_one) continue;\n\t\tgf_bs_write_int(bs, 0, 4);\n\t\tgf_bs_write_int(bs, ctx->linf[i].layer_id_plus_one - 1, 6);\n\t\tgf_bs_write_int(bs, ctx->linf[i].min_temporal_id, 3);\n\t\tgf_bs_write_int(bs, ctx->linf[i].max_temporal_id, 3);\n\t\tgf_bs_write_int(bs, 0, 1);\n\t\tgf_bs_write_int(bs, 0xFF, 7);", "\t}\n\tgf_bs_get_content(bs, &data, &data_size);\n\tgf_bs_del(bs);\n\tgf_filter_pid_set_info_str(ctx->opid, \"hevc:linf\", &PROP_DATA_NO_COPY(data, data_size) );\n}", "static void naludmx_create_hevc_decoder_config(GF_NALUDmxCtx *ctx, u8 **dsi, u32 *dsi_size, u8 **dsi_enh, u32 *dsi_enh_size, u32 *max_width, u32 *max_height, u32 *max_enh_width, u32 *max_enh_height, GF_Fraction *sar, Bool *has_hevc_base)\n{\n#ifndef GPAC_DISABLE_HEVC\n\tu32 i, count;\n\tu8 layer_id;\n\tBool first = GF_TRUE;\n\tBool first_lhvc = GF_TRUE;\n\tGF_HEVCConfig *cfg;\n\tGF_HEVCConfig *hvcc;\n\tGF_HEVCConfig *lvcc;\n\tu32 max_w, max_h, max_ew, max_eh;", "\t*has_hevc_base = GF_FALSE;", "\n\tmax_w = max_h = 0;\n\tmax_ew = max_eh = 0;\n\tsar->num = sar->den = 0;", "\thvcc = gf_odf_hevc_cfg_new();\n\tlvcc = gf_odf_hevc_cfg_new();\n\thvcc->nal_unit_size = ctx->nal_length;\n\tlvcc->nal_unit_size = ctx->nal_length;\n\tlvcc->is_lhvc = GF_TRUE;\n\t//check we have one pps or sps in base layer\n\tcount = gf_list_count(ctx->sps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->sps, i);\n\t\tlayer_id = ((sl->data[0] & 0x1) << 5) | (sl->data[1] >> 3);\n\t\tif (!layer_id) {\n\t\t\t*has_hevc_base = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t}\n\tcount = gf_list_count(ctx->pps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->pps, i);\n\t\tlayer_id = ((sl->data[0] & 0x1) << 5) | (sl->data[1] >> 3);\n\t\tif (!layer_id) {\n\t\t\t*has_hevc_base = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t}\n\t//assign vps first so that they are serialized first\n\tcount = gf_list_count(ctx->vps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->vps, i);\n\t\tHEVC_VPS *vps = &ctx->hevc_state->vps[sl->id];", "\t\tif (!i) {\n\t\t\thvcc->avgFrameRate = lvcc->avgFrameRate = vps->rates[0].avg_pic_rate;\n\t\t\thvcc->constantFrameRate = lvcc->constantFrameRate = vps->rates[0].constand_pic_rate_idc;\n\t\t\thvcc->numTemporalLayers = lvcc->numTemporalLayers = vps->max_sub_layers;\n\t\t\thvcc->temporalIdNested = lvcc->temporalIdNested = vps->temporal_id_nesting;\n\t\t}\n\t\t//TODO set scalability mask\n\t\tif (!ctx->analyze)\n\t\t\tnaludmx_add_param_nalu((ctx->explicit || ! (*has_hevc_base) ) ? lvcc->param_array : hvcc->param_array, sl, GF_HEVC_NALU_VID_PARAM);\n\t}", "\tcount = gf_list_count(ctx->sps);\n\tfor (i=0; i<count; i++) {\n\t\tBool is_lhvc = GF_FALSE;\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->sps, i);\n\t\tHEVC_SPS *sps = &ctx->hevc_state->sps[sl->id];\n\t\tlayer_id = ((sl->data[0] & 0x1) << 5) | (sl->data[1] >> 3);\n\t\tif (!layer_id) *has_hevc_base = GF_TRUE;", "\t\tif (ctx->explicit || layer_id) {\n\t\t\tcfg = lvcc;\n\t\t\tis_lhvc = GF_TRUE;\n\t\t} else {\n\t\t\tcfg = hvcc;\n\t\t}", "\t\tif (first || (is_lhvc && first_lhvc) ) {\n\t\t\tcfg->configurationVersion = 1;\n\t\t\tcfg->profile_space = sps->ptl.profile_space;\n\t\t\tcfg->tier_flag = sps->ptl.tier_flag;\n\t\t\tcfg->profile_idc = sps->ptl.profile_idc;\n\t\t\tcfg->general_profile_compatibility_flags = sps->ptl.profile_compatibility_flag;\n\t\t\tcfg->progressive_source_flag = sps->ptl.general_progressive_source_flag;\n\t\t\tcfg->interlaced_source_flag = sps->ptl.general_interlaced_source_flag;\n\t\t\tcfg->non_packed_constraint_flag = sps->ptl.general_non_packed_constraint_flag;\n\t\t\tcfg->frame_only_constraint_flag = sps->ptl.general_frame_only_constraint_flag;\n\t\t\tcfg->constraint_indicator_flags = sps->ptl.general_reserved_44bits;\n\t\t\tcfg->level_idc = sps->ptl.level_idc;\n\t\t\tcfg->chromaFormat = sps->chroma_format_idc;\n\t\t\tcfg->luma_bit_depth = sps->bit_depth_luma;\n\t\t\tcfg->chroma_bit_depth = sps->bit_depth_chroma;\n\t\t\tctx->interlaced = cfg->interlaced_source_flag ? GF_TRUE : GF_FALSE;", "\t\t\tif (sps->aspect_ratio_info_present_flag && sps->sar_width && sps->sar_height) {\n\t\t\t\tsar->num = sps->sar_width;\n\t\t\t\tsar->den = sps->sar_height;\n\t\t\t}", "\t\t\t/*disable frame rate scan, most bitstreams have wrong values there*/\n\t\t\tif (!ctx->timescale && first && (!ctx->fps.num || !ctx->fps.den) && sps->has_timing_info\n\t\t\t\t/*if detected FPS is greater than 1000, assume wrong timing info*/\n\t\t\t\t&& (sps->time_scale <= 1000*sps->num_units_in_tick)\n\t\t\t) {\n\t\t\t\tctx->cur_fps.num = sps->time_scale;\n\t\t\t\tctx->cur_fps.den = sps->num_units_in_tick;", "\t\t\t\tif (!ctx->fps.num && ctx->dts==ctx->fps.den)\n\t\t\t\t\tctx->dts = ctx->cur_fps.den;\n\t\t\t}\n\t\t\tctx->fps = ctx->cur_fps;\n\t\t}\n\t\tfirst = GF_FALSE;\n\t\tif (is_lhvc) {\n\t\t\tfirst_lhvc = GF_FALSE;\n\t\t\tif (sps->width > max_ew) max_ew = sps->width;\n\t\t\tif (sps->height > max_eh) max_eh = sps->height;\n\t\t} else {\n\t\t\tif (sps->width > max_w) max_w = sps->width;\n\t\t\tif (sps->height > max_h) max_h = sps->height;\n\t\t}\n\t\tif (!ctx->analyze)\n\t\t\tnaludmx_add_param_nalu(cfg->param_array, sl, GF_HEVC_NALU_SEQ_PARAM);\n\t}", "\tcfg = ctx->explicit ? lvcc : hvcc;\n\tcount = gf_list_count(ctx->pps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->pps, i);\n\t\tlayer_id = ((sl->data[0] & 0x1) << 5) | (sl->data[1] >> 3);\n\t\tif (!layer_id) *has_hevc_base = GF_TRUE;\n\t\tif (!ctx->analyze)\n\t\t\tnaludmx_add_param_nalu(layer_id ? lvcc->param_array : cfg->param_array, sl, GF_HEVC_NALU_PIC_PARAM);\n\t}", "\t*dsi = *dsi_enh = NULL;\n\t*dsi_size = *dsi_enh_size = 0;", "\tif (ctx->explicit || ! (*has_hevc_base) ) {\n\t\tnaludmx_hevc_set_parall_type(ctx, lvcc);\n\t\tgf_odf_hevc_cfg_write(lvcc, dsi, dsi_size);\n\t\t*max_width = *max_enh_width = max_ew;\n\t\t*max_height = *max_enh_height = max_eh;\n\t} else {\n\t\tnaludmx_hevc_set_parall_type(ctx, hvcc);\n\t\tgf_odf_hevc_cfg_write(hvcc, dsi, dsi_size);\n\t\tif (gf_list_count(lvcc->param_array) ) {\n\t\t\tnaludmx_hevc_set_parall_type(ctx, lvcc);\n\t\t\tgf_odf_hevc_cfg_write(lvcc, dsi_enh, dsi_enh_size);\n\t\t}\n\t\t*max_width = max_w;\n\t\t*max_height = max_h;\n\t\t*max_enh_width = max_ew;\n\t\t*max_enh_height = max_eh;\n\t}\n\tcount = gf_list_count(hvcc->param_array);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParamArray *pa = gf_list_get(hvcc->param_array, i);\n\t\tgf_list_reset(pa->nalus);\n\t}\n\tcount = gf_list_count(lvcc->param_array);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParamArray *pa = gf_list_get(lvcc->param_array, i);\n\t\tgf_list_reset(pa->nalus);\n\t}\n\tgf_odf_hevc_cfg_del(hvcc);\n\tgf_odf_hevc_cfg_del(lvcc);\n#endif // GPAC_DISABLE_HEVC\n}", "\nstatic void naludmx_create_vvc_decoder_config(GF_NALUDmxCtx *ctx, u8 **dsi, u32 *dsi_size, u8 **dsi_enh, u32 *dsi_enh_size, u32 *max_width, u32 *max_height, u32 *max_enh_width, u32 *max_enh_height, GF_Fraction *sar, Bool *has_vvc_base)\n{\n\tu32 i, count;\n\tu8 layer_id;\n\tBool first = GF_TRUE;\n\tBool first_lvvc = GF_TRUE;\n\tGF_VVCConfig *cfg;\n\tu32 max_w, max_h, max_ew, max_eh;", "\t*has_vvc_base = GF_FALSE;", "\tmax_w = max_h = 0;\n\tmax_ew = max_eh = 0;\n\tsar->num = sar->den = 0;", "\tcfg = gf_odf_vvc_cfg_new();\n\tcfg->nal_unit_size = ctx->nal_length;", "\t//check we have one pps or sps in base layer\n\tcount = gf_list_count(ctx->sps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->sps, i);\n\t\tlayer_id = (sl->data[0] & 0x3f);\n\t\t//todo, base is not always 0 !\n\t\tif (!layer_id) {\n\t\t\t*has_vvc_base = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t}\n\tcount = gf_list_count(ctx->pps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->pps, i);\n\t\tlayer_id = (sl->data[0] & 0x3f);\n\t\t//todo, base is not always 0 !\n\t\tif (!layer_id) {\n\t\t\t*has_vvc_base = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t}\n\t//assign vps first so that they are serialized first\n\tcount = gf_list_count(ctx->vps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->vps, i);\n\t\tVVC_VPS *vps = &ctx->vvc_state->vps[sl->id];", "\t\tif (!i) {\n\t\t\tcfg->avgFrameRate = vps->rates[0].avg_pic_rate;\n\t\t\tcfg->constantFrameRate = vps->rates[0].constand_pic_rate_idc;\n\t\t\tcfg->numTemporalLayers = vps->max_sub_layers;\n\t\t}\n\t\tif (!ctx->analyze)\n\t\t\tnaludmx_add_param_nalu(cfg->param_array, sl, GF_VVC_NALU_VID_PARAM);\n\t}", "\tcount = gf_list_count(ctx->sps);\n\tfor (i=0; i<count; i++) {\n\t\tBool is_lvvc = GF_FALSE;\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->sps, i);\n\t\tVVC_SPS *sps = &ctx->vvc_state->sps[sl->id];\n\t\tlayer_id = sl->data[0] & 0x3f;\n\t\tif (!layer_id) *has_vvc_base = GF_TRUE;", "\t\tif (ctx->explicit || layer_id) {\n\t\t\tis_lvvc = GF_TRUE;\n\t\t}", "\t\tif (first || (is_lvvc && first_lvvc) ) {\n\t\t\tVVC_VPS *vps = &ctx->vvc_state->vps[sps->vps_id];\n\t\t\tcfg->avgFrameRate = 0;\n\t\t\tcfg->constantFrameRate = 1;\n\t\t\tcfg->numTemporalLayers = sps->max_sublayers;\n\t\t\tcfg->nal_unit_size = ctx->nal_length;\n\t\t\tcfg->ptl_present = vps->num_ptl ? 1 : 0;", "\t\t\tif (vps->num_ptl) {\n\t\t\t\tcfg->num_constraint_info = vps->ptl[0].gci_present ? 1 : 12;\n\t\t\t\tcfg->general_profile_idc = vps->ptl[0].general_profile_idc;\n\t\t\t\tcfg->general_tier_flag = vps->ptl[0].general_tier_flag;\n\t\t\t\tcfg->general_level_idc = vps->ptl[0].general_level_idc;\n\t\t\t\tcfg->ptl_frame_only_constraint = vps->ptl[0].frame_only_constraint;\n\t\t\t\tcfg->ptl_multilayer_enabled = vps->ptl[0].multilayer_enabled;", "\t\t\t\tcfg->general_constraint_info = gf_malloc(sizeof(u8) * cfg-> num_constraint_info);\n\t\t\t\tif (cfg->general_constraint_info)\n\t\t\t\t\tmemcpy(cfg->general_constraint_info, vps->ptl[0].gci, cfg->num_constraint_info);", "\t\t\t\t//todo set temporal sublayers\n\t\t\t\tcfg->ptl_sublayer_present_mask = 0;\n\t\t\t\tcfg->num_sub_profiles = 0;\n\t\t\t\tcfg->ols_idx = 0;\n\t\t\t}\n\t\t\tcfg->chroma_format = sps->chroma_format_idc;\n\t\t\tcfg->bit_depth = sps->bitdepth;\n\t\t\tcfg->maxPictureWidth = sps->width;\n\t\t\tcfg->maxPictureHeight = sps->height;", "\t\t\tif (sps->aspect_ratio_info_present_flag && sps->sar_width && sps->sar_height) {\n\t\t\t\tsar->num = sps->sar_width;\n\t\t\t\tsar->den = sps->sar_height;\n\t\t\t}", "\t\t\t/*disable frame rate scan, most bitstreams have wrong values there*/\n\t\t\tif (!ctx->timescale && first && (!ctx->fps.num || !ctx->fps.den) && sps->has_timing_info\n\t\t\t\t/*if detected FPS is greater than 1000, assume wrong timing info*/\n\t\t\t\t&& (sps->time_scale <= 1000*sps->num_units_in_tick)\n\t\t\t) {\n\t\t\t\tctx->cur_fps.num = sps->time_scale;\n\t\t\t\tctx->cur_fps.den = sps->num_units_in_tick;", "\t\t\t\tif (!ctx->fps.num && ctx->dts==ctx->fps.den)\n\t\t\t\t\tctx->dts = ctx->cur_fps.den;\n\t\t\t}\n\t\t\tctx->fps = ctx->cur_fps;\n\t\t}\n\t\tfirst = GF_FALSE;\n\t\tif (is_lvvc) {\n\t\t\tfirst_lvvc = GF_FALSE;\n\t\t\tif (sps->width > max_ew) max_ew = sps->width;\n\t\t\tif (sps->height > max_eh) max_eh = sps->height;\n\t\t} else {\n\t\t\tif (sps->width > max_w) max_w = sps->width;\n\t\t\tif (sps->height > max_h) max_h = sps->height;\n\t\t}\n\t\tif (!ctx->analyze)\n\t\t\tnaludmx_add_param_nalu(cfg->param_array, sl, GF_VVC_NALU_SEQ_PARAM);\n\t}", "\tcount = gf_list_count(ctx->pps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->pps, i);\n\t\tlayer_id = sl->data[0] & 0x3F;\n\t\tif (!layer_id) *has_vvc_base = GF_TRUE;\n\t\tif (!ctx->analyze)\n\t\t\tnaludmx_add_param_nalu(cfg->param_array, sl, GF_VVC_NALU_PIC_PARAM);\n\t}", "\tcount = gf_list_count(ctx->vvc_dci);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->vvc_dci, i);\n\t\tlayer_id = sl->data[0] & 0x3F;\n\t\tif (!layer_id) *has_vvc_base = GF_TRUE;\n\t\tif (!ctx->analyze)\n\t\t\tnaludmx_add_param_nalu(cfg->param_array, sl, GF_VVC_NALU_DEC_PARAM);\n\t}", "\tcount = gf_list_count(ctx->vvc_aps_pre);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->vvc_aps_pre, i);\n\t\tlayer_id = sl->data[0] & 0x3F;\n\t\tif (!layer_id) *has_vvc_base = GF_TRUE;\n\t\tif (!ctx->analyze)\n\t\t\tnaludmx_add_param_nalu(cfg->param_array, sl, GF_VVC_NALU_APS_PREFIX);\n\t}", "\t*dsi = *dsi_enh = NULL;\n\t*dsi_size = *dsi_enh_size = 0;", "\tgf_odf_vvc_cfg_write(cfg, dsi, dsi_size);\n\t*max_width = max_w;\n\t*max_height = max_h;\n\t*max_enh_width = max_ew;\n\t*max_enh_height = max_eh;", "\tcount = gf_list_count(cfg->param_array);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParamArray *pa = gf_list_get(cfg->param_array, i);\n\t\tgf_list_reset(pa->nalus);\n\t}\n\tgf_odf_vvc_cfg_del(cfg);\n}", "void naludmx_create_avc_decoder_config(GF_NALUDmxCtx *ctx, u8 **dsi, u32 *dsi_size, u8 **dsi_enh, u32 *dsi_enh_size, u32 *max_width, u32 *max_height, u32 *max_enh_width, u32 *max_enh_height, GF_Fraction *sar)\n{\n\tu32 i, count;\n\tBool first = GF_TRUE;\n\tBool first_svc = GF_TRUE;\n\tGF_AVCConfig *cfg;\n\tGF_AVCConfig *avcc;\n\tGF_AVCConfig *svcc;\n\tu32 max_w, max_h, max_ew, max_eh;", "\n\tmax_w = max_h = max_ew = max_eh = 0;\n\tsar->num = sar->den = 0;", "\tavcc = gf_odf_avc_cfg_new();\n\tsvcc = gf_odf_avc_cfg_new();\n\tavcc->nal_unit_size = ctx->nal_length;\n\tsvcc->nal_unit_size = ctx->nal_length;", "\tctx->is_mvc = GF_FALSE;\n\tcount = gf_list_count(ctx->sps);\n\tfor (i=0; i<count; i++) {\n\t\tBool is_svc = GF_FALSE;\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->sps, i);\n\t\tAVC_SPS *sps = &ctx->avc_state->sps[sl->id];\n\t\tu32 nal_type = sl->data[0] & 0x1F;", "\t\tif ((sps->profile_idc == 118) || (sps->profile_idc == 128)) {\n\t\t\tctx->is_mvc = GF_TRUE;\n\t\t}", "\t\tif (ctx->explicit) {\n\t\t\tcfg = svcc;\n\t\t} else if (nal_type == GF_AVC_NALU_SVC_SUBSEQ_PARAM) {\n\t\t\tcfg = svcc;\n\t\t\tis_svc = GF_TRUE;\n\t\t} else {\n\t\t\tcfg = avcc;\n\t\t}", "\t\tif (first || (is_svc && first_svc) ) {\n\t\t\tcfg->configurationVersion = 1;\n\t\t\tcfg->profile_compatibility = sps->prof_compat;\n\t\t\tcfg->AVCProfileIndication = sps->profile_idc;\n\t\t\tcfg->AVCLevelIndication = sps->level_idc;\n\t\t\tcfg->chroma_format = sps->chroma_format;\n\t\t\tcfg->luma_bit_depth = 8 + sps->luma_bit_depth_m8;\n\t\t\tcfg->chroma_bit_depth = 8 + sps->chroma_bit_depth_m8;\n\t\t\t/*try to patch ?*/\n\t\t\tif (!gf_avc_is_rext_profile(cfg->AVCProfileIndication)\n\t\t\t\t&& ((cfg->chroma_format>1) || (cfg->luma_bit_depth>8) || (cfg->chroma_bit_depth>8))\n\t\t\t) {\n\t\t\t\tif ((cfg->luma_bit_depth>8) || (cfg->chroma_bit_depth>8)) {\n\t\t\t\t\tcfg->AVCProfileIndication = 110;\n\t\t\t\t} else {\n\t\t\t\t\tcfg->AVCProfileIndication = (cfg->chroma_format==3) ? 244 : 122;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (sps->vui_parameters_present_flag && sps->vui.par_num && sps->vui.par_den) {\n\t\t\t\tsar->num = sps->vui.par_num;\n\t\t\t\tsar->den = sps->vui.par_den;\n\t\t\t}\n\t\t\tctx->interlaced = sps->frame_mbs_only_flag ? GF_FALSE : GF_TRUE;", "\n\t\t\t/*disable frame rate scan, most bitstreams have wrong values there*/\n\t\t\tif (first && (!ctx->fps.num || !ctx->fps.den) && sps->vui.timing_info_present_flag\n\t\t\t\t/*if detected FPS is greater than 1000, assume wrong timing info*/\n\t\t\t\t&& (sps->vui.time_scale <= 1000*sps->vui.num_units_in_tick)\n\t\t\t) {\n\t\t\t\t/*ISO/IEC 14496-10 n11084 Table E-6*/\n\t\t\t\t/* not used :\t\t\t\tu8 DeltaTfiDivisorTable[] = {1,1,1,2,2,2,2,3,3,4,6}; */\n\t\t\t\tu8 DeltaTfiDivisorIdx;\n\t\t\t\tif (!sps->vui.pic_struct_present_flag) {\n\t\t\t\t\tDeltaTfiDivisorIdx = 1 + (1 - ctx->avc_state->s_info.field_pic_flag);\n\t\t\t\t} else {\n\t\t\t\t\tif (!ctx->avc_state->sei.pic_timing.pic_struct)\n\t\t\t\t\t\tDeltaTfiDivisorIdx = 2;\n\t\t\t\t\telse if (ctx->avc_state->sei.pic_timing.pic_struct == 8)\n\t\t\t\t\t\tDeltaTfiDivisorIdx = 6;\n\t\t\t\t\telse\n\t\t\t\t\t\tDeltaTfiDivisorIdx = (ctx->avc_state->sei.pic_timing.pic_struct+1) / 2;\n\t\t\t\t}\n\t\t\t\tif (!ctx->timescale) {\n\t\t\t\t\tctx->cur_fps.num = 2 * sps->vui.time_scale;\n\t\t\t\t\tctx->cur_fps.den = 2 * sps->vui.num_units_in_tick * DeltaTfiDivisorIdx;", "\t\t\t\t\tif (!ctx->fps.num && ctx->dts==ctx->fps.den)\n\t\t\t\t\t\tctx->dts = ctx->cur_fps.den;\n\t\t\t\t}\n\t\t\t\tif (! sps->vui.fixed_frame_rate_flag)\n\t\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_PARSER, (\"[%s] Possible Variable Frame Rate: VUI \\\"fixed_frame_rate_flag\\\" absent\\n\", ctx->log_name));\n\t\t\t}\n\t\t\tctx->fps = ctx->cur_fps;\n\t\t}\n\t\tfirst = GF_FALSE;\n\t\tif (is_svc) {\n\t\t\tfirst_svc = GF_FALSE;\n\t\t\tif (sps->width > max_ew) max_ew = sps->width;\n\t\t\tif (sps->height > max_eh) max_eh = sps->height;\n\t\t} else {\n\t\t\tif (sps->width > max_w) max_w = sps->width;\n\t\t\tif (sps->height > max_h) max_h = sps->height;\n\t\t}\n\t\tif (!ctx->analyze)\n\t\t\tgf_list_add(cfg->sequenceParameterSets, sl);\n\t}", "\tcfg = ctx->explicit ? svcc : avcc;\n\tcount = gf_list_count(ctx->sps_ext);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->sps_ext, i);\n\t\tif (!cfg->sequenceParameterSetExtensions) cfg->sequenceParameterSetExtensions = gf_list_new();\n\t\tif (!ctx->analyze)\n\t\t\tgf_list_add(cfg->sequenceParameterSetExtensions, sl);\n\t}", "\tcfg = ctx->explicit ? svcc : avcc;\n\tcount = gf_list_count(ctx->pps);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->pps, i);\n\t\tif (!ctx->analyze)\n\t\t\tgf_list_add(cfg->pictureParameterSets, sl);\n\t}", "\tcfg = svcc;\n\tcount = gf_list_count(ctx->pps_svc);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = gf_list_get(ctx->pps_svc, i);\n\t\tif (!ctx->analyze)\n\t\t\tgf_list_add(cfg->pictureParameterSets, sl);\n\t}", "\t*dsi = *dsi_enh = NULL;\n\t*dsi_size = *dsi_enh_size = 0;", "\tif (ctx->explicit) {\n\t\tgf_odf_avc_cfg_write(svcc, dsi, dsi_size);\n\t} else {\n\t\tgf_odf_avc_cfg_write(avcc, dsi, dsi_size);\n\t\tif (gf_list_count(svcc->sequenceParameterSets) || svcc->sequenceParameterSetExtensions) {\n\t\t\tgf_odf_avc_cfg_write(svcc, dsi_enh, dsi_enh_size);\n\t\t}\n\t}\n\tgf_list_reset(avcc->sequenceParameterSets);\n\tgf_list_reset(avcc->sequenceParameterSetExtensions);\n\tgf_list_reset(avcc->pictureParameterSets);\n\tgf_list_reset(svcc->sequenceParameterSets);\n\tgf_list_reset(svcc->sequenceParameterSetExtensions);\n\tgf_list_reset(svcc->pictureParameterSets);\n\tgf_odf_avc_cfg_del(avcc);\n\tgf_odf_avc_cfg_del(svcc);\n\t*max_width = max_w;\n\t*max_height = max_h;\n\t*max_enh_width = max_ew;\n\t*max_enh_height = max_eh;\n}", "static void naludmx_check_pid(GF_Filter *filter, GF_NALUDmxCtx *ctx)\n{\n\tu32 w, h, ew, eh;\n\tu8 *dsi, *dsi_enh;\n\tu32 dsi_size, dsi_enh_size;\n\tu32 crc_cfg, crc_cfg_enh;\n\tGF_Fraction sar;\n\tBool has_hevc_base = GF_TRUE;\n\tBool has_colr_info = GF_FALSE;", "\tif (ctx->analyze) {\n\t\tif (ctx->opid && !ctx->ps_modified) return;\n\t} else {\n\t\tif (!ctx->ps_modified) return;\n\t}\n\tctx->ps_modified = GF_FALSE;", "\tdsi = dsi_enh = NULL;", "\tif (!ctx->timescale) {\n\t\tctx->cur_fps = ctx->fps;\n\t\tif (!ctx->cur_fps.num || !ctx->cur_fps.den) {\n\t\t\tctx->cur_fps.num = 25000;\n\t\t\tctx->cur_fps.den = 1000;\n\t\t}\n\t}", "\tif (ctx->codecid==GF_CODECID_HEVC) {\n\t\tnaludmx_create_hevc_decoder_config(ctx, &dsi, &dsi_size, &dsi_enh, &dsi_enh_size, &w, &h, &ew, &eh, &sar, &has_hevc_base);\n\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\tnaludmx_create_vvc_decoder_config(ctx, &dsi, &dsi_size, &dsi_enh, &dsi_enh_size, &w, &h, &ew, &eh, &sar, &has_hevc_base);\n\t} else {\n\t\tnaludmx_create_avc_decoder_config(ctx, &dsi, &dsi_size, &dsi_enh, &dsi_enh_size, &w, &h, &ew, &eh, &sar);\n\t}\n\tcrc_cfg = crc_cfg_enh = 0;\n\tif (dsi) crc_cfg = gf_crc_32(dsi, dsi_size);\n\tif (dsi_enh) crc_cfg_enh = gf_crc_32(dsi_enh, dsi_enh_size);", "\tif (!ctx->opid) {\n\t\tctx->opid = gf_filter_pid_new(filter);", "\t\tnaludmx_check_dur(filter, ctx);\n\t\tctx->first_slice_in_au = GF_TRUE;\n\t}", "\tif ((ctx->crc_cfg == crc_cfg) && (ctx->crc_cfg_enh == crc_cfg_enh)\n\t\t&& (ctx->width==w) && (ctx->height==h)\n\t\t&& (ctx->sar.num * sar.den == ctx->sar.den * sar.num)\n\t) {\n\t\tif (dsi) gf_free(dsi);\n\t\tif (dsi_enh) gf_free(dsi_enh);\n\t\treturn;\n\t}", "\tnaludmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE);\n\tif (!ctx->analyze && (gf_list_count(ctx->pck_queue)>1)) {\n\t\tGF_LOG(dsi_enh ? GF_LOG_DEBUG : GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] xPS changed but could not flush frames before signaling state change %s\\n\", ctx->log_name, dsi_enh ? \"- likely scalable xPS update\" : \"!\"));\n\t}", "\t//copy properties at init or reconfig\n\tgf_filter_pid_copy_properties(ctx->opid, ctx->ipid);\n\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_STREAM_TYPE, & PROP_UINT(GF_STREAM_VISUAL));\n\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_UNFRAMED, NULL);\n\tif (!gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_ID))\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_ID, &PROP_UINT(1));", "\tctx->width = w;\n\tctx->height = h;\n\tctx->sar = sar;\n\tctx->crc_cfg = crc_cfg;\n\tctx->crc_cfg_enh = crc_cfg_enh;", "\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_WIDTH, & PROP_UINT( ctx->width));\n\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_HEIGHT, & PROP_UINT( ctx->height));\n\tif (ew && eh) {\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_WIDTH_MAX, & PROP_UINT( ew ));\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_HEIGHT_MAX, & PROP_UINT( eh ));\n\t}\n\tif (ctx->sar.den)\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_SAR, & PROP_FRAC(ctx->sar));\n\telse\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_SAR, NULL);", "\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_FPS, & PROP_FRAC(ctx->cur_fps));\n\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_TIMESCALE, & PROP_UINT(ctx->timescale ? ctx->timescale : ctx->cur_fps.num));", "\tif (ctx->explicit || !has_hevc_base) {\n\t\tu32 enh_cid = GF_CODECID_SVC;\n\t\tif (ctx->codecid==GF_CODECID_HEVC) enh_cid = GF_CODECID_LHVC;\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_CODECID, & PROP_UINT(enh_cid));\n\t\tif (dsi) gf_filter_pid_set_property(ctx->opid, GF_PROP_PID_DECODER_CONFIG, &PROP_DATA_NO_COPY(dsi, dsi_size) );\n\t} else {\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_CODECID, & PROP_UINT(ctx->codecid));\n\t\tif (dsi) gf_filter_pid_set_property(ctx->opid, GF_PROP_PID_DECODER_CONFIG, &PROP_DATA_NO_COPY(dsi, dsi_size) );\n\t\tif (dsi_enh) gf_filter_pid_set_property(ctx->opid, GF_PROP_PID_DECODER_CONFIG_ENHANCEMENT, &PROP_DATA_NO_COPY(dsi_enh, dsi_enh_size) );\n\t}", "\tif (ctx->bitrate) {\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_BITRATE, & PROP_UINT(ctx->bitrate));\n\t}", "\tif ((ctx->codecid==GF_CODECID_HEVC) && gf_list_count(ctx->vps) ) {\n\t\tGF_Err e = naludmx_set_hevc_oinf(ctx, NULL);\n\t\tif (e) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, (\"[%s] Failed to create OINF chunk\\n\", ctx->log_name));\n\t\t}\n\t\tnaludmx_set_hevc_linf(ctx);\n\t}\n\tif (ctx->duration.num)\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_DURATION, & PROP_FRAC64(ctx->duration));", "\tif (ctx->is_file /* && ctx->index*/) {\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_PLAYBACK_MODE, & PROP_UINT(GF_PLAYBACK_MODE_FASTFORWARD) );\n\t}\n\t//set interlaced or remove interlaced property\n\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_INTERLACED, ctx->interlaced ? & PROP_UINT(GF_TRUE) : NULL);", "\tif (ctx->codecid==GF_CODECID_HEVC) {\n\t\tHEVC_SPS *sps = &ctx->hevc_state->sps[ctx->hevc_state->sps_active_idx];\n\t\tif (sps->colour_description_present_flag) {\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_PRIMARIES, & PROP_UINT(sps->colour_primaries) );\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_TRANSFER, & PROP_UINT(sps->transfer_characteristic) );\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_MX, & PROP_UINT(sps->matrix_coeffs) );\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_RANGE, & PROP_BOOL(sps->video_full_range_flag) );\n\t\t\thas_colr_info = GF_TRUE;\n\t\t}\n\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t} else {\n\t\t/*use the last active SPS*/\n\t\tif (ctx->avc_state->sps[ctx->avc_state->sps_active_idx].vui_parameters_present_flag\n\t\t&& ctx->avc_state->sps[ctx->avc_state->sps_active_idx].vui.colour_description_present_flag) {\n\t\t\tAVC_VUI *vui = &ctx->avc_state->sps[ctx->avc_state->sps_active_idx].vui;", "\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_PRIMARIES, & PROP_UINT(vui->colour_primaries) );\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_TRANSFER, & PROP_UINT(vui->transfer_characteristics) );\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_MX, & PROP_UINT(vui->matrix_coefficients) );\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_RANGE, & PROP_BOOL(vui->video_full_range_flag) );\n\t\t\thas_colr_info = GF_TRUE;\n\t\t}\n\t}", "\tif (!has_colr_info) {\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_PRIMARIES, NULL);\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_TRANSFER, NULL);\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_MX, NULL);\n\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_COLR_RANGE, NULL);\n\t}\n}", "static Bool naludmx_process_event(GF_Filter *filter, const GF_FilterEvent *evt)\n{\n\tu32 i;\n\tu64 file_pos = 0;\n\tGF_FilterEvent fevt;\n\tGF_NALUDmxCtx *ctx = gf_filter_get_udta(filter);", "\tswitch (evt->base.type) {\n\tcase GF_FEVT_PLAY:\n\t\tif (!ctx->is_playing) {\n\t\t\tctx->is_playing = GF_TRUE;\n\t\t\tctx->cts = ctx->dts = 0;\n\t\t}\n\t\tif (! ctx->is_file) {\n\t\t\tif (!ctx->initial_play_done) {\n\t\t\t\tctx->initial_play_done = GF_TRUE;\n\t\t\t\tif (evt->play.start_range<0.1)\n\t\t\t\t\treturn GF_FALSE;\n\t\t\t}\n\t\t\tctx->resume_from = 0;\n\t\t\tctx->nal_store_size = 0;\n\t\t\treturn GF_FALSE;\n\t\t}\n\t\tif (ctx->start_range && (ctx->index<0)) {\n\t\t\tctx->index = -ctx->index;\n\t\t\tctx->file_loaded = GF_FALSE;\n\t\t\tctx->duration.den = ctx->duration.num = 0;\n\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_PARSER, (\"[%s] Play request from %d, building index\\n\", ctx->log_name, ctx->start_range));\n\t\t\tnaludmx_check_dur(filter, ctx);\n\t\t}\n\t\tctx->start_range = evt->play.start_range;\n\t\tctx->in_seek = GF_TRUE;", "\t\tif (ctx->start_range) {\n\t\t\tctx->nb_nalus = ctx->nb_i = ctx->nb_p = ctx->nb_b = ctx->nb_sp = ctx->nb_si = ctx->nb_sei = ctx->nb_idr = 0;\n\t\t\tfor (i=1; i<ctx->index_size; i++) {\n\t\t\t\tif (ctx->indexes[i].duration>ctx->start_range) {\n\t\t\t\t\tctx->cts = ctx->dts = (u64) (ctx->indexes[i-1].duration * ctx->cur_fps.num);\n\t\t\t\t\tfile_pos = ctx->indexes[i-1].pos;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!ctx->initial_play_done) {\n\t\t\tctx->initial_play_done = GF_TRUE;\n\t\t\t//seek will not change the current source state, don't send a seek\n\t\t\tif (!file_pos) {\n\t\t\t\t//very short streams, input is done before we get notified for play and everything stored in memory: flush\n\t\t\t\tif (gf_filter_pid_is_eos(ctx->ipid) && (ctx->nal_store_size)) {\n\t\t\t\t\tgf_filter_post_process_task(filter);\n\t\t\t\t}\n\t\t\t\treturn GF_TRUE;\n\t\t\t}\n\t\t}\n\t\tctx->nb_frames = 0;\n\t\tctx->nb_nalus = 0;\n\t\tctx->resume_from = 0;\n\t\tctx->nal_store_size = 0;", "\t\t//post a seek\n\t\tGF_FEVT_INIT(fevt, GF_FEVT_SOURCE_SEEK, ctx->ipid);\n\t\tfevt.seek.start_offset = file_pos;\n\t\tgf_filter_pid_send_event(ctx->ipid, &fevt);", "\t\t//cancel event\n\t\treturn GF_TRUE;", "\tcase GF_FEVT_STOP:\n\t\t//don't cancel event\n\t\tctx->is_playing = GF_FALSE;\n\t\tctx->nal_store_size = 0;\n\t\tctx->resume_from = 0;\n\t\treturn GF_FALSE;", "\tcase GF_FEVT_SET_SPEED:\n\t\t//cancel event\n\t\treturn GF_TRUE;\n\tdefault:\n\t\tbreak;\n\t}\n\t//by default don't cancel event - to rework once we have downloading in place\n\treturn GF_FALSE;\n}", "static GFINLINE void naludmx_update_time(GF_NALUDmxCtx *ctx)\n{\n\tassert(ctx->cur_fps.num);", "\tif (ctx->timescale) {\n\t\t//very first frame, no dts diff, assume 3000/90k. It should only hurt if we have several frames packet in the first packet sent\n\t\tu64 dts_inc = ctx->cur_fps.den ? ctx->cur_fps.den : 3000;\n\t\tctx->cts += dts_inc;\n\t\tctx->dts += dts_inc;\n\t} else {\n\t\tassert(ctx->cur_fps.den);\n\t\tctx->cts += ctx->cur_fps.den;\n\t\tctx->dts += ctx->cur_fps.den;\n\t}\n}", "static void naludmx_queue_param_set(GF_NALUDmxCtx *ctx, char *data, u32 size, u32 ps_type, s32 ps_id)\n{\n\tGF_List *list = NULL, *alt_list = NULL;\n\tGF_NALUFFParam *sl;", "\tu32 i, count, crc;", "\tif (!size) return;\n\tcrc = gf_crc_32(data, size);", "\n\tif (ctx->codecid==GF_CODECID_HEVC) {\n\t\tswitch (ps_type) {\n\t\tcase GF_HEVC_NALU_VID_PARAM:\n\t\t\tif (!ctx->vps) ctx->vps = gf_list_new();\n\t\t\tlist = ctx->vps;\n\t\t\tbreak;\n\t\tcase GF_HEVC_NALU_SEQ_PARAM:\n\t\t\tlist = ctx->sps;\n\t\t\tbreak;\n\t\tcase GF_HEVC_NALU_PIC_PARAM:\n\t\t\tlist = ctx->pps;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tassert(0);\n\t\t\treturn;\n\t\t}\n\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\tswitch (ps_type) {\n\t\tcase GF_VVC_NALU_VID_PARAM:\n\t\t\tif (!ctx->vps) ctx->vps = gf_list_new();\n\t\t\tlist = ctx->vps;\n\t\t\tbreak;\n\t\tcase GF_VVC_NALU_SEQ_PARAM:\n\t\t\tlist = ctx->sps;\n\t\t\tbreak;\n\t\tcase GF_VVC_NALU_PIC_PARAM:\n\t\t\tlist = ctx->pps;\n\t\t\tbreak;\n\t\tcase GF_VVC_NALU_DEC_PARAM:\n\t\t\tif (!ctx->vvc_dci) ctx->vvc_dci = gf_list_new();\n\t\t\tlist = ctx->vvc_dci;\n\t\t\tbreak;\n\t\tcase GF_VVC_NALU_APS_PREFIX:\n\t\t\tif (!ctx->vvc_aps_pre) ctx->vvc_aps_pre = gf_list_new();\n\t\t\tlist = ctx->vvc_aps_pre;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tassert(0);\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tswitch (ps_type) {\n\t\tcase GF_AVC_NALU_SVC_SUBSEQ_PARAM:\n\t\tcase GF_AVC_NALU_SEQ_PARAM:\n\t\t\tlist = ctx->sps;\n\t\t\tbreak;\n\t\tcase GF_AVC_NALU_PIC_PARAM:\n\t\t\tlist = ctx->pps;\n\t\t\talt_list = ctx->pps_svc;\n\t\t\tbreak;\n\t\tcase GF_AVC_NALU_SEQ_PARAM_EXT:\n\t\t\tif (!ctx->sps_ext) ctx->sps_ext = gf_list_new();\n\t\t\tlist = ctx->sps_ext;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tassert(0);\n\t\t\treturn;\n\t\t}\n\t}\n\tsl = NULL;\n\tcount = gf_list_count(list);\n\tfor (i=0; i<count; i++) {\n\t\tsl = gf_list_get(list, i);\n\t\tif (sl->id != ps_id) {\n\t\t\tsl = NULL;\n\t\t\tcontinue;\n\t\t}\n\t\t//same ID, same CRC, we don't change our state\n\t\tif (sl->crc == crc) return;\n\t\tbreak;\n\t}\n\t//handle alt PPS list for SVC\n\tif (!sl && alt_list) {\n\t\tcount = gf_list_count(alt_list);\n\t\tfor (i=0; i<count; i++) {\n\t\t\tsl = gf_list_get(alt_list, i);\n\t\t\tif (sl->id != ps_id) {\n\t\t\t\tsl = NULL;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t//same ID, same CRC, we don't change our state\n\t\t\tif (sl->crc == crc) return;\n\t\t\tbreak;\n\t\t}\n\t}", "\tif (sl) {\n\t\t//otherwise we keep this new param set\n\t\tsl->data = gf_realloc(sl->data, size);\n\t\tmemcpy(sl->data, data, size);\n\t\tsl->size = size;\n\t\tsl->crc = crc;\n\t\tctx->ps_modified = GF_TRUE;\n\t\treturn;\n\t}\n\t//TODO we might want to purge the list after a while !!", "\tGF_SAFEALLOC(sl, GF_NALUFFParam);\n\tif (!sl) return;\n\tsl->data = gf_malloc(sizeof(char) * size);\n\tif (!sl->data) {\n\t\tgf_free(sl);\n\t\treturn;\n\t}\n\tmemcpy(sl->data, data, size);\n\tsl->size = size;\n\tsl->id = ps_id;\n\tsl->crc = crc;", "\tctx->ps_modified = GF_TRUE;\n\tgf_list_add(list, sl);\n}", "static void naludmx_finalize_au_flags(GF_NALUDmxCtx *ctx)\n{\n\tu64 ts;\n\tBool is_rap = GF_FALSE;", "\tif (!ctx->first_pck_in_au)\n\t\treturn;\n\tif (ctx->au_sap) {\n\t\tgf_filter_pck_set_sap(ctx->first_pck_in_au, ctx->au_sap);\n\t\tif (ctx->au_sap == GF_FILTER_SAP_1) {\n\t\t\tctx->dts_last_IDR = gf_filter_pck_get_dts(ctx->first_pck_in_au);\n\t\t\tif (ctx->is_paff)\n\t\t\t\tctx->dts_last_IDR *= 2;\n\t\t}\n\t\tif (ctx->au_sap <= GF_FILTER_SAP_3) {\n\t\t\tis_rap = GF_TRUE;\n\t\t}\n\t}\n\telse if (ctx->has_islice && ctx->force_sync && (ctx->sei_recovery_frame_count==0)) {\n\t\tgf_filter_pck_set_sap(ctx->first_pck_in_au, GF_FILTER_SAP_1);\n\t\tif (!ctx->use_opengop_gdr) {\n\t\t\tctx->use_opengop_gdr = 1;\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[%s] Forcing non-IDR samples with I slices to be marked as sync points - resulting file will not be ISOBMFF conformant\\n\", ctx->log_name));\n\t\t}\n\t\tis_rap = GF_TRUE;\n\t}\n\t/*set roll info sampleGroups info*/\n\telse if (!ctx->au_sap && ( (ctx->sei_recovery_frame_count >= 0) || ctx->has_islice) ) {\n\t\t/*generic GDR*/\n\t\tif (ctx->sei_recovery_frame_count > 0) {\n\t\t\tif (!ctx->use_opengop_gdr) ctx->use_opengop_gdr = 1;\n\t\t\tgf_filter_pck_set_sap(ctx->first_pck_in_au, GF_FILTER_SAP_4);\n\t\t\tgf_filter_pck_set_roll_info(ctx->first_pck_in_au, ctx->sei_recovery_frame_count);\n\t\t}\n\t\t/*open-GOP*/\n\t\telse if ((ctx->sei_recovery_frame_count == 0) && ctx->has_islice) {\n\t\t\tif (!ctx->use_opengop_gdr) ctx->use_opengop_gdr = 2;\n\t\t\tgf_filter_pck_set_sap(ctx->first_pck_in_au, GF_FILTER_SAP_3);\n\t\t\tis_rap = GF_TRUE;\n\t\t}\n\t}\n\tif (ctx->is_paff) {\n\t\tgf_filter_pck_set_interlaced(ctx->first_pck_in_au, ctx->bottom_field_flag ? 2 : 1);\n\t}", "\t//if TS is set, the packet was the first in AU in the input timed packet (eg PES), we reuse the input timing\n\tts = gf_filter_pck_get_cts(ctx->first_pck_in_au);\n\tif (ts == GF_FILTER_NO_TS) {\n\t\t/*we store the POC (last POC minus the poc shift) as the CTS offset and re-update the CTS when dispatching*/\n\t\tassert(ctx->last_poc >= ctx->poc_shift);\n\t\tgf_filter_pck_set_cts(ctx->first_pck_in_au, CTS_POC_OFFSET_SAFETY + ctx->last_poc - ctx->poc_shift);\n\t\t//we use the carousel flag temporarly to indicate the cts must be recomputed\n\t\tgf_filter_pck_set_carousel_version(ctx->first_pck_in_au, 1);\n\t}", "\tif (ctx->subsamp_buffer_size) {\n\t\tgf_filter_pck_set_property(ctx->first_pck_in_au, GF_PROP_PCK_SUBS, &PROP_DATA(ctx->subsamp_buffer, ctx->subsamp_buffer_size) );\n\t\tctx->subsamp_buffer_size = 0;\n\t\tctx->subs_mapped_bytes = 0;\n\t}\n\tif (ctx->deps) {\n\t\tu8 flags = 0;\n\t\t//dependsOn\n\t\tflags = (is_rap) ? 2 : 1;\n\t\tflags <<= 2;\n\t\t//dependedOn\n\t \tflags |= ctx->has_ref_slices ? 1 : 2;\n\t\tflags <<= 2;\n\t\t//hasRedundant\n\t \tflags |= ctx->has_redundant ? 1 : 2;\n\t \tgf_filter_pck_set_dependency_flags(ctx->first_pck_in_au, flags);\n\t}\n\tctx->has_ref_slices = GF_FALSE;\n\tctx->has_redundant = GF_FALSE;", "\t//if we reuse input packets timing, we can dispatch asap.\n\t//otherwise if poc probe is done (we know the min_poc_diff between images) and we are not in strict mode, dispatch asap\n\t//otherwise we will need to wait for the next ref frame to make sure we know all pocs ...\n\tif (ctx->timescale || (!ctx->strict_poc && ctx->poc_probe_done) )\n\t\tnaludmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE);", "\tctx->first_pck_in_au = NULL;\n}", "static void naludmx_update_nalu_maxsize(GF_NALUDmxCtx *ctx, u32 size)\n{\n\tif (ctx->max_nalu_size < size) {\n\t\tctx->max_nalu_size = size;\n\t\tif (size > ctx->max_nalu_size_allowed) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] nal size %d larger than max allowed size %d - change import settings\\n\", ctx->log_name, size, ctx->max_nalu_size_allowed ));\n\t\t}\n\t}\n}", "\nGF_Err naludmx_realloc_last_pck(GF_NALUDmxCtx *ctx, u32 nb_bytes_to_add, u8 **data_ptr)\n{\n\tGF_Err e;\n\tu8 *pck_data;\n\tu32 full_size;\n\tGF_FilterPacket *pck = gf_list_last(ctx->pck_queue);\n\t*data_ptr = NULL;\n\tif (!pck) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] attempt to reallocate a non-existing packet!\\n\", ctx->log_name));\n\t\treturn GF_SERVICE_ERROR;\n\t}\n\te = gf_filter_pck_expand(pck, nb_bytes_to_add, &pck_data, data_ptr, &full_size);\n\tif (e) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Failed to reallocate packet buffer: %s\\n\", ctx->log_name, gf_error_to_string(e) ));\n\t\treturn e;\n\t}\n\tassert(ctx->bs_w);\n\t//rewrite NALU size length\n\tfull_size -= ctx->nal_length;\n\tgf_bs_reassign_buffer(ctx->bs_w, pck_data, ctx->nal_length);\n\tgf_bs_write_int(ctx->bs_w, full_size, 8*ctx->nal_length);\n\tnaludmx_update_nalu_maxsize(ctx, full_size);\n\t//rewrite subsample size\n\tif (ctx->subsamples) {\n\t\tassert(ctx->subsamp_buffer_size>=14);\n\t\t//reassign to beginning of size field (after first u32 flags)\n\t\tgf_bs_reassign_buffer(ctx->bs_w, ctx->subsamp_buffer + ctx->subsamp_buffer_size-14 + 4, 14 - 4);\n\t\tgf_bs_write_u32(ctx->bs_w, full_size + ctx->nal_length);\n\t}\n\treturn GF_OK;\n}", "GF_FilterPacket *naludmx_start_nalu(GF_NALUDmxCtx *ctx, u32 nal_size, Bool skip_nal_field, Bool *au_start, u8 **pck_data)\n{\n\tGF_FilterPacket *dst_pck = gf_filter_pck_new_alloc(ctx->opid, nal_size + (skip_nal_field ? 0 : ctx->nal_length), pck_data);\n\tif (!dst_pck) return NULL;", "\tif (!skip_nal_field) {\n\t\tif (!ctx->bs_w) ctx->bs_w = gf_bs_new(*pck_data, ctx->nal_length, GF_BITSTREAM_WRITE);\n\t\telse gf_bs_reassign_buffer(ctx->bs_w, *pck_data, ctx->nal_length);\n\t\tgf_bs_write_int(ctx->bs_w, nal_size, 8*ctx->nal_length);\n\t}", "\tif (*au_start) {\n\t\tctx->first_pck_in_au = dst_pck;\n\t\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck);", "\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_FALSE);\n\t\t//we reuse the timing of the input packet for the first nal of the first frame starting in this packet\n\t\tif (ctx->input_is_au_start) {\n\t\t\tctx->input_is_au_start = GF_FALSE;\n\t\t\tgf_filter_pck_set_dts(dst_pck, ctx->dts);\n\t\t\tgf_filter_pck_set_cts(dst_pck, ctx->cts);\n\t\t} else {\n\t\t\t//we don't set the CTS, it will be set once we detect frame end\n\t\t\tgf_filter_pck_set_dts(dst_pck, ctx->dts);\n\t\t}\n\t\t//we use the carousel flag temporarly to indicate the cts must be recomputed\n\t\tgf_filter_pck_set_carousel_version(dst_pck, ctx->timescale ? 0 : 1);", "\t\tgf_filter_pck_set_duration(dst_pck, ctx->pck_duration ? ctx->pck_duration : ctx->cur_fps.den);\n\t\tif (ctx->in_seek) gf_filter_pck_set_seek_flag(dst_pck, GF_TRUE);", "\t\tnaludmx_update_time(ctx);\n\t\t*au_start = GF_FALSE;\n\t\tctx->nb_frames++;\n\t} else {\n\t\tgf_filter_pck_set_framing(dst_pck, GF_FALSE, GF_FALSE);\n\t}\n\tnaludmx_update_nalu_maxsize(ctx, nal_size);", "\tnaludmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE);", "\treturn dst_pck;\n}", "void naludmx_add_subsample(GF_NALUDmxCtx *ctx, u32 subs_size, u8 subs_priority, u32 subs_reserved)\n{\n\tif (ctx->subsamp_buffer_alloc < ctx->subsamp_buffer_size+14 ) {\n\t\tctx->subsamp_buffer_alloc = ctx->subsamp_buffer_size+14;\n\t\tctx->subsamp_buffer = gf_realloc(ctx->subsamp_buffer, ctx->subsamp_buffer_alloc);\n\t}\n\tassert(ctx->subsamp_buffer);\n\tgf_bs_reassign_buffer(ctx->bs_w, ctx->subsamp_buffer + ctx->subsamp_buffer_size, 14);\n\tgf_bs_write_u32(ctx->bs_w, 0); //flags\n\tgf_bs_write_u32(ctx->bs_w, subs_size + ctx->nal_length);\n\tgf_bs_write_u32(ctx->bs_w, subs_reserved); //reserved\n\tgf_bs_write_u8(ctx->bs_w, subs_priority); //priority\n\tgf_bs_write_u8(ctx->bs_w, 0); //discardable - todo\n\tctx->subsamp_buffer_size += 14;\n\tctx->subs_mapped_bytes += subs_size + ctx->nal_length;\n}", "static s32 naludmx_parse_nal_hevc(GF_NALUDmxCtx *ctx, char *data, u32 size, Bool *skip_nal, Bool *is_slice, Bool *is_islice)\n{\n#ifdef GPAC_DISABLE_HEVC\n\treturn -1;\n#else\n\ts32 ps_idx = 0;\n\ts32 res;\n\tu8 nal_unit_type, temporal_id, layer_id;\n\t*skip_nal = GF_FALSE;", "\tgf_bs_reassign_buffer(ctx->bs_r, data, size);\n\tres = gf_hevc_parse_nalu_bs(ctx->bs_r, ctx->hevc_state, &nal_unit_type, &temporal_id, &layer_id);\n\tctx->nb_nalus++;", "\tif (res < 0) {\n\t\tif (res == -1) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Warning: Error parsing NAL unit\\n\", ctx->log_name));\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t}", "\tif (layer_id && ctx->nosvc) {\n\t\t*skip_nal = GF_TRUE;\n\t\treturn 0;\n\t}", "\tswitch (nal_unit_type) {\n\tcase GF_HEVC_NALU_VID_PARAM:\n\t\tif (ctx->novpsext) {\n\t\t\t//this may modify nal_size, but we don't use it for bitstream reading\n\t\t\tps_idx = gf_hevc_read_vps_ex(data, &size, ctx->hevc_state, GF_TRUE);\n\t\t} else {\n\t\t\tps_idx = ctx->hevc_state->last_parsed_vps_id;\n\t\t}\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Video Param Set\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_HEVC_NALU_VID_PARAM, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_HEVC_NALU_SEQ_PARAM:\n\t\tps_idx = ctx->hevc_state->last_parsed_sps_id;\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Sequence Param Set\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_HEVC_NALU_SEQ_PARAM, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_HEVC_NALU_PIC_PARAM:\n\t\tps_idx = ctx->hevc_state->last_parsed_pps_id;\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Picture Param Set\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_HEVC_NALU_PIC_PARAM, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_HEVC_NALU_SEI_PREFIX:\n\t\tgf_hevc_parse_sei(data, size, ctx->hevc_state);\n\t\tif (!ctx->nosei) {\n\t\t\tctx->nb_sei++;", "\t\t\tif (ctx->sei_buffer_alloc < ctx->sei_buffer_size + size + ctx->nal_length) {\n\t\t\t\tctx->sei_buffer_alloc = ctx->sei_buffer_size + size + ctx->nal_length;\n\t\t\t\tctx->sei_buffer = gf_realloc(ctx->sei_buffer, ctx->sei_buffer_alloc);\n\t\t\t}", "\t\t\tif (!ctx->bs_w) ctx->bs_w = gf_bs_new(ctx->sei_buffer + ctx->sei_buffer_size, ctx->nal_length + size, GF_BITSTREAM_WRITE);\n\t\t\telse gf_bs_reassign_buffer(ctx->bs_w, ctx->sei_buffer + ctx->sei_buffer_size, ctx->nal_length + size);\n\t\t\tgf_bs_write_int(ctx->bs_w, size, 8*ctx->nal_length);\n\t\t\tmemcpy(ctx->sei_buffer + ctx->sei_buffer_size + ctx->nal_length, data, size);\n\t\t\tctx->sei_buffer_size += size + ctx->nal_length;\n\t\t} else {\n\t\t\tctx->nb_nalus--;\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_HEVC_NALU_SEI_SUFFIX:\n\t\tif (! ctx->is_playing) return 0;\n\t\tif (ctx->nosei) {\n\t\t\t*skip_nal = GF_TRUE;\n\t\t\tctx->nb_nalus--;\n\t\t} else {\n\t\t\tctx->nb_sei++;\n\t\t}\n\t\tbreak;", "\t/*slice_segment_layer_rbsp*/\n\tcase GF_HEVC_NALU_SLICE_STSA_N:\n\tcase GF_HEVC_NALU_SLICE_STSA_R:\n\tcase GF_HEVC_NALU_SLICE_RADL_R:\n\tcase GF_HEVC_NALU_SLICE_RASL_R:\n\tcase GF_HEVC_NALU_SLICE_RADL_N:\n\tcase GF_HEVC_NALU_SLICE_RASL_N:\n\tcase GF_HEVC_NALU_SLICE_TRAIL_N:\n\tcase GF_HEVC_NALU_SLICE_TRAIL_R:\n\tcase GF_HEVC_NALU_SLICE_TSA_N:\n\tcase GF_HEVC_NALU_SLICE_TSA_R:\n\tcase GF_HEVC_NALU_SLICE_BLA_W_LP:\n\tcase GF_HEVC_NALU_SLICE_BLA_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_BLA_N_LP:\n\tcase GF_HEVC_NALU_SLICE_IDR_W_DLP:\n\tcase GF_HEVC_NALU_SLICE_IDR_N_LP:\n\tcase GF_HEVC_NALU_SLICE_CRA:\n\t\tif (! ctx->is_playing) return 0;\n\t\t*is_slice = GF_TRUE;\n\t\tif (! *skip_nal) {\n\t\t\tswitch (ctx->hevc_state->s_info.slice_type) {\n\t\t\tcase GF_HEVC_SLICE_TYPE_P:\n\t\t\t\tif (layer_id) ctx->nb_e_p++;\n\t\t\t\telse ctx->nb_p++;\n\t\t\t\tbreak;\n\t\t\tcase GF_HEVC_SLICE_TYPE_I:\n\t\t\t\tif (layer_id) ctx->nb_e_i++;\n\t\t\t\telse ctx->nb_i++;\n\t\t\t\t*is_islice = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tcase GF_HEVC_SLICE_TYPE_B:\n\t\t\t\tif (layer_id) ctx->nb_e_b++;\n\t\t\t\telse ctx->nb_b++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;", "\tcase GF_HEVC_NALU_ACCESS_UNIT:\n\t\tctx->nb_aud++;\n\t\tif (!ctx->audelim) {\n\t\t\t*skip_nal = GF_TRUE;\n\t\t} else if (!ctx->opid) {\n\t\t\tctx->has_initial_aud = GF_TRUE;\n\t\t\tmemcpy(ctx->init_aud, data, 3);\n\t\t}\n\t\tbreak;\n\t/*remove*/\n\tcase GF_HEVC_NALU_FILLER_DATA:\n\tcase GF_HEVC_NALU_END_OF_SEQ:\n\tcase GF_HEVC_NALU_END_OF_STREAM:\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;", "\t//parsing is partial, see https://github.com/DolbyLaboratories/dlb_mp4base/blob/70a2e1d4d99a8439b7b8087bf50dd503eeea2291/src/esparser/parser_hevc.c#L1233\n\tcase GF_HEVC_NALU_DV_RPU:\n\t\tctx->hevc_state->dv_rpu = GF_TRUE;\n\t\tbreak;\n\tcase GF_HEVC_NALU_DV_EL:\n\t\tctx->hevc_state->dv_el = GF_TRUE;\n\t\tbreak;", "\tdefault:\n\t\tif (! ctx->is_playing) return 0;\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, (\"[%s] NAL Unit type %d not handled - adding\\n\", ctx->log_name, nal_unit_type));\n\t\tbreak;\n\t}\n\tif (*skip_nal) return res;", "\tctx->linf[layer_id].layer_id_plus_one = layer_id + 1;\n\tif (! ctx->linf[layer_id].max_temporal_id ) ctx->linf[layer_id].max_temporal_id = temporal_id;\n\telse if (ctx->linf[layer_id].max_temporal_id < temporal_id) ctx->linf[layer_id].max_temporal_id = temporal_id;", "\tif (! ctx->linf[layer_id].min_temporal_id ) ctx->linf[layer_id].min_temporal_id = temporal_id;\n\telse if (ctx->linf[layer_id].min_temporal_id > temporal_id) ctx->linf[layer_id].min_temporal_id = temporal_id;", "\tif (ctx->max_temporal_id[layer_id] < temporal_id)\n\t\tctx->max_temporal_id[layer_id] = temporal_id;\n\tif (ctx->min_layer_id > layer_id) ctx->min_layer_id = layer_id;\n\treturn res;\n#endif // GPAC_DISABLE_HEVC\n}", "\nstatic s32 naludmx_parse_nal_vvc(GF_NALUDmxCtx *ctx, char *data, u32 size, Bool *skip_nal, Bool *is_slice, Bool *is_islice)\n{\n\ts32 ps_idx = 0;\n\ts32 res;\n\tu8 nal_unit_type, temporal_id, layer_id;\n\t*skip_nal = GF_FALSE;", "\tgf_bs_reassign_buffer(ctx->bs_r, data, size);\n\tres = gf_media_vvc_parse_nalu_bs(ctx->bs_r, ctx->vvc_state, &nal_unit_type, &temporal_id, &layer_id);\n\tctx->nb_nalus++;", "\tif (res < 0) {\n\t\tif (res == -1) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Warning: Error parsing NAL unit\\n\", ctx->log_name));\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t}", "\tif (layer_id && ctx->nosvc) {\n\t\t*skip_nal = GF_TRUE;\n\t\treturn 0;\n\t}", "\tswitch (nal_unit_type) {\n\tcase GF_VVC_NALU_VID_PARAM:\n\t\tif (ctx->novpsext) {\n\t\t\t//this may modify nal_size, but we don't use it for bitstream reading\n//\t\t\tps_idx = gf_hevc_read_vps_ex(data, &size, ctx->hevc_state, GF_TRUE);\n\t\t\tps_idx = ctx->vvc_state->last_parsed_vps_id;\n\t\t} else {\n\t\t\tps_idx = ctx->vvc_state->last_parsed_vps_id;\n\t\t}\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Video Param Set\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_VVC_NALU_VID_PARAM, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_VVC_NALU_SEQ_PARAM:\n\t\tps_idx = ctx->vvc_state->last_parsed_sps_id;\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Sequence Param Set\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_VVC_NALU_SEQ_PARAM, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_VVC_NALU_PIC_PARAM:\n\t\tps_idx = ctx->vvc_state->last_parsed_pps_id;\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Picture Param Set\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_VVC_NALU_PIC_PARAM, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_VVC_NALU_DEC_PARAM:\n\t\tps_idx = 0;\n\t\tnaludmx_queue_param_set(ctx, data, size, GF_VVC_NALU_DEC_PARAM, ps_idx);\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_VVC_NALU_APS_PREFIX:\n\t\t//for now we keep APS in the stream\n#if 0\n\t\tps_idx = ctx->vvc_state->last_parsed_aps_id;\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Decoder Param Set\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_VVC_NALU_APS_PREFIX, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n#endif\n\t\tbreak;\n\tcase GF_VVC_NALU_SEI_PREFIX:\n\t\tgf_media_vvc_parse_sei(data, size, ctx->vvc_state);\n\t\tif (!ctx->nosei) {\n\t\t\tctx->nb_sei++;", "\t\t\tif (ctx->sei_buffer_alloc < ctx->sei_buffer_size + size + ctx->nal_length) {\n\t\t\t\tctx->sei_buffer_alloc = ctx->sei_buffer_size + size + ctx->nal_length;\n\t\t\t\tctx->sei_buffer = gf_realloc(ctx->sei_buffer, ctx->sei_buffer_alloc);\n\t\t\t}", "\t\t\tif (!ctx->bs_w) ctx->bs_w = gf_bs_new(ctx->sei_buffer + ctx->sei_buffer_size, ctx->nal_length + size, GF_BITSTREAM_WRITE);\n\t\t\telse gf_bs_reassign_buffer(ctx->bs_w, ctx->sei_buffer + ctx->sei_buffer_size, ctx->nal_length + size);\n\t\t\tgf_bs_write_int(ctx->bs_w, size, 8*ctx->nal_length);\n\t\t\tmemcpy(ctx->sei_buffer + ctx->sei_buffer_size + ctx->nal_length, data, size);\n\t\t\tctx->sei_buffer_size += size + ctx->nal_length;\n\t\t} else {\n\t\t\tctx->nb_nalus--;\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;\n\tcase GF_VVC_NALU_SEI_SUFFIX:\n\t\tif (! ctx->is_playing) return 0;\n\t\tif (ctx->nosei) {\n\t\t\t*skip_nal = GF_TRUE;\n\t\t\tctx->nb_nalus--;\n\t\t} else {\n\t\t\tctx->nb_sei++;\n\t\t}\n\t\tbreak;", "\tcase GF_VVC_NALU_PIC_HEADER:\n\t\tif (! ctx->is_playing) return 0;\n\t\tbreak;", "\t/*slice_segment_layer_rbsp*/\n\tcase GF_VVC_NALU_SLICE_TRAIL:\n\tcase GF_VVC_NALU_SLICE_STSA:\n\tcase GF_VVC_NALU_SLICE_RADL:\n\tcase GF_VVC_NALU_SLICE_RASL:\n\tcase GF_VVC_NALU_SLICE_IDR_W_RADL:\n\tcase GF_VVC_NALU_SLICE_IDR_N_LP:\n\tcase GF_VVC_NALU_SLICE_CRA:\n\tcase GF_VVC_NALU_SLICE_GDR:\n\t\tif (! ctx->is_playing) return 0;\n\t\t*is_slice = GF_TRUE;\n\t\tif (! *skip_nal) {\n\t\t\tswitch (ctx->vvc_state->s_info.slice_type) {\n\t\t\tcase GF_VVC_SLICE_TYPE_P:\n\t\t\t\tif (layer_id) ctx->nb_e_p++;\n\t\t\t\telse ctx->nb_p++;\n\t\t\t\tbreak;\n\t\t\tcase GF_VVC_SLICE_TYPE_I:\n\t\t\t\tif (layer_id) ctx->nb_e_i++;\n\t\t\t\telse ctx->nb_i++;\n\t\t\t\t*is_islice = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tcase GF_VVC_SLICE_TYPE_B:\n\t\t\t\tif (layer_id) ctx->nb_e_b++;\n\t\t\t\telse ctx->nb_b++;\n\t\t\t\tbreak;\n\t\t\tcase GF_VVC_SLICE_TYPE_UNKNOWN:\n\t\t\t\tctx->vvc_no_stats = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;", "\tcase GF_VVC_NALU_ACCESS_UNIT:\n\t\tctx->nb_aud++;\n\t\t//no skip AUD in VVC", "\t\tif (!ctx->opid) {\n\t\t\tctx->has_initial_aud = GF_TRUE;\n\t\t\tmemcpy(ctx->init_aud, data, 3);\n\t\t}\n\t\tbreak;\n\t/*remove*/\n\tcase GF_VVC_NALU_FILLER_DATA:\n\tcase GF_VVC_NALU_END_OF_SEQ:\n\tcase GF_VVC_NALU_END_OF_STREAM:\n\t\t*skip_nal = GF_TRUE;\n\t\tbreak;", "\tcase GF_VVC_NALU_OPI:\n\t\tif (! ctx->is_playing) return 0;\n\t\tbreak;", "\tdefault:\n\t\tif (! ctx->is_playing) return 0;\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, (\"[%s] NAL Unit type %d not handled - adding\\n\", ctx->log_name, nal_unit_type));\n\t\tbreak;\n\t}\n\tif (*skip_nal) return res;", "\tctx->linf[layer_id].layer_id_plus_one = layer_id + 1;\n\tif (! ctx->linf[layer_id].max_temporal_id ) ctx->linf[layer_id].max_temporal_id = temporal_id;\n\telse if (ctx->linf[layer_id].max_temporal_id < temporal_id) ctx->linf[layer_id].max_temporal_id = temporal_id;", "\tif (! ctx->linf[layer_id].min_temporal_id ) ctx->linf[layer_id].min_temporal_id = temporal_id;\n\telse if (ctx->linf[layer_id].min_temporal_id > temporal_id) ctx->linf[layer_id].min_temporal_id = temporal_id;", "\tif (ctx->max_temporal_id[layer_id] < temporal_id)\n\t\tctx->max_temporal_id[layer_id] = temporal_id;\n\tif (ctx->min_layer_id > layer_id) ctx->min_layer_id = layer_id;\n\treturn res;\n}", "static s32 naludmx_parse_nal_avc(GF_NALUDmxCtx *ctx, char *data, u32 size, u32 nal_type, Bool *skip_nal, Bool *is_slice, Bool *is_islice)\n{\n\ts32 ps_idx = 0;\n\ts32 res = 0;", "\tgf_bs_reassign_buffer(ctx->bs_r, data, size);\n\t*skip_nal = GF_FALSE;\n\tres = gf_avc_parse_nalu(ctx->bs_r, ctx->avc_state);\n\tif (res < 0) {\n\t\tif (res == -1) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Warning: Error parsing NAL unit\\n\", ctx->log_name));\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t}\n\tctx->nb_nalus++;", "\tswitch (nal_type) {\n\tcase GF_AVC_NALU_SVC_SUBSEQ_PARAM:\n\tcase GF_AVC_NALU_SEQ_PARAM:\n\t\tps_idx = ctx->avc_state->last_ps_idx;\n\t\tif (ps_idx<0) {\n\t\t\tif (ctx->avc_state->sps[0].profile_idc) {\n\t\t\t\tGF_LOG(ctx->avc_state->sps[0].profile_idc ? GF_LOG_WARNING : GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Sequence Param Set\\n\", ctx->log_name));\n\t\t\t}\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_AVC_NALU_SEQ_PARAM, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\treturn 0;", "\tcase GF_AVC_NALU_PIC_PARAM:\n\t\tps_idx = ctx->avc_state->last_ps_idx;\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Picture Param Set\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_AVC_NALU_PIC_PARAM, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\treturn 0;", "\tcase GF_AVC_NALU_SEQ_PARAM_EXT:\n\t\tps_idx = ctx->avc_state->last_ps_idx;\n\t\tif (ps_idx<0) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing Sequence Param Set Extension\\n\", ctx->log_name));\n\t\t} else {\n\t\t\tnaludmx_queue_param_set(ctx, data, size, GF_AVC_NALU_SEQ_PARAM_EXT, ps_idx);\n\t\t}\n\t\t*skip_nal = GF_TRUE;\n\t\treturn 0;", "\tcase GF_AVC_NALU_SEI:\n\t\tif (ctx->avc_state->sps_active_idx != -1) {\n\t\t\tu32 rw_sei_size, sei_size = size;\n\t\t\tif (ctx->sei_buffer_alloc < ctx->sei_buffer_size + sei_size + ctx->nal_length) {\n\t\t\t\tctx->sei_buffer_alloc = ctx->sei_buffer_size + sei_size + ctx->nal_length;\n\t\t\t\tctx->sei_buffer = gf_realloc(ctx->sei_buffer, ctx->sei_buffer_alloc);\n\t\t\t}", "\t\t\tif (!ctx->bs_w) ctx->bs_w = gf_bs_new(ctx->sei_buffer + ctx->sei_buffer_size, ctx->nal_length + sei_size, GF_BITSTREAM_WRITE);\n\t\t\telse gf_bs_reassign_buffer(ctx->bs_w, ctx->sei_buffer + ctx->sei_buffer_size, ctx->nal_length + sei_size);\n\t\t\tgf_bs_write_int(ctx->bs_w, sei_size, 8*ctx->nal_length);", "\t\t\tmemcpy(ctx->sei_buffer + ctx->sei_buffer_size + ctx->nal_length, data, sei_size);\n\t\t\trw_sei_size = gf_media_avc_reformat_sei(ctx->sei_buffer + ctx->sei_buffer_size + ctx->nal_length, sei_size, ctx->seirw, ctx->avc_state);\n\t\t\tif (rw_sei_size < sei_size) {\n\t\t\t\tgf_bs_seek(ctx->bs_w, 0);\n\t\t\t\tgf_bs_write_int(ctx->bs_w, rw_sei_size, 8*ctx->nal_length);\n\t\t\t}", "\t\t\t*skip_nal = GF_TRUE;\n\t\t\tctx->sei_buffer_size += rw_sei_size + ctx->nal_length;", "\t\t\tif (ctx->nosei) {\n\t\t\t\tctx->sei_buffer_size = 0;\n\t\t\t} else {\n\t\t\t\tctx->nb_sei++;\n\t\t\t}\n\t\t}\n\t\treturn 0;", "\tcase GF_AVC_NALU_ACCESS_UNIT:\n\t\tctx->nb_aud++;\n\t\tif (!ctx->audelim) {\n\t\t\t*skip_nal = GF_TRUE;\n\t\t} else if (!ctx->opid) {\n\t\t\tctx->has_initial_aud = GF_TRUE;\n\t\t\tmemcpy(ctx->init_aud, data, 2);\n\t\t}\n\t\treturn 1;\n\t/*remove*/\n\tcase GF_AVC_NALU_FILLER_DATA:\n\tcase GF_AVC_NALU_END_OF_SEQ:\n\tcase GF_AVC_NALU_END_OF_STREAM:\n\t\t*skip_nal = GF_TRUE;\n\t\treturn 0;", "\t//update stats\n\tcase GF_AVC_NALU_NON_IDR_SLICE:\n\tcase GF_AVC_NALU_DP_A_SLICE:\n\tcase GF_AVC_NALU_DP_B_SLICE:\n\tcase GF_AVC_NALU_DP_C_SLICE:\n\tcase GF_AVC_NALU_IDR_SLICE:\n\t\t*is_slice = GF_TRUE;\n\t\tswitch (ctx->avc_state->s_info.slice_type) {\n\t\tcase GF_AVC_TYPE_P:\n\t\tcase GF_AVC_TYPE2_P:\n\t\t\tctx->nb_p++;\n\t\t\tbreak;\n\t\tcase GF_AVC_TYPE_I:\n\t\tcase GF_AVC_TYPE2_I:\n\t\t\tctx->nb_i++;\n\t\t\t*is_islice = GF_TRUE;\n\t\t\tbreak;\n\t\tcase GF_AVC_TYPE_B:\n\t\tcase GF_AVC_TYPE2_B:\n\t\t\tctx->nb_b++;\n\t\t\tbreak;\n\t\tcase GF_AVC_TYPE_SP:\n\t\tcase GF_AVC_TYPE2_SP:\n\t\t\tctx->nb_sp++;\n\t\t\tbreak;\n\t\tcase GF_AVC_TYPE_SI:\n\t\tcase GF_AVC_TYPE2_SI:\n\t\t\tctx->nb_si++;\n\t\t\tbreak;\n\t\t}\n\t\tbreak;", "\tcase GF_AVC_NALU_SVC_SLICE:\n\t\tif (!ctx->explicit) {\n\t\t\tu32 i;\n\t\t\tfor (i = 0; i < gf_list_count(ctx->pps); i ++) {\n\t\t\t\tGF_NALUFFParam *slc = (GF_NALUFFParam*)gf_list_get(ctx->pps, i);\n\t\t\t\tif (ctx->avc_state->s_info.pps && ctx->avc_state->s_info.pps->id == slc->id) {\n\t\t\t\t\t/* This PPS is used by an SVC NAL unit, it should be moved to the SVC Config Record) */\n\t\t\t\t\tgf_list_rem(ctx->pps, i);\n\t\t\t\t\ti--;\n\t\t\t\t\tif (!ctx->pps_svc) ctx->pps_svc = gf_list_new(ctx->pps_svc);\n\t\t\t\t\tgf_list_add(ctx->pps_svc, slc);\n\t\t\t\t\tctx->ps_modified = GF_TRUE;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t*is_slice = GF_TRUE;\n\t\t//we disable temporal scalability when parsing mvc - never used and many encoders screw up POC in enhancemen\n\t\tif (ctx->is_mvc && (res>=0)) {\n\t\t\tres=0;\n\t\t\tctx->avc_state->s_info.poc = ctx->last_poc;\n\t\t}\n if (ctx->avc_state->s_info.sps) {\n switch (ctx->avc_state->s_info.slice_type) {\n case GF_AVC_TYPE_P:\n case GF_AVC_TYPE2_P:\n ctx->avc_state->s_info.sps->nb_ep++;\n break;\n case GF_AVC_TYPE_I:\n case GF_AVC_TYPE2_I:\n ctx->avc_state->s_info.sps->nb_ei++;\n break;\n case GF_AVC_TYPE_B:\n case GF_AVC_TYPE2_B:\n ctx->avc_state->s_info.sps->nb_eb++;\n break;\n }\n }\n break;\n\tcase GF_AVC_NALU_SLICE_AUX:\n\t\t*is_slice = GF_TRUE;\n\t\tbreak;\n\t}\n\treturn res;\n}", "static void naldmx_switch_timestamps(GF_NALUDmxCtx *ctx, GF_FilterPacket *pck)\n{\n\t//input pid sets some timescale - we flushed pending data , update cts\n\tif (ctx->timescale) {\n\t\tu64 ts = gf_filter_pck_get_cts(pck);\n\t\tif (ts != GF_FILTER_NO_TS) {\n\t\t\tctx->prev_cts = ctx->cts;\n\t\t\tctx->cts = ts;\n\t\t}\n\t\tts = gf_filter_pck_get_dts(pck);\n\t\tif (ts != GF_FILTER_NO_TS) {\n\t\t\tif (ctx->full_au_source) {\n\t\t\t\tctx->prev_dts = ctx->dts;\n\t\t\t\tctx->dts = ts;\n\t\t\t} else {\n\t\t\t\tGF_FilterClockType ck_type = gf_filter_pid_get_clock_info(ctx->ipid, NULL, NULL);\n\t\t\t\tif (ck_type==GF_FILTER_CLOCK_PCR_DISC)\n\t\t\t\t\tctx->dts = ts;\n\t\t\t\telse if (ctx->dts<ts)\n\t\t\t\t\tctx->dts=ts;", "\t\t\t\tif (!ctx->prev_dts) ctx->prev_dts = ts;\n\t\t\t\telse if (ctx->prev_dts != ts) {\n\t\t\t\t\tu64 diff = ts;\n\t\t\t\t\tdiff -= ctx->prev_dts;\n\t\t\t\t\tif (!ctx->cur_fps.den)\n\t\t\t\t\t\tctx->cur_fps.den = (u32) diff;\n\t\t\t\t\telse if (ctx->cur_fps.den > diff)\n\t\t\t\t\t\tctx->cur_fps.den = (u32) diff;", "\t\t\t\t\tctx->prev_dts = ts;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tctx->pck_duration = gf_filter_pck_get_duration(pck);\n\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\tctx->src_pck = pck;\n\t\tgf_filter_pck_ref_props(&ctx->src_pck);\n\t\t//store framing flags. If input_is_au_start, the first NAL of the first frame beginning in this packet will\n\t\t//use the DTS/CTS of the input packet, otherwise we will use our internal POC recompute\n\t\tgf_filter_pck_get_framing(pck, &ctx->input_is_au_start, NULL);\n\t}\n}", "static void naldmx_check_timestamp_switch(GF_NALUDmxCtx *ctx, u32 *nalu_store_before, u32 bytes_drop, Bool *drop_packet, GF_FilterPacket *pck)\n{\n\tif (*nalu_store_before) {\n\t\tif (*nalu_store_before > bytes_drop) {\n\t\t\t*nalu_store_before -= bytes_drop;\n\t\t} else {\n\t\t\t//all data from previous frame consumed, update timestamps with info from current packet\n\t\t\t*nalu_store_before = 0;\n\t\t\tnaldmx_switch_timestamps(ctx, pck);\n\t\t\tif (*drop_packet) {\n\t\t\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\t\t\t*drop_packet = GF_FALSE;\n\t\t\t}\n\t\t}\n\t}\n}", "static void naldmx_bs_log(void *udta, const char *field_name, u32 nb_bits, u64 field_val, s32 idx1, s32 idx2, s32 idx3)\n{\n\tGF_NALUDmxCtx *ctx = (GF_NALUDmxCtx *) udta;\n\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\" %s\", field_name));\n\tif (idx1>=0) {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"_%d\", idx1));\n\t\tif (idx2>=0) {\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"_%d\", idx2));\n\t\t\tif (idx3>=0) {\n\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"_%d\", idx3));\n\t\t\t}\n\t\t}\n\t}\n\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"=\\\"\"LLD, field_val));\n\tif ((ctx->bsdbg==2) && ((s32) nb_bits > 1) )\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"(%u)\", nb_bits));", "\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"\\\" \"));\n}", "GF_Err naludmx_process(GF_Filter *filter)\n{\n\tGF_NALUDmxCtx *ctx = gf_filter_get_udta(filter);\n\tGF_FilterPacket *pck;\n\tGF_Err e;\n\tu8 *start;\n\tu32 nalu_before = ctx->nb_nalus;\n\tu32 nalu_store_before = 0;\n\ts32 remain;\n\tBool is_eos = GF_FALSE;\n\tBool drop_packet = GF_FALSE;\n\tu64 byte_offset = GF_FILTER_NO_BO;", "\t//always reparse duration\n\tif (!ctx->file_loaded)\n\t\tnaludmx_check_dur(filter, ctx);", "\tpck = gf_filter_pid_get_packet(ctx->ipid);\n\tif (!ctx->resume_from && !pck) {\n\t\tif (gf_filter_pid_is_eos(ctx->ipid)) {\n\t\t\tif (ctx->nal_store_size) {\n\t\t\t\tif (!ctx->is_playing)\n\t\t\t\t\treturn GF_OK;", "\t\t\t\tstart = ctx->nal_store;\n\t\t\t\tremain = ctx->nal_store_size;\n\t\t\t\tis_eos = GF_TRUE;\n\t\t\t\tgoto naldmx_flush;\n\t\t\t}\n\t\t\tif (ctx->first_pck_in_au) {\n\t\t\t\tnaludmx_finalize_au_flags(ctx);\n\t\t\t}\n\t\t\t//single-frame stream\n\t\t\tif (!ctx->poc_diff) ctx->poc_diff = 1;\n\t\t\tctx->strict_poc = STRICT_POC_OFF;\n\t\t\tnaludmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE);\n\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\tctx->src_pck = NULL;\n\t\t\tif (!ctx->opid) return GF_EOS;", "\t\t\tgf_filter_pid_set_info(ctx->opid, GF_PROP_PID_MAX_NALU_SIZE, &PROP_UINT(ctx->max_nalu_size) );\n\t\t\tif (ctx->codecid==GF_CODECID_HEVC) {\n\t\t\t\tnaludmx_set_hevc_oinf(ctx, ctx->max_temporal_id);\n\t\t\t\tnaludmx_set_hevc_linf(ctx);\n\t\t\t\tgf_filter_pid_set_info_str(ctx->opid, \"hevc:min_lid\", &PROP_UINT(ctx->min_layer_id) );\n\t\t\t}\n\t\t\tif (ctx->opid)\n\t\t\t\tgf_filter_pid_set_eos(ctx->opid);\n\t\t\treturn GF_EOS;\n\t\t}\n\t\treturn GF_OK;\n\t}", "\tif (!ctx->is_playing && ctx->opid)\n\t\treturn GF_OK;", "\t//if we have bytes from previous packet in the header, we cannot switch timing until we know what these bytes are\n\tif (!ctx->nal_store_size)\n\t\tnaldmx_switch_timestamps(ctx, pck);", "\tnalu_store_before = ctx->nal_store_size;\n\tif (!ctx->resume_from && pck) {\n\t\tu32 pck_size;\n\t\tconst u8 *data = gf_filter_pck_get_data(pck, &pck_size);\n\t\tif (ctx->nal_store_alloc < ctx->nal_store_size + pck_size) {\n\t\t\tctx->nal_store_alloc = ctx->nal_store_size + pck_size;\n\t\t\tctx->nal_store = gf_realloc(ctx->nal_store, sizeof(char)*ctx->nal_store_alloc);\n\t\t\tif (!ctx->nal_store) {\n\t\t\t\tctx->nal_store_alloc = 0;\n\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t}\n\t\t}\n\t\tbyte_offset = gf_filter_pck_get_byte_offset(pck);\n\t\tif (byte_offset != GF_FILTER_NO_BO)\n\t\t\tbyte_offset -= ctx->nal_store_size;\n\t\tmemcpy(ctx->nal_store + ctx->nal_store_size, data, sizeof(char)*pck_size);\n\t\tctx->nal_store_size += pck_size;\n\t\tdrop_packet = GF_TRUE;\n\t}\n\tstart = ctx->nal_store;\n\tremain = ctx->nal_store_size;", "\tif (ctx->resume_from) {\n\t\tif (ctx->opid && gf_filter_pid_would_block(ctx->opid))\n\t\t\treturn GF_OK;", "\t\tassert(ctx->resume_from < ctx->nal_store_size);\n\t\tstart += ctx->resume_from;\n\t\tremain -= ctx->resume_from;\n\t\tctx->resume_from = 0;", "\t\tif (!pck && gf_filter_pid_is_eos(ctx->ipid))\n\t\t\tis_eos = GF_TRUE;\n\t}", "naldmx_flush:\n\tif (!ctx->bs_r) {\n\t\tctx->bs_r = gf_bs_new(start, remain, GF_BITSTREAM_READ);", "#ifndef GPAC_DISABLE_LOG\n\t\tif (ctx->bsdbg && gf_log_tool_level_on(GF_LOG_PARSER, GF_LOG_DEBUG))\n\t\t\tgf_bs_set_logger(ctx->bs_r, naldmx_bs_log, ctx);\n#endif", "\t} else {\n\t\tgf_bs_reassign_buffer(ctx->bs_r, start, remain);\n\t}", " assert(remain>=0);", "\twhile (remain) {\n\t\tu8 *pck_data;\n\t\tu8 *nal_data;\n\t\tu32 nal_size;\n\t\ts32 current;\n\t\tBool skip_nal = GF_FALSE;\n\t\tu32 sc_size=0;\n\t\tu32 nal_type = 0;\n\t\tu32 nal_ref_idc = 0;\n\t\ts32 next=0;\n\t\tu32 next_sc_size=0;\n\t\ts32 nal_parse_result;\n\t\tBool slice_is_ref, slice_force_ref;\n\t\tBool is_slice = GF_FALSE;\n\t\tBool is_islice = GF_FALSE;\n\t\tBool bottom_field_flag = GF_FALSE;\n\t\tBool au_start;\n\t\tu32 avc_svc_subs_reserved = 0;\n\t\tu8 avc_svc_subs_priority = 0;\n\t\tBool recovery_point_valid = GF_FALSE;\n\t\tu32 recovery_point_frame_cnt = 0;\n\t\tBool bIntraSlice = GF_FALSE;\n\t\tGF_FilterSAPType au_sap_type = GF_FILTER_SAP_NONE;\n\t\tBool slice_is_b = GF_FALSE;\n\t\tBool check_dep = GF_FALSE;\n\t\ts32 slice_poc = 0;", "\t\t//not enough bytes to parse start code + nal hdr\n\t\tif (!is_eos && (remain<6)) {\n\t\t\tbreak;\n\t\t}", "\t\t//locate next start code\n\t\tcurrent = gf_media_nalu_next_start_code(start, remain, &sc_size);\n\t\tif (current == remain)\n\t\t\tcurrent = -1;", "\t\t//no start code: if eos or full AU dispatch mode, send remaining otherwise gather\n\t\tif (current<0) {\n\t\t\tif (!is_eos && !ctx->full_au_source) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\te = naludmx_realloc_last_pck(ctx, (u32) remain, &pck_data);\n\t\t\tif (e==GF_OK)\n\t\t\t\tmemcpy(pck_data, start, (size_t) remain);\n\t\t\tremain = 0;\n\t\t\tbreak;\n\t\t}", "\t\tassert(current>=0);", "\t\t//skip if no output pid\n\t\tif (!ctx->opid && current) {\n\t\t\tassert(remain>=current);\n assert((s32) current >= 0);", "\t\t\tstart += current;\n\t\t\tremain -= current;\n\t\t\tcurrent = 0;\n\t\t}", "\t\t//dispatch remaining bytes\n\t\tif (current>0) {\n\t\t\t//flush remaining bytes in NAL\n\t\t\tif (gf_list_count(ctx->pck_queue)) {\n\t\t\t\te = naludmx_realloc_last_pck(ctx, current, &pck_data);\n\t\t\t\tif (e==GF_OK) {\n\t\t\t\t\tmemcpy(pck_data, start, current);\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert(remain>=current);\n\t\t\tstart += current;\n\t\t\tremain -= current;\n\t\t\tnaldmx_check_timestamp_switch(ctx, &nalu_store_before, current, &drop_packet, pck);\n\t\t}\n\t\tif (!remain)\n\t\t\tbreak;", "\t\t//not enough bytes to parse start code + nal hdr\n\t\tif (!is_eos && (remain<6)) {\n\t\t\tbreak;\n\t\t}", "\t\tnal_data = start + sc_size;\n\t\tnal_size = remain - sc_size;", "\t\t//figure out which nal we need to completely load\n\t\tif (ctx->codecid==GF_CODECID_HEVC) {\n\t\t\tnal_type = nal_data[0];\n\t\t\tnal_type = (nal_type & 0x7E) >> 1;", "\t\t\tswitch (nal_type) {\n\t\t\tcase GF_HEVC_NALU_VID_PARAM:\n\t\t\tcase GF_HEVC_NALU_SEQ_PARAM:\n\t\t\tcase GF_HEVC_NALU_PIC_PARAM:\n\t\t\tcase GF_HEVC_NALU_SEI_PREFIX:\n\t\t\tcase GF_HEVC_NALU_SEI_SUFFIX:\n\t\t\t\tbreak;\n\t\t\tcase GF_HEVC_NALU_SLICE_TRAIL_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_TSA_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_STSA_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_RADL_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_RASL_N:\n\t\t\tcase GF_HEVC_NALU_SLICE_RSV_VCL_N10:\n\t\t\tcase GF_HEVC_NALU_SLICE_RSV_VCL_N12:\n\t\t\tcase GF_HEVC_NALU_SLICE_RSV_VCL_N14:\n\t\t\t\tcheck_dep = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (nal_type<GF_HEVC_NALU_VID_PARAM)\n\t\t\t\t\tnal_ref_idc = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\t\tnal_type = nal_data[1]>>3;\n\t\t\tswitch (nal_type) {\n\t\t\tcase GF_VVC_NALU_OPI:\n\t\t\tcase GF_VVC_NALU_DEC_PARAM:\n\t\t\tcase GF_VVC_NALU_VID_PARAM:\n\t\t\tcase GF_VVC_NALU_SEQ_PARAM:\n\t\t\tcase GF_VVC_NALU_PIC_PARAM:\n\t\t\tcase GF_VVC_NALU_SEI_PREFIX:\n\t\t\tcase GF_VVC_NALU_SEI_SUFFIX:\n\t\t\tcase GF_VVC_NALU_APS_PREFIX:\n\t\t\tcase GF_VVC_NALU_APS_SUFFIX:\n\t\t\tcase GF_VVC_NALU_PIC_HEADER:\n\t\t\t\tbreak;", "\t\t\tcase GF_VVC_NALU_SLICE_TRAIL:\n\t\t\tcase GF_VVC_NALU_SLICE_STSA:\n\t\t\tcase GF_VVC_NALU_SLICE_RADL:\n\t\t\tcase GF_VVC_NALU_SLICE_RASL:\n\t\t\tcase GF_VVC_NALU_SLICE_IDR_W_RADL:\n\t\t\tcase GF_VVC_NALU_SLICE_IDR_N_LP:\n\t\t\tcase GF_VVC_NALU_SLICE_CRA:\n\t\t\tcase GF_VVC_NALU_SLICE_GDR:\n\t\t\t\tif (ctx->deps) {\n\t\t\t\t\tcheck_dep = GF_TRUE;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (nal_type<GF_HEVC_NALU_VID_PARAM)\n\t\t\t\t\tnal_ref_idc = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tnal_type = nal_data[0] & 0x1F;\n\t\t\tnal_ref_idc = (nal_data[0] & 0x60) >> 5;\n\t\t}", "\t\t//locate next NAL start\n\t\tnext = gf_media_nalu_next_start_code(nal_data, nal_size, &next_sc_size);\n\t\tif (!is_eos && (next == nal_size) && !ctx->full_au_source) {\n\t\t\tnext = -1;\n\t\t}", "\t\t//next nal start not found, wait\n\t\tif (next<0) {\n\t\t\tbreak;\n\t\t}", "\t\t//this is our exact NAL size, without start code\n\t\tnal_size = next;", "\t\tif (ctx->codecid==GF_CODECID_HEVC) {\n\t\t\tnal_parse_result = naludmx_parse_nal_hevc(ctx, nal_data, nal_size, &skip_nal, &is_slice, &is_islice);\n\t\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\t\tnal_parse_result = naludmx_parse_nal_vvc(ctx, nal_data, nal_size, &skip_nal, &is_slice, &is_islice);\n\t\t} else {\n\t\t\tnal_parse_result = naludmx_parse_nal_avc(ctx, nal_data, nal_size, nal_type, &skip_nal, &is_slice, &is_islice);\n\t\t}", "\t\t//dispatch right away if analyze\n\t\tif (ctx->analyze) {\n\t\t\tskip_nal = GF_FALSE;\n\t\t\tctx->sei_buffer_size = 0;\n\t\t}", "\t\t//new frame - if no slices, we detected the new frame on AU delimiter, don't flush new frame !\n\t\tif ((nal_parse_result>0) && !ctx->first_slice_in_au) {\n\t\t\t//new frame - we flush later on\n\t\t\tnaludmx_finalize_au_flags(ctx);", "\t\t\tctx->has_islice = GF_FALSE;\n\t\t\tctx->first_slice_in_au = GF_TRUE;\n\t\t\tctx->sei_recovery_frame_count = -1;\n\t\t\tctx->au_sap = GF_FILTER_SAP_NONE;\n\t\t\tctx->bottom_field_flag = GF_FALSE;\n\t\t}", "\t\tnaludmx_check_pid(filter, ctx);\n\t\tif (!ctx->opid) skip_nal = GF_TRUE;", "\t\tif (skip_nal) {\n\t\t\tnal_size += sc_size;\n\t\t\tassert((u32) remain >= nal_size);\n\t\t\tstart += nal_size;\n\t\t\tremain -= nal_size;\n\t\t\tnaldmx_check_timestamp_switch(ctx, &nalu_store_before, nal_size, &drop_packet, pck);\n\t\t\tcontinue;\n\t\t}", "\t\tif (!ctx->is_playing) {\n\t\t\tctx->resume_from = (u32) (start - ctx->nal_store);\n assert(ctx->resume_from<=ctx->nal_store_size);\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"[%s] not yet playing\\n\", ctx->log_name));", "\t\t\tif (drop_packet)\n\t\t\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\t\treturn GF_OK;\n\t\t}\n\t\tif (ctx->in_seek) {\n\t\t\tu64 nb_frames_at_seek = (u64) (ctx->start_range * ctx->cur_fps.num);\n\t\t\tif (ctx->cts + ctx->cur_fps.den >= nb_frames_at_seek) {\n\t\t\t\t//u32 samples_to_discard = (ctx->cts + ctx->dts_inc) - nb_samples_at_seek;\n\t\t\t\tctx->in_seek = GF_FALSE;\n\t\t\t}\n\t\t}", "\t\tif (nal_parse_result<0) {\n\t\t\tif (byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\tu64 bo = byte_offset;\n\t\t\t\tbo += (start - ctx->nal_store);", "\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing NAL Unit %d (byte offset \"LLU\" size %d type %d frame %d last POC %d) - skipping\\n\", ctx->log_name, ctx->nb_nalus, bo, nal_size, nal_type, ctx->nb_frames, ctx->last_poc));\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[%s] Error parsing NAL Unit %d (size %d type %d frame %d last POC %d) - skipping\\n\", ctx->log_name, ctx->nb_nalus, nal_size, nal_type, ctx->nb_frames, ctx->last_poc));\n\t\t\t}\n\t\t\tnal_size += sc_size;\n\t\t\tassert((u32) remain >= nal_size);\n\t\t\tstart += nal_size;\n\t\t\tremain -= nal_size;\n\t\t\tnaldmx_check_timestamp_switch(ctx, &nalu_store_before, nal_size, &drop_packet, pck);\n\t\t\tcontinue;\n\t\t}", "\t\tif (check_dep) {\n\t\t\tif ((ctx->codecid==GF_CODECID_HEVC) && ctx->hevc_state->s_info.sps) {\n\t\t\t\tHEVC_VPS *vps;\n\t\t\t\tu32 temporal_id = nal_data[1] & 0x7;\n\t\t\t\tvps = & ctx->hevc_state->vps[ctx->hevc_state->s_info.sps->vps_id];\n\t\t\t\tif (temporal_id + 1 < vps->max_sub_layers) {\n\t\t\t\t\tnal_ref_idc = GF_TRUE;\n\t\t\t\t}\n\t\t\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\t\t\tif (ctx->vvc_state->s_info.non_ref_pic) {\n\t\t\t\t\tnal_ref_idc = GF_FALSE;\n\t\t\t\t} else {\n\t\t\t\t\t//todo\n\t\t\t\t\tnal_ref_idc = GF_TRUE;\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\n\t\tif (is_islice) ctx->has_islice = GF_TRUE;", "\t\t//store all variables needed to compute POC/CTS and sample SAP and recovery info\n\t\tif (ctx->codecid==GF_CODECID_HEVC) {\n#ifndef GPAC_DISABLE_HEVC\n\t\t\tslice_is_ref = gf_hevc_slice_is_IDR(ctx->hevc_state);", "\t\t\trecovery_point_valid = ctx->hevc_state->sei.recovery_point.valid;\n\t\t\trecovery_point_frame_cnt = ctx->hevc_state->sei.recovery_point.frame_cnt;\n\t\t\tbIntraSlice = gf_hevc_slice_is_intra(ctx->hevc_state);", "\t\t\tau_sap_type = GF_FILTER_SAP_NONE;\n\t\t\tif (gf_hevc_slice_is_IDR(ctx->hevc_state)) {\n\t\t\t\tau_sap_type = GF_FILTER_SAP_1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tswitch (ctx->hevc_state->s_info.nal_unit_type) {\n\t\t\t\tcase GF_HEVC_NALU_SLICE_BLA_W_LP:\n\t\t\t\tcase GF_HEVC_NALU_SLICE_BLA_W_DLP:\n\t\t\t\t\tau_sap_type = GF_FILTER_SAP_3;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_HEVC_NALU_SLICE_BLA_N_LP:\n\t\t\t\t\tau_sap_type = GF_FILTER_SAP_1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_HEVC_NALU_SLICE_CRA:\n\t\t\t\t\tau_sap_type = GF_FILTER_SAP_3;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}", "\t\t\tslice_poc = ctx->hevc_state->s_info.poc;", "\t\t\t/*need to store TS offsets*/\n\t\t\tswitch (ctx->hevc_state->s_info.slice_type) {\n\t\t\tcase GF_AVC_TYPE_B:\n\t\t\tcase GF_AVC_TYPE2_B:\n\t\t\t\tslice_is_b = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n#endif // GPAC_DISABLE_HEVC\n\t\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\t\tslice_is_ref = gf_media_vvc_slice_is_ref(ctx->vvc_state);\n\t\t\trecovery_point_valid = ctx->vvc_state->s_info.recovery_point_valid;\n\t\t\trecovery_point_frame_cnt = ctx->vvc_state->s_info.gdr_recovery_count;", "//\t\t\tcommented, set below\n//\t\t\tif (ctx->vvc_state->s_info.irap_or_gdr_pic && !ctx->vvc_state->s_info.gdr_pic)\n//\t\t\t\tbIntraSlice = GF_TRUE; //gf_hevc_slice_is_intra(ctx->hevc_state);", "\t\t\tau_sap_type = GF_FILTER_SAP_NONE;\n\t\t\tif (ctx->vvc_state->s_info.irap_or_gdr_pic && !ctx->vvc_state->s_info.gdr_pic) {\n\t\t\t\tau_sap_type = GF_FILTER_SAP_1;\n\t\t\t\tbIntraSlice = GF_TRUE;\n\t\t\t\tslice_is_ref = 1;\n\t\t\t} else {\n\t\t\t\tswitch (ctx->vvc_state->s_info.nal_unit_type) {\n\t\t\t\tcase GF_VVC_NALU_SLICE_IDR_N_LP:\n\t\t\t\t\tau_sap_type = GF_FILTER_SAP_1;\n\t\t\t\t\tslice_is_ref = 1;\n\t\t\t\t\tbIntraSlice = GF_TRUE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_VVC_NALU_SLICE_CRA:\n\t\t\t\t\tau_sap_type = GF_FILTER_SAP_3;\n\t\t\t\t\tbIntraSlice = GF_TRUE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_VVC_NALU_SLICE_IDR_W_RADL:\n\t\t\t\t\tbIntraSlice = GF_TRUE;\n\t\t\t\t\tif (ctx->vvc_state->s_info.gdr_pic) {\n\t\t\t\t\t\tau_sap_type = GF_FILTER_SAP_3;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tau_sap_type = GF_FILTER_SAP_1;\n\t\t\t\t\t\tslice_is_ref = 1;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}", "\t\t\tslice_poc = ctx->vvc_state->s_info.poc;", "\t\t\t/*need to store TS offsets*/\n\t\t\tswitch (ctx->vvc_state->s_info.slice_type) {\n\t\t\tcase GF_AVC_TYPE_B:\n\t\t\tcase GF_AVC_TYPE2_B:\n\t\t\t\tslice_is_b = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {", "\t\t\t/*fixme - we need finer grain for priority*/\n\t\t\tif ((nal_type==GF_AVC_NALU_SVC_PREFIX_NALU) || (nal_type==GF_AVC_NALU_SVC_SLICE)) {\n\t\t\t\tif (!ctx->is_mvc) {\n\t\t\t\t\tunsigned char *p = (unsigned char *) start;\n\t\t\t\t\t// RefPicFlag\n\t\t\t\t\tavc_svc_subs_reserved |= (p[0] & 0x60) ? 0x80000000 : 0;\n\t\t\t\t\t// RedPicFlag TODO: not supported, would require to parse NAL unit payload\n\t\t\t\t\tavc_svc_subs_reserved |= (0) ? 0x40000000 : 0;\n\t\t\t\t\t// VclNALUnitFlag\n\t\t\t\t\tavc_svc_subs_reserved |= (1<=nal_type && nal_type<=5) || (nal_type==GF_AVC_NALU_SVC_PREFIX_NALU) || (nal_type==GF_AVC_NALU_SVC_SLICE) ? 0x20000000 : 0;\n\t\t\t\t\t// use values of IdrFlag and PriorityId directly from SVC extension header\n\t\t\t\t\tavc_svc_subs_reserved |= p[1] << 16;\n\t\t\t\t\t// use values of DependencyId and QualityId directly from SVC extension header\n\t\t\t\t\tavc_svc_subs_reserved |= p[2] << 8;\n\t\t\t\t\t// use values of TemporalId and UseRefBasePicFlag directly from SVC extension header\n\t\t\t\t\tavc_svc_subs_reserved |= p[3] & 0xFC;\n\t\t\t\t\t// StoreBaseRepFlag TODO: SVC FF mentions a store_base_rep_flag which cannot be found in SVC spec\n\t\t\t\t\tavc_svc_subs_reserved |= (0) ? 0x00000002 : 0;", "\t\t\t\t\t// priority_id (6 bits) in SVC has inverse meaning -> lower value means higher priority - invert it and scale it to 8 bits\n\t\t\t\t\tavc_svc_subs_priority = (63 - (p[1] & 0x3F)) << 2;\n\t\t\t\t}\n\t\t\t\tif (nal_type==GF_AVC_NALU_SVC_PREFIX_NALU) {\n if (ctx->svc_prefix_buffer_size) {\n GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[%s] broken bitstream, two consecutive SVC prefix NALU without SVC slice in-between\\n\", ctx->log_name));\n ctx->svc_prefix_buffer_size = 0;\n }", "\t\t\t\t\t/* remember reserved and priority value */\n\t\t\t\t\tctx->svc_nalu_prefix_reserved = avc_svc_subs_reserved;\n\t\t\t\t\tctx->svc_nalu_prefix_priority = avc_svc_subs_priority;", "\t\t\t\t\tctx->svc_prefix_buffer_size = nal_size;\n\t\t\t\t\tif (ctx->svc_prefix_buffer_size > ctx->svc_prefix_buffer_alloc) {\n\t\t\t\t\t\tctx->svc_prefix_buffer_alloc = ctx->svc_prefix_buffer_size;\n\t\t\t\t\t\tctx->svc_prefix_buffer = gf_realloc(ctx->svc_prefix_buffer, ctx->svc_prefix_buffer_size);\n\t\t\t\t\t}\n\t\t\t\t\tmemcpy(ctx->svc_prefix_buffer, start+sc_size, ctx->svc_prefix_buffer_size);", "\t\t\t\t\tassert( (u32) remain >= sc_size + nal_size);\n\t\t\t\t\tstart += sc_size + nal_size;\n\t\t\t\t\tremain -= sc_size + nal_size;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else if (is_slice) {\n\t\t\t\t// RefPicFlag\n\t\t\t\tavc_svc_subs_reserved |= (start[0] & 0x60) ? 0x80000000 : 0;\n\t\t\t\t// VclNALUnitFlag\n\t\t\t\tavc_svc_subs_reserved |= (1<=nal_type && nal_type<=5) || (nal_type==GF_AVC_NALU_SVC_PREFIX_NALU) || (nal_type==GF_AVC_NALU_SVC_SLICE) ? 0x20000000 : 0;\n\t\t\t\tavc_svc_subs_priority = 0;\n\t\t\t}", "\t\t\tif (is_slice && ctx->avc_state->s_info.field_pic_flag) {\n\t\t\t\tctx->is_paff = GF_TRUE;\n\t\t\t\tbottom_field_flag = ctx->avc_state->s_info.bottom_field_flag;\n\t\t\t}", "\t\t\tslice_is_ref = (ctx->avc_state->s_info.nal_unit_type==GF_AVC_NALU_IDR_SLICE) ? GF_TRUE : GF_FALSE;", "\t\t\trecovery_point_valid = ctx->avc_state->sei.recovery_point.valid;\n\t\t\trecovery_point_frame_cnt = ctx->avc_state->sei.recovery_point.frame_cnt;\n\t\t\tbIntraSlice = gf_media_avc_slice_is_intra(ctx->avc_state);", "\t\t\tau_sap_type = GF_FILTER_SAP_NONE;\n\t\t\tif (ctx->avc_state->s_info.nal_unit_type == GF_AVC_NALU_IDR_SLICE)\n\t\t\t\tau_sap_type = GF_FILTER_SAP_1;", "\t\t\tslice_poc = ctx->avc_state->s_info.poc;\n\t\t\t/*need to store TS offsets*/\n\t\t\tswitch (ctx->avc_state->s_info.slice_type) {\n\t\t\tcase GF_AVC_TYPE_B:\n\t\t\tcase GF_AVC_TYPE2_B:\n\t\t\t\tslice_is_b = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "\t\tif (is_slice) {\n\t\t\tBool first_in_au = ctx->first_slice_in_au;", "\t\t\tif (slice_is_ref)\n\t\t\t\tctx->nb_idr++;\n\t\t\tslice_force_ref = GF_FALSE;", "\t\t\t/*we only indicate TRUE IDRs for sync samples (cf AVC file format spec).\n\t\t\tSEI recovery should be used to build sampleToGroup & RollRecovery tables*/\n\t\t\tif (ctx->first_slice_in_au) {\n\t\t\t\tctx->first_slice_in_au = GF_FALSE;\n\t\t\t\tif (recovery_point_valid) {\n\t\t\t\t\tctx->sei_recovery_frame_count = recovery_point_frame_cnt;", "\t\t\t\t\t/*we allow to mark I-frames as sync on open-GOPs (with sei_recovery_frame_count=0) when forcing sync even when the SEI RP is not available*/\n\t\t\t\t\tif (!recovery_point_frame_cnt && bIntraSlice) {\n\t\t\t\t\t\tctx->has_islice = 1;\n\t\t\t\t\t\tif (ctx->use_opengop_gdr == 1) {\n\t\t\t\t\t\t\tctx->use_opengop_gdr = 2; /*avoid message flooding*/\n\t\t\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[%s] No valid SEI Recovery Point found although needed - forcing\\n\", ctx->log_name));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (ctx->codecid==GF_CODECID_HEVC) {\n\t\t\t\t\t\tctx->hevc_state->sei.recovery_point.valid = 0;\n\t\t\t\t\t} else if (ctx->codecid==GF_CODECID_VVC) {\n\t\t\t\t\t\tctx->vvc_state->s_info.recovery_point_valid = 0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tctx->avc_state->sei.recovery_point.valid = 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (bIntraSlice && ctx->force_sync && (ctx->sei_recovery_frame_count==0))\n\t\t\t\t\t\tslice_force_ref = GF_TRUE;\n\t\t\t\t}\n\t\t\t\tctx->au_sap = au_sap_type;\n\t\t\t\tctx->bottom_field_flag = bottom_field_flag;\n\t\t\t}", "\t\t\tif (slice_poc < ctx->poc_shift) {", "\t\t\t\tu32 i, count = gf_list_count(ctx->pck_queue);\n\t\t\t\tfor (i=0; i<count; i++) {\n\t\t\t\t\tu64 dts, cts;\n\t\t\t\t\tGF_FilterPacket *q_pck = gf_list_get(ctx->pck_queue, i);\n\t\t\t\t\tassert(q_pck);\n\t\t\t\t\tdts = gf_filter_pck_get_dts(q_pck);\n\t\t\t\t\tif (dts == GF_FILTER_NO_TS) continue;\n\t\t\t\t\tcts = gf_filter_pck_get_cts(q_pck);\n\t\t\t\t\tcts += ctx->poc_shift;\n\t\t\t\t\tcts -= slice_poc;\n\t\t\t\t\tgf_filter_pck_set_cts(q_pck, cts);\n\t\t\t\t}", "\t\t\t\tctx->poc_shift = slice_poc;\n\t\t\t}", "\t\t\t/*if #pics, compute smallest POC increase*/\n\t\t\tif (slice_poc != ctx->last_poc) {\n\t\t\t\ts32 pdiff = ABS(ctx->last_poc - slice_poc);", "\t\t\t\tif ((slice_poc < 0) && !ctx->last_poc)\n\t\t\t\t\tctx->poc_diff = 0;", "\t\t\t\tif (!ctx->poc_diff || (ctx->poc_diff > (s32) pdiff ) ) {\n\t\t\t\t\tctx->poc_diff = pdiff;\n\t\t\t\t\tctx->poc_probe_done = GF_FALSE;\n\t\t\t\t} else if (first_in_au) {\n\t\t\t\t\t//second frame with the same poc diff, we should be able to properly recompute CTSs\n\t\t\t\t\tctx->poc_probe_done = GF_TRUE;\n\t\t\t\t}\n\t\t\t\tctx->last_poc = slice_poc;\n\t\t\t}\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, (\"[%s] POC is %d - min poc diff %d - slice is ref %d\\n\", ctx->log_name, slice_poc, ctx->poc_diff, slice_is_ref));", "\t\t\t/*ref slice, reset poc*/\n\t\t\tif (slice_is_ref) {\n\t\t\t\tif (first_in_au) {\n\t\t\t\t\tBool temp_poc_diff = GF_FALSE;\n\t\t\t\t\t//two consecutive IDRs, force poc_diff to 1 if 0 (when we have intra-only) to force frame dispatch\n\t\t\t\t\tif (ctx->last_frame_is_idr && !ctx->poc_diff) {\n\t\t\t\t\t\ttemp_poc_diff = GF_TRUE;\n\t\t\t\t\t\tctx->poc_diff = 1;\n\t\t\t\t\t}\n\t\t\t\t\t//new ref frame, dispatch all pending packets\n\t\t\t\t\tnaludmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE);", "\t\t\t\t\tctx->max_last_poc = ctx->last_poc = ctx->max_last_b_poc = 0;\n\t\t\t\t\tctx->poc_shift = 0;\n\t\t\t\t\t//force probing of POC diff, this will prevent dispatching frames with wrong CTS until we have a clue of min poc_diff used\n\t\t\t\t\tctx->poc_probe_done = 0;\n\t\t\t\t\tctx->last_frame_is_idr = GF_TRUE;\n\t\t\t\t\tif (temp_poc_diff)\n\t\t\t\t\t\tctx->poc_diff = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*forced ref slice*/\n\t\t\telse if (slice_force_ref) {\n\t\t\t\tctx->last_frame_is_idr = GF_FALSE;\n\t\t\t\tif (first_in_au) {\n\t\t\t\t\t//new ref frame, dispatch all pending packets\n\t\t\t\t\tnaludmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE);", "\t\t\t\t\t/*adjust POC shift as sample will now be marked as sync, so we must store poc as if IDR (eg POC=0) for our CTS offset computing to be correct*/\n\t\t\t\t\tctx->poc_shift = slice_poc;", "\t\t\t\t\t//force probing of POC diff, this will prevent dispatching frames with wrong CTS until we have a clue of min poc_diff used\n\t\t\t\t\tctx->poc_probe_done = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*strictly less - this is a new P slice*/\n\t\t\telse if (ctx->max_last_poc < ctx->last_poc) {\n\t\t\t\tctx->max_last_b_poc = 0;\n\t\t\t\tctx->max_last_poc = ctx->last_poc;\n\t\t\t\tctx->last_frame_is_idr = GF_FALSE;\n\t\t\t}\n\t\t\t/*stricly greater*/\n\t\t\telse if (slice_is_b && (ctx->max_last_poc > ctx->last_poc)) {\n\t\t\t\tctx->last_frame_is_idr = GF_FALSE;\n\t\t\t\tif (!ctx->max_last_b_poc) {\n\t\t\t\t\tctx->max_last_b_poc = ctx->last_poc;\n\t\t\t\t}\n\t\t\t\t/*if same poc than last max, this is a B-slice*/\n\t\t\t\telse if (ctx->last_poc > ctx->max_last_b_poc) {\n\t\t\t\t\tctx->max_last_b_poc = ctx->last_poc;\n\t\t\t\t}\n\t\t\t\t/*otherwise we had a B-slice reference: do nothing*/\n\t\t\t} else {\n\t\t\t\tctx->last_frame_is_idr = GF_FALSE;\n\t\t\t}", "\n\t\t\tif (ctx->deps) {\n\t\t\t\tif (nal_ref_idc) {\n\t\t\t\t\tctx->has_ref_slices = GF_TRUE;\n\t\t\t\t}\n\t\t\t\tif ((ctx->codecid==GF_CODECID_AVC) && (ctx->avc_state->s_info.redundant_pic_cnt) ) {\n\t\t\t\t\tctx->has_redundant = GF_TRUE;\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\n\t\tau_start = ctx->first_pck_in_au ? GF_FALSE : GF_TRUE;", "\t\tif (ctx->has_initial_aud) {\n\t\t\tu32 audelim_size = (ctx->codecid!=GF_CODECID_AVC) ? 3 : 2;\n\t\t\t/*dst_pck = */naludmx_start_nalu(ctx, audelim_size, GF_FALSE, &au_start, &pck_data);\n\t\t\tmemcpy(pck_data + ctx->nal_length , ctx->init_aud, audelim_size);\n\t\t\tctx->has_initial_aud = GF_FALSE;\n\t\t\tif (ctx->subsamples) {\n\t\t\t\tnaludmx_add_subsample(ctx, audelim_size, avc_svc_subs_priority, avc_svc_subs_reserved);\n\t\t\t}\n\t\t}\n\t\tif (ctx->sei_buffer_size) {\n\t\t\t//sei buffer is already nal size prefixed\n\t\t\t/*dst_pck = */naludmx_start_nalu(ctx, ctx->sei_buffer_size, GF_TRUE, &au_start, &pck_data);\n\t\t\tmemcpy(pck_data, ctx->sei_buffer, ctx->sei_buffer_size);\n\t\t\tif (ctx->subsamples) {\n\t\t\t\tnaludmx_add_subsample(ctx, ctx->sei_buffer_size - ctx->nal_length, avc_svc_subs_priority, avc_svc_subs_reserved);\n\t\t\t}\n\t\t\tctx->sei_buffer_size = 0;\n\t\t}", "\t\tif (ctx->svc_prefix_buffer_size) {\n\t\t\t/*dst_pck = */naludmx_start_nalu(ctx, ctx->svc_prefix_buffer_size, GF_FALSE, &au_start, &pck_data);\n\t\t\tmemcpy(pck_data + ctx->nal_length, ctx->svc_prefix_buffer, ctx->svc_prefix_buffer_size);\n\t\t\tif (ctx->subsamples) {\n\t\t\t\tnaludmx_add_subsample(ctx, ctx->svc_prefix_buffer_size, ctx->svc_nalu_prefix_priority, ctx->svc_nalu_prefix_reserved);\n\t\t\t}\n\t\t\tctx->svc_prefix_buffer_size = 0;\n\t\t}", "\t\t//nalu size field\n\t\t/*dst_pck = */naludmx_start_nalu(ctx, (u32) nal_size, GF_FALSE, &au_start, &pck_data);\n\t\tpck_data += ctx->nal_length;", "\t\t//add subsample info before touching the size\n\t\tif (ctx->subsamples) {\n\t\t\tnaludmx_add_subsample(ctx, (u32) nal_size, avc_svc_subs_priority, avc_svc_subs_reserved);\n\t\t}", "\n\t\t//bytes only come from the data packet\n\t\tmemcpy(pck_data, nal_data, (size_t) nal_size);", "\t\tnal_size += sc_size;\n\t\tstart += nal_size;\n\t\tremain -= nal_size;\n\t\tnaldmx_check_timestamp_switch(ctx, &nalu_store_before, nal_size, &drop_packet, pck);", "\t\t//don't demux too much of input, abort when we would block. This avoid dispatching\n\t\t//a huge number of frames in a single call\n\t\tif (remain && gf_filter_pid_would_block(ctx->opid)) {\n\t\t\tctx->resume_from = (u32) (start - ctx->nal_store);\n\t\t\tassert(ctx->resume_from <= ctx->nal_store_size);\n\t\t\tassert(ctx->resume_from == ctx->nal_store_size - remain);\n\t\t\tif (drop_packet)\n\t\t\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\t\treturn GF_OK;\n\t\t}\n\t}", "\tif (remain) {\n\t\tif (is_eos && (remain == ctx->nal_store_size)) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, (\"[%s] Incomplete last NAL and eos, discarding\\n\", ctx->log_name));\n\t\t\tremain = 0;\n\t\t} else {\n\t\t\tassert((u32) remain<=ctx->nal_store_size);\n\t\t\tmemmove(ctx->nal_store, start, remain);\n\t\t}\n\t}\n\tctx->nal_store_size = remain;", "\tif (drop_packet)\n\t\tgf_filter_pid_drop_packet(ctx->ipid);", "\tif (is_eos)\n\t\treturn naludmx_process(filter);", "\tif ((ctx->nb_nalus>nalu_before) && gf_filter_reporting_enabled(filter)) {\n\t\tchar szStatus[1024];", "\t\tsprintf(szStatus, \"%s %dx%d % 10d NALU % 8d I % 8d P % 8d B % 8d SEI\", ctx->log_name, ctx->width, ctx->height, ctx->nb_nalus, ctx->nb_i, ctx->nb_p, ctx->nb_b, ctx->nb_sei);\n\t\tgf_filter_update_status(filter, -1, szStatus);\n\t}\n\tif (ctx->full_au_source && ctx->poc_probe_done) {\n\t\tif (ctx->first_pck_in_au)\n\t\t\tnaludmx_finalize_au_flags(ctx);", "\t\tnaludmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE);\n\t}\n\treturn GF_OK;\n}", "static GF_Err naludmx_initialize(GF_Filter *filter)\n{\n\tGF_NALUDmxCtx *ctx = gf_filter_get_udta(filter);\n\tctx->sps = gf_list_new();\n\tctx->pps = gf_list_new();\n\tswitch (ctx->nal_length) {\n\tcase 1:\n\t\tctx->max_nalu_size_allowed = 0xFF;\n\t\tbreak;\n\tcase 2:\n\t\tctx->max_nalu_size_allowed = 0xFFFF;\n\t\tbreak;\n\tcase 4:\n\t\tctx->max_nalu_size_allowed = 0xFFFFFFFF;\n\t\tbreak;\n\tcase 0:\n\t\tctx->max_nalu_size_allowed = 0xFFFFFFFF;\n\t\tctx->nal_length = 4;\n\t\tctx->nal_adjusted = GF_TRUE;\n\t\tbreak;\n\tdefault:\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CODING, (\"[%s] NAL size length %d is not allowed, defaulting to 4 bytes\\n\", ctx->log_name));\n\t\tctx->max_nalu_size_allowed = 0xFFFFFFFF;\n\t\tctx->nal_length = 4;\n\t\tbreak;\n\t}\n\treturn GF_OK;\n}", "static void naludmx_del_param_list(GF_List *ps)\n{\n\tif (!ps) return;\n\twhile (gf_list_count(ps)) {\n\t\tGF_NALUFFParam *sl = gf_list_pop_back(ps);\n\t\tif (sl->data) gf_free(sl->data);\n\t\tgf_free(sl);\n\t}\n\tgf_list_del(ps);\n}", "static void naludmx_log_stats(GF_NALUDmxCtx *ctx)\n{\n\tu32 i, count;\n\tconst char *msg_import;\n\tu32 nb_frames = 0;\n\tif (ctx->cur_fps.den)\n\t\tnb_frames = (u32) (ctx->dts / ctx->cur_fps.den);", "\tif (ctx->idur.den && ctx->idur.num) {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s duration specified at import time, may have parsed more frames than imported\\n\", ctx->log_name));\n\t\tmsg_import = \"parsed\";\n\t} else {\n\t\tmsg_import = \"Import results:\";\n\t}", "\tif (ctx->nb_si || ctx->nb_sp) {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s %s %d frames (%d NALUs) - Slices: %d I %d P %d B %d SP %d SI - %d SEI - %d IDR\\n\", ctx->log_name, msg_import, nb_frames, ctx->nb_nalus, ctx->nb_i, ctx->nb_p, ctx->nb_b, ctx->nb_sp, ctx->nb_si, ctx->nb_sei, ctx->nb_idr ));\n\t} else if (ctx->vvc_no_stats) {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s %s %d samples (%d NALUs) - %d SEI - %d IDR\\n\",\n\t\t\t ctx->log_name, msg_import, nb_frames, ctx->nb_nalus, ctx->nb_sei, ctx->nb_idr));\n\t} else {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s %s %d samples (%d NALUs) - Slices: %d I %d P %d B - %d SEI - %d IDR\\n\",\n\t\t\t ctx->log_name, msg_import, nb_frames, ctx->nb_nalus, ctx->nb_i, ctx->nb_p, ctx->nb_b, ctx->nb_sei, ctx->nb_idr));\n\t}", "\tif (ctx->codecid==GF_CODECID_AVC) {\n\t\tcount = gf_list_count(ctx->sps);\n\t\tfor (i=0; i<count; i++) {\n\t\t\tAVC_SPS *sps;\n\t\t\tGF_NALUFFParam *svcc = (GF_NALUFFParam*)gf_list_get(ctx->sps, i);\n\t\t\tsps = & ctx->avc_state->sps[svcc->id];\n\t\t\tif (sps->nb_ei || sps->nb_ep) {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s SVC (SSPS ID %d, %dx%d) %s Slices: %d I %d P %d B\\n\", ctx->log_name, svcc->id - GF_SVC_SSPS_ID_SHIFT, sps->width, sps->height, msg_import, sps->nb_ei, sps->nb_ep, sps->nb_eb ));\n\t\t\t}\n\t\t}\n\t} else if (ctx->nb_e_i || ctx->nb_e_p || ctx->nb_e_b) {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s L-HEVC %s Slices: %d I %d P %d B\\n\", ctx->log_name, msg_import, ctx->nb_e_i, ctx->nb_e_p, ctx->nb_e_b ));\n\t}", "\tif (ctx->max_total_delay>1) {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s Stream uses forward prediction - stream CTS offset: %d frames\\n\", ctx->log_name, ctx->max_total_delay));\n\t}", "\tif (!ctx->nal_adjusted) {\n\t\tif ((ctx->max_nalu_size < 0xFF) && (ctx->nal_length>1) ){\n\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s Max NALU size is %d - stream could be optimized by setting nal_length=1\\n\", ctx->log_name, ctx->max_nalu_size));\n\t\t} else if ((ctx->max_nalu_size < 0xFFFF) && (ctx->nal_length>2) ){\n\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_AUTHOR, (\"%s Max NALU size is %d - stream could be optimized by setting nal_length=2\\n\", ctx->log_name, ctx->max_nalu_size));\n\t\t}\n\t}\n}", "static void naludmx_finalize(GF_Filter *filter)\n{\n\tGF_NALUDmxCtx *ctx = gf_filter_get_udta(filter);", "\tif (ctx->importer) naludmx_log_stats(ctx);", "\tif (ctx->bs_r) gf_bs_del(ctx->bs_r);\n\tif (ctx->bs_w) gf_bs_del(ctx->bs_w);\n\tif (ctx->indexes) gf_free(ctx->indexes);\n\tif (ctx->nal_store) gf_free(ctx->nal_store);\n\tif (ctx->pck_queue) {\n\t\twhile (gf_list_count(ctx->pck_queue)) {\n\t\t\tGF_FilterPacket *pck = gf_list_pop_back(ctx->pck_queue);\n\t\t\tgf_filter_pck_discard(pck);\n\t\t}\n\t\tgf_list_del(ctx->pck_queue);\n\t}\n\tif (ctx->sei_buffer) gf_free(ctx->sei_buffer);\n\tif (ctx->svc_prefix_buffer) gf_free(ctx->svc_prefix_buffer);\n\tif (ctx->subsamp_buffer) gf_free(ctx->subsamp_buffer);", "\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\tctx->src_pck = NULL;", "\tnaludmx_del_param_list(ctx->sps);\n\tnaludmx_del_param_list(ctx->pps);\n\tnaludmx_del_param_list(ctx->vps);\n\tnaludmx_del_param_list(ctx->sps_ext);\n\tnaludmx_del_param_list(ctx->pps_svc);\n\tnaludmx_del_param_list(ctx->vvc_aps_pre);\n\tnaludmx_del_param_list(ctx->vvc_dci);", "\tif (ctx->avc_state) gf_free(ctx->avc_state);\n\tif (ctx->hevc_state) gf_free(ctx->hevc_state);\n\tif (ctx->vvc_state) gf_free(ctx->vvc_state);\n}", "\nstatic const char *naludmx_probe_data(const u8 *data, u32 size, GF_FilterProbeScore *score)\n{\n\tu32 sc, sc_size;\n\tu32 not_hevc=0;\n\tu32 not_avc=0;\n\tu32 not_vvc=0;\n\tu32 nb_hevc=0;\n\tu32 nb_avc=0;\n\tu32 nb_vvc=0;\n\tu32 nb_nalus=0;\n\tu32 nb_hevc_zero=0;\n\tu32 nb_avc_zero=0;\n\tu32 nb_vvc_zero=0;\n\tu32 nb_sps_hevc=0,nb_pps_hevc=0,nb_vps_hevc=0;\n\tu32 nb_sps_avc=0,nb_pps_avc=0;\n\tu32 nb_sps_vvc=0,nb_pps_vvc=0,nb_vps_vvc=0;", "\twhile (size>3) {\n\t\tu32 nal_type=0;\n\t\tsc = gf_media_nalu_next_start_code(data, size, &sc_size);\n\t\tif (!sc_size) break;", "\t\tdata += sc + sc_size;\n\t\tif (size <= sc + sc_size) break;\n\t\tsize -= sc + sc_size;", "\t\tif (data[0] & 0x80) {\n\t\t\tnot_avc++;\n\t\t\tnot_hevc++;\n\t\t\tnot_vvc++;\n\t\t\tcontinue;\n\t\t}\n\t\tnb_nalus++;", "\t\tnal_type = (data[0] & 0x7E) >> 1;\n\t\tif (nal_type<=40) {\n\t\t\tnb_hevc++;\n\t\t\tswitch (nal_type) {\n\t\t\tcase GF_HEVC_NALU_PIC_PARAM:\n\t\t\t\tif (nb_sps_hevc)\n\t\t\t\t\tnb_pps_hevc++;\n\t\t\t\tbreak;\n\t\t\tcase GF_HEVC_NALU_SEQ_PARAM:\n\t\t\t\tnb_sps_hevc++;\n\t\t\t\tbreak;\n\t\t\tcase GF_HEVC_NALU_VID_PARAM:\n\t\t\t\tnb_vps_hevc++;\n\t\t\t\tbreak;\n\t\t\tcase 0:\n\t\t\t\tnb_hevc_zero++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tnot_hevc++;\n\t\t}", "\t\tnal_type = data[0] & 0x1F;\n\t\tif (nal_type && nal_type<=24) {\n\t\t\tnb_avc++;\n\t\t\tswitch (nal_type) {\n\t\t\tcase GF_AVC_NALU_PIC_PARAM:\n\t\t\t\tif (nb_sps_avc)\n\t\t\t\t\tnb_pps_avc++;\n\t\t\t\tbreak;\n\t\t\tcase GF_AVC_NALU_SEQ_PARAM:\n\t\t\t\tnb_sps_avc++;\n\t\t\t\tbreak;\n\t\t\tcase 0:\n\t\t\t\tnb_avc_zero++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tnot_avc++;\n\t\t}", "\t\t//check vvc - 2nd bit reserved to 0\n\t\tif (data[0] & 0x40) {\n\t\t\tnot_vvc++;\n\t\t\tcontinue;\n\t\t}\n\t\tnal_type = data[1] >> 3;\n\t\tif (nal_type>31) {\n\t\t\tnot_vvc++;\n\t\t\tcontinue;\n\t\t}\n\t\tnb_vvc++;\n\t\tswitch (nal_type) {\n\t\tcase GF_VVC_NALU_PIC_PARAM:\n\t\t\tif (nb_sps_vvc)\n\t\t\t\tnb_pps_vvc++;\n\t\t\tbreak;\n\t\tcase GF_VVC_NALU_SEQ_PARAM:\n\t\t\tnb_sps_vvc++;\n\t\t\tbreak;\n\t\tcase GF_VVC_NALU_VID_PARAM:\n\t\t\tnb_vps_vvc++;\n\t\t\tbreak;\n\t\tcase 0:\n\t\t\tnb_vvc_zero++;\n\t\t\tbreak;\n\t\t}\n\t}", "\tif (!nb_sps_avc || !nb_pps_avc) nb_avc=0;\n\tif (!nb_sps_hevc || !nb_pps_hevc || !nb_vps_hevc) nb_hevc=0;\n\tif (!nb_sps_vvc || !nb_pps_vvc || !nb_vps_vvc) nb_vvc=0;\n\tif (not_avc) nb_avc=0;\n\tif (not_hevc) nb_hevc=0;\n\tif (not_vvc) nb_vvc=0;", "\tif (not_avc && not_hevc && not_vvc) return NULL;\n\tif (nb_avc==nb_avc_zero) nb_avc=0;\n\tif (nb_hevc==nb_hevc_zero) nb_hevc=0;\n\tif (nb_vvc==nb_vvc_zero) nb_vvc=0;", "\tif (!nb_hevc && !nb_avc && !nb_vvc) return NULL;\n\t*score = GF_FPROBE_SUPPORTED;\n\tif (!nb_hevc) return (nb_vvc>nb_avc) ? \"video/vvc\" : \"video/avc\";\n\tif (!nb_avc) return (nb_vvc>nb_hevc) ? \"video/vvc\" : \"video/hevc\";\n\tif (!nb_vvc) return (nb_avc>nb_hevc) ? \"video/avc\" : \"video/hevc\";", "\tif ((nb_hevc>nb_avc) && (nb_hevc>nb_vvc)) return \"video/hevc\";\n\tif ((nb_vvc>nb_avc) && (nb_vvc>nb_hevc)) return \"video/vvc\";\n\treturn \"video/avc\";\n}", "static const GF_FilterCapability NALUDmxCaps[] =\n{\n\tCAP_UINT(GF_CAPS_INPUT, GF_PROP_PID_STREAM_TYPE, GF_STREAM_FILE),\n\tCAP_STRING(GF_CAPS_INPUT, GF_PROP_PID_FILE_EXT, \"264|h264|26L|h26L|h26l|avc|svc|mvc|hevc|hvc|265|h265|shvc|lvhc|mhvc|266|vvc|lvvc\"),\n\tCAP_STRING(GF_CAPS_INPUT, GF_PROP_PID_MIME, \"video/avc|video/h264|video/svc|video/mvc|video/hevc|video/lhvc|video/shvc|video/mhvc|video/vvc\"),\n\tCAP_UINT(GF_CAPS_OUTPUT_STATIC, GF_PROP_PID_STREAM_TYPE, GF_STREAM_VISUAL),\n\tCAP_UINT(GF_CAPS_OUTPUT_STATIC, GF_PROP_PID_CODECID, GF_CODECID_AVC),\n\tCAP_UINT(GF_CAPS_OUTPUT_STATIC, GF_PROP_PID_CODECID, GF_CODECID_AVC_PS),\n\tCAP_UINT(GF_CAPS_OUTPUT_STATIC, GF_PROP_PID_CODECID, GF_CODECID_SVC),\n\tCAP_UINT(GF_CAPS_OUTPUT_STATIC, GF_PROP_PID_CODECID, GF_CODECID_MVC),\n\tCAP_UINT(GF_CAPS_OUTPUT_STATIC, GF_PROP_PID_CODECID, GF_CODECID_HEVC),\n\tCAP_UINT(GF_CAPS_OUTPUT_STATIC, GF_PROP_PID_CODECID, GF_CODECID_LHVC),\n\tCAP_UINT(GF_CAPS_OUTPUT_STATIC, GF_PROP_PID_CODECID, GF_CODECID_VVC),\n\tCAP_BOOL(GF_CAPS_OUTPUT_STATIC_EXCLUDED, GF_PROP_PID_UNFRAMED, GF_TRUE),\n\tCAP_BOOL(GF_CAPS_OUTPUT_STATIC_EXCLUDED, GF_PROP_PID_TILE_BASE, GF_TRUE),\n\t{0},\n\tCAP_UINT(GF_CAPS_INPUT,GF_PROP_PID_STREAM_TYPE, GF_STREAM_VISUAL),\n\tCAP_UINT(GF_CAPS_INPUT,GF_PROP_PID_CODECID, GF_CODECID_AVC),\n\tCAP_UINT(GF_CAPS_INPUT,GF_PROP_PID_CODECID, GF_CODECID_AVC_PS),\n\tCAP_UINT(GF_CAPS_INPUT,GF_PROP_PID_CODECID, GF_CODECID_SVC),\n\tCAP_UINT(GF_CAPS_INPUT,GF_PROP_PID_CODECID, GF_CODECID_MVC),\n\tCAP_UINT(GF_CAPS_INPUT,GF_PROP_PID_CODECID, GF_CODECID_HEVC),\n\tCAP_UINT(GF_CAPS_INPUT,GF_PROP_PID_CODECID, GF_CODECID_LHVC),\n\tCAP_UINT(GF_CAPS_INPUT,GF_PROP_PID_CODECID, GF_CODECID_VVC),\n\tCAP_BOOL(GF_CAPS_INPUT,GF_PROP_PID_UNFRAMED, GF_TRUE),\n\tCAP_BOOL(GF_CAPS_INPUT_EXCLUDED, GF_PROP_PID_TILE_BASE, GF_TRUE),\n};", "#define OFFS(_n)\t#_n, offsetof(GF_NALUDmxCtx, _n)\nstatic const GF_FilterArgs NALUDmxArgs[] =\n{\n\t{ OFFS(fps), \"import frame rate (0 default to FPS from bitstream or 25 Hz)\", GF_PROP_FRACTION, \"0/1000\", NULL, 0},\n\t{ OFFS(index), \"indexing window length. If 0, bitstream is not probed for duration. A negative value skips the indexing if the source file is larger than 100M (slows down importers) unless a play with start range > 0 is issued, otherwise uses the positive value\", GF_PROP_DOUBLE, \"-1.0\", NULL, 0},\n\t{ OFFS(explicit), \"use explicit layered (SVC/LHVC) import\", GF_PROP_BOOL, \"false\", NULL, GF_FS_ARG_HINT_ADVANCED},\n\t{ OFFS(strict_poc), \"delay frame output of an entire GOP to ensure CTS info is correct when POC suddenly changes\\n\"\n\t\t\"- off: disable GOP buffering\\n\"\n\t\t\"- on: enable GOP buffering, assuming no error in POC\\n\"\n\t\t\"- error: enable GOP buffering and try to detect lost frames\", GF_PROP_UINT, \"off\", \"off|on|error\", GF_FS_ARG_HINT_ADVANCED},\n\t{ OFFS(nosei), \"remove all sei messages\", GF_PROP_BOOL, \"false\", NULL, GF_FS_ARG_HINT_ADVANCED},\n\t{ OFFS(nosvc), \"remove all SVC/MVC/LHVC data\", GF_PROP_BOOL, \"false\", NULL, GF_FS_ARG_HINT_ADVANCED},\n\t{ OFFS(novpsext), \"remove all VPS extensions\", GF_PROP_BOOL, \"false\", NULL, GF_FS_ARG_HINT_ADVANCED},\n\t{ OFFS(importer), \"compatibility with old importer, displays import results\", GF_PROP_BOOL, \"false\", NULL, GF_FS_ARG_HINT_ADVANCED},\n\t{ OFFS(idur), \"compatibility with old importer to log imported frames only\", GF_PROP_FRACTION, \"0\", NULL, GF_FS_ARG_HINT_HIDE},\n\t{ OFFS(nal_length), \"set number of bytes used to code length field: 1, 2 or 4\", GF_PROP_UINT, \"4\", NULL, GF_FS_ARG_HINT_EXPERT},\n\t{ OFFS(subsamples), \"import subsamples information\", GF_PROP_BOOL, \"false\", NULL, GF_FS_ARG_HINT_EXPERT},\n\t{ OFFS(deps), \"import samples dependencies information\", GF_PROP_BOOL, \"false\", NULL, GF_FS_ARG_HINT_EXPERT},\n\t{ OFFS(seirw), \"rewrite AVC sei messages for ISOBMFF constraints\", GF_PROP_BOOL, \"true\", NULL, GF_FS_ARG_HINT_EXPERT},\n\t{ OFFS(audelim), \"keep Access Unit delimiter in payload\", GF_PROP_BOOL, \"false\", NULL, GF_FS_ARG_HINT_EXPERT},\n\t{ OFFS(analyze), \"skip reformat of decoder config and SEI and dispatch all NAL in input order - shall only be used with inspect filter analyze mode!\", GF_PROP_UINT, \"off\", \"off|on|bs|full\", GF_FS_ARG_HINT_HIDE},", "\t{ OFFS(bsdbg), \"debug NAL parsing in parser@debug logs\\n\"\n\t\t\"- off: not enabled\\n\"\n\t\t\"- on: enabled\\n\"\n\t\t\"- full: enable with number of bits dumped\", GF_PROP_UINT, \"off\", \"off|on|full\", GF_FS_ARG_HINT_EXPERT},\n\t{0}\n};", "\nGF_FilterRegister NALUDmxRegister = {\n\t.name = \"rfnalu\",\n\tGF_FS_SET_DESCRIPTION(\"AVC/HEVC reframer\")\n\tGF_FS_SET_HELP(\"This filter parses AVC|H264 and HEVC files/data and outputs corresponding video PID and frames.\\n\"\n\t\"This demuxer only produces ISOBMFF-compatible output: start codes are removed, NALU length field added and avcC/hvcC config created.\\nNote: The demux uses negative CTS offsets: CTS is corrrect, but some frames may have DTS greater than CTS.\")\n\t.private_size = sizeof(GF_NALUDmxCtx),\n\t.args = NALUDmxArgs,\n\t.initialize = naludmx_initialize,\n\t.finalize = naludmx_finalize,\n\tSETCAPS(NALUDmxCaps),\n\t.configure_pid = naludmx_configure_pid,\n\t.process = naludmx_process,\n\t.process_event = naludmx_process_event,\n\t.probe_data = naludmx_probe_data,\n};", "\nconst GF_FilterRegister *naludmx_register(GF_FilterSession *session)\n{\n\treturn &NALUDmxRegister;\n}", "#else\nconst GF_FilterRegister *naludmx_register(GF_FilterSession *session)\n{\n\treturn NULL;\n}\n#endif //GPAC_DISABLE_AV_PARSERS" ]
[ 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, 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, 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, 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, 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, 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, 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, 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, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1685], "buggy_code_start_loc": [1683], "filenames": ["src/filters/reframe_nalu.c"], "fixing_code_end_loc": [1687], "fixing_code_start_loc": [1683], "message": "A Segmentation fault exists casued by null pointer dereference exists in Gpac through 1.0.1 via the naludmx_create_avc_decoder_config function in reframe_nalu.c when using mp4box, which causes a denial of service.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gpac:gpac:*:*:*:*:*:*:*:*", "matchCriteriaId": "72EEF01B-F945-4AEF-B5C2-6F84A51311C9", "versionEndExcluding": null, "versionEndIncluding": "1.0.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A Segmentation fault exists casued by null pointer dereference exists in Gpac through 1.0.1 via the naludmx_create_avc_decoder_config function in reframe_nalu.c when using mp4box, which causes a denial of service."}, {"lang": "es", "value": "Se presenta un fallo de segmentaci\u00f3n causado por una desreferencia de puntero null en Gpac versiones hasta 1.0.1, por medio de la funci\u00f3n naludmx_create_avc_decoder_config en el archivo reframe_nalu.c cuando es usado mp4box, que causa una denegaci\u00f3n de servicio"}], "evaluatorComment": null, "id": "CVE-2021-40563", "lastModified": "2023-05-27T04:15:16.293", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-01-12T22:15:07.807", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gpac/gpac/commit/5ce0c906ed8599d218036b18b78e8126a496f137"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/gpac/gpac/issues/1892"}, {"source": "cve@mitre.org", "tags": null, "url": "https://www.debian.org/security/2023/dsa-5411"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gpac/gpac/commit/5ce0c906ed8599d218036b18b78e8126a496f137"}, "type": "CWE-476"}
176
Determine whether the {function_name} code is vulnerable or not.
[ "<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n\t<PropertyGroup>\r\n\t\t<ProjectGuid>{838C77E9-8237-4097-964C-EBB952D2E9A8}</ProjectGuid>\r\n\t\t<ProjectVersion>15.4</ProjectVersion>\r\n\t\t<Config Condition=\"'$(Config)'==''\">Release</Config>\r\n\t\t<FrameworkType>None</FrameworkType>\r\n\t\t<Base>True</Base>\r\n\t\t<Platform Condition=\"'$(Platform)'==''\">Win32</Platform>\r\n\t\t<TargetedPlatforms>1</TargetedPlatforms>\r\n\t\t<AppType>Console</AppType>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Base' or '$(Base)'!=''\">\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Debug' or '$(Cfg_1)'!=''\">\r\n\t\t<Cfg_1>true</Cfg_1>\r\n\t\t<CfgParent>Base</CfgParent>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Release' or '$(Cfg_2)'!=''\">\r\n\t\t<Cfg_2>true</Cfg_2>\r\n\t\t<CfgParent>Base</CfgParent>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Base)'!=''\">\r\n\t\t<_TCHARMapping>wchar_t</_TCHARMapping>\r\n\t\t<AllPackageLibs>rtl.lib</AllPackageLibs>\r\n\t\t<BCC_AllWarnings>true</BCC_AllWarnings>\r\n\t\t<BCC_ExtendedErrorInfo>true</BCC_ExtendedErrorInfo>\r\n\t\t<BCC_OptimizeForSpeed>true</BCC_OptimizeForSpeed>\r\n\t\t<DCC_CBuilderOutput>JPHNE</DCC_CBuilderOutput>\r\n\t\t<DCC_Namespace>System;Xml;Data;Datasnap;Web;Soap;Vcl;$(DCC_Namespace)</DCC_Namespace>\r\n\t\t<FinalOutputDir>$(FINAL_PATH)\\$(Platform)\\$(Config)</FinalOutputDir>\r\n\t\t<ILINK_LibraryPath>console\\;$(ILINK_LibraryPath)</ILINK_LibraryPath>\r\n\t\t<IncludePath>console\\;$(BDS)\\include;$(BDS)\\include\\windows\\vcl;$(IncludePath)</IncludePath>\r\n\t\t<IntermediateOutputDir>$(INTERM_PATH)\\$(Platform)\\$(Config)</IntermediateOutputDir>\r\n\t\t<LinkPackageStatics>rtl.lib</LinkPackageStatics>\r\n\t\t<Manifest_File>None</Manifest_File>\r\n\t\t<Multithreaded>true</Multithreaded>\r\n\t\t<NoVCL>true</NoVCL>\r\n\t\t<OutputExt>com</OutputExt>\r\n\t\t<PackageImports>rtl.bpi;$(PackageImports)</PackageImports>\r\n\t\t<ProjectType>CppConsoleApplication</ProjectType>\r\n\t\t<SanitizedProjectName>Console</SanitizedProjectName>\r\n\t\t<VerInfo_IncludeVerInfo>true</VerInfo_IncludeVerInfo>\r", "\t\t<VerInfo_Keys>CompanyName=Martin Prikryl;FileDescription=Console interface for WinSCP;FileVersion=5.0.1.0;InternalName=console;LegalCopyright=(c) 2000-2020 Martin Prikryl;LegalTrademarks=;OriginalFilename=winscp.com;ProductName=WinSCP;ProductVersion=5.17.10.0;ReleaseType=stable;WWW=https://winscp.net/</VerInfo_Keys>\r", "\t\t<VerInfo_Locale>1033</VerInfo_Locale>\r\n\t\t<VerInfo_MajorVer>5</VerInfo_MajorVer>\r\n\t\t<VerInfo_MinorVer>0</VerInfo_MinorVer>\r\n\t\t<VerInfo_Release>1</VerInfo_Release>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_1)'!=''\">\r\n\t\t<BCC_DebugLineNumbers>true</BCC_DebugLineNumbers>\r\n\t\t<BCC_DisableOptimizations>true</BCC_DisableOptimizations>\r\n\t\t<BCC_InlineFunctionExpansion>false</BCC_InlineFunctionExpansion>\r\n\t\t<BCC_OptimizeForSpeed>false</BCC_OptimizeForSpeed>\r\n\t\t<BCC_SourceDebuggingOn>true</BCC_SourceDebuggingOn>\r\n\t\t<BCC_StackFrames>true</BCC_StackFrames>\r\n\t\t<BCC_UseRegisterVariables>None</BCC_UseRegisterVariables>\r\n\t\t<DCC_DebugInfoInExe>true</DCC_DebugInfoInExe>\r\n\t\t<DCC_Define>DEBUG</DCC_Define>\r\n\t\t<DCC_Optimize>false</DCC_Optimize>\r\n\t\t<Defines>_DEBUG;$(Defines)</Defines>\r\n\t\t<ILINK_FullDebugInfo>true</ILINK_FullDebugInfo>\r\n\t\t<TASM_Debugging>Full</TASM_Debugging>\r\n\t\t<TASM_DisplaySourceLines>true</TASM_DisplaySourceLines>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_2)'!=''\">\r\n\t\t<Defines>NDEBUG;$(Defines)</Defines>\r\n\t\t<TASM_Debugging>None</TASM_Debugging>\r\n\t</PropertyGroup>\r\n\t<ItemGroup>\r\n\t\t<CppCompile Include=\"console\\Main.cpp\">\r\n\t\t\t<BuildOrder>8</BuildOrder>\r\n\t\t\t<BuildOrder>0</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<BuildConfiguration Include=\"Base\">\r\n\t\t\t<Key>Base</Key>\r\n\t\t</BuildConfiguration>\r\n\t\t<BuildConfiguration Include=\"Debug\">\r\n\t\t\t<Key>Cfg_1</Key>\r\n\t\t\t<CfgParent>Base</CfgParent>\r\n\t\t</BuildConfiguration>\r\n\t\t<BuildConfiguration Include=\"Release\">\r\n\t\t\t<Key>Cfg_2</Key>\r\n\t\t\t<CfgParent>Base</CfgParent>\r\n\t\t</BuildConfiguration>\r\n\t</ItemGroup>\r\n\t<Import Condition=\"Exists('$(BDS)\\Bin\\CodeGear.Cpp.Targets')\" Project=\"$(BDS)\\Bin\\CodeGear.Cpp.Targets\"/>\r\n\t<PropertyGroup Condition=\"'$(FileToCompile)'==''\">\r\n\t\t<PostBuildEvent>if exist \"$(FinalOutputDir)\\Console.com\" (\r\ncopy /y \"$(FinalOutputDir)\\Console.com\" \"$(FinalOutputDir)\\WinSCP.com\"\r\n) else (\r\nexit 0\r\n)</PostBuildEvent>\r\n\t</PropertyGroup>\r\n\t<ProjectExtensions>\r\n\t\t<Borland.Personality>CPlusPlusBuilder.Personality.12</Borland.Personality>\r\n\t\t<Borland.ProjectType>CppConsoleApplication</Borland.ProjectType>\r\n\t\t<BorlandProject>\r\n\t\t\t<CPlusPlusBuilder.Personality>\r\n\t\t\t\t<ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"AutoShowDeps\">False</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"ManagePaths\">True</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"VerifyPackages\">True</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"IndexFiles\">False</ProjectProperties>\r\n\t\t\t\t</ProjectProperties>\r\n\t\t\t</CPlusPlusBuilder.Personality>\r\n\t\t\t<Platforms>\r\n\t\t\t\t<Platform value=\"Win32\">True</Platform>\r\n\t\t\t\t<Platform value=\"Win64\">False</Platform>\r\n\t\t\t</Platforms>\r\n\t\t</BorlandProject>\r\n\t\t<ProjectFileVersion>12</ProjectFileVersion>\r\n\t</ProjectExtensions>\r\n\t<Import Condition=\"Exists('$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj')\" Project=\"$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj\"/>\r\n</Project>" ]
[ 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 53, 80, 2275, 473, 1511, 2372, 1100], "buggy_code_start_loc": [46, 52, 79, 599, 57, 1510, 2371, 1099], "filenames": ["source/Console.cbproj", "source/DragExt.cbproj", "source/WinSCP.cbproj", "source/core/SessionData.cpp", "source/core/SessionData.h", "source/forms/Custom.cpp", "source/windows/ConsoleRunner.cpp", "source/windows/WinMain.cpp"], "fixing_code_end_loc": [47, 53, 80, 2294, 474, 1511, 2372, 1103], "fixing_code_start_loc": [46, 52, 79, 599, 58, 1510, 2371, 1099], "message": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:winscp:winscp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C081564B-8EF8-4C8A-9EB0-1C50D5A8F18B", "versionEndExcluding": "5.17.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)"}, {"lang": "es", "value": "WinSCP anterior a la versi\u00f3n 5.17.10 permite a los atacantes remotos ejecutar programas arbitrarios cuando el manejador de URLs encuentra una URL manipulada que carga la configuraci\u00f3n de la sesi\u00f3n. (Por ejemplo, esto es explotable en una instalaci\u00f3n por defecto en la que WinSCP es el manejador de URLs sftp://)"}], "evaluatorComment": null, "id": "CVE-2021-3331", "lastModified": "2021-02-04T15:59:24.960", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-01-27T21:15:16.840", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://winscp.net/eng/docs/history#5.17.10"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://winscp.net/eng/docs/rawsettings"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://winscp.net/tracker/1943"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, "type": "NVD-CWE-Other"}
177
Determine whether the {function_name} code is vulnerable or not.
[ "<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n\t<PropertyGroup>\r\n\t\t<ProjectGuid>{838C77E9-8237-4097-964C-EBB952D2E9A8}</ProjectGuid>\r\n\t\t<ProjectVersion>15.4</ProjectVersion>\r\n\t\t<Config Condition=\"'$(Config)'==''\">Release</Config>\r\n\t\t<FrameworkType>None</FrameworkType>\r\n\t\t<Base>True</Base>\r\n\t\t<Platform Condition=\"'$(Platform)'==''\">Win32</Platform>\r\n\t\t<TargetedPlatforms>1</TargetedPlatforms>\r\n\t\t<AppType>Console</AppType>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Base' or '$(Base)'!=''\">\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Debug' or '$(Cfg_1)'!=''\">\r\n\t\t<Cfg_1>true</Cfg_1>\r\n\t\t<CfgParent>Base</CfgParent>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Release' or '$(Cfg_2)'!=''\">\r\n\t\t<Cfg_2>true</Cfg_2>\r\n\t\t<CfgParent>Base</CfgParent>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Base)'!=''\">\r\n\t\t<_TCHARMapping>wchar_t</_TCHARMapping>\r\n\t\t<AllPackageLibs>rtl.lib</AllPackageLibs>\r\n\t\t<BCC_AllWarnings>true</BCC_AllWarnings>\r\n\t\t<BCC_ExtendedErrorInfo>true</BCC_ExtendedErrorInfo>\r\n\t\t<BCC_OptimizeForSpeed>true</BCC_OptimizeForSpeed>\r\n\t\t<DCC_CBuilderOutput>JPHNE</DCC_CBuilderOutput>\r\n\t\t<DCC_Namespace>System;Xml;Data;Datasnap;Web;Soap;Vcl;$(DCC_Namespace)</DCC_Namespace>\r\n\t\t<FinalOutputDir>$(FINAL_PATH)\\$(Platform)\\$(Config)</FinalOutputDir>\r\n\t\t<ILINK_LibraryPath>console\\;$(ILINK_LibraryPath)</ILINK_LibraryPath>\r\n\t\t<IncludePath>console\\;$(BDS)\\include;$(BDS)\\include\\windows\\vcl;$(IncludePath)</IncludePath>\r\n\t\t<IntermediateOutputDir>$(INTERM_PATH)\\$(Platform)\\$(Config)</IntermediateOutputDir>\r\n\t\t<LinkPackageStatics>rtl.lib</LinkPackageStatics>\r\n\t\t<Manifest_File>None</Manifest_File>\r\n\t\t<Multithreaded>true</Multithreaded>\r\n\t\t<NoVCL>true</NoVCL>\r\n\t\t<OutputExt>com</OutputExt>\r\n\t\t<PackageImports>rtl.bpi;$(PackageImports)</PackageImports>\r\n\t\t<ProjectType>CppConsoleApplication</ProjectType>\r\n\t\t<SanitizedProjectName>Console</SanitizedProjectName>\r\n\t\t<VerInfo_IncludeVerInfo>true</VerInfo_IncludeVerInfo>\r", "\t\t<VerInfo_Keys>CompanyName=Martin Prikryl;FileDescription=Console interface for WinSCP;FileVersion=5.0.1.0;InternalName=console;LegalCopyright=(c) 2000-2021 Martin Prikryl;LegalTrademarks=;OriginalFilename=winscp.com;ProductName=WinSCP;ProductVersion=5.17.10.0;ReleaseType=stable;WWW=https://winscp.net/</VerInfo_Keys>\r", "\t\t<VerInfo_Locale>1033</VerInfo_Locale>\r\n\t\t<VerInfo_MajorVer>5</VerInfo_MajorVer>\r\n\t\t<VerInfo_MinorVer>0</VerInfo_MinorVer>\r\n\t\t<VerInfo_Release>1</VerInfo_Release>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_1)'!=''\">\r\n\t\t<BCC_DebugLineNumbers>true</BCC_DebugLineNumbers>\r\n\t\t<BCC_DisableOptimizations>true</BCC_DisableOptimizations>\r\n\t\t<BCC_InlineFunctionExpansion>false</BCC_InlineFunctionExpansion>\r\n\t\t<BCC_OptimizeForSpeed>false</BCC_OptimizeForSpeed>\r\n\t\t<BCC_SourceDebuggingOn>true</BCC_SourceDebuggingOn>\r\n\t\t<BCC_StackFrames>true</BCC_StackFrames>\r\n\t\t<BCC_UseRegisterVariables>None</BCC_UseRegisterVariables>\r\n\t\t<DCC_DebugInfoInExe>true</DCC_DebugInfoInExe>\r\n\t\t<DCC_Define>DEBUG</DCC_Define>\r\n\t\t<DCC_Optimize>false</DCC_Optimize>\r\n\t\t<Defines>_DEBUG;$(Defines)</Defines>\r\n\t\t<ILINK_FullDebugInfo>true</ILINK_FullDebugInfo>\r\n\t\t<TASM_Debugging>Full</TASM_Debugging>\r\n\t\t<TASM_DisplaySourceLines>true</TASM_DisplaySourceLines>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_2)'!=''\">\r\n\t\t<Defines>NDEBUG;$(Defines)</Defines>\r\n\t\t<TASM_Debugging>None</TASM_Debugging>\r\n\t</PropertyGroup>\r\n\t<ItemGroup>\r\n\t\t<CppCompile Include=\"console\\Main.cpp\">\r\n\t\t\t<BuildOrder>8</BuildOrder>\r\n\t\t\t<BuildOrder>0</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<BuildConfiguration Include=\"Base\">\r\n\t\t\t<Key>Base</Key>\r\n\t\t</BuildConfiguration>\r\n\t\t<BuildConfiguration Include=\"Debug\">\r\n\t\t\t<Key>Cfg_1</Key>\r\n\t\t\t<CfgParent>Base</CfgParent>\r\n\t\t</BuildConfiguration>\r\n\t\t<BuildConfiguration Include=\"Release\">\r\n\t\t\t<Key>Cfg_2</Key>\r\n\t\t\t<CfgParent>Base</CfgParent>\r\n\t\t</BuildConfiguration>\r\n\t</ItemGroup>\r\n\t<Import Condition=\"Exists('$(BDS)\\Bin\\CodeGear.Cpp.Targets')\" Project=\"$(BDS)\\Bin\\CodeGear.Cpp.Targets\"/>\r\n\t<PropertyGroup Condition=\"'$(FileToCompile)'==''\">\r\n\t\t<PostBuildEvent>if exist \"$(FinalOutputDir)\\Console.com\" (\r\ncopy /y \"$(FinalOutputDir)\\Console.com\" \"$(FinalOutputDir)\\WinSCP.com\"\r\n) else (\r\nexit 0\r\n)</PostBuildEvent>\r\n\t</PropertyGroup>\r\n\t<ProjectExtensions>\r\n\t\t<Borland.Personality>CPlusPlusBuilder.Personality.12</Borland.Personality>\r\n\t\t<Borland.ProjectType>CppConsoleApplication</Borland.ProjectType>\r\n\t\t<BorlandProject>\r\n\t\t\t<CPlusPlusBuilder.Personality>\r\n\t\t\t\t<ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"AutoShowDeps\">False</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"ManagePaths\">True</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"VerifyPackages\">True</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"IndexFiles\">False</ProjectProperties>\r\n\t\t\t\t</ProjectProperties>\r\n\t\t\t</CPlusPlusBuilder.Personality>\r\n\t\t\t<Platforms>\r\n\t\t\t\t<Platform value=\"Win32\">True</Platform>\r\n\t\t\t\t<Platform value=\"Win64\">False</Platform>\r\n\t\t\t</Platforms>\r\n\t\t</BorlandProject>\r\n\t\t<ProjectFileVersion>12</ProjectFileVersion>\r\n\t</ProjectExtensions>\r\n\t<Import Condition=\"Exists('$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj')\" Project=\"$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj\"/>\r\n</Project>" ]
[ 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 53, 80, 2275, 473, 1511, 2372, 1100], "buggy_code_start_loc": [46, 52, 79, 599, 57, 1510, 2371, 1099], "filenames": ["source/Console.cbproj", "source/DragExt.cbproj", "source/WinSCP.cbproj", "source/core/SessionData.cpp", "source/core/SessionData.h", "source/forms/Custom.cpp", "source/windows/ConsoleRunner.cpp", "source/windows/WinMain.cpp"], "fixing_code_end_loc": [47, 53, 80, 2294, 474, 1511, 2372, 1103], "fixing_code_start_loc": [46, 52, 79, 599, 58, 1510, 2371, 1099], "message": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:winscp:winscp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C081564B-8EF8-4C8A-9EB0-1C50D5A8F18B", "versionEndExcluding": "5.17.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)"}, {"lang": "es", "value": "WinSCP anterior a la versi\u00f3n 5.17.10 permite a los atacantes remotos ejecutar programas arbitrarios cuando el manejador de URLs encuentra una URL manipulada que carga la configuraci\u00f3n de la sesi\u00f3n. (Por ejemplo, esto es explotable en una instalaci\u00f3n por defecto en la que WinSCP es el manejador de URLs sftp://)"}], "evaluatorComment": null, "id": "CVE-2021-3331", "lastModified": "2021-02-04T15:59:24.960", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-01-27T21:15:16.840", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://winscp.net/eng/docs/history#5.17.10"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://winscp.net/eng/docs/rawsettings"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://winscp.net/tracker/1943"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, "type": "NVD-CWE-Other"}
177
Determine whether the {function_name} code is vulnerable or not.
[ "<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n\t<PropertyGroup>\r\n\t\t<ProjectGuid>{414309A3-9B7C-4261-9989-4BC118D3A1C0}</ProjectGuid>\r\n\t\t<ProjectVersion>15.4</ProjectVersion>\r\n\t\t<Config Condition=\"'$(Config)'==''\">Release</Config>\r\n\t\t<FrameworkType>None</FrameworkType>\r\n\t\t<Base>True</Base>\r\n\t\t<Platform Condition=\"'$(Platform)'==''\">Win32</Platform>\r\n\t\t<TargetedPlatforms>3</TargetedPlatforms>\r\n\t\t<AppType>Library</AppType>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Base' or '$(Base)'!=''\">\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"('$(Platform)'=='Win64' and '$(Base)'=='true') or '$(Base_Win64)'!=''\">\r\n\t\t<Base_Win64>true</Base_Win64>\r\n\t\t<CfgParent>Base</CfgParent>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Debug' or '$(Cfg_1)'!=''\">\r\n\t\t<Cfg_1>true</Cfg_1>\r\n\t\t<CfgParent>Base</CfgParent>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Release' or '$(Cfg_2)'!=''\">\r\n\t\t<Cfg_2>true</Cfg_2>\r\n\t\t<CfgParent>Base</CfgParent>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Base)'!=''\">\r\n\t\t<_TCHARMapping>wchar_t</_TCHARMapping>\r\n\t\t<BCC_AllWarnings>true</BCC_AllWarnings>\r\n\t\t<BCC_ExtendedErrorInfo>true</BCC_ExtendedErrorInfo>\r\n\t\t<BCC_OptimizeForSpeed>true</BCC_OptimizeForSpeed>\r\n\t\t<BCC_wdlx>false</BCC_wdlx>\r\n\t\t<DCC_CBuilderOutput>JPHNE</DCC_CBuilderOutput>\r\n\t\t<DCC_Namespace>System;Xml;Data;Datasnap;Web;Soap;Vcl;$(DCC_Namespace)</DCC_Namespace>\r\n\t\t<FinalOutputDir>$(FINAL_PATH)\\$(Platform)\\$(Config)</FinalOutputDir>\r\n\t\t<ILINK_GenerateImportLibrary>true</ILINK_GenerateImportLibrary>\r\n\t\t<ILINK_LibraryPath>dragext\\;$(BDS)\\lib;$(BDS)\\lib\\obj;$(BDS)\\lib\\psdk;$(ILINK_LibraryPath)</ILINK_LibraryPath>\r\n\t\t<IncludePath>dragext\\;$(BDS)\\include;$(BDS)\\include\\windows\\vcl;$(IncludePath)</IncludePath>\r\n\t\t<IntermediateOutputDir>$(INTERM_PATH)\\$(Platform)\\$(Config)</IntermediateOutputDir>\r\n\t\t<Manifest_File>None</Manifest_File>\r\n\t\t<Multithreaded>true</Multithreaded>\r\n\t\t<NoVCL>true</NoVCL>\r\n\t\t<OutputExt>dll</OutputExt>\r\n\t\t<PackageImports>rtl.bpi;$(PackageImports)</PackageImports>\r\n\t\t<ProjectType>CppDynamicLibrary</ProjectType>\r\n\t\t<SanitizedProjectName>DragExt</SanitizedProjectName>\r\n\t\t<VerInfo_DLL>true</VerInfo_DLL>\r\n\t\t<VerInfo_IncludeVerInfo>true</VerInfo_IncludeVerInfo>\r", "\t\t<VerInfo_Keys>CompanyName=Martin Prikryl;FileDescription=Drag&amp;Drop shell extension for WinSCP ($(Platform));FileVersion=2.0.0.0;InternalName=dragext;LegalCopyright=(c) 2000-2020 Martin Prikryl;LegalTrademarks=;OriginalFilename=dragext.dll;ProductName=WinSCP;ProductVersion=5.17.10.0;ReleaseType=stable;WWW=https://winscp.net/</VerInfo_Keys>\r", "\t\t<VerInfo_Locale>1033</VerInfo_Locale>\r\n\t\t<VerInfo_MajorVer>2</VerInfo_MajorVer>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Base_Win64)'!=''\">\r\n\t\t<OutputName>DragExt64</OutputName>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_1)'!=''\">\r\n\t\t<BCC_DebugLineNumbers>true</BCC_DebugLineNumbers>\r\n\t\t<BCC_DisableOptimizations>true</BCC_DisableOptimizations>\r\n\t\t<BCC_InlineFunctionExpansion>false</BCC_InlineFunctionExpansion>\r\n\t\t<BCC_OptimizeForSpeed>false</BCC_OptimizeForSpeed>\r\n\t\t<BCC_SourceDebuggingOn>true</BCC_SourceDebuggingOn>\r\n\t\t<BCC_StackFrames>true</BCC_StackFrames>\r\n\t\t<BCC_UseRegisterVariables>None</BCC_UseRegisterVariables>\r\n\t\t<DCC_DebugInfoInExe>true</DCC_DebugInfoInExe>\r\n\t\t<DCC_Define>DEBUG</DCC_Define>\r\n\t\t<DCC_Optimize>false</DCC_Optimize>\r\n\t\t<Defines>_DEBUG;$(Defines)</Defines>\r\n\t\t<ILINK_FullDebugInfo>true</ILINK_FullDebugInfo>\r\n\t\t<TASM_Debugging>Full</TASM_Debugging>\r\n\t\t<TASM_DisplaySourceLines>true</TASM_DisplaySourceLines>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_2)'!=''\">\r\n\t\t<Defines>NDEBUG;$(Defines)</Defines>\r\n\t\t<TASM_Debugging>None</TASM_Debugging>\r\n\t</PropertyGroup>\r\n\t<ItemGroup>\r\n\t\t<CppCompile Include=\"dragext\\DragExt.cpp\">\r\n\t\t\t<BuildOrder>5</BuildOrder>\r\n\t\t\t<BuildOrder>1</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<BuildConfiguration Include=\"Base\">\r\n\t\t\t<Key>Base</Key>\r\n\t\t</BuildConfiguration>\r\n\t\t<BuildConfiguration Include=\"Debug\">\r\n\t\t\t<Key>Cfg_1</Key>\r\n\t\t\t<CfgParent>Base</CfgParent>\r\n\t\t</BuildConfiguration>\r\n\t\t<BuildConfiguration Include=\"Release\">\r\n\t\t\t<Key>Cfg_2</Key>\r\n\t\t\t<CfgParent>Base</CfgParent>\r\n\t\t</BuildConfiguration>\r\n\t</ItemGroup>\r\n\t<Import Condition=\"Exists('$(BDS)\\Bin\\CodeGear.Cpp.Targets')\" Project=\"$(BDS)\\Bin\\CodeGear.Cpp.Targets\"/>\r\n\t<ProjectExtensions>\r\n\t\t<Borland.Personality>CPlusPlusBuilder.Personality.12</Borland.Personality>\r\n\t\t<Borland.ProjectType>CppDynamicLibrary</Borland.ProjectType>\r\n\t\t<BorlandProject>\r\n\t\t\t<CPlusPlusBuilder.Personality>\r\n\t\t\t\t<ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"AutoShowDeps\">False</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"ManagePaths\">True</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"VerifyPackages\">True</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"IndexFiles\">False</ProjectProperties>\r\n\t\t\t\t</ProjectProperties>\r\n\t\t\t</CPlusPlusBuilder.Personality>\r\n\t\t\t<Platforms>\r\n\t\t\t\t<Platform value=\"Win32\">True</Platform>\r\n\t\t\t\t<Platform value=\"Win64\">True</Platform>\r\n\t\t\t</Platforms>\r\n\t\t</BorlandProject>\r\n\t\t<ProjectFileVersion>12</ProjectFileVersion>\r\n\t</ProjectExtensions>\r\n\t<Import Condition=\"Exists('$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj')\" Project=\"$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj\"/>\r\n</Project>" ]
[ 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 53, 80, 2275, 473, 1511, 2372, 1100], "buggy_code_start_loc": [46, 52, 79, 599, 57, 1510, 2371, 1099], "filenames": ["source/Console.cbproj", "source/DragExt.cbproj", "source/WinSCP.cbproj", "source/core/SessionData.cpp", "source/core/SessionData.h", "source/forms/Custom.cpp", "source/windows/ConsoleRunner.cpp", "source/windows/WinMain.cpp"], "fixing_code_end_loc": [47, 53, 80, 2294, 474, 1511, 2372, 1103], "fixing_code_start_loc": [46, 52, 79, 599, 58, 1510, 2371, 1099], "message": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:winscp:winscp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C081564B-8EF8-4C8A-9EB0-1C50D5A8F18B", "versionEndExcluding": "5.17.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)"}, {"lang": "es", "value": "WinSCP anterior a la versi\u00f3n 5.17.10 permite a los atacantes remotos ejecutar programas arbitrarios cuando el manejador de URLs encuentra una URL manipulada que carga la configuraci\u00f3n de la sesi\u00f3n. (Por ejemplo, esto es explotable en una instalaci\u00f3n por defecto en la que WinSCP es el manejador de URLs sftp://)"}], "evaluatorComment": null, "id": "CVE-2021-3331", "lastModified": "2021-02-04T15:59:24.960", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-01-27T21:15:16.840", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://winscp.net/eng/docs/history#5.17.10"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://winscp.net/eng/docs/rawsettings"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://winscp.net/tracker/1943"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, "type": "NVD-CWE-Other"}
177
Determine whether the {function_name} code is vulnerable or not.
[ "<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n\t<PropertyGroup>\r\n\t\t<ProjectGuid>{414309A3-9B7C-4261-9989-4BC118D3A1C0}</ProjectGuid>\r\n\t\t<ProjectVersion>15.4</ProjectVersion>\r\n\t\t<Config Condition=\"'$(Config)'==''\">Release</Config>\r\n\t\t<FrameworkType>None</FrameworkType>\r\n\t\t<Base>True</Base>\r\n\t\t<Platform Condition=\"'$(Platform)'==''\">Win32</Platform>\r\n\t\t<TargetedPlatforms>3</TargetedPlatforms>\r\n\t\t<AppType>Library</AppType>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Base' or '$(Base)'!=''\">\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"('$(Platform)'=='Win64' and '$(Base)'=='true') or '$(Base_Win64)'!=''\">\r\n\t\t<Base_Win64>true</Base_Win64>\r\n\t\t<CfgParent>Base</CfgParent>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Debug' or '$(Cfg_1)'!=''\">\r\n\t\t<Cfg_1>true</Cfg_1>\r\n\t\t<CfgParent>Base</CfgParent>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Release' or '$(Cfg_2)'!=''\">\r\n\t\t<Cfg_2>true</Cfg_2>\r\n\t\t<CfgParent>Base</CfgParent>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Base)'!=''\">\r\n\t\t<_TCHARMapping>wchar_t</_TCHARMapping>\r\n\t\t<BCC_AllWarnings>true</BCC_AllWarnings>\r\n\t\t<BCC_ExtendedErrorInfo>true</BCC_ExtendedErrorInfo>\r\n\t\t<BCC_OptimizeForSpeed>true</BCC_OptimizeForSpeed>\r\n\t\t<BCC_wdlx>false</BCC_wdlx>\r\n\t\t<DCC_CBuilderOutput>JPHNE</DCC_CBuilderOutput>\r\n\t\t<DCC_Namespace>System;Xml;Data;Datasnap;Web;Soap;Vcl;$(DCC_Namespace)</DCC_Namespace>\r\n\t\t<FinalOutputDir>$(FINAL_PATH)\\$(Platform)\\$(Config)</FinalOutputDir>\r\n\t\t<ILINK_GenerateImportLibrary>true</ILINK_GenerateImportLibrary>\r\n\t\t<ILINK_LibraryPath>dragext\\;$(BDS)\\lib;$(BDS)\\lib\\obj;$(BDS)\\lib\\psdk;$(ILINK_LibraryPath)</ILINK_LibraryPath>\r\n\t\t<IncludePath>dragext\\;$(BDS)\\include;$(BDS)\\include\\windows\\vcl;$(IncludePath)</IncludePath>\r\n\t\t<IntermediateOutputDir>$(INTERM_PATH)\\$(Platform)\\$(Config)</IntermediateOutputDir>\r\n\t\t<Manifest_File>None</Manifest_File>\r\n\t\t<Multithreaded>true</Multithreaded>\r\n\t\t<NoVCL>true</NoVCL>\r\n\t\t<OutputExt>dll</OutputExt>\r\n\t\t<PackageImports>rtl.bpi;$(PackageImports)</PackageImports>\r\n\t\t<ProjectType>CppDynamicLibrary</ProjectType>\r\n\t\t<SanitizedProjectName>DragExt</SanitizedProjectName>\r\n\t\t<VerInfo_DLL>true</VerInfo_DLL>\r\n\t\t<VerInfo_IncludeVerInfo>true</VerInfo_IncludeVerInfo>\r", "\t\t<VerInfo_Keys>CompanyName=Martin Prikryl;FileDescription=Drag&amp;Drop shell extension for WinSCP ($(Platform));FileVersion=2.0.0.0;InternalName=dragext;LegalCopyright=(c) 2000-2021 Martin Prikryl;LegalTrademarks=;OriginalFilename=dragext.dll;ProductName=WinSCP;ProductVersion=5.17.10.0;ReleaseType=stable;WWW=https://winscp.net/</VerInfo_Keys>\r", "\t\t<VerInfo_Locale>1033</VerInfo_Locale>\r\n\t\t<VerInfo_MajorVer>2</VerInfo_MajorVer>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Base_Win64)'!=''\">\r\n\t\t<OutputName>DragExt64</OutputName>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_1)'!=''\">\r\n\t\t<BCC_DebugLineNumbers>true</BCC_DebugLineNumbers>\r\n\t\t<BCC_DisableOptimizations>true</BCC_DisableOptimizations>\r\n\t\t<BCC_InlineFunctionExpansion>false</BCC_InlineFunctionExpansion>\r\n\t\t<BCC_OptimizeForSpeed>false</BCC_OptimizeForSpeed>\r\n\t\t<BCC_SourceDebuggingOn>true</BCC_SourceDebuggingOn>\r\n\t\t<BCC_StackFrames>true</BCC_StackFrames>\r\n\t\t<BCC_UseRegisterVariables>None</BCC_UseRegisterVariables>\r\n\t\t<DCC_DebugInfoInExe>true</DCC_DebugInfoInExe>\r\n\t\t<DCC_Define>DEBUG</DCC_Define>\r\n\t\t<DCC_Optimize>false</DCC_Optimize>\r\n\t\t<Defines>_DEBUG;$(Defines)</Defines>\r\n\t\t<ILINK_FullDebugInfo>true</ILINK_FullDebugInfo>\r\n\t\t<TASM_Debugging>Full</TASM_Debugging>\r\n\t\t<TASM_DisplaySourceLines>true</TASM_DisplaySourceLines>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_2)'!=''\">\r\n\t\t<Defines>NDEBUG;$(Defines)</Defines>\r\n\t\t<TASM_Debugging>None</TASM_Debugging>\r\n\t</PropertyGroup>\r\n\t<ItemGroup>\r\n\t\t<CppCompile Include=\"dragext\\DragExt.cpp\">\r\n\t\t\t<BuildOrder>5</BuildOrder>\r\n\t\t\t<BuildOrder>1</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<BuildConfiguration Include=\"Base\">\r\n\t\t\t<Key>Base</Key>\r\n\t\t</BuildConfiguration>\r\n\t\t<BuildConfiguration Include=\"Debug\">\r\n\t\t\t<Key>Cfg_1</Key>\r\n\t\t\t<CfgParent>Base</CfgParent>\r\n\t\t</BuildConfiguration>\r\n\t\t<BuildConfiguration Include=\"Release\">\r\n\t\t\t<Key>Cfg_2</Key>\r\n\t\t\t<CfgParent>Base</CfgParent>\r\n\t\t</BuildConfiguration>\r\n\t</ItemGroup>\r\n\t<Import Condition=\"Exists('$(BDS)\\Bin\\CodeGear.Cpp.Targets')\" Project=\"$(BDS)\\Bin\\CodeGear.Cpp.Targets\"/>\r\n\t<ProjectExtensions>\r\n\t\t<Borland.Personality>CPlusPlusBuilder.Personality.12</Borland.Personality>\r\n\t\t<Borland.ProjectType>CppDynamicLibrary</Borland.ProjectType>\r\n\t\t<BorlandProject>\r\n\t\t\t<CPlusPlusBuilder.Personality>\r\n\t\t\t\t<ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"AutoShowDeps\">False</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"ManagePaths\">True</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"VerifyPackages\">True</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"IndexFiles\">False</ProjectProperties>\r\n\t\t\t\t</ProjectProperties>\r\n\t\t\t</CPlusPlusBuilder.Personality>\r\n\t\t\t<Platforms>\r\n\t\t\t\t<Platform value=\"Win32\">True</Platform>\r\n\t\t\t\t<Platform value=\"Win64\">True</Platform>\r\n\t\t\t</Platforms>\r\n\t\t</BorlandProject>\r\n\t\t<ProjectFileVersion>12</ProjectFileVersion>\r\n\t</ProjectExtensions>\r\n\t<Import Condition=\"Exists('$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj')\" Project=\"$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj\"/>\r\n</Project>" ]
[ 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 53, 80, 2275, 473, 1511, 2372, 1100], "buggy_code_start_loc": [46, 52, 79, 599, 57, 1510, 2371, 1099], "filenames": ["source/Console.cbproj", "source/DragExt.cbproj", "source/WinSCP.cbproj", "source/core/SessionData.cpp", "source/core/SessionData.h", "source/forms/Custom.cpp", "source/windows/ConsoleRunner.cpp", "source/windows/WinMain.cpp"], "fixing_code_end_loc": [47, 53, 80, 2294, 474, 1511, 2372, 1103], "fixing_code_start_loc": [46, 52, 79, 599, 58, 1510, 2371, 1099], "message": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:winscp:winscp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C081564B-8EF8-4C8A-9EB0-1C50D5A8F18B", "versionEndExcluding": "5.17.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)"}, {"lang": "es", "value": "WinSCP anterior a la versi\u00f3n 5.17.10 permite a los atacantes remotos ejecutar programas arbitrarios cuando el manejador de URLs encuentra una URL manipulada que carga la configuraci\u00f3n de la sesi\u00f3n. (Por ejemplo, esto es explotable en una instalaci\u00f3n por defecto en la que WinSCP es el manejador de URLs sftp://)"}], "evaluatorComment": null, "id": "CVE-2021-3331", "lastModified": "2021-02-04T15:59:24.960", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-01-27T21:15:16.840", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://winscp.net/eng/docs/history#5.17.10"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://winscp.net/eng/docs/rawsettings"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://winscp.net/tracker/1943"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, "type": "NVD-CWE-Other"}
177
Determine whether the {function_name} code is vulnerable or not.
[ "<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n\t<PropertyGroup>\r\n\t\t<ProjectGuid>{0B0C5EC6-5DCB-4F16-9504-1E6D37FFBB77}</ProjectGuid>\r\n\t\t<ProjectVersion>15.4</ProjectVersion>\r\n\t\t<MainSource>WinSCP.cpp</MainSource>\r\n\t\t<Config Condition=\"'$(Config)'==''\">Release</Config>\r\n\t\t<FrameworkType>VCL</FrameworkType>\r\n\t\t<Base>True</Base>\r\n\t\t<Platform Condition=\"'$(Platform)'==''\">Win32</Platform>\r\n\t\t<TargetedPlatforms>1</TargetedPlatforms>\r\n\t\t<AppType>Application</AppType>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Base' or '$(Base)'!=''\">\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Debug' or '$(Cfg_1)'!=''\">\r\n\t\t<Cfg_1>true</Cfg_1>\r\n\t\t<CfgParent>Base</CfgParent>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"('$(Platform)'=='Win32' and '$(Cfg_1)'=='true') or '$(Cfg_1_Win32)'!=''\">\r\n\t\t<Cfg_1_Win32>true</Cfg_1_Win32>\r\n\t\t<CfgParent>Cfg_1</CfgParent>\r\n\t\t<Cfg_1>true</Cfg_1>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"('$(Platform)'=='Win64' and '$(Cfg_1)'=='true') or '$(Cfg_1_Win64)'!=''\">\r\n\t\t<Cfg_1_Win64>true</Cfg_1_Win64>\r\n\t\t<CfgParent>Cfg_1</CfgParent>\r\n\t\t<Cfg_1>true</Cfg_1>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Release' or '$(Cfg_2)'!=''\">\r\n\t\t<Cfg_2>true</Cfg_2>\r\n\t\t<CfgParent>Base</CfgParent>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"('$(Platform)'=='Win32' and '$(Cfg_2)'=='true') or '$(Cfg_2_Win32)'!=''\">\r\n\t\t<Cfg_2_Win32>true</Cfg_2_Win32>\r\n\t\t<CfgParent>Cfg_2</CfgParent>\r\n\t\t<Cfg_2>true</Cfg_2>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"('$(Platform)'=='Win64' and '$(Cfg_2)'=='true') or '$(Cfg_2_Win64)'!=''\">\r\n\t\t<Cfg_2_Win64>true</Cfg_2_Win64>\r\n\t\t<CfgParent>Cfg_2</CfgParent>\r\n\t\t<Cfg_2>true</Cfg_2>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Base)'!=''\">\r\n\t\t<_TCHARMapping>wchar_t</_TCHARMapping>\r\n\t\t<AllPackageLibs>vcl.lib;rtl.lib;vclx.lib;ws2_32.lib;secur32.lib;My.lib;DriveDir.lib;DragDropP.lib;tb2k.lib;tbxp.lib;bcbie.lib;Crypt32.lib;PngComponents.lib;xmlrtl.lib;vclactnband.lib;vclimg.lib;winhttp.lib;jcl.lib;vclie.lib;urlmon.lib;shlwapi.lib;powrprof.lib;soaprtl.lib;fmx.lib;dbrtl.lib;inet.lib</AllPackageLibs>\r\n\t\t<BCC_AllWarnings>true</BCC_AllWarnings>\r\n\t\t<BCC_ExtendedErrorInfo>true</BCC_ExtendedErrorInfo>\r\n\t\t<BCC_OptimizeForSpeed>true</BCC_OptimizeForSpeed>\r\n\t\t<BCC_wdiu>false</BCC_wdiu>\r\n\t\t<BRCC_CodePage>65001</BRCC_CodePage>\r\n\t\t<DCC_CBuilderOutput>JPHNE</DCC_CBuilderOutput>\r\n\t\t<DCC_Namespace>Vcl;Vcl.Imaging;Vcl.Touch;Vcl.Samples;Vcl.Shell;System;Xml;Data;Datasnap;Web;Soap;Vcl;$(DCC_Namespace)</DCC_Namespace>\r\n\t\t<DCC_SYMBOL_DEPRECATED>false</DCC_SYMBOL_DEPRECATED>\r\n\t\t<DCC_SYMBOL_PLATFORM>false</DCC_SYMBOL_PLATFORM>\r\n\t\t<DCC_UNSUPPORTED_CONSTRUCT>false</DCC_UNSUPPORTED_CONSTRUCT>\r\n\t\t<Defines>STRICT;$(Defines)</Defines>\r\n\t\t<FinalOutputDir>$(FINAL_PATH)\\$(Platform)\\$(Config)</FinalOutputDir>\r\n\t\t<Icon_MainIcon>resource\\Application.ico</Icon_MainIcon>\r\n\t\t<ILINK_GenerateDRC>true</ILINK_GenerateDRC>\r\n\t\t<ILINK_LibraryPath>windows\\;forms\\;packages\\filemng;packages\\tbx;packages\\png;..\\libs\\lib;$(LIB_PATH);$(ILINK_LibraryPath)</ILINK_LibraryPath>\r\n\t\t<ILINK_MapFileType>DetailedSegments</ILINK_MapFileType>\r\n\t\t<IncludePath>console;windows\\;forms\\;core;resource;components;dragext;packages\\filemng;packages\\dragndrop;packages\\my;packages\\tb2k;packages\\tbx;packages\\png;packages\\jcl;$(BDS)\\include\\mfc;$(BDS)\\include\\windows;$(BDS)\\include\\windows\\sdk;$(BDS)\\include\\windows\\vcl;$(IncludePath)</IncludePath>\r\n\t\t<IntermediateOutputDir>$(INTERM_PATH)\\$(Platform)\\$(Config)</IntermediateOutputDir>\r\n\t\t<LinkPackageStatics>vcl.lib;rtl.lib;vclx.lib;ws2_32.lib;secur32.lib;My.lib;DriveDir.lib;DragDropP.lib;tb2k.lib;tbxp.lib;bcbie.lib;Crypt32.lib;PngComponents.lib;xmlrtl.lib;vclactnband.lib;vclimg.lib;winhttp.lib;jcl.lib;vclie.lib;urlmon.lib;shlwapi.lib;powrprof.lib;soaprtl.lib</LinkPackageStatics>\r\n\t\t<Manifest_File>windows\\WinSCP.exe.manifest</Manifest_File>\r\n\t\t<Multithreaded>true</Multithreaded>\r\n\t\t<OutputExt>exe</OutputExt>\r\n\t\t<ProjectType>CppVCLApplication</ProjectType>\r\n\t\t<SanitizedProjectName>WinSCP</SanitizedProjectName>\r\n\t\t<UsingDelphiRTL>true</UsingDelphiRTL>\r\n\t\t<VerInfo_IncludeVerInfo>true</VerInfo_IncludeVerInfo>\r", "\t\t<VerInfo_Keys>CompanyName=Martin Prikryl;FileDescription=WinSCP: SFTP, FTP, WebDAV, S3 and SCP client;FileVersion=5.17.10.0;InternalName=winscp;LegalCopyright=(c) 2000-2020 Martin Prikryl;LegalTrademarks=;OriginalFilename=winscp.exe;ProductName=WinSCP;ProductVersion=5.17.10.0;ReleaseType=stable;WWW=https://winscp.net/</VerInfo_Keys>\r", "\t\t<VerInfo_Locale>1033</VerInfo_Locale>\r\n\t\t<VerInfo_MajorVer>5</VerInfo_MajorVer>\r\n\t\t<VerInfo_MinorVer>17</VerInfo_MinorVer>\r\n\t\t<VerInfo_Release>10</VerInfo_Release>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_1)'!=''\">\r\n\t\t<BCC_AllCodeguardOptions>true</BCC_AllCodeguardOptions>\r\n\t\t<BCC_DebugLineNumbers>true</BCC_DebugLineNumbers>\r\n\t\t<BCC_DisableOptimizations>true</BCC_DisableOptimizations>\r\n\t\t<BCC_InlineFunctionExpansion>false</BCC_InlineFunctionExpansion>\r\n\t\t<BCC_MonitorGlobalAndStackData>true</BCC_MonitorGlobalAndStackData>\r\n\t\t<BCC_MonitorInlinePtrAccess>true</BCC_MonitorInlinePtrAccess>\r\n\t\t<BCC_MonitorThis>true</BCC_MonitorThis>\r\n\t\t<BCC_OptimizeForSpeed>false</BCC_OptimizeForSpeed>\r\n\t\t<BCC_SourceDebuggingOn>true</BCC_SourceDebuggingOn>\r\n\t\t<BCC_StackFrames>true</BCC_StackFrames>\r\n\t\t<BCC_UseRegisterVariables>None</BCC_UseRegisterVariables>\r\n\t\t<DCC_DebugDCUs>true</DCC_DebugDCUs>\r\n\t\t<DCC_DebugInfoInExe>true</DCC_DebugInfoInExe>\r\n\t\t<DCC_Define>DEBUG</DCC_Define>\r\n\t\t<DCC_Optimize>false</DCC_Optimize>\r\n\t\t<Debugger_DebugSourcePath>packages\\my;packages\\filemng;packages\\jcl;..\\libs\\openssl\\crypto\\bio;..\\libs\\openssl\\ssl;..\\libs\\openssl\\crypto\\stack;..\\libs\\openssl\\crypto\\x509;..\\libs\\openssl\\crypto\\evp;..\\libs\\openssl\\crypto\\pkcs12;..\\libs\\openssl\\crypto\\pem;..\\libs\\openssl\\crypto\\asn1;..\\libs\\openssl\\crypto\\err;..\\libs\\openssl\\crypto\\rand;..\\libs\\neon\\src;..\\libs\\libs3\\src;..\\libs\\expat\\lib;$(Debugger_DebugSourcePath)</Debugger_DebugSourcePath>\r\n\t\t<Defines>_DEBUG;$(Defines)</Defines>\r\n\t\t<ILINK_FullDebugInfo>true</ILINK_FullDebugInfo>\r\n\t\t<TASM_Debugging>Full</TASM_Debugging>\r\n\t\t<TASM_DisplaySourceLines>true</TASM_DisplaySourceLines>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_1_Win32)'!=''\">\r\n\t\t<ILINK_DisableIncrementalLinking>true</ILINK_DisableIncrementalLinking>\r\n\t\t<ILINK_LibraryPath>$(INTERM_PATH)\\Win32\\Debug\\;$(BDS)\\lib\\Win32\\Debug\\;$(BDS)\\lib\\Win32\\Release\\;$(BDS)\\lib\\Win32\\Release\\psdk\\;$(ILINK_LibraryPath)</ILINK_LibraryPath>\r\n\t\t<LinkPackageStatics>vcl.lib;rtl.lib;vclx.lib;ws2_32.lib;secur32.lib;My.lib;DriveDir.lib;DragDropP.lib;tb2k.lib;tbxp.lib;bcbie.lib;Crypt32.lib;PngComponents.lib;xmlrtl.lib;vclactnband.lib;vclimg.lib;winhttp.lib;jcl.lib;vclie.lib;urlmon.lib;shlwapi.lib;powrprof.lib;soaprtl.lib;fmx.lib;dbrtl.lib;inet.lib</LinkPackageStatics>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_1_Win64)'!=''\">\r\n\t\t<ILINK_LibraryPath>$(INTERM_PATH)\\Win64\\Debug\\;$(BDS)\\lib\\Win64\\Debug\\;$(BDS)\\lib\\Win64\\Release\\;$(BDS)\\lib\\Win64\\Release\\psdk\\;$(ILINK_LibraryPath)</ILINK_LibraryPath>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_2)'!=''\">\r\n\t\t<Defines>NDEBUG;$(Defines)</Defines>\r\n\t\t<TASM_Debugging>None</TASM_Debugging>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_2_Win32)'!=''\">\r\n\t\t<ILINK_LibraryPath>$(INTERM_PATH)\\Win32\\Release\\;$(BDS)\\lib\\Win32\\Release\\;$(BDS)\\lib\\Win32\\Release\\psdk\\;$(ILINK_LibraryPath)</ILINK_LibraryPath>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_2_Win64)'!=''\">\r\n\t\t<ILINK_LibraryPath>$(INTERM_PATH)\\Win64\\Release\\;$(BDS)\\lib\\Win64\\Release\\;$(BDS)\\lib\\Win64\\Release\\psdk\\;$(ILINK_LibraryPath)</ILINK_LibraryPath>\r\n\t</PropertyGroup>\r\n\t<ItemGroup>\r\n\t\t<CppCompile Include=\"forms\\CustomScpExplorer.cpp\">\r\n\t\t\t<BuildOrder>8</BuildOrder>\r\n\t\t\t<Form>CustomScpExplorerForm</Form>\r\n\t\t\t<DependentOn>forms\\CustomScpExplorer.h</DependentOn>\r\n\t\t\t<BuildOrder>21</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<FormResources Include=\"forms\\CustomScpExplorer.dfm\"/>\r\n\t\t<CppCompile Include=\"forms\\NonVisual.cpp\">\r\n\t\t\t<BuildOrder>23</BuildOrder>\r\n\t\t\t<Form>NonVisualDataModule</Form>\r\n\t\t\t<DesignClass>TDataModule</DesignClass>\r\n\t\t\t<DependentOn>forms\\NonVisual.h</DependentOn>\r\n\t\t\t<BuildOrder>22</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<FormResources Include=\"forms\\NonVisual.dfm\"/>\r\n\t\t<CppCompile Include=\"forms\\ScpCommander.cpp\">\r\n\t\t\t<BuildOrder>38</BuildOrder>\r\n\t\t\t<Form>ScpCommanderForm</Form>\r\n\t\t\t<DependentOn>forms\\ScpCommander.h</DependentOn>\r\n\t\t\t<BuildOrder>23</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<FormResources Include=\"forms\\ScpCommander.dfm\"/>\r\n\t\t<CppCompile Include=\"forms\\ScpExplorer.cpp\">\r\n\t\t\t<BuildOrder>41</BuildOrder>\r\n\t\t\t<Form>ScpExplorerForm</Form>\r\n\t\t\t<DependentOn>forms\\ScpExplorer.h</DependentOn>\r\n\t\t\t<BuildOrder>24</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<FormResources Include=\"forms\\ScpExplorer.dfm\"/>\r\n\t\t<CppCompile Include=\"windows\\ConsoleRunner.cpp\">\r\n\t\t\t<BuildOrder>27</BuildOrder>\r\n\t\t\t<BuildOrder>26</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\CustomWinConfiguration.cpp\">\r\n\t\t\t<BuildOrder>18</BuildOrder>\r\n\t\t\t<BuildOrder>11</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\EditorManager.cpp\">\r\n\t\t\t<BuildOrder>15</BuildOrder>\r\n\t\t\t<BuildOrder>14</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\GUIConfiguration.cpp\">\r\n\t\t\t<BuildOrder>17</BuildOrder>\r\n\t\t\t<BuildOrder>16</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\GUITools.cpp\">\r\n\t\t\t<BuildOrder>20</BuildOrder>\r\n\t\t\t<BuildOrder>17</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\ProgParams.cpp\">\r\n\t\t\t<BuildOrder>29</BuildOrder>\r\n\t\t\t<BuildOrder>28</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\QueueController.cpp\">\r\n\t\t\t<BuildOrder>32</BuildOrder>\r\n\t\t\t<BuildOrder>29</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\Setup.cpp\">\r\n\t\t\t<BuildOrder>35</BuildOrder>\r\n\t\t\t<BuildOrder>26</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\SynchronizeController.cpp\">\r\n\t\t\t<BuildOrder>44</BuildOrder>\r\n\t\t\t<BuildOrder>25</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\TerminalManager.cpp\">\r\n\t\t\t<BuildOrder>47</BuildOrder>\r\n\t\t\t<BuildOrder>4</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\Tools.cpp\">\r\n\t\t\t<BuildOrder>50</BuildOrder>\r\n\t\t\t<BuildOrder>5</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\UserInterface.cpp\">\r\n\t\t\t<BuildOrder>6</BuildOrder>\r\n\t\t\t<BuildOrder>53</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\WinConfiguration.cpp\">\r\n\t\t\t<BuildOrder>56</BuildOrder>\r\n\t\t\t<BuildOrder>3</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<ResourceCompile Include=\"windows\\Windows.rc\">\r\n\t\t\t<BuildOrder>5</BuildOrder>\r\n\t\t\t<BuildOrder>20</BuildOrder>\r\n\t\t</ResourceCompile>\r\n\t\t<CppCompile Include=\"windows\\WinHelp.cpp\">\r\n\t\t\t<BuildOrder>59</BuildOrder>\r\n\t\t\t<BuildOrder>0</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\WinInterface.cpp\">\r\n\t\t\t<BuildOrder>62</BuildOrder>\r\n\t\t\t<BuildOrder>1</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\WinMain.cpp\">\r\n\t\t\t<BuildOrder>65</BuildOrder>\r\n\t\t\t<BuildOrder>2</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"WinSCP.cpp\">\r\n\t\t\t<BuildOrder>2</BuildOrder>\r\n\t\t\t<BuildOrder>19</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<LibFiles Include=\"..\\libs\\lib\\libs3.lib\" Condition=\"'$(Platform)'=='Win32'\">\r\n\t\t\t<BuildOrder>34</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"FileZilla.lib\">\r\n\t\t\t<BuildOrder>27</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"libeay32.lib\">\r\n\t\t\t<BuildOrder>28</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"libexpats_mtd.lib\">\r\n\t\t\t<BuildOrder>31</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"neon.lib\">\r\n\t\t\t<BuildOrder>33</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"Putty.lib\">\r\n\t\t\t<BuildOrder>23</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"PuTTYVS.lib\">\r\n\t\t\t<BuildOrder>33</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"RScpComp.lib\">\r\n\t\t\t<BuildOrder>24</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"ScpCore.lib\">\r\n\t\t\t<BuildOrder>25</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"ScpForms.lib\">\r\n\t\t\t<BuildOrder>26</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"ScpResources.lib\">\r\n\t\t\t<BuildOrder>26</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"ssleay32.lib\">\r\n\t\t\t<BuildOrder>29</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<BuildConfiguration Include=\"Base\">\r\n\t\t\t<Key>Base</Key>\r\n\t\t</BuildConfiguration>\r\n\t\t<BuildConfiguration Include=\"Debug\">\r\n\t\t\t<Key>Cfg_1</Key>\r\n\t\t\t<CfgParent>Base</CfgParent>\r\n\t\t</BuildConfiguration>\r\n\t\t<BuildConfiguration Include=\"Release\">\r\n\t\t\t<Key>Cfg_2</Key>\r\n\t\t\t<CfgParent>Base</CfgParent>\r\n\t\t</BuildConfiguration>\r\n\t</ItemGroup>\r\n\t<Import Condition=\"Exists('$(BDS)\\Bin\\CodeGear.Cpp.Targets')\" Project=\"$(BDS)\\Bin\\CodeGear.Cpp.Targets\"/>\r\n\t<ProjectExtensions>\r\n\t\t<Borland.Personality>CPlusPlusBuilder.Personality.12</Borland.Personality>\r\n\t\t<Borland.ProjectType>CppVCLApplication</Borland.ProjectType>\r\n\t\t<BorlandProject>\r\n\t\t\t<CPlusPlusBuilder.Personality>\r\n\t\t\t\t<Source>\r\n\t\t\t\t\t<Source Name=\"MainSource\">WinSCP.cpp</Source>\r\n\t\t\t\t</Source>\r\n\t\t\t\t<ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"AutoShowDeps\">False</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"ManagePaths\">True</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"VerifyPackages\">True</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"IndexFiles\">False</ProjectProperties>\r\n\t\t\t\t</ProjectProperties>\r\n\t\t\t</CPlusPlusBuilder.Personality>\r\n\t\t\t<Platforms>\r\n\t\t\t\t<Platform value=\"Win32\">True</Platform>\r\n\t\t\t\t<Platform value=\"Win64\">False</Platform>\r\n\t\t\t</Platforms>\r\n\t\t</BorlandProject>\r\n\t\t<ProjectFileVersion>12</ProjectFileVersion>\r\n\t</ProjectExtensions>\r\n\t<Import Condition=\"Exists('$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj')\" Project=\"$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj\"/>\r\n</Project>" ]
[ 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 53, 80, 2275, 473, 1511, 2372, 1100], "buggy_code_start_loc": [46, 52, 79, 599, 57, 1510, 2371, 1099], "filenames": ["source/Console.cbproj", "source/DragExt.cbproj", "source/WinSCP.cbproj", "source/core/SessionData.cpp", "source/core/SessionData.h", "source/forms/Custom.cpp", "source/windows/ConsoleRunner.cpp", "source/windows/WinMain.cpp"], "fixing_code_end_loc": [47, 53, 80, 2294, 474, 1511, 2372, 1103], "fixing_code_start_loc": [46, 52, 79, 599, 58, 1510, 2371, 1099], "message": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:winscp:winscp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C081564B-8EF8-4C8A-9EB0-1C50D5A8F18B", "versionEndExcluding": "5.17.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)"}, {"lang": "es", "value": "WinSCP anterior a la versi\u00f3n 5.17.10 permite a los atacantes remotos ejecutar programas arbitrarios cuando el manejador de URLs encuentra una URL manipulada que carga la configuraci\u00f3n de la sesi\u00f3n. (Por ejemplo, esto es explotable en una instalaci\u00f3n por defecto en la que WinSCP es el manejador de URLs sftp://)"}], "evaluatorComment": null, "id": "CVE-2021-3331", "lastModified": "2021-02-04T15:59:24.960", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-01-27T21:15:16.840", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://winscp.net/eng/docs/history#5.17.10"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://winscp.net/eng/docs/rawsettings"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://winscp.net/tracker/1943"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, "type": "NVD-CWE-Other"}
177
Determine whether the {function_name} code is vulnerable or not.
[ "<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n\t<PropertyGroup>\r\n\t\t<ProjectGuid>{0B0C5EC6-5DCB-4F16-9504-1E6D37FFBB77}</ProjectGuid>\r\n\t\t<ProjectVersion>15.4</ProjectVersion>\r\n\t\t<MainSource>WinSCP.cpp</MainSource>\r\n\t\t<Config Condition=\"'$(Config)'==''\">Release</Config>\r\n\t\t<FrameworkType>VCL</FrameworkType>\r\n\t\t<Base>True</Base>\r\n\t\t<Platform Condition=\"'$(Platform)'==''\">Win32</Platform>\r\n\t\t<TargetedPlatforms>1</TargetedPlatforms>\r\n\t\t<AppType>Application</AppType>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Base' or '$(Base)'!=''\">\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Debug' or '$(Cfg_1)'!=''\">\r\n\t\t<Cfg_1>true</Cfg_1>\r\n\t\t<CfgParent>Base</CfgParent>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"('$(Platform)'=='Win32' and '$(Cfg_1)'=='true') or '$(Cfg_1_Win32)'!=''\">\r\n\t\t<Cfg_1_Win32>true</Cfg_1_Win32>\r\n\t\t<CfgParent>Cfg_1</CfgParent>\r\n\t\t<Cfg_1>true</Cfg_1>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"('$(Platform)'=='Win64' and '$(Cfg_1)'=='true') or '$(Cfg_1_Win64)'!=''\">\r\n\t\t<Cfg_1_Win64>true</Cfg_1_Win64>\r\n\t\t<CfgParent>Cfg_1</CfgParent>\r\n\t\t<Cfg_1>true</Cfg_1>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Config)'=='Release' or '$(Cfg_2)'!=''\">\r\n\t\t<Cfg_2>true</Cfg_2>\r\n\t\t<CfgParent>Base</CfgParent>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"('$(Platform)'=='Win32' and '$(Cfg_2)'=='true') or '$(Cfg_2_Win32)'!=''\">\r\n\t\t<Cfg_2_Win32>true</Cfg_2_Win32>\r\n\t\t<CfgParent>Cfg_2</CfgParent>\r\n\t\t<Cfg_2>true</Cfg_2>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"('$(Platform)'=='Win64' and '$(Cfg_2)'=='true') or '$(Cfg_2_Win64)'!=''\">\r\n\t\t<Cfg_2_Win64>true</Cfg_2_Win64>\r\n\t\t<CfgParent>Cfg_2</CfgParent>\r\n\t\t<Cfg_2>true</Cfg_2>\r\n\t\t<Base>true</Base>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Base)'!=''\">\r\n\t\t<_TCHARMapping>wchar_t</_TCHARMapping>\r\n\t\t<AllPackageLibs>vcl.lib;rtl.lib;vclx.lib;ws2_32.lib;secur32.lib;My.lib;DriveDir.lib;DragDropP.lib;tb2k.lib;tbxp.lib;bcbie.lib;Crypt32.lib;PngComponents.lib;xmlrtl.lib;vclactnband.lib;vclimg.lib;winhttp.lib;jcl.lib;vclie.lib;urlmon.lib;shlwapi.lib;powrprof.lib;soaprtl.lib;fmx.lib;dbrtl.lib;inet.lib</AllPackageLibs>\r\n\t\t<BCC_AllWarnings>true</BCC_AllWarnings>\r\n\t\t<BCC_ExtendedErrorInfo>true</BCC_ExtendedErrorInfo>\r\n\t\t<BCC_OptimizeForSpeed>true</BCC_OptimizeForSpeed>\r\n\t\t<BCC_wdiu>false</BCC_wdiu>\r\n\t\t<BRCC_CodePage>65001</BRCC_CodePage>\r\n\t\t<DCC_CBuilderOutput>JPHNE</DCC_CBuilderOutput>\r\n\t\t<DCC_Namespace>Vcl;Vcl.Imaging;Vcl.Touch;Vcl.Samples;Vcl.Shell;System;Xml;Data;Datasnap;Web;Soap;Vcl;$(DCC_Namespace)</DCC_Namespace>\r\n\t\t<DCC_SYMBOL_DEPRECATED>false</DCC_SYMBOL_DEPRECATED>\r\n\t\t<DCC_SYMBOL_PLATFORM>false</DCC_SYMBOL_PLATFORM>\r\n\t\t<DCC_UNSUPPORTED_CONSTRUCT>false</DCC_UNSUPPORTED_CONSTRUCT>\r\n\t\t<Defines>STRICT;$(Defines)</Defines>\r\n\t\t<FinalOutputDir>$(FINAL_PATH)\\$(Platform)\\$(Config)</FinalOutputDir>\r\n\t\t<Icon_MainIcon>resource\\Application.ico</Icon_MainIcon>\r\n\t\t<ILINK_GenerateDRC>true</ILINK_GenerateDRC>\r\n\t\t<ILINK_LibraryPath>windows\\;forms\\;packages\\filemng;packages\\tbx;packages\\png;..\\libs\\lib;$(LIB_PATH);$(ILINK_LibraryPath)</ILINK_LibraryPath>\r\n\t\t<ILINK_MapFileType>DetailedSegments</ILINK_MapFileType>\r\n\t\t<IncludePath>console;windows\\;forms\\;core;resource;components;dragext;packages\\filemng;packages\\dragndrop;packages\\my;packages\\tb2k;packages\\tbx;packages\\png;packages\\jcl;$(BDS)\\include\\mfc;$(BDS)\\include\\windows;$(BDS)\\include\\windows\\sdk;$(BDS)\\include\\windows\\vcl;$(IncludePath)</IncludePath>\r\n\t\t<IntermediateOutputDir>$(INTERM_PATH)\\$(Platform)\\$(Config)</IntermediateOutputDir>\r\n\t\t<LinkPackageStatics>vcl.lib;rtl.lib;vclx.lib;ws2_32.lib;secur32.lib;My.lib;DriveDir.lib;DragDropP.lib;tb2k.lib;tbxp.lib;bcbie.lib;Crypt32.lib;PngComponents.lib;xmlrtl.lib;vclactnband.lib;vclimg.lib;winhttp.lib;jcl.lib;vclie.lib;urlmon.lib;shlwapi.lib;powrprof.lib;soaprtl.lib</LinkPackageStatics>\r\n\t\t<Manifest_File>windows\\WinSCP.exe.manifest</Manifest_File>\r\n\t\t<Multithreaded>true</Multithreaded>\r\n\t\t<OutputExt>exe</OutputExt>\r\n\t\t<ProjectType>CppVCLApplication</ProjectType>\r\n\t\t<SanitizedProjectName>WinSCP</SanitizedProjectName>\r\n\t\t<UsingDelphiRTL>true</UsingDelphiRTL>\r\n\t\t<VerInfo_IncludeVerInfo>true</VerInfo_IncludeVerInfo>\r", "\t\t<VerInfo_Keys>CompanyName=Martin Prikryl;FileDescription=WinSCP: SFTP, FTP, WebDAV, S3 and SCP client;FileVersion=5.17.10.0;InternalName=winscp;LegalCopyright=(c) 2000-2021 Martin Prikryl;LegalTrademarks=;OriginalFilename=winscp.exe;ProductName=WinSCP;ProductVersion=5.17.10.0;ReleaseType=stable;WWW=https://winscp.net/</VerInfo_Keys>\r", "\t\t<VerInfo_Locale>1033</VerInfo_Locale>\r\n\t\t<VerInfo_MajorVer>5</VerInfo_MajorVer>\r\n\t\t<VerInfo_MinorVer>17</VerInfo_MinorVer>\r\n\t\t<VerInfo_Release>10</VerInfo_Release>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_1)'!=''\">\r\n\t\t<BCC_AllCodeguardOptions>true</BCC_AllCodeguardOptions>\r\n\t\t<BCC_DebugLineNumbers>true</BCC_DebugLineNumbers>\r\n\t\t<BCC_DisableOptimizations>true</BCC_DisableOptimizations>\r\n\t\t<BCC_InlineFunctionExpansion>false</BCC_InlineFunctionExpansion>\r\n\t\t<BCC_MonitorGlobalAndStackData>true</BCC_MonitorGlobalAndStackData>\r\n\t\t<BCC_MonitorInlinePtrAccess>true</BCC_MonitorInlinePtrAccess>\r\n\t\t<BCC_MonitorThis>true</BCC_MonitorThis>\r\n\t\t<BCC_OptimizeForSpeed>false</BCC_OptimizeForSpeed>\r\n\t\t<BCC_SourceDebuggingOn>true</BCC_SourceDebuggingOn>\r\n\t\t<BCC_StackFrames>true</BCC_StackFrames>\r\n\t\t<BCC_UseRegisterVariables>None</BCC_UseRegisterVariables>\r\n\t\t<DCC_DebugDCUs>true</DCC_DebugDCUs>\r\n\t\t<DCC_DebugInfoInExe>true</DCC_DebugInfoInExe>\r\n\t\t<DCC_Define>DEBUG</DCC_Define>\r\n\t\t<DCC_Optimize>false</DCC_Optimize>\r\n\t\t<Debugger_DebugSourcePath>packages\\my;packages\\filemng;packages\\jcl;..\\libs\\openssl\\crypto\\bio;..\\libs\\openssl\\ssl;..\\libs\\openssl\\crypto\\stack;..\\libs\\openssl\\crypto\\x509;..\\libs\\openssl\\crypto\\evp;..\\libs\\openssl\\crypto\\pkcs12;..\\libs\\openssl\\crypto\\pem;..\\libs\\openssl\\crypto\\asn1;..\\libs\\openssl\\crypto\\err;..\\libs\\openssl\\crypto\\rand;..\\libs\\neon\\src;..\\libs\\libs3\\src;..\\libs\\expat\\lib;$(Debugger_DebugSourcePath)</Debugger_DebugSourcePath>\r\n\t\t<Defines>_DEBUG;$(Defines)</Defines>\r\n\t\t<ILINK_FullDebugInfo>true</ILINK_FullDebugInfo>\r\n\t\t<TASM_Debugging>Full</TASM_Debugging>\r\n\t\t<TASM_DisplaySourceLines>true</TASM_DisplaySourceLines>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_1_Win32)'!=''\">\r\n\t\t<ILINK_DisableIncrementalLinking>true</ILINK_DisableIncrementalLinking>\r\n\t\t<ILINK_LibraryPath>$(INTERM_PATH)\\Win32\\Debug\\;$(BDS)\\lib\\Win32\\Debug\\;$(BDS)\\lib\\Win32\\Release\\;$(BDS)\\lib\\Win32\\Release\\psdk\\;$(ILINK_LibraryPath)</ILINK_LibraryPath>\r\n\t\t<LinkPackageStatics>vcl.lib;rtl.lib;vclx.lib;ws2_32.lib;secur32.lib;My.lib;DriveDir.lib;DragDropP.lib;tb2k.lib;tbxp.lib;bcbie.lib;Crypt32.lib;PngComponents.lib;xmlrtl.lib;vclactnband.lib;vclimg.lib;winhttp.lib;jcl.lib;vclie.lib;urlmon.lib;shlwapi.lib;powrprof.lib;soaprtl.lib;fmx.lib;dbrtl.lib;inet.lib</LinkPackageStatics>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_1_Win64)'!=''\">\r\n\t\t<ILINK_LibraryPath>$(INTERM_PATH)\\Win64\\Debug\\;$(BDS)\\lib\\Win64\\Debug\\;$(BDS)\\lib\\Win64\\Release\\;$(BDS)\\lib\\Win64\\Release\\psdk\\;$(ILINK_LibraryPath)</ILINK_LibraryPath>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_2)'!=''\">\r\n\t\t<Defines>NDEBUG;$(Defines)</Defines>\r\n\t\t<TASM_Debugging>None</TASM_Debugging>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_2_Win32)'!=''\">\r\n\t\t<ILINK_LibraryPath>$(INTERM_PATH)\\Win32\\Release\\;$(BDS)\\lib\\Win32\\Release\\;$(BDS)\\lib\\Win32\\Release\\psdk\\;$(ILINK_LibraryPath)</ILINK_LibraryPath>\r\n\t</PropertyGroup>\r\n\t<PropertyGroup Condition=\"'$(Cfg_2_Win64)'!=''\">\r\n\t\t<ILINK_LibraryPath>$(INTERM_PATH)\\Win64\\Release\\;$(BDS)\\lib\\Win64\\Release\\;$(BDS)\\lib\\Win64\\Release\\psdk\\;$(ILINK_LibraryPath)</ILINK_LibraryPath>\r\n\t</PropertyGroup>\r\n\t<ItemGroup>\r\n\t\t<CppCompile Include=\"forms\\CustomScpExplorer.cpp\">\r\n\t\t\t<BuildOrder>8</BuildOrder>\r\n\t\t\t<Form>CustomScpExplorerForm</Form>\r\n\t\t\t<DependentOn>forms\\CustomScpExplorer.h</DependentOn>\r\n\t\t\t<BuildOrder>21</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<FormResources Include=\"forms\\CustomScpExplorer.dfm\"/>\r\n\t\t<CppCompile Include=\"forms\\NonVisual.cpp\">\r\n\t\t\t<BuildOrder>23</BuildOrder>\r\n\t\t\t<Form>NonVisualDataModule</Form>\r\n\t\t\t<DesignClass>TDataModule</DesignClass>\r\n\t\t\t<DependentOn>forms\\NonVisual.h</DependentOn>\r\n\t\t\t<BuildOrder>22</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<FormResources Include=\"forms\\NonVisual.dfm\"/>\r\n\t\t<CppCompile Include=\"forms\\ScpCommander.cpp\">\r\n\t\t\t<BuildOrder>38</BuildOrder>\r\n\t\t\t<Form>ScpCommanderForm</Form>\r\n\t\t\t<DependentOn>forms\\ScpCommander.h</DependentOn>\r\n\t\t\t<BuildOrder>23</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<FormResources Include=\"forms\\ScpCommander.dfm\"/>\r\n\t\t<CppCompile Include=\"forms\\ScpExplorer.cpp\">\r\n\t\t\t<BuildOrder>41</BuildOrder>\r\n\t\t\t<Form>ScpExplorerForm</Form>\r\n\t\t\t<DependentOn>forms\\ScpExplorer.h</DependentOn>\r\n\t\t\t<BuildOrder>24</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<FormResources Include=\"forms\\ScpExplorer.dfm\"/>\r\n\t\t<CppCompile Include=\"windows\\ConsoleRunner.cpp\">\r\n\t\t\t<BuildOrder>27</BuildOrder>\r\n\t\t\t<BuildOrder>26</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\CustomWinConfiguration.cpp\">\r\n\t\t\t<BuildOrder>18</BuildOrder>\r\n\t\t\t<BuildOrder>11</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\EditorManager.cpp\">\r\n\t\t\t<BuildOrder>15</BuildOrder>\r\n\t\t\t<BuildOrder>14</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\GUIConfiguration.cpp\">\r\n\t\t\t<BuildOrder>17</BuildOrder>\r\n\t\t\t<BuildOrder>16</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\GUITools.cpp\">\r\n\t\t\t<BuildOrder>20</BuildOrder>\r\n\t\t\t<BuildOrder>17</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\ProgParams.cpp\">\r\n\t\t\t<BuildOrder>29</BuildOrder>\r\n\t\t\t<BuildOrder>28</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\QueueController.cpp\">\r\n\t\t\t<BuildOrder>32</BuildOrder>\r\n\t\t\t<BuildOrder>29</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\Setup.cpp\">\r\n\t\t\t<BuildOrder>35</BuildOrder>\r\n\t\t\t<BuildOrder>26</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\SynchronizeController.cpp\">\r\n\t\t\t<BuildOrder>44</BuildOrder>\r\n\t\t\t<BuildOrder>25</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\TerminalManager.cpp\">\r\n\t\t\t<BuildOrder>47</BuildOrder>\r\n\t\t\t<BuildOrder>4</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\Tools.cpp\">\r\n\t\t\t<BuildOrder>50</BuildOrder>\r\n\t\t\t<BuildOrder>5</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\UserInterface.cpp\">\r\n\t\t\t<BuildOrder>6</BuildOrder>\r\n\t\t\t<BuildOrder>53</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\WinConfiguration.cpp\">\r\n\t\t\t<BuildOrder>56</BuildOrder>\r\n\t\t\t<BuildOrder>3</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<ResourceCompile Include=\"windows\\Windows.rc\">\r\n\t\t\t<BuildOrder>5</BuildOrder>\r\n\t\t\t<BuildOrder>20</BuildOrder>\r\n\t\t</ResourceCompile>\r\n\t\t<CppCompile Include=\"windows\\WinHelp.cpp\">\r\n\t\t\t<BuildOrder>59</BuildOrder>\r\n\t\t\t<BuildOrder>0</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\WinInterface.cpp\">\r\n\t\t\t<BuildOrder>62</BuildOrder>\r\n\t\t\t<BuildOrder>1</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"windows\\WinMain.cpp\">\r\n\t\t\t<BuildOrder>65</BuildOrder>\r\n\t\t\t<BuildOrder>2</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<CppCompile Include=\"WinSCP.cpp\">\r\n\t\t\t<BuildOrder>2</BuildOrder>\r\n\t\t\t<BuildOrder>19</BuildOrder>\r\n\t\t</CppCompile>\r\n\t\t<LibFiles Include=\"..\\libs\\lib\\libs3.lib\" Condition=\"'$(Platform)'=='Win32'\">\r\n\t\t\t<BuildOrder>34</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"FileZilla.lib\">\r\n\t\t\t<BuildOrder>27</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"libeay32.lib\">\r\n\t\t\t<BuildOrder>28</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"libexpats_mtd.lib\">\r\n\t\t\t<BuildOrder>31</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"neon.lib\">\r\n\t\t\t<BuildOrder>33</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"Putty.lib\">\r\n\t\t\t<BuildOrder>23</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"PuTTYVS.lib\">\r\n\t\t\t<BuildOrder>33</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"RScpComp.lib\">\r\n\t\t\t<BuildOrder>24</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"ScpCore.lib\">\r\n\t\t\t<BuildOrder>25</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"ScpForms.lib\">\r\n\t\t\t<BuildOrder>26</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"ScpResources.lib\">\r\n\t\t\t<BuildOrder>26</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<LibFiles Include=\"ssleay32.lib\">\r\n\t\t\t<BuildOrder>29</BuildOrder>\r\n\t\t\t<IgnorePath>true</IgnorePath>\r\n\t\t</LibFiles>\r\n\t\t<BuildConfiguration Include=\"Base\">\r\n\t\t\t<Key>Base</Key>\r\n\t\t</BuildConfiguration>\r\n\t\t<BuildConfiguration Include=\"Debug\">\r\n\t\t\t<Key>Cfg_1</Key>\r\n\t\t\t<CfgParent>Base</CfgParent>\r\n\t\t</BuildConfiguration>\r\n\t\t<BuildConfiguration Include=\"Release\">\r\n\t\t\t<Key>Cfg_2</Key>\r\n\t\t\t<CfgParent>Base</CfgParent>\r\n\t\t</BuildConfiguration>\r\n\t</ItemGroup>\r\n\t<Import Condition=\"Exists('$(BDS)\\Bin\\CodeGear.Cpp.Targets')\" Project=\"$(BDS)\\Bin\\CodeGear.Cpp.Targets\"/>\r\n\t<ProjectExtensions>\r\n\t\t<Borland.Personality>CPlusPlusBuilder.Personality.12</Borland.Personality>\r\n\t\t<Borland.ProjectType>CppVCLApplication</Borland.ProjectType>\r\n\t\t<BorlandProject>\r\n\t\t\t<CPlusPlusBuilder.Personality>\r\n\t\t\t\t<Source>\r\n\t\t\t\t\t<Source Name=\"MainSource\">WinSCP.cpp</Source>\r\n\t\t\t\t</Source>\r\n\t\t\t\t<ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"AutoShowDeps\">False</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"ManagePaths\">True</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"VerifyPackages\">True</ProjectProperties>\r\n\t\t\t\t\t<ProjectProperties Name=\"IndexFiles\">False</ProjectProperties>\r\n\t\t\t\t</ProjectProperties>\r\n\t\t\t</CPlusPlusBuilder.Personality>\r\n\t\t\t<Platforms>\r\n\t\t\t\t<Platform value=\"Win32\">True</Platform>\r\n\t\t\t\t<Platform value=\"Win64\">False</Platform>\r\n\t\t\t</Platforms>\r\n\t\t</BorlandProject>\r\n\t\t<ProjectFileVersion>12</ProjectFileVersion>\r\n\t</ProjectExtensions>\r\n\t<Import Condition=\"Exists('$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj')\" Project=\"$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj\"/>\r\n</Project>" ]
[ 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 53, 80, 2275, 473, 1511, 2372, 1100], "buggy_code_start_loc": [46, 52, 79, 599, 57, 1510, 2371, 1099], "filenames": ["source/Console.cbproj", "source/DragExt.cbproj", "source/WinSCP.cbproj", "source/core/SessionData.cpp", "source/core/SessionData.h", "source/forms/Custom.cpp", "source/windows/ConsoleRunner.cpp", "source/windows/WinMain.cpp"], "fixing_code_end_loc": [47, 53, 80, 2294, 474, 1511, 2372, 1103], "fixing_code_start_loc": [46, 52, 79, 599, 58, 1510, 2371, 1099], "message": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:winscp:winscp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C081564B-8EF8-4C8A-9EB0-1C50D5A8F18B", "versionEndExcluding": "5.17.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)"}, {"lang": "es", "value": "WinSCP anterior a la versi\u00f3n 5.17.10 permite a los atacantes remotos ejecutar programas arbitrarios cuando el manejador de URLs encuentra una URL manipulada que carga la configuraci\u00f3n de la sesi\u00f3n. (Por ejemplo, esto es explotable en una instalaci\u00f3n por defecto en la que WinSCP es el manejador de URLs sftp://)"}], "evaluatorComment": null, "id": "CVE-2021-3331", "lastModified": "2021-02-04T15:59:24.960", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-01-27T21:15:16.840", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://winscp.net/eng/docs/history#5.17.10"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://winscp.net/eng/docs/rawsettings"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://winscp.net/tracker/1943"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, "type": "NVD-CWE-Other"}
177
Determine whether the {function_name} code is vulnerable or not.
[ "//---------------------------------------------------------------------------\r\n#include <vcl.h>\r\n#pragma hdrstop\r\n\r\n#include \"SessionData.h\"\r\n\r\n#include \"Common.h\"\r\n#include \"Exceptions.h\"\r\n#include \"FileBuffer.h\"\r\n#include \"CoreMain.h\"\r\n#include \"TextsCore.h\"\r\n#include \"PuttyIntf.h\"\r\n#include \"RemoteFiles.h\"\r\n#include \"SFTPFileSystem.h\"\r\n#include \"S3FileSystem.h\"\r\n#include <Soap.EncdDecd.hpp>\r\n#include <StrUtils.hpp>\r\n#include <XMLDoc.hpp>\r\n#include <StrUtils.hpp>\r\n#include <algorithm>\r\n//---------------------------------------------------------------------------\r\n#pragma package(smart_init)\r\n//---------------------------------------------------------------------------\r\n#define SET_SESSION_PROPERTY_FROM(PROPERTY, FROM) \\\r\n if (F##PROPERTY != FROM) { F##PROPERTY = FROM; Modify(); }\r\n//---------------------------------------------------------------------------\r\n#define SET_SESSION_PROPERTY(PROPERTY) \\\r\n SET_SESSION_PROPERTY_FROM(PROPERTY, value)\r\n//---------------------------------------------------------------------------\r\nconst wchar_t * PingTypeNames = L\"Off;Null;Dummy\";\r\nconst wchar_t * ProxyMethodNames = L\"None;SOCKS4;SOCKS5;HTTP;Telnet;Cmd\";\r\nconst wchar_t * DefaultName = L\"Default Settings\";\r\nconst UnicodeString CipherNames[CIPHER_COUNT] = {L\"WARN\", L\"3des\", L\"blowfish\", L\"aes\", L\"des\", L\"arcfour\", L\"chacha20\"};\r\nconst UnicodeString KexNames[KEX_COUNT] = {L\"WARN\", L\"dh-group1-sha1\", L\"dh-group14-sha1\", L\"dh-gex-sha1\", L\"rsa\", L\"ecdh\"};\r\nconst UnicodeString HostKeyNames[HOSTKEY_COUNT] = {L\"WARN\", L\"rsa\", L\"dsa\", L\"ecdsa\", L\"ed25519\"};\r\nconst UnicodeString GssLibNames[GSSLIB_COUNT] = {L\"gssapi32\", L\"sspi\", L\"custom\"};\r\nconst wchar_t SshProtList[][10] = {L\"1\", L\"1>2\", L\"2>1\", L\"2\"};\r\n// Update also order in Ssh2CipherList()\r\nconst TCipher DefaultCipherList[CIPHER_COUNT] =\r\n { cipAES, cipChaCha20, cipBlowfish, cip3DES, cipWarn, cipArcfour, cipDES };\r\n// Update also order in SshKexList()\r\nconst TKex DefaultKexList[KEX_COUNT] =\r\n { kexECDH, kexDHGEx, kexDHGroup14, kexRSA, kexWarn, kexDHGroup1 };\r\nconst THostKey DefaultHostKeyList[HOSTKEY_COUNT] =\r\n { hkED25519, hkECDSA, hkRSA, hkDSA, hkWarn };\r\nconst TGssLib DefaultGssLibList[GSSLIB_COUNT] =\r\n { gssGssApi32, gssSspi, gssCustom };\r\nconst wchar_t FSProtocolNames[FSPROTOCOL_COUNT][16] = { L\"SCP\", L\"SFTP (SCP)\", L\"SFTP\", L\"\", L\"\", L\"FTP\", L\"WebDAV\", L\"S3\" };\r\nconst int SshPortNumber = 22;\r\nconst int FtpPortNumber = 21;\r\nconst int FtpsImplicitPortNumber = 990;\r\nconst int HTTPPortNumber = 80;\r\nconst int HTTPSPortNumber = 443;\r\nconst int TelnetPortNumber = 23;\r\nconst int DefaultSendBuf = 262144;\r\nconst int ProxyPortNumber = 80;\r\nconst UnicodeString AnonymousUserName(L\"anonymous\");\r\nconst UnicodeString AnonymousPassword(L\"anonymous@example.com\");\r\nconst UnicodeString PuttySshProtocol(L\"ssh\");\r\nconst UnicodeString PuttyTelnetProtocol(L\"telnet\");\r\nconst UnicodeString SftpProtocol(L\"sftp\");\r\nconst UnicodeString ScpProtocol(L\"scp\");\r\nconst UnicodeString FtpProtocol(L\"ftp\");\r\nconst UnicodeString FtpsProtocol(L\"ftps\");\r\nconst UnicodeString FtpesProtocol(L\"ftpes\");\r\nconst UnicodeString WebDAVProtocol(L\"dav\");\r\nconst UnicodeString WebDAVSProtocol(L\"davs\");\r\nconst UnicodeString S3Protocol(L\"s3\");\r\nconst UnicodeString SshProtocol(L\"ssh\");\r\nconst UnicodeString WinSCPProtocolPrefix(L\"winscp-\");\r\nconst wchar_t UrlParamSeparator = L';';\r\nconst wchar_t UrlParamValueSeparator = L'=';\r\nconst UnicodeString UrlHostKeyParamName(L\"fingerprint\");\r\nconst UnicodeString UrlSaveParamName(L\"save\");\r\nconst UnicodeString UrlRawSettingsParamNamePrefix(L\"x-\");\r\nconst UnicodeString PassphraseOption(L\"passphrase\");\r\nconst UnicodeString RawSettingsOption(L\"rawsettings\");\r\nconst UnicodeString S3HostName(S3LibDefaultHostName());\r\n//---------------------------------------------------------------------\r\nTDateTime __fastcall SecToDateTime(int Sec)\r\n{\r\n return TDateTime(double(Sec) / SecsPerDay);\r\n}\r\n//--- TSessionData ----------------------------------------------------\r\n__fastcall TSessionData::TSessionData(UnicodeString aName):\r\n TNamedObject(aName)\r\n{\r\n Default();\r\n FModified = true;\r\n}\r\n//---------------------------------------------------------------------\r\n_fastcall TSessionData::~TSessionData()\r\n{\r\n}\r\n//---------------------------------------------------------------------\r\nint __fastcall TSessionData::Compare(TNamedObject * Other)\r\n{\r\n int Result;\r\n // To avoid using CompareLogicalText on hex names of sessions in workspace.\r\n // The session 000A would be sorted before 0001.\r\n if (IsWorkspace && DebugNotNull(dynamic_cast<TSessionData *>(Other))->IsWorkspace)\r\n {\r\n Result = CompareText(Name, Other->Name);\r\n }\r\n else\r\n {\r\n Result = TNamedObject::Compare(Other);\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nTSessionData * __fastcall TSessionData::Clone()\r\n{\r\n std::unique_ptr<TSessionData> Data(new TSessionData(L\"\"));\r\n Data->Assign(this);\r\n return Data.release();\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::DefaultSettings()\r\n{\r\n HostName = L\"\";\r\n PortNumber = SshPortNumber;\r\n UserName = L\"\";\r\n Password = L\"\";\r\n NewPassword = L\"\";\r\n ChangePassword = false;\r\n PingInterval = 30;\r\n PingType = ptOff;\r\n Timeout = 15;\r\n TryAgent = true;\r\n AgentFwd = false;\r\n AuthTIS = false;\r\n AuthKI = true;\r\n AuthKIPassword = true;\r\n AuthGSSAPI = true;\r\n GSSAPIFwdTGT = false;\r\n LogicalHostName = L\"\";\r\n ChangeUsername = false;\r\n Compression = false;\r\n SshProt = ssh2only;\r\n Ssh2DES = false;\r\n SshNoUserAuth = false;\r\n for (int Index = 0; Index < CIPHER_COUNT; Index++)\r\n {\r\n Cipher[Index] = DefaultCipherList[Index];\r\n }\r\n for (int Index = 0; Index < KEX_COUNT; Index++)\r\n {\r\n Kex[Index] = DefaultKexList[Index];\r\n }\r\n for (int Index = 0; Index < HOSTKEY_COUNT; Index++)\r\n {\r\n HostKeys[Index] = DefaultHostKeyList[Index];\r\n }\r\n for (int Index = 0; Index < GSSLIB_COUNT; Index++)\r\n {\r\n GssLib[Index] = DefaultGssLibList[Index];\r\n }\r\n GssLibCustom = L\"\";\r\n PublicKeyFile = L\"\";\r\n Passphrase = L\"\";\r\n FPuttyProtocol = L\"\";\r\n TcpNoDelay = false;\r\n SendBuf = DefaultSendBuf;\r\n SourceAddress = L\"\";\r\n SshSimple = true;\r\n HostKey = L\"\";\r\n FingerprintScan = false;\r\n FOverrideCachedHostKey = true;\r\n Note = L\"\";\r\n WinTitle = L\"\";\r\n InternalEditorEncoding = -1;\r\n\r\n EncryptKey = UnicodeString();\r\n\r\n ProxyMethod = ::pmNone;\r\n ProxyHost = L\"proxy\";\r\n ProxyPort = ProxyPortNumber;\r\n ProxyUsername = L\"\";\r\n ProxyPassword = L\"\";\r\n ProxyTelnetCommand = L\"connect %host %port\\\\n\";\r\n ProxyLocalCommand = L\"\";\r\n ProxyDNS = asAuto;\r\n ProxyLocalhost = false;\r\n\r\n for (unsigned int Index = 0; Index < LENOF(FBugs); Index++)\r\n {\r\n Bug[(TSshBug)Index] = asAuto;\r\n }\r\n\r\n Special = false;\r\n FSProtocol = fsSFTP;\r\n AddressFamily = afAuto;\r\n RekeyData = L\"1G\";\r\n RekeyTime = MinsPerHour;\r\n\r\n // FS common\r\n LocalDirectory = L\"\";\r\n RemoteDirectory = L\"\";\r\n SynchronizeBrowsing = false;\r\n UpdateDirectories = true;\r\n CacheDirectories = true;\r\n CacheDirectoryChanges = true;\r\n PreserveDirectoryChanges = true;\r\n LockInHome = false;\r\n ResolveSymlinks = true;\r\n FollowDirectorySymlinks = false;\r\n DSTMode = dstmUnix;\r\n DeleteToRecycleBin = false;\r\n OverwrittenToRecycleBin = false;\r\n RecycleBinPath = L\"\";\r\n Color = 0;\r\n PostLoginCommands = L\"\";\r\n\r\n // SCP\r\n LookupUserGroups = asAuto;\r\n EOLType = eolLF;\r\n TrimVMSVersions = false;\r\n Shell = L\"\"; //default shell\r\n ReturnVar = L\"\";\r\n ExitCode1IsError = false;\r\n ClearAliases = true;\r\n UnsetNationalVars = true;\r\n ListingCommand = L\"ls -la\";\r\n IgnoreLsWarnings = true;\r\n Scp1Compatibility = false;\r\n TimeDifference = 0;\r\n TimeDifferenceAuto = true;\r\n SCPLsFullTime = asAuto;\r\n NotUtf = asAuto;\r\n\r\n S3DefaultRegion = L\"\";\r\n S3UrlStyle = s3usVirtualHost;\r\n\r\n // SFTP\r\n SftpServer = L\"\";\r\n SFTPDownloadQueue = 32;\r\n SFTPUploadQueue = 32;\r\n SFTPListingQueue = 2;\r\n SFTPMaxVersion = ::SFTPMaxVersion;\r\n SFTPMaxPacketSize = 0;\r\n\r\n for (unsigned int Index = 0; Index < LENOF(FSFTPBugs); Index++)\r\n {\r\n SFTPBug[(TSftpBug)Index] = asAuto;\r\n }\r\n\r\n Tunnel = false;\r\n TunnelHostName = L\"\";\r\n TunnelPortNumber = SshPortNumber;\r\n TunnelUserName = L\"\";\r\n TunnelPassword = L\"\";\r\n TunnelPublicKeyFile = L\"\";\r\n TunnelLocalPortNumber = 0;\r\n TunnelPortFwd = L\"\";\r\n TunnelHostKey = L\"\";\r\n\r\n // FTP\r\n FtpPasvMode = true;\r\n FtpForcePasvIp = asAuto;\r\n FtpUseMlsd = asAuto;\r\n FtpAccount = L\"\";\r\n FtpPingInterval = 30;\r\n FtpPingType = ptDummyCommand;\r\n FtpTransferActiveImmediately = asAuto;\r\n Ftps = ftpsNone;\r\n MinTlsVersion = tls10;\r\n MaxTlsVersion = tls12;\r\n FtpListAll = asAuto;\r\n FtpHost = asAuto;\r\n FtpDeleteFromCwd = asAuto;\r\n SslSessionReuse = true;\r\n TlsCertificateFile = L\"\";\r\n\r\n FtpProxyLogonType = 0; // none\r\n\r\n PuttySettings = UnicodeString();\r\n\r\n CustomParam1 = L\"\";\r\n CustomParam2 = L\"\";\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::Default()\r\n{\r\n DefaultSettings();\r\n\r\n IsWorkspace = false;\r\n Link = L\"\";\r\n NameOverride = L\"\";\r\n\r\n Selected = false;\r\n FModified = false;\r\n FSource = ::ssNone;\r\n FSaveOnly = false;\r\n\r\n // add also to TSessionLog::AddStartupInfo()\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::NonPersistant()\r\n{\r\n UpdateDirectories = false;\r\n PreserveDirectoryChanges = false;\r\n}\r\n//---------------------------------------------------------------------\r\n#define PROPERTY(P) PROPERTY_HANDLER(P, )\r\n#define BASE_PROPERTIES \\\r\n PROPERTY(HostName); \\\r\n PROPERTY(PortNumber); \\\r\n PROPERTY(UserName); \\\r\n PROPERTY_HANDLER(Password, F); \\\r\n PROPERTY(PublicKeyFile); \\\r\n PROPERTY_HANDLER(Passphrase, F); \\\r\n PROPERTY(FSProtocol); \\\r\n PROPERTY(Ftps); \\\r\n PROPERTY(LocalDirectory); \\\r\n PROPERTY(RemoteDirectory); \\\r\n PROPERTY(Color); \\\r\n PROPERTY(SynchronizeBrowsing); \\\r\n PROPERTY(Note);\r\n//---------------------------------------------------------------------\r\n#define ADVANCED_PROPERTIES \\\r\n PROPERTY_HANDLER(NewPassword, F); \\\r\n PROPERTY(ChangePassword); \\\r\n PROPERTY(PingInterval); \\\r\n PROPERTY(PingType); \\\r\n PROPERTY(Timeout); \\\r\n PROPERTY(TryAgent); \\\r\n PROPERTY(AgentFwd); \\\r\n PROPERTY(AuthTIS); \\\r\n PROPERTY(LogicalHostName); \\\r\n PROPERTY(ChangeUsername); \\\r\n PROPERTY(Compression); \\\r\n PROPERTY(SshProt); \\\r\n PROPERTY(Ssh2DES); \\\r\n PROPERTY(SshNoUserAuth); \\\r\n PROPERTY(CipherList); \\\r\n PROPERTY(KexList); \\\r\n PROPERTY(HostKeyList); \\\r\n PROPERTY(GssLibList); \\\r\n PROPERTY(GssLibCustom); \\\r\n PROPERTY(AddressFamily); \\\r\n PROPERTY(RekeyData); \\\r\n PROPERTY(RekeyTime); \\\r\n PROPERTY(HostKey); \\\r\n PROPERTY(FingerprintScan); \\\r\n PROPERTY(InternalEditorEncoding); \\\r\n \\\r\n PROPERTY(UpdateDirectories); \\\r\n PROPERTY(CacheDirectories); \\\r\n PROPERTY(CacheDirectoryChanges); \\\r\n PROPERTY(PreserveDirectoryChanges); \\\r\n \\\r\n PROPERTY(ResolveSymlinks); \\\r\n PROPERTY(FollowDirectorySymlinks); \\\r\n PROPERTY(DSTMode); \\\r\n PROPERTY(LockInHome); \\\r\n PROPERTY(Special); \\\r\n PROPERTY(Selected); \\\r\n PROPERTY(ReturnVar); \\\r\n PROPERTY(ExitCode1IsError); \\\r\n PROPERTY(LookupUserGroups); \\\r\n PROPERTY(EOLType); \\\r\n PROPERTY(TrimVMSVersions); \\\r\n PROPERTY(Shell); \\\r\n PROPERTY(ClearAliases); \\\r\n PROPERTY(Scp1Compatibility); \\\r\n PROPERTY(UnsetNationalVars); \\\r\n PROPERTY(ListingCommand); \\\r\n PROPERTY(IgnoreLsWarnings); \\\r\n PROPERTY(SCPLsFullTime); \\\r\n \\\r\n PROPERTY(TimeDifference); \\\r\n PROPERTY(TimeDifferenceAuto); \\\r\n PROPERTY(TcpNoDelay); \\\r\n PROPERTY(SendBuf); \\\r\n PROPERTY(SourceAddress); \\\r\n PROPERTY(SshSimple); \\\r\n PROPERTY(AuthKI); \\\r\n PROPERTY(AuthKIPassword); \\\r\n PROPERTY(AuthGSSAPI); \\\r\n PROPERTY(GSSAPIFwdTGT); \\\r\n PROPERTY(DeleteToRecycleBin); \\\r\n PROPERTY(OverwrittenToRecycleBin); \\\r\n PROPERTY(RecycleBinPath); \\\r\n PROPERTY(NotUtf); \\\r\n PROPERTY(PostLoginCommands); \\\r\n \\\r\n PROPERTY(S3DefaultRegion); \\\r\n PROPERTY(S3UrlStyle); \\\r\n \\\r\n PROPERTY(ProxyMethod); \\\r\n PROPERTY(ProxyHost); \\\r\n PROPERTY(ProxyPort); \\\r\n PROPERTY(ProxyUsername); \\\r\n PROPERTY_HANDLER(ProxyPassword, F); \\\r\n PROPERTY(ProxyTelnetCommand); \\\r\n PROPERTY(ProxyLocalCommand); \\\r\n PROPERTY(ProxyDNS); \\\r\n PROPERTY(ProxyLocalhost); \\\r\n \\\r\n for (unsigned int Index = 0; Index < LENOF(FBugs); Index++) \\\r\n { \\\r\n PROPERTY(Bug[(TSshBug)Index]); \\\r\n } \\\r\n \\\r\n PROPERTY(SftpServer); \\\r\n PROPERTY(SFTPDownloadQueue); \\\r\n PROPERTY(SFTPUploadQueue); \\\r\n PROPERTY(SFTPListingQueue); \\\r\n PROPERTY(SFTPMaxVersion); \\\r\n PROPERTY(SFTPMaxPacketSize); \\\r\n \\\r\n for (unsigned int Index = 0; Index < LENOF(FSFTPBugs); Index++) \\\r\n { \\\r\n PROPERTY(SFTPBug[(TSftpBug)Index]); \\\r\n } \\\r\n \\\r\n PROPERTY(Tunnel); \\\r\n PROPERTY(TunnelHostName); \\\r\n PROPERTY(TunnelPortNumber); \\\r\n PROPERTY(TunnelUserName); \\\r\n PROPERTY_HANDLER(TunnelPassword, F); \\\r\n PROPERTY(TunnelPublicKeyFile); \\\r\n PROPERTY(TunnelLocalPortNumber); \\\r\n PROPERTY(TunnelPortFwd); \\\r\n PROPERTY(TunnelHostKey); \\\r\n \\\r\n PROPERTY(FtpPasvMode); \\\r\n PROPERTY(FtpForcePasvIp); \\\r\n PROPERTY(FtpUseMlsd); \\\r\n PROPERTY(FtpAccount); \\\r\n PROPERTY(FtpPingInterval); \\\r\n PROPERTY(FtpPingType); \\\r\n PROPERTY(FtpTransferActiveImmediately); \\\r\n PROPERTY(FtpListAll); \\\r\n PROPERTY(FtpHost); \\\r\n PROPERTY(FtpDeleteFromCwd); \\\r\n PROPERTY(SslSessionReuse); \\\r\n PROPERTY(TlsCertificateFile); \\\r\n \\\r\n PROPERTY(FtpProxyLogonType); \\\r\n \\\r\n PROPERTY(MinTlsVersion); \\\r\n PROPERTY(MaxTlsVersion); \\\r\n \\\r\n PROPERTY(WinTitle); \\\r\n \\\r\n PROPERTY_HANDLER(EncryptKey, F); \\\r\n \\\r\n PROPERTY(PuttySettings); \\\r\n \\\r\n PROPERTY(CustomParam1); \\\r\n PROPERTY(CustomParam2);\r\n#define META_PROPERTIES \\\r\n PROPERTY(IsWorkspace); \\\r\n PROPERTY(Link); \\\r\n PROPERTY(NameOverride);\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::Assign(TPersistent * Source)\r\n{\r\n if (Source && Source->InheritsFrom(__classid(TSessionData)))\r\n {\r\n TSessionData * SourceData = (TSessionData *)Source;\r\n // Master password prompt shows implicitly here, when cloning the session data for a new terminal\r\n CopyData(SourceData);\r\n FSource = SourceData->FSource;\r\n }\r\n else\r\n {\r\n TNamedObject::Assign(Source);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::DoCopyData(TSessionData * SourceData, bool NoRecrypt)\r\n{\r\n #define PROPERTY_HANDLER(P, F) \\\r\n if (NoRecrypt) \\\r\n { \\\r\n F##P = SourceData->F##P; \\\r\n } \\\r\n else \\\r\n { \\\r\n P = SourceData->P; \\\r\n }\r\n PROPERTY(Name);\r\n BASE_PROPERTIES;\r\n ADVANCED_PROPERTIES;\r\n META_PROPERTIES;\r\n #undef PROPERTY_HANDLER\r\n FOverrideCachedHostKey = SourceData->FOverrideCachedHostKey;\r\n FModified = SourceData->Modified;\r\n FSaveOnly = SourceData->FSaveOnly;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::CopyData(TSessionData * SourceData)\r\n{\r\n DoCopyData(SourceData, false);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::CopyDataNoRecrypt(TSessionData * SourceData)\r\n{\r\n DoCopyData(SourceData, true);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::CopyDirectoriesStateData(TSessionData * SourceData)\r\n{\r\n RemoteDirectory = SourceData->RemoteDirectory;\r\n LocalDirectory = SourceData->LocalDirectory;\r\n SynchronizeBrowsing = SourceData->SynchronizeBrowsing;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::HasStateData()\r\n{\r\n return\r\n !RemoteDirectory.IsEmpty() ||\r\n !LocalDirectory.IsEmpty() ||\r\n (Color != 0);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::CopyStateData(TSessionData * SourceData)\r\n{\r\n // Keep in sync with TCustomScpExplorerForm::UpdateSessionData.\r\n CopyDirectoriesStateData(SourceData);\r\n Color = SourceData->Color;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::CopyNonCoreData(TSessionData * SourceData)\r\n{\r\n CopyStateData(SourceData);\r\n UpdateDirectories = SourceData->UpdateDirectories;\r\n Note = SourceData->Note;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsSame(\r\n const TSessionData * Default, bool AdvancedOnly, TStrings * DifferentProperties, bool Decrypted)\r\n{\r\n bool Result = true;\r\n #define PROPERTY_HANDLER(P, F) \\\r\n if ((Decrypted && (P != Default->P)) || \\\r\n (!Decrypted && (F##P != Default->F##P))) \\\r\n { \\\r\n Result = false; \\\r\n if (DifferentProperties != NULL) \\\r\n { \\\r\n DifferentProperties->Add(#P); \\\r\n } \\\r\n else \\\r\n { \\\r\n return Result; \\\r\n } \\\r\n }\r\n\r\n if (!AdvancedOnly)\r\n {\r\n BASE_PROPERTIES;\r\n META_PROPERTIES;\r\n }\r\n ADVANCED_PROPERTIES;\r\n #undef PROPERTY_HANDLER\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsSame(const TSessionData * Default, bool AdvancedOnly)\r\n{\r\n return IsSame(Default, AdvancedOnly, NULL, false);\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsSameDecrypted(const TSessionData * Default)\r\n{\r\n return IsSame(Default, false, NULL, true);\r\n}\r\n//---------------------------------------------------------------------\r\nTFSProtocol NormalizeFSProtocol(TFSProtocol FSProtocol)\r\n{\r\n if (FSProtocol == fsSFTPonly)\r\n {\r\n FSProtocol = fsSFTP;\r\n }\r\n return FSProtocol;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsSameSite(const TSessionData * Other)\r\n{\r\n return\r\n // Particularly when handling /refresh,\r\n // fsSFTPonly sites when compared against sftp:// URLs (fsSFTP) have to match.\r\n // But similarly also falled back SCP sites.\r\n (NormalizeFSProtocol(FSProtocol) == NormalizeFSProtocol(Other->FSProtocol)) &&\r\n (HostName == Other->HostName) &&\r\n (PortNumber == Other->PortNumber) &&\r\n (UserName == Other->UserName);\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsInFolderOrWorkspace(UnicodeString AFolder)\r\n{\r\n return StartsText(UnixIncludeTrailingBackslash(AFolder), Name);\r\n}\r\n//---------------------------------------------------------------------\r", "void __fastcall TSessionData::DoLoad(THierarchicalStorage * Storage, bool PuttyImport, bool & RewritePassword)\r", "{\r\n // Make sure we only ever use methods supported by TOptionsStorage\r\n // (implemented by TOptionsIniFile)\r\n\r\n PortNumber = Storage->ReadInteger(L\"PortNumber\", PortNumber);\r\n UserName = Storage->ReadString(L\"UserName\", UserName);\r\n // must be loaded after UserName, because HostName may be in format user@host\r\n HostName = Storage->ReadString(L\"HostName\", HostName);\r\n\r\n if (!Configuration->DisablePasswordStoring)\r\n {\r\n if (Storage->ValueExists(L\"PasswordPlain\"))\r\n {\r\n Password = Storage->ReadString(L\"PasswordPlain\", Password);\r\n RewritePassword = true;\r\n }\r\n else\r\n {\r\n RawByteString APassword = Storage->ReadStringAsBinaryData(L\"Password\", FPassword);\r\n SET_SESSION_PROPERTY_FROM(Password, APassword);\r\n }\r\n }\r\n HostKey = Storage->ReadString(L\"SshHostKey\", HostKey); // probably never used\r\n Note = Storage->ReadString(L\"Note\", Note);\r\n // Putty uses PingIntervalSecs\r\n int PingIntervalSecs = Storage->ReadInteger(L\"PingIntervalSecs\", -1);\r\n if (PingIntervalSecs < 0)\r\n {\r\n PingIntervalSecs = Storage->ReadInteger(L\"PingIntervalSec\", PingInterval%SecsPerMin);\r\n }\r\n PingInterval =\r\n Storage->ReadInteger(L\"PingInterval\", PingInterval/SecsPerMin)*SecsPerMin +\r\n PingIntervalSecs;\r\n if (PingInterval == 0)\r\n {\r\n PingInterval = 30;\r\n }\r\n PingType = static_cast<TPingType>(Storage->ReadInteger(L\"PingType\", PingType));\r\n Timeout = Storage->ReadInteger(L\"Timeout\", Timeout);\r\n TryAgent = Storage->ReadBool(L\"TryAgent\", TryAgent);\r\n AgentFwd = Storage->ReadBool(L\"AgentFwd\", AgentFwd);\r\n AuthTIS = Storage->ReadBool(L\"AuthTIS\", AuthTIS);\r\n AuthKI = Storage->ReadBool(L\"AuthKI\", AuthKI);\r\n AuthKIPassword = Storage->ReadBool(L\"AuthKIPassword\", AuthKIPassword);\r\n // Continue to use setting keys of previous kerberos implementation (vaclav tomec),\r\n // but fallback to keys of other implementations (official putty and vintela quest putty),\r\n // to allow imports from all putty versions.\r\n // Both vaclav tomec and official putty use AuthGSSAPI\r\n AuthGSSAPI = Storage->ReadBool(L\"AuthGSSAPI\", Storage->ReadBool(L\"AuthSSPI\", AuthGSSAPI));\r\n GSSAPIFwdTGT = Storage->ReadBool(L\"GSSAPIFwdTGT\", Storage->ReadBool(L\"GssapiFwd\", Storage->ReadBool(L\"SSPIFwdTGT\", GSSAPIFwdTGT)));\r\n // KerbPrincipal was used by Quest PuTTY\r\n // GSSAPIServerRealm was used by Vaclav Tomec\r\n LogicalHostName = Storage->ReadString(L\"LogicalHostName\", Storage->ReadString(L\"GSSAPIServerRealm\", Storage->ReadString(L\"KerbPrincipal\", LogicalHostName)));\r\n ChangeUsername = Storage->ReadBool(L\"ChangeUsername\", ChangeUsername);\r\n Compression = Storage->ReadBool(L\"Compression\", Compression);\r\n TSshProt ASshProt = (TSshProt)Storage->ReadInteger(L\"SshProt\", SshProt);\r\n // Old sessions may contain the values correponding to the fallbacks we used to allow; migrate them\r\n if (ASshProt == ssh2deprecated)\r\n {\r\n ASshProt = ssh2only;\r\n }\r\n else if (ASshProt == ssh1deprecated)\r\n {\r\n ASshProt = ssh1only;\r\n }\r\n SshProt = ASshProt;\r\n Ssh2DES = Storage->ReadBool(L\"Ssh2DES\", Ssh2DES);\r\n SshNoUserAuth = Storage->ReadBool(L\"SshNoUserAuth\", SshNoUserAuth);\r\n CipherList = Storage->ReadString(L\"Cipher\", CipherList);\r\n KexList = Storage->ReadString(L\"KEX\", KexList);\r\n HostKeyList = Storage->ReadString(L\"HostKey\", HostKeyList);\r", " GssLibList = Storage->ReadString(L\"GSSLibs\", GssLibList);\r", " GssLibCustom = Storage->ReadString(L\"GSSCustom\", GssLibCustom);\r\n PublicKeyFile = Storage->ReadString(L\"PublicKeyFile\", PublicKeyFile);\r\n AddressFamily = static_cast<TAddressFamily>\r\n (Storage->ReadInteger(L\"AddressFamily\", AddressFamily));\r\n RekeyData = Storage->ReadString(L\"RekeyBytes\", RekeyData);\r\n RekeyTime = Storage->ReadInteger(L\"RekeyTime\", RekeyTime);\r\n\r\n FSProtocol = (TFSProtocol)Storage->ReadInteger(L\"FSProtocol\", FSProtocol);\r\n LocalDirectory = Storage->ReadString(L\"LocalDirectory\", LocalDirectory);\r\n RemoteDirectory = Storage->ReadString(L\"RemoteDirectory\", RemoteDirectory);\r\n SynchronizeBrowsing = Storage->ReadBool(L\"SynchronizeBrowsing\", SynchronizeBrowsing);\r\n UpdateDirectories = Storage->ReadBool(L\"UpdateDirectories\", UpdateDirectories);\r\n CacheDirectories = Storage->ReadBool(L\"CacheDirectories\", CacheDirectories);\r\n CacheDirectoryChanges = Storage->ReadBool(L\"CacheDirectoryChanges\", CacheDirectoryChanges);\r\n PreserveDirectoryChanges = Storage->ReadBool(L\"PreserveDirectoryChanges\", PreserveDirectoryChanges);\r\n\r\n ResolveSymlinks = Storage->ReadBool(L\"ResolveSymlinks\", ResolveSymlinks);\r\n FollowDirectorySymlinks = Storage->ReadBool(L\"FollowDirectorySymlinks\", FollowDirectorySymlinks);\r\n DSTMode = (TDSTMode)Storage->ReadInteger(L\"ConsiderDST\", DSTMode);\r\n LockInHome = Storage->ReadBool(L\"LockInHome\", LockInHome);\r\n Special = Storage->ReadBool(L\"Special\", Special);\r", " Shell = Storage->ReadString(L\"Shell\", Shell);\r", " ClearAliases = Storage->ReadBool(L\"ClearAliases\", ClearAliases);\r\n UnsetNationalVars = Storage->ReadBool(L\"UnsetNationalVars\", UnsetNationalVars);\r", " ListingCommand = Storage->ReadString(L\"ListingCommand\",\r\n Storage->ReadBool(L\"AliasGroupList\", false) ? UnicodeString(L\"ls -gla\") : ListingCommand);\r", " IgnoreLsWarnings = Storage->ReadBool(L\"IgnoreLsWarnings\", IgnoreLsWarnings);\r\n SCPLsFullTime = TAutoSwitch(Storage->ReadInteger(L\"SCPLsFullTime\", SCPLsFullTime));\r\n Scp1Compatibility = Storage->ReadBool(L\"Scp1Compatibility\", Scp1Compatibility);\r\n TimeDifference = Storage->ReadFloat(L\"TimeDifference\", TimeDifference);\r\n TimeDifferenceAuto = Storage->ReadBool(L\"TimeDifferenceAuto\", (TimeDifference == TDateTime()));\r", " DeleteToRecycleBin = Storage->ReadBool(L\"DeleteToRecycleBin\", DeleteToRecycleBin);\r\n OverwrittenToRecycleBin = Storage->ReadBool(L\"OverwrittenToRecycleBin\", OverwrittenToRecycleBin);\r\n RecycleBinPath = Storage->ReadString(L\"RecycleBinPath\", RecycleBinPath);\r\n PostLoginCommands = Storage->ReadString(L\"PostLoginCommands\", PostLoginCommands);\r\n\r\n ReturnVar = Storage->ReadString(L\"ReturnVar\", ReturnVar);\r", " ExitCode1IsError = Storage->ReadBool(L\"ExitCode1IsError\", ExitCode1IsError);\r\n LookupUserGroups = TAutoSwitch(Storage->ReadInteger(L\"LookupUserGroups2\", LookupUserGroups));\r\n EOLType = (TEOLType)Storage->ReadInteger(L\"EOLType\", EOLType);\r\n TrimVMSVersions = Storage->ReadBool(L\"TrimVMSVersions\", TrimVMSVersions);\r\n NotUtf = TAutoSwitch(Storage->ReadInteger(L\"Utf\", Storage->ReadInteger(L\"SFTPUtfBug\", NotUtf)));\r\n InternalEditorEncoding = Storage->ReadInteger(L\"InternalEditorEncoding\", InternalEditorEncoding);\r\n\r\n S3DefaultRegion = Storage->ReadString(L\"S3DefaultRegion\", S3DefaultRegion);\r\n S3UrlStyle = (TS3UrlStyle)Storage->ReadInteger(L\"S3UrlStyle\", S3UrlStyle);\r\n\r\n // PuTTY defaults to TcpNoDelay, but the psftp/pscp ignores this preference, and always set this to off (what is our default too)\r\n if (!PuttyImport)\r\n {\r\n TcpNoDelay = Storage->ReadBool(L\"TcpNoDelay\", TcpNoDelay);\r\n }\r\n SendBuf = Storage->ReadInteger(L\"SendBuf\", Storage->ReadInteger(\"SshSendBuf\", SendBuf));\r\n SourceAddress = Storage->ReadString(L\"SourceAddress\", SourceAddress);\r\n SshSimple = Storage->ReadBool(L\"SshSimple\", SshSimple);\r\n\r\n ProxyMethod = (TProxyMethod)Storage->ReadInteger(L\"ProxyMethod\", ProxyMethod);\r\n ProxyHost = Storage->ReadString(L\"ProxyHost\", ProxyHost);\r\n ProxyPort = Storage->ReadInteger(L\"ProxyPort\", ProxyPort);\r\n ProxyUsername = Storage->ReadString(L\"ProxyUsername\", ProxyUsername);\r\n if (Storage->ValueExists(L\"ProxyPassword\"))\r\n {\r\n // encrypt unencrypted password\r\n ProxyPassword = Storage->ReadString(L\"ProxyPassword\", L\"\");\r\n }\r\n else\r\n {\r\n // load encrypted password\r\n RawByteString AProxyPassword = Storage->ReadStringAsBinaryData(L\"ProxyPasswordEnc\", FProxyPassword);\r\n SET_SESSION_PROPERTY_FROM(ProxyPassword, AProxyPassword);\r\n }\r", " if (ProxyMethod == pmCmd)\r\n {\r\n ProxyLocalCommand = Storage->ReadStringRaw(L\"ProxyTelnetCommand\", ProxyLocalCommand);\r\n }\r\n else\r\n {\r\n ProxyTelnetCommand = Storage->ReadStringRaw(L\"ProxyTelnetCommand\", ProxyTelnetCommand);\r", " }\r\n ProxyDNS = TAutoSwitch((Storage->ReadInteger(L\"ProxyDNS\", (ProxyDNS + 2) % 3) + 1) % 3);\r\n ProxyLocalhost = Storage->ReadBool(L\"ProxyLocalhost\", ProxyLocalhost);\r\n\r\n #define READ_BUG(BUG) \\\r\n Bug[sb##BUG] = TAutoSwitch(2 - Storage->ReadInteger(L\"Bug\"#BUG, \\\r\n 2 - Bug[sb##BUG]));\r\n READ_BUG(Ignore1);\r\n READ_BUG(PlainPW1);\r\n READ_BUG(RSA1);\r\n READ_BUG(HMAC2);\r\n READ_BUG(DeriveKey2);\r\n READ_BUG(RSAPad2);\r\n READ_BUG(PKSessID2);\r\n READ_BUG(Rekey2);\r\n READ_BUG(MaxPkt2);\r\n READ_BUG(Ignore2);\r\n READ_BUG(OldGex2);\r\n READ_BUG(WinAdj);\r\n READ_BUG(ChanReq);\r\n #undef READ_BUG\r\n\r\n if ((Bug[sbHMAC2] == asAuto) &&\r\n Storage->ReadBool(L\"BuggyMAC\", false))\r\n {\r\n Bug[sbHMAC2] = asOn;\r\n }\r\n\r", " SftpServer = Storage->ReadString(L\"SftpServer\", SftpServer);\r", " #define READ_SFTP_BUG(BUG) \\\r\n SFTPBug[sb##BUG] = TAutoSwitch(Storage->ReadInteger(L\"SFTP\" #BUG \"Bug\", SFTPBug[sb##BUG]));\r\n READ_SFTP_BUG(Symlink);\r\n READ_SFTP_BUG(SignedTS);\r\n #undef READ_SFTP_BUG\r\n\r\n SFTPMaxVersion = Storage->ReadInteger(L\"SFTPMaxVersion\", SFTPMaxVersion);\r\n SFTPMaxPacketSize = Storage->ReadInteger(L\"SFTPMaxPacketSize\", SFTPMaxPacketSize);\r\n SFTPDownloadQueue = Storage->ReadInteger(L\"SFTPDownloadQueue\", SFTPDownloadQueue);\r\n SFTPUploadQueue = Storage->ReadInteger(L\"SFTPUploadQueue\", SFTPUploadQueue);\r\n SFTPListingQueue = Storage->ReadInteger(L\"SFTPListingQueue\", SFTPListingQueue);\r\n\r\n Color = Storage->ReadInteger(L\"Color\", Color);\r\n\r\n PuttyProtocol = Storage->ReadString(L\"Protocol\", PuttyProtocol);\r\n\r\n Tunnel = Storage->ReadBool(L\"Tunnel\", Tunnel);\r\n TunnelPortNumber = Storage->ReadInteger(L\"TunnelPortNumber\", TunnelPortNumber);\r\n TunnelUserName = Storage->ReadString(L\"TunnelUserName\", TunnelUserName);\r\n // must be loaded after TunnelUserName,\r\n // because TunnelHostName may be in format user@host\r\n TunnelHostName = Storage->ReadString(L\"TunnelHostName\", TunnelHostName);\r\n if (!Configuration->DisablePasswordStoring)\r\n {\r\n if (Storage->ValueExists(L\"TunnelPasswordPlain\"))\r\n {\r\n TunnelPassword = Storage->ReadString(L\"TunnelPasswordPlain\", TunnelPassword);\r\n RewritePassword = true;\r\n }\r\n else\r\n {\r\n RawByteString ATunnelPassword = Storage->ReadStringAsBinaryData(L\"TunnelPassword\", FTunnelPassword);\r\n SET_SESSION_PROPERTY_FROM(TunnelPassword, ATunnelPassword);\r\n }\r\n }\r\n TunnelPublicKeyFile = Storage->ReadString(L\"TunnelPublicKeyFile\", TunnelPublicKeyFile);\r\n TunnelLocalPortNumber = Storage->ReadInteger(L\"TunnelLocalPortNumber\", TunnelLocalPortNumber);\r\n TunnelHostKey = Storage->ReadString(L\"TunnelHostKey\", TunnelHostKey);\r\n\r\n // Ftp prefix\r\n FtpPasvMode = Storage->ReadBool(L\"FtpPasvMode\", FtpPasvMode);\r\n FtpForcePasvIp = TAutoSwitch(Storage->ReadInteger(L\"FtpForcePasvIp2\", FtpForcePasvIp));\r\n FtpUseMlsd = TAutoSwitch(Storage->ReadInteger(L\"FtpUseMlsd\", FtpUseMlsd));\r\n FtpAccount = Storage->ReadString(L\"FtpAccount\", FtpAccount);\r\n FtpPingInterval = Storage->ReadInteger(L\"FtpPingInterval\", FtpPingInterval);\r\n FtpPingType = static_cast<TPingType>(Storage->ReadInteger(L\"FtpPingType\", FtpPingType));\r\n FtpTransferActiveImmediately = static_cast<TAutoSwitch>(Storage->ReadInteger(L\"FtpTransferActiveImmediately2\", FtpTransferActiveImmediately));\r\n Ftps = static_cast<TFtps>(Storage->ReadInteger(L\"Ftps\", Ftps));\r\n FtpListAll = TAutoSwitch(Storage->ReadInteger(L\"FtpListAll\", FtpListAll));\r\n FtpHost = TAutoSwitch(Storage->ReadInteger(L\"FtpHost\", FtpHost));\r\n FtpDeleteFromCwd = TAutoSwitch(Storage->ReadInteger(L\"FtpDeleteFromCwd\", FtpDeleteFromCwd));\r\n SslSessionReuse = Storage->ReadBool(L\"SslSessionReuse\", SslSessionReuse);\r\n TlsCertificateFile = Storage->ReadString(L\"TlsCertificateFile\", TlsCertificateFile);\r\n\r\n FtpProxyLogonType = Storage->ReadInteger(L\"FtpProxyLogonType\", FtpProxyLogonType);\r\n\r\n MinTlsVersion = static_cast<TTlsVersion>(Storage->ReadInteger(L\"MinTlsVersion\", MinTlsVersion));\r\n MaxTlsVersion = static_cast<TTlsVersion>(Storage->ReadInteger(L\"MaxTlsVersion\", MaxTlsVersion));\r\n\r\n if (Storage->ValueExists(L\"EncryptKeyPlain\"))\r\n {\r\n EncryptKey = Storage->ReadString(L\"EncryptKeyPlain\", EncryptKey);\r\n RewritePassword = true;\r\n }\r\n else\r\n {\r\n RawByteString AEncryptKey = Storage->ReadStringAsBinaryData(L\"EncryptKey\", FEncryptKey);\r\n SET_SESSION_PROPERTY_FROM(EncryptKey, AEncryptKey);\r\n }\r\n\r\n IsWorkspace = Storage->ReadBool(L\"IsWorkspace\", IsWorkspace);\r\n Link = Storage->ReadString(L\"Link\", Link);\r\n NameOverride = Storage->ReadString(L\"NameOverride\", NameOverride);\r\n\r\n PuttySettings = Storage->ReadString(L\"PuttySettings\", PuttySettings);\r\n\r\n CustomParam1 = Storage->ReadString(L\"CustomParam1\", CustomParam1);\r\n CustomParam2 = Storage->ReadString(L\"CustomParam2\", CustomParam2);\r\n\r\n#ifdef TEST\r\n #define KEX_TEST(VALUE, EXPECTED) KexList = VALUE; DebugAssert(KexList == EXPECTED);\r\n #define KEX_DEFAULT L\"ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN,dh-group1-sha1\"\r\n // Empty source should result in default list\r\n KEX_TEST(L\"\", KEX_DEFAULT);\r\n // Default of pre 5.8.1\r\n KEX_TEST(L\"dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN\", L\"ecdh,dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN\");\r\n // Missing first two priority algos, and last non-priority algo\r\n KEX_TEST(L\"dh-group14-sha1,dh-group1-sha1,WARN\", L\"ecdh,dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN\");\r\n // Missing first two priority algos, last non-priority algo and WARN\r\n KEX_TEST(L\"dh-group14-sha1,dh-group1-sha1\", L\"ecdh,dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN\");\r\n // Old algos, with all but the first below WARN\r\n KEX_TEST(L\"dh-gex-sha1,WARN,dh-group14-sha1,dh-group1-sha1,rsa\", L\"ecdh,dh-gex-sha1,WARN,dh-group14-sha1,dh-group1-sha1,rsa\");\r\n // Unknown algo at front\r\n KEX_TEST(L\"unknown,ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN,dh-group1-sha1\", KEX_DEFAULT);\r\n // Unknown algo at back\r\n KEX_TEST(L\"ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN,dh-group1-sha1,unknown\", KEX_DEFAULT);\r\n // Unknown algo in the middle\r\n KEX_TEST(L\"ecdh,dh-gex-sha1,dh-group14-sha1,unknown,rsa,WARN,dh-group1-sha1\", KEX_DEFAULT);\r\n #undef KEX_DEFAULT\r\n #undef KEX_TEST\r\n\r\n #define CIPHER_TEST(VALUE, EXPECTED) CipherList = VALUE; DebugAssert(CipherList == EXPECTED);\r\n #define CIPHER_DEFAULT L\"aes,chacha20,blowfish,3des,WARN,arcfour,des\"\r\n // Empty source should result in default list\r\n CIPHER_TEST(L\"\", CIPHER_DEFAULT);\r\n // Default of pre 5.8.1\r\n CIPHER_TEST(L\"aes,blowfish,3des,WARN,arcfour,des\", L\"aes,blowfish,3des,chacha20,WARN,arcfour,des\");\r\n // Missing priority algo\r\n CIPHER_TEST(L\"chacha20,blowfish,3des,WARN,arcfour,des\", CIPHER_DEFAULT);\r\n // Missing non-priority algo\r\n CIPHER_TEST(L\"aes,chacha20,3des,WARN,arcfour,des\", L\"aes,chacha20,3des,blowfish,WARN,arcfour,des\");\r\n // Missing last warn algo\r\n CIPHER_TEST(L\"aes,blowfish,chacha20,3des,WARN,arcfour\", L\"aes,blowfish,chacha20,3des,WARN,arcfour,des\");\r\n // Missing first warn algo\r\n CIPHER_TEST(L\"aes,blowfish,chacha20,3des,WARN,des\", L\"aes,blowfish,chacha20,3des,WARN,des,arcfour\");\r\n #undef CIPHER_DEFAULT\r\n #undef CIPHER_TEST\r\n\r\n #define HOSTKEY_TEST(VALUE, EXPECTED) HostKeyList = VALUE; DebugAssert(HostKeyList == EXPECTED);\r\n #define HOSTKEY_DEFAULT L\"ed25519,ecdsa,rsa,dsa,WARN\"\r\n // Empty source should result in default list\r\n HOSTKEY_TEST(L\"\", HOSTKEY_DEFAULT);\r\n // Missing priority algo\r\n HOSTKEY_TEST(L\"ecdsa,rsa,dsa,WARN\", HOSTKEY_DEFAULT);\r\n // Missing non-priority algo\r\n HOSTKEY_TEST(L\"ed25519,ecdsa,dsa,WARN\", L\"ed25519,ecdsa,dsa,rsa,WARN\");\r\n #undef HOSTKEY_DEFAULT\r\n #undef HOSTKEY_TEST\r\n#endif\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::Load(THierarchicalStorage * Storage, bool PuttyImport)\r\n{\r\n bool RewritePassword = false;\r\n if (Storage->OpenSubKey(InternalStorageKey, False))\r\n {\r\n // In case we are re-loading, reset passwords, to avoid pointless\r\n // re-cryption, while loading username/hostname. And moreover, when\r\n // the password is wrongly encrypted (using a different master password),\r\n // this breaks sites reload and consequently an overal operation,\r\n // such as opening Sites menu\r\n ClearSessionPasswords();\r\n FProxyPassword = L\"\";\r\n\r", " DoLoad(Storage, PuttyImport, RewritePassword);\r", "\r\n Storage->CloseSubKey();\r\n }\r\n\r\n if (RewritePassword)\r\n {\r\n TStorageAccessMode AccessMode = Storage->AccessMode;\r\n Storage->AccessMode = smReadWrite;\r\n\r\n try\r\n {\r\n if (Storage->OpenSubKey(InternalStorageKey, true))\r\n {\r\n Storage->DeleteValue(L\"PasswordPlain\");\r\n if (!Password.IsEmpty())\r\n {\r\n Storage->WriteBinaryDataAsString(L\"Password\", FPassword);\r\n }\r\n Storage->DeleteValue(L\"TunnelPasswordPlain\");\r\n if (!TunnelPassword.IsEmpty())\r\n {\r\n Storage->WriteBinaryDataAsString(L\"TunnelPassword\", FTunnelPassword);\r\n }\r\n Storage->DeleteValue(L\"EncryptKeyPlain\");\r\n if (!EncryptKey.IsEmpty())\r\n {\r\n Storage->WriteBinaryDataAsString(L\"EncryptKey\", FEncryptKey);\r\n }\r\n Storage->CloseSubKey();\r\n }\r\n }\r\n catch(...)\r\n {\r\n // ignore errors (like read-only INI file)\r\n }\r\n\r\n Storage->AccessMode = AccessMode;\r\n }\r\n\r\n FModified = false;\r\n FSource = ssStored;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::DoSave(THierarchicalStorage * Storage,\r\n bool PuttyExport, const TSessionData * Default, bool DoNotEncryptPasswords)\r\n{\r\n // Same as in TCopyParamType::Save\r\n #define WRITE_DATA_EX(TYPE, NAME, PROPERTY, CONV) \\\r\n if ((Default != NULL) && (CONV(Default->PROPERTY) == CONV(PROPERTY))) \\\r\n { \\\r\n Storage->DeleteValue(NAME); \\\r\n } \\\r\n else \\\r\n { \\\r\n Storage->Write ## TYPE(NAME, CONV(PROPERTY)); \\\r\n }\r\n #define WRITE_DATA_CONV(TYPE, NAME, PROPERTY) WRITE_DATA_EX(TYPE, NAME, PROPERTY, WRITE_DATA_CONV_FUNC)\r\n #define WRITE_DATA(TYPE, PROPERTY) WRITE_DATA_EX(TYPE, TEXT(#PROPERTY), PROPERTY, )\r\n\r\n WRITE_DATA(String, HostName);\r\n WRITE_DATA(Integer, PortNumber);\r\n WRITE_DATA_EX(Integer, L\"PingInterval\", PingInterval / SecsPerMin, );\r\n WRITE_DATA_EX(Integer, L\"PingIntervalSecs\", PingInterval % SecsPerMin, );\r\n Storage->DeleteValue(L\"PingIntervalSec\"); // obsolete\r\n WRITE_DATA(Integer, PingType);\r\n WRITE_DATA(Integer, Timeout);\r\n WRITE_DATA(Bool, TryAgent);\r\n WRITE_DATA(Bool, AgentFwd);\r\n WRITE_DATA(Bool, AuthTIS);\r\n WRITE_DATA(Bool, AuthKI);\r\n WRITE_DATA(Bool, AuthKIPassword);\r\n WRITE_DATA(String, Note);\r\n\r\n WRITE_DATA(Bool, AuthGSSAPI);\r\n WRITE_DATA(Bool, GSSAPIFwdTGT);\r\n Storage->DeleteValue(L\"TryGSSKEX\");\r\n Storage->DeleteValue(L\"UserNameFromEnvironment\");\r\n Storage->DeleteValue(\"GSSAPIServerChoosesUserName\");\r\n Storage->DeleteValue(L\"GSSAPITrustDNS\");\r\n WRITE_DATA(String, LogicalHostName);\r\n if (PuttyExport)\r\n {\r\n // duplicate kerberos setting with keys of the vintela quest putty\r\n WRITE_DATA_EX(Bool, L\"AuthSSPI\", AuthGSSAPI, );\r\n WRITE_DATA_EX(Bool, L\"SSPIFwdTGT\", GSSAPIFwdTGT, );\r\n WRITE_DATA_EX(String, L\"KerbPrincipal\", LogicalHostName, );\r\n // duplicate kerberos setting with keys of the official putty\r\n WRITE_DATA_EX(Bool, L\"GssapiFwd\", GSSAPIFwdTGT, );\r\n }\r\n\r\n WRITE_DATA(Bool, ChangeUsername);\r\n WRITE_DATA(Bool, Compression);\r\n WRITE_DATA(Integer, SshProt);\r\n WRITE_DATA(Bool, Ssh2DES);\r\n WRITE_DATA(Bool, SshNoUserAuth);\r\n WRITE_DATA_EX(String, L\"Cipher\", CipherList, );\r\n WRITE_DATA_EX(String, L\"KEX\", KexList, );\r\n WRITE_DATA_EX(String, L\"HostKey\", HostKeyList, );\r\n WRITE_DATA_EX(String, L\"GSSLibs\", GssLibList, );\r\n WRITE_DATA_EX(String, L\"GSSCustom\", GssLibCustom, );\r\n WRITE_DATA(Integer, AddressFamily);\r\n WRITE_DATA_EX(String, L\"RekeyBytes\", RekeyData, );\r\n WRITE_DATA(Integer, RekeyTime);\r\n\r\n WRITE_DATA(Bool, TcpNoDelay);\r\n\r\n if (PuttyExport)\r\n {\r\n WRITE_DATA(StringRaw, UserName);\r\n // PuTTY is started in its binary directory to allow relative paths when opening PuTTY's own stored session.\r\n // To allow relative paths in our sessions, we have to expand them for PuTTY.\r\n WRITE_DATA_EX(StringRaw, L\"PublicKeyFile\", PublicKeyFile, ExpandFileName);\r\n }\r\n else\r\n {\r\n WRITE_DATA(String, UserName);\r\n WRITE_DATA(String, PublicKeyFile);\r\n WRITE_DATA(Integer, FSProtocol);\r\n WRITE_DATA(String, LocalDirectory);\r\n WRITE_DATA(String, RemoteDirectory);\r\n WRITE_DATA(Bool, SynchronizeBrowsing);\r\n WRITE_DATA(Bool, UpdateDirectories);\r\n WRITE_DATA(Bool, CacheDirectories);\r\n WRITE_DATA(Bool, CacheDirectoryChanges);\r\n WRITE_DATA(Bool, PreserveDirectoryChanges);\r\n\r\n WRITE_DATA(Bool, ResolveSymlinks);\r\n WRITE_DATA(Bool, FollowDirectorySymlinks);\r\n WRITE_DATA_EX(Integer, L\"ConsiderDST\", DSTMode, );\r\n WRITE_DATA(Bool, LockInHome);\r\n // Special is never stored (if it would, login dialog must be modified not to\r\n // duplicate Special parameter when Special session is loaded and then stored\r\n // under different name)\r\n // WRITE_DATA(Bool, Special);\r\n WRITE_DATA(String, Shell);\r\n WRITE_DATA(Bool, ClearAliases);\r\n WRITE_DATA(Bool, UnsetNationalVars);\r\n WRITE_DATA(String, ListingCommand);\r\n WRITE_DATA(Bool, IgnoreLsWarnings);\r\n WRITE_DATA(Integer, SCPLsFullTime);\r\n WRITE_DATA(Bool, Scp1Compatibility);\r\n // TimeDifferenceAuto is valid for FTP protocol only.\r\n // For other protocols it's typically true (default value),\r\n // but ignored so TimeDifference is still taken into account (SCP only actually)\r\n if (TimeDifferenceAuto && (FSProtocol == fsFTP))\r\n {\r\n // Have to delete it as TimeDifferenceAuto is not saved when enabled,\r\n // but the default is derived from value of TimeDifference.\r\n Storage->DeleteValue(L\"TimeDifference\");\r\n }\r\n else\r\n {\r\n WRITE_DATA(Float, TimeDifference);\r\n }\r\n WRITE_DATA(Bool, TimeDifferenceAuto);\r\n WRITE_DATA(Bool, DeleteToRecycleBin);\r\n WRITE_DATA(Bool, OverwrittenToRecycleBin);\r\n WRITE_DATA(String, RecycleBinPath);\r\n WRITE_DATA(String, PostLoginCommands);\r\n\r\n WRITE_DATA(String, ReturnVar);\r\n WRITE_DATA(Bool, ExitCode1IsError);\r\n WRITE_DATA_EX(Integer, L\"LookupUserGroups2\", LookupUserGroups, );\r\n WRITE_DATA(Integer, EOLType);\r\n WRITE_DATA(Bool, TrimVMSVersions);\r\n Storage->DeleteValue(L\"SFTPUtfBug\");\r\n WRITE_DATA_EX(Integer, L\"Utf\", NotUtf, );\r\n WRITE_DATA(Integer, InternalEditorEncoding);\r\n WRITE_DATA(String, S3DefaultRegion);\r\n WRITE_DATA(Integer, S3UrlStyle);\r\n WRITE_DATA(Integer, SendBuf);\r\n WRITE_DATA(String, SourceAddress);\r\n WRITE_DATA(Bool, SshSimple);\r\n }\r\n\r\n WRITE_DATA(Integer, ProxyMethod);\r\n WRITE_DATA(String, ProxyHost);\r\n WRITE_DATA(Integer, ProxyPort);\r\n WRITE_DATA(String, ProxyUsername);\r\n if (ProxyMethod == pmCmd)\r\n {\r\n WRITE_DATA_EX(StringRaw, L\"ProxyTelnetCommand\", ProxyLocalCommand, );\r\n }\r\n else\r\n {\r\n WRITE_DATA(StringRaw, ProxyTelnetCommand);\r\n }\r\n #define WRITE_DATA_CONV_FUNC(X) (((X) + 2) % 3)\r\n WRITE_DATA_CONV(Integer, L\"ProxyDNS\", ProxyDNS);\r\n #undef WRITE_DATA_CONV_FUNC\r\n WRITE_DATA(Bool, ProxyLocalhost);\r\n\r\n #define WRITE_DATA_CONV_FUNC(X) (2 - (X))\r\n #define WRITE_BUG(BUG) WRITE_DATA_CONV(Integer, L\"Bug\" #BUG, Bug[sb##BUG]);\r\n WRITE_BUG(Ignore1);\r\n WRITE_BUG(PlainPW1);\r\n WRITE_BUG(RSA1);\r\n WRITE_BUG(HMAC2);\r\n WRITE_BUG(DeriveKey2);\r\n WRITE_BUG(RSAPad2);\r\n WRITE_BUG(PKSessID2);\r\n WRITE_BUG(Rekey2);\r\n WRITE_BUG(MaxPkt2);\r\n WRITE_BUG(Ignore2);\r\n WRITE_BUG(OldGex2);\r\n WRITE_BUG(WinAdj);\r\n WRITE_BUG(ChanReq);\r\n #undef WRITE_BUG\r\n #undef WRITE_DATA_CONV_FUNC\r\n\r\n Storage->DeleteValue(L\"BuggyMAC\");\r\n Storage->DeleteValue(L\"AliasGroupList\");\r\n\r\n if (PuttyExport)\r\n {\r\n WRITE_DATA_EX(String, L\"Protocol\", GetNormalizedPuttyProtocol(), );\r\n WRITE_DATA(String, WinTitle);\r\n }\r\n\r\n if (!PuttyExport)\r\n {\r\n WRITE_DATA(String, SftpServer);\r\n\r\n #define WRITE_SFTP_BUG(BUG) WRITE_DATA_EX(Integer, L\"SFTP\" #BUG \"Bug\", SFTPBug[sb##BUG], );\r\n WRITE_SFTP_BUG(Symlink);\r\n WRITE_SFTP_BUG(SignedTS);\r\n #undef WRITE_SFTP_BUG\r\n\r\n WRITE_DATA(Integer, SFTPMaxVersion);\r\n WRITE_DATA(Integer, SFTPMaxPacketSize);\r\n WRITE_DATA(Integer, SFTPDownloadQueue);\r\n WRITE_DATA(Integer, SFTPUploadQueue);\r\n WRITE_DATA(Integer, SFTPListingQueue);\r\n\r\n WRITE_DATA(Integer, Color);\r\n\r\n WRITE_DATA(Bool, Tunnel);\r\n WRITE_DATA(String, TunnelHostName);\r\n WRITE_DATA(Integer, TunnelPortNumber);\r\n WRITE_DATA(String, TunnelUserName);\r\n WRITE_DATA(String, TunnelPublicKeyFile);\r\n WRITE_DATA(Integer, TunnelLocalPortNumber);\r\n\r\n WRITE_DATA(Bool, FtpPasvMode);\r\n WRITE_DATA_EX(Integer, L\"FtpForcePasvIp2\", FtpForcePasvIp, );\r\n WRITE_DATA(Integer, FtpUseMlsd);\r\n WRITE_DATA(String, FtpAccount);\r\n WRITE_DATA(Integer, FtpPingInterval);\r\n WRITE_DATA(Integer, FtpPingType);\r\n WRITE_DATA_EX(Integer, L\"FtpTransferActiveImmediately2\", FtpTransferActiveImmediately, );\r\n WRITE_DATA(Integer, Ftps);\r\n WRITE_DATA(Integer, FtpListAll);\r\n WRITE_DATA(Integer, FtpHost);\r\n WRITE_DATA(Integer, FtpDeleteFromCwd);\r\n WRITE_DATA(Bool, SslSessionReuse);\r\n WRITE_DATA(String, TlsCertificateFile);\r\n\r\n WRITE_DATA(Integer, FtpProxyLogonType);\r\n\r\n WRITE_DATA(Integer, MinTlsVersion);\r\n WRITE_DATA(Integer, MaxTlsVersion);\r\n\r\n WRITE_DATA(Bool, IsWorkspace);\r\n WRITE_DATA(String, Link);\r\n WRITE_DATA(String, NameOverride);\r\n\r\n WRITE_DATA(String, PuttySettings);\r\n\r\n WRITE_DATA(String, CustomParam1);\r\n WRITE_DATA(String, CustomParam2);\r\n }\r\n\r\n // This is for collecting all keys for TSiteRawDialog::AddButtonClick.\r\n // It should be enough to test for (Default == NULL),\r\n // the DoNotEncryptPasswords and PuttyExport were added to limit a possible unintended impact.\r\n bool SaveAll = (Default == NULL) && DoNotEncryptPasswords && !PuttyExport;\r\n\r\n SavePasswords(Storage, PuttyExport, DoNotEncryptPasswords, SaveAll);\r\n\r\n if (PuttyExport)\r\n {\r\n WritePuttySettings(Storage, PuttySettings);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nTStrings * __fastcall TSessionData::SaveToOptions(const TSessionData * Default, bool SaveName, bool PuttyExport)\r\n{\r\n std::unique_ptr<TStringList> Options(new TStringList());\r\n std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));\r\n if (SaveName)\r\n {\r\n OptionsStorage->WriteString(L\"Name\", Name);\r\n }\r\n DoSave(OptionsStorage.get(), PuttyExport, Default, true);\r\n return Options.release();\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::Save(THierarchicalStorage * Storage,\r\n bool PuttyExport, const TSessionData * Default)\r\n{\r\n if (Storage->OpenSubKey(InternalStorageKey, true))\r\n {\r\n DoSave(Storage, PuttyExport, Default, false);\r\n\r\n Storage->CloseSubKey();\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::ReadXmlNode(_di_IXMLNode Node, const UnicodeString & Name, const UnicodeString & Default)\r\n{\r\n _di_IXMLNode TheNode = Node->ChildNodes->FindNode(Name);\r\n UnicodeString Result;\r\n if (TheNode != NULL)\r\n {\r\n Result = TheNode->Text.Trim();\r\n }\r\n\r\n if (Result.IsEmpty())\r\n {\r\n Result = Default;\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nint __fastcall TSessionData::ReadXmlNode(_di_IXMLNode Node, const UnicodeString & Name, int Default)\r\n{\r\n _di_IXMLNode TheNode = Node->ChildNodes->FindNode(Name);\r\n int Result;\r\n if (TheNode != NULL)\r\n {\r\n Result = StrToIntDef(TheNode->Text.Trim(), Default);\r\n }\r\n else\r\n {\r\n Result = Default;\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\n_di_IXMLNode __fastcall TSessionData::FindSettingsNode(_di_IXMLNode Node, const UnicodeString & Name)\r\n{\r\n for (int Index = 0; Index < Node->ChildNodes->Count; Index++)\r\n {\r\n _di_IXMLNode ChildNode = Node->ChildNodes->Get(Index);\r\n if (ChildNode->NodeName == L\"Setting\")\r\n {\r\n OleVariant SettingName = ChildNode->GetAttribute(L\"name\");\r\n if (SettingName == Name)\r\n {\r\n return ChildNode;\r\n }\r\n }\r\n }\r\n\r\n return NULL;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::ReadSettingsNode(_di_IXMLNode Node, const UnicodeString & Name, const UnicodeString & Default)\r\n{\r\n _di_IXMLNode TheNode = FindSettingsNode(Node, Name);\r\n UnicodeString Result;\r\n if (TheNode != NULL)\r\n {\r\n Result = TheNode->Text.Trim();\r\n }\r\n\r\n if (Result.IsEmpty())\r\n {\r\n Result = Default;\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nint __fastcall TSessionData::ReadSettingsNode(_di_IXMLNode Node, const UnicodeString & Name, int Default)\r\n{\r\n _di_IXMLNode TheNode = FindSettingsNode(Node, Name);\r\n int Result;\r\n if (TheNode != NULL)\r\n {\r\n Result = StrToIntDef(TheNode->Text.Trim(), Default);\r\n }\r\n else\r\n {\r\n Result = Default;\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::ImportFromFilezilla(\r\n _di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode)\r\n{\r\n Name = UnixIncludeTrailingBackslash(Path) + MakeValidName(ReadXmlNode(Node, L\"Name\", Name));\r\n HostName = ReadXmlNode(Node, L\"Host\", HostName);\r\n PortNumber = ReadXmlNode(Node, L\"Port\", PortNumber);\r\n\r\n int AProtocol = ReadXmlNode(Node, L\"Protocol\", 0);\r\n // ServerProtocol enum\r\n switch (AProtocol)\r\n {\r\n case 0: // FTP\r\n default: // UNKNOWN, HTTP, HTTPS, INSECURE_FTP\r\n FSProtocol = fsFTP;\r\n break;\r\n\r\n case 1: // SFTP\r\n FSProtocol = fsSFTP;\r\n break;\r\n\r\n case 3: // FTPS\r\n FSProtocol = fsFTP;\r\n Ftps = ftpsImplicit;\r\n break;\r\n\r\n case 4: // FTPES\r\n FSProtocol = fsFTP;\r\n Ftps = ftpsExplicitTls;\r\n break;\r\n }\r\n\r\n // LogonType enum\r\n int LogonType = ReadXmlNode(Node, L\"Logontype\", 0);\r\n if (LogonType == 0) // ANONYMOUS\r\n {\r\n UserName = AnonymousUserName;\r\n Password = AnonymousPassword;\r\n }\r\n else\r\n {\r\n UserName = ReadXmlNode(Node, L\"User\", UserName);\r\n FtpAccount = ReadXmlNode(Node, L\"Account\", FtpAccount);\r\n\r\n _di_IXMLNode PassNode = Node->ChildNodes->FindNode(L\"Pass\");\r\n if (PassNode != NULL)\r\n {\r\n UnicodeString APassword = PassNode->Text.Trim();\r\n OleVariant EncodingValue = PassNode->GetAttribute(L\"encoding\");\r\n if (!EncodingValue.IsNull())\r\n {\r\n UnicodeString EncodingValueStr = EncodingValue;\r\n if (SameText(EncodingValueStr, L\"base64\"))\r\n {\r\n TBytes Bytes = DecodeBase64(APassword);\r\n APassword = TEncoding::UTF8->GetString(Bytes);\r\n }\r\n }\r\n Password = APassword;\r\n }\r\n }\r\n\r\n PublicKeyFile = ReadXmlNode(Node, L\"Keyfile\", PublicKeyFile);\r\n\r\n int DefaultTimeDifference = TimeToSeconds(TimeDifference);\r\n TimeDifference =\r\n (double(ReadXmlNode(Node, L\"TimezoneOffset\", DefaultTimeDifference) / SecsPerDay));\r\n TimeDifferenceAuto = (TimeDifference == TDateTime());\r\n\r\n UnicodeString PasvMode = ReadXmlNode(Node, L\"PasvMode\", L\"\");\r\n if (SameText(PasvMode, L\"MODE_PASSIVE\"))\r\n {\r\n FtpPasvMode = true;\r\n }\r\n else if (SameText(PasvMode, L\"MODE_ACTIVE\"))\r\n {\r\n FtpPasvMode = false;\r\n }\r\n\r\n UnicodeString EncodingType = ReadXmlNode(Node, L\"EncodingType\", L\"\");\r\n if (SameText(EncodingType, L\"Auto\"))\r\n {\r\n NotUtf = asAuto;\r\n }\r\n else if (SameText(EncodingType, L\"UTF-8\"))\r\n {\r\n NotUtf = asOff;\r\n }\r\n\r\n // todo PostLoginCommands\r\n\r\n Note = ReadXmlNode(Node, L\"Comments\", Note);\r\n\r\n LocalDirectory = ReadXmlNode(Node, L\"LocalDir\", LocalDirectory);\r\n\r\n UnicodeString RemoteDir = ReadXmlNode(Node, L\"RemoteDir\", L\"\");\r\n if (!RemoteDir.IsEmpty())\r\n {\r\n CutToChar(RemoteDir, L' ', false); // type\r\n int PrefixSize = StrToIntDef(CutToChar(RemoteDir, L' ', false), 0); // prefix size\r\n if (PrefixSize > 0)\r\n {\r\n RemoteDir.Delete(1, PrefixSize);\r\n }\r\n RemoteDirectory = L\"/\";\r\n while (!RemoteDir.IsEmpty())\r\n {\r\n int SegmentSize = StrToIntDef(CutToChar(RemoteDir, L' ', false), 0);\r\n UnicodeString Segment = RemoteDir.SubString(1, SegmentSize);\r\n RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory) + Segment;\r\n RemoteDir.Delete(1, SegmentSize + 1);\r\n }\r\n }\r\n\r\n SynchronizeBrowsing = (ReadXmlNode(Node, L\"SyncBrowsing\", SynchronizeBrowsing ? 1 : 0) != 0);\r\n\r\n if (SettingsNode != NULL)\r\n {\r\n if (UsesSsh && PublicKeyFile.IsEmpty())\r\n {\r\n UnicodeString KeyFiles = ReadSettingsNode(SettingsNode, L\"SFTP keyfiles\", UnicodeString());\r\n UnicodeString KeyFile = CutToChar(KeyFiles, L'\\n', true).Trim();\r\n KeyFiles = KeyFiles.Trim();\r\n // If there are more keys, ignore them, as we do not know which one to use\r\n if (!KeyFile.IsEmpty() && KeyFiles.IsEmpty())\r\n {\r\n PublicKeyFile = KeyFile;\r\n }\r\n }\r\n\r\n bool BypassProxy = (ReadXmlNode(Node, L\"BypassProxy\", 0) != 0);\r\n if (!BypassProxy)\r\n {\r\n int FtpProxyType = ReadSettingsNode(SettingsNode, L\"FTP Proxy type\", -1);\r\n if (FtpProxyType > 0)\r\n {\r\n switch (FtpProxyType)\r\n {\r\n case 1:\r\n FtpProxyLogonType = 2;\r\n break;\r\n case 2:\r\n FtpProxyLogonType = 1;\r\n break;\r\n case 3:\r\n FtpProxyLogonType = 3;\r\n break;\r\n case 4:\r\n // custom\r\n // TODO: map known sequences to our enumeration\r\n FtpProxyLogonType = 0;\r\n break;\r\n default:\r\n DebugFail();\r\n FtpProxyLogonType = 0;\r\n break;\r\n }\r\n\r\n ProxyHost = ReadSettingsNode(SettingsNode, L\"FTP Proxy host\", ProxyHost);\r\n ProxyUsername = ReadSettingsNode(SettingsNode, L\"FTP Proxy user\", ProxyUsername);\r\n ProxyPassword = ReadSettingsNode(SettingsNode, L\"FTP Proxy password\", ProxyPassword);\r\n // ProxyPort is not used with FtpProxyLogonType\r\n }\r\n else\r\n {\r\n int ProxyType = ReadSettingsNode(SettingsNode, L\"Proxy type\", -1);\r\n if (ProxyType >= 0)\r\n {\r\n switch (ProxyType)\r\n {\r\n case 0:\r\n ProxyMethod = ::pmNone;\r\n break;\r\n\r\n case 1:\r\n ProxyMethod = pmHTTP;\r\n break;\r\n\r\n case 2:\r\n ProxyMethod = pmSocks5;\r\n break;\r\n\r\n case 3:\r\n ProxyMethod = pmSocks4;\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n ProxyMethod = ::pmNone;\r\n break;\r\n }\r\n\r\n ProxyHost = ReadSettingsNode(SettingsNode, L\"Proxy host\", ProxyHost);\r\n ProxyPort = ReadSettingsNode(SettingsNode, L\"Proxy port\", ProxyPort);\r\n ProxyUsername = ReadSettingsNode(SettingsNode, L\"Proxy user\", ProxyUsername);\r\n ProxyPassword = ReadSettingsNode(SettingsNode, L\"Proxy password\", ProxyPassword);\r\n }\r\n }\r\n }\r\n }\r\n\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SavePasswords(THierarchicalStorage * Storage, bool PuttyExport, bool DoNotEncryptPasswords, bool SaveAll)\r\n{\r\n if (!Configuration->DisablePasswordStoring && !PuttyExport && (!FPassword.IsEmpty() || SaveAll))\r\n {\r\n if (DoNotEncryptPasswords)\r\n {\r\n Storage->WriteString(L\"PasswordPlain\", Password);\r\n Storage->DeleteValue(L\"Password\");\r\n }\r\n else\r\n {\r\n Storage->WriteBinaryDataAsString(L\"Password\", StronglyRecryptPassword(FPassword, UserName+HostName));\r\n Storage->DeleteValue(L\"PasswordPlain\");\r\n }\r\n }\r\n else\r\n {\r\n Storage->DeleteValue(L\"Password\");\r\n Storage->DeleteValue(L\"PasswordPlain\");\r\n }\r\n\r\n if (PuttyExport)\r\n {\r\n // save password unencrypted\r\n Storage->WriteString(L\"ProxyPassword\", ProxyPassword);\r\n }\r\n else\r\n {\r\n if (DoNotEncryptPasswords)\r\n {\r\n if (!FProxyPassword.IsEmpty() || SaveAll)\r\n {\r\n Storage->WriteString(L\"ProxyPassword\", ProxyPassword);\r\n }\r\n else\r\n {\r\n Storage->DeleteValue(L\"ProxyPassword\");\r\n }\r\n Storage->DeleteValue(L\"ProxyPasswordEnc\");\r\n }\r\n else\r\n {\r\n // save password encrypted\r\n if (!FProxyPassword.IsEmpty() || SaveAll)\r\n {\r\n Storage->WriteBinaryDataAsString(L\"ProxyPasswordEnc\", StronglyRecryptPassword(FProxyPassword, ProxyUsername+ProxyHost));\r\n }\r\n else\r\n {\r\n Storage->DeleteValue(L\"ProxyPasswordEnc\");\r\n }\r\n Storage->DeleteValue(L\"ProxyPassword\");\r\n }\r\n\r\n if (DoNotEncryptPasswords)\r\n {\r\n if (!FTunnelPassword.IsEmpty() || SaveAll)\r\n {\r\n Storage->WriteString(L\"TunnelPasswordPlain\", TunnelPassword);\r\n }\r\n else\r\n {\r\n Storage->DeleteValue(L\"TunnelPasswordPlain\");\r\n }\r\n }\r\n else\r\n {\r\n if (!Configuration->DisablePasswordStoring && (!FTunnelPassword.IsEmpty() || SaveAll))\r\n {\r\n Storage->WriteBinaryDataAsString(L\"TunnelPassword\", StronglyRecryptPassword(FTunnelPassword, TunnelUserName+TunnelHostName));\r\n }\r\n else\r\n {\r\n Storage->DeleteValue(L\"TunnelPassword\");\r\n }\r\n }\r\n\r\n if (DoNotEncryptPasswords)\r\n {\r\n if (!FEncryptKey.IsEmpty() || SaveAll)\r\n {\r\n Storage->WriteString(L\"EncryptKeyPlain\", EncryptKey);\r\n }\r\n else\r\n {\r\n Storage->DeleteValue(L\"EncryptKeyPlain\");\r\n }\r\n Storage->DeleteValue(L\"EncryptKey\");\r\n }\r\n else\r\n {\r\n if (!FEncryptKey.IsEmpty() || SaveAll)\r\n {\r\n Storage->WriteBinaryDataAsString(L\"EncryptKey\", StronglyRecryptPassword(FEncryptKey, UserName+HostName));\r\n }\r\n else\r\n {\r\n Storage->DeleteValue(L\"EncryptKey\");\r\n }\r\n Storage->DeleteValue(L\"EncryptKeyPlain\");\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::RecryptPasswords()\r\n{\r\n Password = Password;\r\n NewPassword = NewPassword;\r\n ProxyPassword = ProxyPassword;\r\n TunnelPassword = TunnelPassword;\r\n Passphrase = Passphrase;\r\n EncryptKey = EncryptKey;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::HasPassword()\r\n{\r\n return !FPassword.IsEmpty();\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::HasAnySessionPassword()\r\n{\r\n // Keep in sync with ClearSessionPasswords\r\n return\r\n HasPassword() ||\r\n !FTunnelPassword.IsEmpty() ||\r\n // will probably be never used\r\n !FNewPassword.IsEmpty();\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::HasAnyPassword()\r\n{\r\n // Keep in sync with MaskPasswords\r\n return\r\n HasAnySessionPassword() ||\r\n !FProxyPassword.IsEmpty() ||\r\n !FEncryptKey.IsEmpty() ||\r\n !FPassphrase.IsEmpty();\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::ClearSessionPasswords()\r\n{\r\n // Keep in sync with HasAnySessionPassword\r\n FPassword = L\"\";\r\n FNewPassword = L\"\";\r\n FTunnelPassword = L\"\";\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::Modify()\r\n{\r\n FModified = true;\r\n if (FSource == ssStored)\r\n {\r\n FSource = ssStoredModified;\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetSource()\r\n{\r\n switch (FSource)\r\n {\r\n case ::ssNone:\r\n return L\"Ad-Hoc site\";\r\n\r\n case ssStored:\r\n return L\"Site\";\r\n\r\n case ssStoredModified:\r\n return L\"Modified site\";\r\n\r\n default:\r\n DebugFail();\r\n return L\"\";\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SaveRecryptedPasswords(THierarchicalStorage * Storage)\r\n{\r\n if (Storage->OpenSubKey(InternalStorageKey, true))\r\n {\r\n try\r\n {\r\n RecryptPasswords();\r\n\r\n SavePasswords(Storage, false, false, false);\r\n }\r\n __finally\r\n {\r\n Storage->CloseSubKey();\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::Remove(THierarchicalStorage * Storage, const UnicodeString & Name)\r\n{\r\n Storage->RecursiveDeleteSubKey(Name);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::Remove()\r\n{\r\n bool SessionList = true;\r\n THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);\r\n try\r\n {\r\n Storage->Explicit = true;\r\n if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, false))\r\n {\r\n Remove(Storage, InternalStorageKey);\r\n }\r\n }\r\n __finally\r\n {\r\n delete Storage;\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::CacheHostKeyIfNotCached()\r\n{\r\n UnicodeString KeyType = KeyTypeFromFingerprint(HostKey);\r\n\r\n // Should allow importing to INI file as ImportHostKeys\r\n UnicodeString TargetKey = Configuration->RegistryStorageKey + L\"\\\\\" + Configuration->SshHostKeysSubKey;\r\n std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(TargetKey));\r\n Storage->AccessMode = smReadWrite;\r\n if (Storage->OpenRootKey(true))\r\n {\r\n UnicodeString HostKeyName = PuttyMungeStr(FORMAT(L\"%s@%d:%s\", (KeyType, PortNumber, HostName)));\r\n if (!Storage->ValueExists(HostKeyName))\r\n {\r\n // fingerprint is a checksum of a host key, so it cannot be translated back to host key,\r\n // so we store fingerprint and TSecureShell::VerifyHostKey was\r\n // modified to accept also fingerprint\r\n Storage->WriteString(HostKeyName, HostKey);\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\ninline void __fastcall MoveStr(UnicodeString & Source, UnicodeString * Dest, int Count)\r\n{\r\n if (Dest != NULL)\r\n {\r\n (*Dest) += Source.SubString(1, Count);\r\n }\r\n\r\n Source.Delete(1, Count);\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::DoIsProtocolUrl(\r\n const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen)\r\n{\r\n bool Result = SameText(Url.SubString(1, Protocol.Length() + 1), Protocol + L\":\");\r\n if (Result)\r\n {\r\n ProtocolLen = Protocol.Length() + 1;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsProtocolUrl(\r\n const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen)\r\n{\r\n return\r\n DoIsProtocolUrl(Url, Protocol, ProtocolLen) ||\r\n DoIsProtocolUrl(Url, WinSCPProtocolPrefix + Protocol, ProtocolLen);\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsSensitiveOption(const UnicodeString & Option)\r\n{\r\n return\r\n SameText(Option, PassphraseOption) ||\r\n SameText(Option, NEWPASSWORD_SWITCH);\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsOptionWithParameters(const UnicodeString & Option)\r\n{\r\n return SameText(Option, RawSettingsOption);\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::MaskPasswordInOptionParameter(const UnicodeString & Option, UnicodeString & Param)\r\n{\r\n bool Result = false;\r\n if (SameText(Option, RawSettingsOption))\r\n {\r\n int P = Param.Pos(L\"=\");\r\n if (P > 0)\r\n {\r\n // TStrings.IndexOfName does not trim\r\n UnicodeString Key = Param.SubString(1, P - 1);\r\n\r\n if (SameText(Key, L\"ProxyPassword\") ||\r\n SameText(Key, L\"ProxyPasswordEnc\") ||\r\n SameText(Key, L\"TunnelPassword\") ||\r\n SameText(Key, L\"TunnelPasswordPlain\") ||\r\n SameText(Key, L\"EncryptKey\"))\r\n {\r\n Param = Key + L\"=\" + PasswordMask;\r\n Result = true;\r\n }\r\n }\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::MaskPasswords()\r\n{\r\n // Keep in sync with HasAnyPassword\r\n if (!Password.IsEmpty())\r\n {\r\n Password = PasswordMask;\r\n }\r\n if (!NewPassword.IsEmpty())\r\n {\r\n NewPassword = PasswordMask;\r\n }\r\n if (!ProxyPassword.IsEmpty())\r\n {\r\n ProxyPassword = PasswordMask;\r\n }\r\n if (!TunnelPassword.IsEmpty())\r\n {\r\n TunnelPassword = PasswordMask;\r\n }\r\n if (!EncryptKey.IsEmpty())\r\n {\r\n EncryptKey = PasswordMask;\r\n }\r\n if (!Passphrase.IsEmpty())\r\n {\r\n Passphrase = PasswordMask;\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::ParseUrl(UnicodeString Url, TOptions * Options,\r\n TStoredSessionList * StoredSessions, bool & DefaultsOnly, UnicodeString * FileName,\r\n bool * AProtocolDefined, UnicodeString * MaskedUrl, int Flags)\r\n{\r\n bool ProtocolDefined = false;\r\n bool PortNumberDefined = false;\r\n TFSProtocol AFSProtocol;\r\n int APortNumber;\r\n TFtps AFtps = ftpsNone;\r\n int ProtocolLen = 0;\r\n if (IsProtocolUrl(Url, ScpProtocol, ProtocolLen))\r\n {\r\n AFSProtocol = fsSCPonly;\r\n APortNumber = SshPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n else if (IsProtocolUrl(Url, SftpProtocol, ProtocolLen))\r\n {\r\n AFSProtocol = fsSFTPonly;\r\n APortNumber = SshPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n else if (IsProtocolUrl(Url, FtpProtocol, ProtocolLen))\r\n {\r\n AFSProtocol = fsFTP;\r\n Ftps = ftpsNone;\r\n APortNumber = FtpPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n else if (IsProtocolUrl(Url, FtpsProtocol, ProtocolLen))\r\n {\r\n AFSProtocol = fsFTP;\r\n AFtps = ftpsImplicit;\r\n APortNumber = FtpsImplicitPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n else if (IsProtocolUrl(Url, FtpesProtocol, ProtocolLen))\r\n {\r\n AFSProtocol = fsFTP;\r\n AFtps = ftpsExplicitTls;\r\n APortNumber = FtpPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n else if (IsProtocolUrl(Url, WebDAVProtocol, ProtocolLen) ||\r\n IsProtocolUrl(Url, HttpProtocol, ProtocolLen))\r\n {\r\n AFSProtocol = fsWebDAV;\r\n AFtps = ftpsNone;\r\n APortNumber = HTTPPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n else if (IsProtocolUrl(Url, WebDAVSProtocol, ProtocolLen) ||\r\n IsProtocolUrl(Url, HttpsProtocol, ProtocolLen))\r\n {\r\n AFSProtocol = fsWebDAV;\r\n AFtps = ftpsImplicit;\r\n APortNumber = HTTPSPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n else if (IsProtocolUrl(Url, S3Protocol, ProtocolLen))\r\n {\r\n AFSProtocol = fsS3;\r\n AFtps = ftpsImplicit;\r\n APortNumber = HTTPSPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n else if (IsProtocolUrl(Url, SshProtocol, ProtocolLen))\r\n {\r\n // For most uses, handling ssh:// the same way as sftp://\r\n // The only place where a difference is made is GetLoginData() in WinMain.cpp\r\n AFSProtocol = fsSFTPonly;\r\n PuttyProtocol = PuttySshProtocol;\r\n APortNumber = SshPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n\r\n if (ProtocolDefined && (Url.SubString(1, 2) == L\"//\"))\r\n {\r\n MoveStr(Url, MaskedUrl, 2);\r\n }\r\n\r\n if (AProtocolDefined != NULL)\r\n {\r\n *AProtocolDefined = ProtocolDefined;\r\n }\r\n\r", "", " if (!Url.IsEmpty())\r\n {\r\n UnicodeString DecodedUrl = DecodeUrlChars(Url);\r\n // lookup stored session even if protocol was defined\r\n // (this allows setting for example default username for host\r\n // by creating stored session named by host)\r\n TSessionData * Data = NULL;\r\n // When using to paste URL on Login dialog, we do not want to lookup the stored sites\r\n if ((StoredSessions != NULL) &&\r\n (!ProtocolDefined || FLAGSET(Flags, pufAllowStoredSiteWithProtocol)))\r\n {\r\n // this can be optimized as the list is sorted\r\n for (Integer Index = 0; Index < StoredSessions->CountIncludingHidden; Index++)\r\n {\r\n TSessionData * AData = (TSessionData *)StoredSessions->Items[Index];\r\n if (!AData->IsWorkspace)\r\n {\r\n bool Match = false;\r\n // Comparison optimizations as this is called many times\r\n // e.g. when updating jumplist\r\n if ((AData->Name.Length() == DecodedUrl.Length()) &&\r\n SameText(AData->Name, DecodedUrl))\r\n {\r\n Match = true;\r\n }\r\n else if ((AData->Name.Length() < DecodedUrl.Length()) &&\r\n (DecodedUrl[AData->Name.Length() + 1] == L'/') &&\r\n // StrLIComp is an equivalent of SameText\r\n (StrLIComp(AData->Name.c_str(), DecodedUrl.c_str(), AData->Name.Length()) == 0))\r\n {\r\n Match = true;\r\n }\r\n\r\n if (Match)\r\n {\r\n Data = AData;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n UnicodeString ARemoteDirectory;\r\n\r\n if (Data != NULL)\r\n {\r\n Assign(Data);\r\n int P = 1;\r\n while (!AnsiSameText(DecodeUrlChars(Url.SubString(1, P)), Data->Name))\r\n {\r\n P++;\r\n DebugAssert(P <= Url.Length());\r\n }\r\n ARemoteDirectory = Url.SubString(P + 1, Url.Length() - P);\r\n\r\n if (Data->Hidden)\r\n {\r\n Data->Remove();\r\n StoredSessions->Remove(Data);\r\n // only modified, implicit\r\n StoredSessions->Save(false, false);\r\n }\r\n\r\n if (MaskedUrl != NULL)\r\n {\r\n (*MaskedUrl) += Url;\r\n }\r\n }\r\n else\r\n {\r\n // This happens when pasting URL on Login dialog\r\n if (StoredSessions != NULL)\r\n {\r\n CopyData(StoredSessions->DefaultSettings);\r\n }\r\n Name = L\"\";\r\n\r\n int PSlash = Url.Pos(L\"/\");\r\n if (PSlash == 0)\r\n {\r\n PSlash = Url.Length() + 1;\r\n }\r\n\r\n UnicodeString ConnectInfo = Url.SubString(1, PSlash - 1);\r\n\r\n int P = ConnectInfo.LastDelimiter(L\"@\");\r\n\r\n UnicodeString UserInfo;\r\n UnicodeString HostInfo;\r\n\r\n if (P > 0)\r\n {\r\n UserInfo = ConnectInfo.SubString(1, P - 1);\r\n HostInfo = ConnectInfo.SubString(P + 1, ConnectInfo.Length() - P);\r\n }\r\n else\r\n {\r\n HostInfo = ConnectInfo;\r\n }\r\n\r\n UnicodeString OrigHostInfo = HostInfo;\r\n if ((HostInfo.Length() >= 2) && (HostInfo[1] == L'[') && ((P = HostInfo.Pos(L\"]\")) > 0))\r\n {\r\n HostName = HostInfo.SubString(2, P - 2);\r\n HostInfo.Delete(1, P);\r\n if (!HostInfo.IsEmpty() && (HostInfo[1] == L':'))\r\n {\r\n HostInfo.Delete(1, 1);\r\n }\r\n }\r\n else\r\n {\r\n HostName = DecodeUrlChars(CutToChar(HostInfo, L':', true));\r\n }\r\n\r\n // expanded from ?: operator, as it caused strange \"access violation\" errors\r\n if (!HostInfo.IsEmpty())\r\n {\r\n PortNumber = StrToIntDef(DecodeUrlChars(HostInfo), -1);\r\n PortNumberDefined = true;\r\n }\r\n else if (ProtocolDefined)\r\n {\r\n PortNumber = APortNumber;\r\n }\r\n\r\n if (ProtocolDefined)\r\n {\r\n Ftps = AFtps;\r\n }\r\n\r\n UnicodeString UserInfoWithoutConnectionParams = CutToChar(UserInfo, UrlParamSeparator, false);\r\n UnicodeString ConnectionParams = UserInfo;\r\n UserInfo = UserInfoWithoutConnectionParams;\r\n\r\n std::unique_ptr<TStrings> RawSettings(new TStringList());\r\n\r\n while (!ConnectionParams.IsEmpty())\r\n {\r\n UnicodeString ConnectionParam = CutToChar(ConnectionParams, UrlParamSeparator, false);\r\n UnicodeString ConnectionParamName = CutToChar(ConnectionParam, UrlParamValueSeparator, false);\r\n if (SameText(ConnectionParamName, UrlHostKeyParamName))\r\n {\r\n HostKey = DecodeUrlChars(ConnectionParam);\r\n FOverrideCachedHostKey = false;\r\n }\r\n else if (StartsText(UrlRawSettingsParamNamePrefix, ConnectionParamName))\r\n {\r\n UnicodeString AName = RightStr(ConnectionParamName, ConnectionParamName.Length() - UrlRawSettingsParamNamePrefix.Length());\r\n AName = DecodeUrlChars(AName);\r\n UnicodeString Value = DecodeUrlChars(ConnectionParam);\r\n if (SameText(AName, L\"Name\"))\r\n {\r\n Name = Value;\r\n }\r\n else\r\n {\r\n RawSettings->Values[AName] = Value;\r\n }\r\n }\r\n }\r\n\r\n if (RawSettings->Count > 0) // optimization\r\n {\r", " ApplyRawSettings(RawSettings.get());\r", " }\r\n\r\n bool HasPassword = (UserInfo.Pos(L':') > 0);\r\n UnicodeString RawUserName = CutToChar(UserInfo, L':', false);\r\n UserName = DecodeUrlChars(RawUserName);\r\n\r\n Password = DecodeUrlChars(UserInfo);\r\n if (HasPassword && Password.IsEmpty())\r\n {\r\n Password = EmptyString;\r\n }\r\n\r\n UnicodeString RemoteDirectoryWithSessionParams = Url.SubString(PSlash, Url.Length() - PSlash + 1);\r\n ARemoteDirectory = CutToChar(RemoteDirectoryWithSessionParams, UrlParamSeparator, false);\r\n UnicodeString SessionParams = RemoteDirectoryWithSessionParams;\r\n\r\n // We should handle session params in \"stored session\" branch too.\r\n // And particularly if there's a \"save\" param, we should actually not try to match the\r\n // URL against site names\r\n while (!SessionParams.IsEmpty())\r\n {\r\n UnicodeString SessionParam = CutToChar(SessionParams, UrlParamSeparator, false);\r\n UnicodeString SessionParamName = CutToChar(SessionParam, UrlParamValueSeparator, false);\r\n if (SameText(SessionParamName, UrlSaveParamName))\r\n {\r\n FSaveOnly = (StrToIntDef(SessionParam, 1) != 0);\r\n }\r\n }\r\n\r\n if (MaskedUrl != NULL)\r\n {\r\n (*MaskedUrl) += RawUserName;\r\n if (HasPassword)\r\n {\r\n (*MaskedUrl) += L\":\" + PasswordMask;\r\n }\r\n if (!RawUserName.IsEmpty() || HasPassword)\r\n {\r\n (*MaskedUrl) += L\"@\";\r\n }\r\n (*MaskedUrl) += OrigHostInfo + ARemoteDirectory;\r\n }\r\n }\r\n\r\n if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory != L\"/\"))\r\n {\r\n if ((ARemoteDirectory[ARemoteDirectory.Length()] != L'/') &&\r\n (FileName != NULL))\r\n {\r\n *FileName = DecodeUrlChars(UnixExtractFileName(ARemoteDirectory));\r\n ARemoteDirectory = UnixExtractFilePath(ARemoteDirectory);\r\n }\r\n RemoteDirectory = DecodeUrlChars(ARemoteDirectory);\r\n }\r\n\r\n DefaultsOnly = false;\r\n }\r\n else\r\n {\r\n // This happens when pasting URL on Login dialog\r\n if (StoredSessions != NULL)\r\n {\r\n CopyData(StoredSessions->DefaultSettings);\r\n }\r\n\r\n DefaultsOnly = true;\r\n }\r\n\r\n if (ProtocolDefined)\r\n {\r\n FSProtocol = AFSProtocol;\r\n }\r\n\r\n if (Options != NULL)\r\n {\r\n // we deliberately do keep defaultonly to false, in presence of any option,\r\n // as the option should not make session \"connectable\"\r\n\r\n UnicodeString Value;\r\n if (Options->FindSwitch(SESSIONNAME_SWICH, Value))\r\n {\r\n Name = Value;\r\n }\r\n if (Options->FindSwitch(NEWPASSWORD_SWITCH, Value))\r\n {\r\n ChangePassword = true;\r\n NewPassword = Value;\r\n }\r\n if (Options->FindSwitch(L\"privatekey\", Value))\r\n {\r\n PublicKeyFile = Value;\r\n }\r\n if (Options->FindSwitch(L\"clientcert\", Value))\r\n {\r\n TlsCertificateFile = Value;\r\n }\r\n if (Options->FindSwitch(PassphraseOption, Value))\r\n {\r\n Passphrase = Value;\r\n }\r\n if (Options->FindSwitch(L\"timeout\", Value))\r\n {\r\n Timeout = StrToInt(Value);\r\n }\r\n if (Options->FindSwitch(L\"hostkey\", Value) ||\r\n Options->FindSwitch(L\"certificate\", Value))\r\n {\r\n HostKey = Value;\r\n FOverrideCachedHostKey = true;\r\n }\r\n FtpPasvMode = Options->SwitchValue(L\"passive\", FtpPasvMode);\r\n if (Options->FindSwitch(L\"implicit\"))\r\n {\r\n bool Enabled = Options->SwitchValue(L\"implicit\", true);\r\n Ftps = Enabled ? ftpsImplicit : ftpsNone;\r\n if (!PortNumberDefined && Enabled)\r\n {\r\n PortNumber = FtpsImplicitPortNumber;\r\n }\r\n }\r\n // BACKWARD COMPATIBILITY with 5.5.x\r\n if (Options->FindSwitch(L\"explicitssl\"))\r\n {\r\n bool Enabled = Options->SwitchValue(L\"explicitssl\", true);\r\n Ftps = Enabled ? ftpsExplicitSsl : ftpsNone;\r\n if (!PortNumberDefined && Enabled)\r\n {\r\n PortNumber = FtpPortNumber;\r\n }\r\n }\r\n if (Options->FindSwitch(L\"explicit\") ||\r\n // BACKWARD COMPATIBILITY with 5.5.x\r\n Options->FindSwitch(L\"explicittls\"))\r\n {\r\n UnicodeString SwitchName =\r\n Options->FindSwitch(L\"explicit\") ? L\"explicit\" : L\"explicittls\";\r\n bool Enabled = Options->SwitchValue(SwitchName, true);\r\n Ftps = Enabled ? ftpsExplicitTls : ftpsNone;\r\n if (!PortNumberDefined && Enabled)\r\n {\r\n PortNumber = FtpPortNumber;\r\n }\r\n }\r\n if (Options->FindSwitch(RawSettingsOption))\r\n {\r\n std::unique_ptr<TStrings> RawSettings(new TStringList());\r\n if (Options->FindSwitch(RawSettingsOption, RawSettings.get()))\r\n {\r", " ApplyRawSettings(RawSettings.get());\r", " }\r\n }\r\n }\r\n\r\n return true;\r\n}\r\n//---------------------------------------------------------------------\r", "void __fastcall TSessionData::ApplyRawSettings(TStrings * RawSettings)\r", "{\r\n std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings, false));\r", " ApplyRawSettings(OptionsStorage.get());\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::ApplyRawSettings(THierarchicalStorage * Storage)\r", "{\r\n bool Dummy;\r", " DoLoad(Storage, false, Dummy);\r", "}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::ConfigureTunnel(int APortNumber)\r\n{\r\n FOrigHostName = HostName;\r\n FOrigPortNumber = PortNumber;\r\n FOrigProxyMethod = ProxyMethod;\r\n\r\n HostName = L\"127.0.0.1\";\r\n PortNumber = APortNumber;\r\n // proxy settings is used for tunnel\r\n ProxyMethod = ::pmNone;\r\n FLogicalHostName = FOrigHostName;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::RollbackTunnel()\r\n{\r\n HostName = FOrigHostName;\r\n PortNumber = FOrigPortNumber;\r\n ProxyMethod = FOrigProxyMethod;\r\n FLogicalHostName = L\"\";\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::ExpandEnvironmentVariables()\r\n{\r\n HostName = HostNameExpanded;\r\n UserName = UserNameExpanded;\r\n PublicKeyFile = ::ExpandEnvironmentVariables(PublicKeyFile);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::ValidatePath(const UnicodeString Path)\r\n{\r\n // noop\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::ValidateName(const UnicodeString Name)\r\n{\r\n // keep consistent with MakeValidName\r\n if (Name.LastDelimiter(L\"/\") > 0)\r\n {\r\n throw Exception(FMTLOAD(ITEM_NAME_INVALID, (Name, L\"/\")));\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::MakeValidName(const UnicodeString & Name)\r\n{\r\n // keep consistent with ValidateName\r\n return ReplaceStr(Name, L\"/\", L\"\\\\\");\r\n}\r\n//---------------------------------------------------------------------\r\nRawByteString __fastcall TSessionData::EncryptPassword(const UnicodeString & Password, UnicodeString Key)\r\n{\r\n return Configuration->EncryptPassword(Password, Key);\r\n}\r\n//---------------------------------------------------------------------\r\nRawByteString __fastcall TSessionData::StronglyRecryptPassword(const RawByteString & Password, UnicodeString Key)\r\n{\r\n return Configuration->StronglyRecryptPassword(Password, Key);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::DecryptPassword(const RawByteString & Password, UnicodeString Key)\r\n{\r\n UnicodeString Result;\r\n try\r\n {\r\n Result = Configuration->DecryptPassword(Password, Key);\r\n }\r\n catch(EAbort &)\r\n {\r\n // silently ignore aborted prompts for master password and return empty password\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::GetCanLogin()\r\n{\r\n return !FHostName.IsEmpty();\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetSessionKey()\r\n{\r\n UnicodeString Result = FORMAT(L\"%s@%s\", (UserName, HostName));\r\n if (PortNumber != DefaultPort(FSProtocol, Ftps))\r\n {\r\n Result += FORMAT(L\":%d\", (PortNumber));\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetInternalStorageKey()\r\n{\r\n // This is probably useless remnant of previous use of this method from OpenSessionInPutty\r\n // that needs the method to return something even for ad-hoc sessions\r\n if (Name.IsEmpty())\r\n {\r\n return SessionKey;\r\n }\r\n else\r\n {\r\n return Name;\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetStorageKey()\r\n{\r\n return SessionName;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::FormatSiteKey(const UnicodeString & HostName, int PortNumber)\r\n{\r\n return FORMAT(L\"%s:%d\", (HostName, PortNumber));\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetSiteKey()\r\n{\r\n return FormatSiteKey(HostNameExpanded, PortNumber);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetHostName(UnicodeString value)\r\n{\r\n if (FHostName != value)\r\n {\r\n // HostName is key for password encryption\r\n UnicodeString XPassword = Password;\r\n UnicodeString XNewPassword = Password;\r\n UnicodeString XEncryptKey = EncryptKey;\r\n\r\n // This is now hardly used as hostname is parsed directly on login dialog.\r\n // But can be used when importing sites from PuTTY, as it allows same format too.\r\n int P = value.LastDelimiter(L\"@\");\r\n if (P > 0)\r\n {\r\n UserName = value.SubString(1, P - 1);\r\n value = value.SubString(P + 1, value.Length() - P);\r\n }\r\n FHostName = value;\r\n Modify();\r\n\r\n Password = XPassword;\r\n NewPassword = XNewPassword;\r\n EncryptKey = XEncryptKey;\r\n Shred(XPassword);\r\n Shred(XNewPassword);\r\n Shred(XEncryptKey);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetHostNameExpanded()\r\n{\r\n return ::ExpandEnvironmentVariables(HostName);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPortNumber(int value)\r\n{\r\n SET_SESSION_PROPERTY(PortNumber);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetShell(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(Shell);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSftpServer(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(SftpServer);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetClearAliases(bool value)\r\n{\r\n SET_SESSION_PROPERTY(ClearAliases);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetListingCommand(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(ListingCommand);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetIgnoreLsWarnings(bool value)\r\n{\r\n SET_SESSION_PROPERTY(IgnoreLsWarnings);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetUnsetNationalVars(bool value)\r\n{\r\n SET_SESSION_PROPERTY(UnsetNationalVars);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetUserName(UnicodeString value)\r\n{\r\n // Avoid password recryption (what may popup master password prompt)\r\n if (FUserName != value)\r\n {\r\n // UserName is key for password encryption\r\n UnicodeString XPassword = Password;\r\n UnicodeString XNewPassword = NewPassword;\r\n UnicodeString XEncryptKey = EncryptKey;\r\n SET_SESSION_PROPERTY(UserName);\r\n Password = XPassword;\r\n NewPassword = XNewPassword;\r\n EncryptKey = XEncryptKey;\r\n Shred(XPassword);\r\n Shred(XNewPassword);\r\n Shred(XEncryptKey);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetUserNameExpanded()\r\n{\r\n return ::ExpandEnvironmentVariables(UserName);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPassword(UnicodeString avalue)\r\n{\r\n RawByteString value = EncryptPassword(avalue, UserName+HostName);\r\n SET_SESSION_PROPERTY(Password);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetPassword() const\r\n{\r\n return DecryptPassword(FPassword, UserName+HostName);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetNewPassword(UnicodeString avalue)\r\n{\r\n RawByteString value = EncryptPassword(avalue, UserName+HostName);\r\n SET_SESSION_PROPERTY(NewPassword);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetNewPassword() const\r\n{\r\n return DecryptPassword(FNewPassword, UserName+HostName);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetChangePassword(bool value)\r\n{\r\n SET_SESSION_PROPERTY(ChangePassword);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPingInterval(int value)\r\n{\r\n SET_SESSION_PROPERTY(PingInterval);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTryAgent(bool value)\r\n{\r\n SET_SESSION_PROPERTY(TryAgent);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetAgentFwd(bool value)\r\n{\r\n SET_SESSION_PROPERTY(AgentFwd);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetAuthTIS(bool value)\r\n{\r\n SET_SESSION_PROPERTY(AuthTIS);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetAuthKI(bool value)\r\n{\r\n SET_SESSION_PROPERTY(AuthKI);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetAuthKIPassword(bool value)\r\n{\r\n SET_SESSION_PROPERTY(AuthKIPassword);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetAuthGSSAPI(bool value)\r\n{\r\n SET_SESSION_PROPERTY(AuthGSSAPI);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetGSSAPIFwdTGT(bool value)\r\n{\r\n SET_SESSION_PROPERTY(GSSAPIFwdTGT);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetChangeUsername(bool value)\r\n{\r\n SET_SESSION_PROPERTY(ChangeUsername);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetCompression(bool value)\r\n{\r\n SET_SESSION_PROPERTY(Compression);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSshProt(TSshProt value)\r\n{\r\n SET_SESSION_PROPERTY(SshProt);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSsh2DES(bool value)\r\n{\r\n SET_SESSION_PROPERTY(Ssh2DES);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSshNoUserAuth(bool value)\r\n{\r\n SET_SESSION_PROPERTY(SshNoUserAuth);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetSshProtStr()\r\n{\r\n return SshProtList[FSshProt];\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::GetUsesSsh()\r\n{\r\n return IsSshProtocol(FSProtocol);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetCipher(int Index, TCipher value)\r\n{\r\n DebugAssert(Index >= 0 && Index < CIPHER_COUNT);\r\n SET_SESSION_PROPERTY(Ciphers[Index]);\r\n}\r\n//---------------------------------------------------------------------\r\nTCipher __fastcall TSessionData::GetCipher(int Index) const\r\n{\r\n DebugAssert(Index >= 0 && Index < CIPHER_COUNT);\r\n return FCiphers[Index];\r\n}\r\n//---------------------------------------------------------------------\r\ntemplate<class AlgoT>\r\nvoid __fastcall TSessionData::SetAlgoList(AlgoT * List, const AlgoT * DefaultList, const UnicodeString * Names,\r\n int Count, AlgoT WarnAlgo, UnicodeString value)\r\n{\r\n std::vector<bool> Used(Count); // initialized to false\r\n std::vector<AlgoT> NewList(Count);\r\n\r\n bool HasWarnAlgo = (WarnAlgo >= AlgoT());\r\n const AlgoT * WarnPtr;\r\n int WarnDefaultIndex;\r\n if (!HasWarnAlgo)\r\n {\r\n WarnPtr = NULL;\r\n WarnDefaultIndex = -1;\r\n }\r\n else\r\n {\r\n WarnPtr = std::find(DefaultList, DefaultList + Count, WarnAlgo);\r\n DebugAssert(WarnPtr != NULL);\r\n WarnDefaultIndex = (WarnPtr - DefaultList);\r\n }\r\n\r\n int Index = 0;\r\n while (!value.IsEmpty())\r\n {\r\n UnicodeString AlgoStr = CutToChar(value, L',', true);\r\n for (int Algo = 0; Algo < Count; Algo++)\r\n {\r\n if (!AlgoStr.CompareIC(Names[Algo]) &&\r\n !Used[Algo] && DebugAlwaysTrue(Index < Count))\r\n {\r\n NewList[Index] = (AlgoT)Algo;\r\n Used[Algo] = true;\r\n Index++;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (HasWarnAlgo && !Used[WarnAlgo] && DebugAlwaysTrue(Index < Count))\r\n {\r\n NewList[Index] = WarnAlgo;\r\n Used[WarnAlgo] = true;\r\n Index++;\r\n }\r\n\r\n int WarnIndex = -1;\r\n if (HasWarnAlgo)\r\n {\r\n WarnIndex = std::find(NewList.begin(), NewList.end(), WarnAlgo) - NewList.begin();\r\n }\r\n\r\n bool Priority = true;\r\n for (int DefaultIndex = 0; (DefaultIndex < Count); DefaultIndex++)\r\n {\r\n AlgoT DefaultAlgo = DefaultList[DefaultIndex];\r\n if (!Used[DefaultAlgo] && DebugAlwaysTrue(Index < Count))\r\n {\r\n int TargetIndex;\r\n // Unused algs that are prioritized in the default list,\r\n // should be merged before the existing custom list\r\n if (Priority)\r\n {\r\n TargetIndex = DefaultIndex;\r\n }\r\n else\r\n {\r\n if (HasWarnAlgo && (DefaultIndex < WarnDefaultIndex))\r\n {\r\n TargetIndex = WarnIndex;\r\n }\r\n else\r\n {\r\n TargetIndex = Index;\r\n }\r\n }\r\n\r\n NewList.insert(NewList.begin() + TargetIndex, DefaultAlgo);\r\n DebugAssert(NewList.back() == AlgoT());\r\n NewList.pop_back();\r\n\r\n if (HasWarnAlgo && (TargetIndex <= WarnIndex))\r\n {\r\n WarnIndex++;\r\n }\r\n\r\n Index++;\r\n }\r\n else\r\n {\r\n Priority = false;\r\n }\r\n }\r\n\r\n if (!std::equal(NewList.begin(), NewList.end(), List))\r\n {\r\n std::copy(NewList.begin(), NewList.end(), List);\r\n Modify();\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetCipherList(UnicodeString value)\r\n{\r\n SetAlgoList(FCiphers, DefaultCipherList, CipherNames, CIPHER_COUNT, cipWarn, value);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetCipherList() const\r\n{\r\n UnicodeString Result;\r\n for (int Index = 0; Index < CIPHER_COUNT; Index++)\r\n {\r\n Result += UnicodeString(Index ? L\",\" : L\"\") + CipherNames[Cipher[Index]];\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetKex(int Index, TKex value)\r\n{\r\n DebugAssert(Index >= 0 && Index < KEX_COUNT);\r\n SET_SESSION_PROPERTY(Kex[Index]);\r\n}\r\n//---------------------------------------------------------------------\r\nTKex __fastcall TSessionData::GetKex(int Index) const\r\n{\r\n DebugAssert(Index >= 0 && Index < KEX_COUNT);\r\n return FKex[Index];\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetKexList(UnicodeString value)\r\n{\r\n SetAlgoList(FKex, DefaultKexList, KexNames, KEX_COUNT, kexWarn, value);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetKexList() const\r\n{\r\n UnicodeString Result;\r\n for (int Index = 0; Index < KEX_COUNT; Index++)\r\n {\r\n Result += UnicodeString(Index ? L\",\" : L\"\") + KexNames[Kex[Index]];\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetHostKeys(int Index, THostKey value)\r\n{\r\n DebugAssert(Index >= 0 && Index < HOSTKEY_COUNT);\r\n SET_SESSION_PROPERTY(HostKeys[Index]);\r\n}\r\n//---------------------------------------------------------------------\r\nTHostKey __fastcall TSessionData::GetHostKeys(int Index) const\r\n{\r\n DebugAssert(Index >= 0 && Index < HOSTKEY_COUNT);\r\n return FHostKeys[Index];\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetHostKeyList(UnicodeString value)\r\n{\r\n SetAlgoList(FHostKeys, DefaultHostKeyList, HostKeyNames, HOSTKEY_COUNT, hkWarn, value);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetHostKeyList() const\r\n{\r\n UnicodeString Result;\r\n for (int Index = 0; Index < HOSTKEY_COUNT; Index++)\r\n {\r\n Result += UnicodeString(Index ? L\",\" : L\"\") + HostKeyNames[HostKeys[Index]];\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetGssLib(int Index, TGssLib value)\r\n{\r\n DebugAssert(Index >= 0 && Index < GSSLIB_COUNT);\r\n SET_SESSION_PROPERTY(GssLib[Index]);\r\n}\r\n//---------------------------------------------------------------------\r\nTGssLib __fastcall TSessionData::GetGssLib(int Index) const\r\n{\r\n DebugAssert(Index >= 0 && Index < GSSLIB_COUNT);\r\n return FGssLib[Index];\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetGssLibList(UnicodeString value)\r\n{\r\n SetAlgoList(FGssLib, DefaultGssLibList, GssLibNames, GSSLIB_COUNT, TGssLib(-1), value);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetGssLibList() const\r\n{\r\n UnicodeString Result;\r\n for (int Index = 0; Index < GSSLIB_COUNT; Index++)\r\n {\r\n Result += UnicodeString(Index ? L\",\" : L\"\") + GssLibNames[GssLib[Index]];\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetGssLibCustom(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(GssLibCustom);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPublicKeyFile(UnicodeString value)\r\n{\r\n if (FPublicKeyFile != value)\r\n {\r\n // PublicKeyFile is key for Passphrase encryption\r\n UnicodeString XPassphrase = Passphrase;\r\n\r\n // StripPathQuotes should not be needed as we do not feed quotes anymore\r\n FPublicKeyFile = StripPathQuotes(value);\r\n Modify();\r\n\r\n Passphrase = XPassphrase;\r\n Shred(XPassphrase);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPassphrase(UnicodeString avalue)\r\n{\r\n RawByteString value = EncryptPassword(avalue, PublicKeyFile);\r\n SET_SESSION_PROPERTY(Passphrase);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetPassphrase() const\r\n{\r\n return DecryptPassword(FPassphrase, PublicKeyFile);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetReturnVar(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(ReturnVar);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetExitCode1IsError(bool value)\r\n{\r\n SET_SESSION_PROPERTY(ExitCode1IsError);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetLookupUserGroups(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(LookupUserGroups);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetEOLType(TEOLType value)\r\n{\r\n SET_SESSION_PROPERTY(EOLType);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTrimVMSVersions(bool value)\r\n{\r\n SET_SESSION_PROPERTY(TrimVMSVersions);\r\n}\r\n//---------------------------------------------------------------------------\r\nTDateTime __fastcall TSessionData::GetTimeoutDT()\r\n{\r\n return SecToDateTime(Timeout);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTimeout(int value)\r\n{\r\n SET_SESSION_PROPERTY(Timeout);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFSProtocol(TFSProtocol value)\r\n{\r\n SET_SESSION_PROPERTY(FSProtocol);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetFSProtocolStr()\r\n{\r\n DebugAssert(FSProtocol >= 0 && FSProtocol < FSPROTOCOL_COUNT);\r\n return FSProtocolNames[FSProtocol];\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetDetectReturnVar(bool value)\r\n{\r\n if (value != DetectReturnVar)\r\n {\r\n ReturnVar = value ? L\"\" : L\"$?\";\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TSessionData::GetDetectReturnVar()\r\n{\r\n return ReturnVar.IsEmpty();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetDefaultShell(bool value)\r\n{\r\n if (value != DefaultShell)\r\n {\r\n Shell = value ? L\"\" : L\"/bin/bash\";\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TSessionData::GetDefaultShell()\r\n{\r\n return Shell.IsEmpty();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPuttyProtocol(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(PuttyProtocol);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetNormalizedPuttyProtocol() const\r\n{\r\n return DefaultStr(PuttyProtocol, PuttySshProtocol);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPingIntervalDT(TDateTime value)\r\n{\r\n unsigned short hour, min, sec, msec;\r\n\r\n value.DecodeTime(&hour, &min, &sec, &msec);\r\n PingInterval = ((int)hour)*SecsPerHour + ((int)min)*SecsPerMin + sec;\r\n}\r\n//---------------------------------------------------------------------------\r\nTDateTime __fastcall TSessionData::GetPingIntervalDT()\r\n{\r\n return SecToDateTime(PingInterval);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPingType(TPingType value)\r\n{\r\n SET_SESSION_PROPERTY(PingType);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetAddressFamily(TAddressFamily value)\r\n{\r\n SET_SESSION_PROPERTY(AddressFamily);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetRekeyData(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(RekeyData);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetRekeyTime(unsigned int value)\r\n{\r\n SET_SESSION_PROPERTY(RekeyTime);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetDefaultSessionName()\r\n{\r\n if (!HostName.IsEmpty() && !UserName.IsEmpty())\r\n {\r\n // If we ever choose to include port number,\r\n // we have to escape IPv6 literals in HostName\r\n return FORMAT(L\"%s@%s\", (UserName, HostName));\r\n }\r\n else if (!HostName.IsEmpty())\r\n {\r\n return HostName;\r\n }\r\n else\r\n {\r\n return L\"session\";\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetNameWithoutHiddenPrefix()\r\n{\r\n UnicodeString Result = Name;\r\n if (Hidden)\r\n {\r\n Result = Result.SubString(TNamedObjectList::HiddenPrefix.Length() + 1, Result.Length() - TNamedObjectList::HiddenPrefix.Length());\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::HasSessionName()\r\n{\r\n return (!GetNameWithoutHiddenPrefix().IsEmpty() && (Name != DefaultName));\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetSessionName()\r\n{\r\n UnicodeString Result;\r\n if (HasSessionName())\r\n {\r\n Result = GetNameWithoutHiddenPrefix();\r\n }\r\n else\r\n {\r\n Result = DefaultSessionName;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsSecure()\r\n{\r\n bool Result;\r\n switch (FSProtocol)\r\n {\r\n case fsSCPonly:\r\n case fsSFTP:\r\n case fsSFTPonly:\r\n Result = true;\r\n break;\r\n\r\n case fsFTP:\r\n case fsWebDAV:\r\n case fsS3:\r\n Result = (Ftps != ftpsNone);\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n break;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetProtocolUrl(bool HttpForWebDAV)\r\n{\r\n UnicodeString Url;\r\n switch (FSProtocol)\r\n {\r\n case fsSCPonly:\r\n Url = ScpProtocol;\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n // fallback\r\n case fsSFTP:\r\n case fsSFTPonly:\r\n Url = SftpProtocol;\r\n break;\r\n\r\n case fsFTP:\r\n if (Ftps == ftpsImplicit)\r\n {\r\n Url = FtpsProtocol;\r\n }\r\n else if ((Ftps == ftpsExplicitTls) || (Ftps == ftpsExplicitSsl))\r\n {\r\n Url = FtpesProtocol;\r\n }\r\n else\r\n {\r\n Url = FtpProtocol;\r\n }\r\n break;\r\n\r\n case fsWebDAV:\r\n if (HttpForWebDAV)\r\n {\r\n if (Ftps == ftpsImplicit)\r\n {\r\n Url = HttpsProtocol;\r\n }\r\n else\r\n {\r\n Url = HttpProtocol;\r\n }\r\n }\r\n else\r\n {\r\n if (Ftps == ftpsImplicit)\r\n {\r\n Url = WebDAVSProtocol;\r\n }\r\n else\r\n {\r\n Url = WebDAVProtocol;\r\n }\r\n }\r\n break;\r\n\r\n case fsS3:\r\n Url = S3Protocol;\r\n break;\r\n }\r\n\r\n Url += ProtocolSeparator;\r\n\r\n return Url;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall IsIPv6Literal(const UnicodeString & HostName)\r\n{\r\n bool Result = (HostName.Pos(L\":\") > 0);\r\n if (Result)\r\n {\r\n for (int Index = 1; Result && (Index <= HostName.Length()); Index++)\r\n {\r\n wchar_t C = HostName[Index];\r\n Result = IsHex(C) || (C == L':');\r\n }\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall EscapeIPv6Literal(const UnicodeString & IP)\r\n{\r\n return L\"[\" + IP + L\"]\";\r\n}\r\n//---------------------------------------------------------------------\r\nTStrings * __fastcall TSessionData::GetRawSettingsForUrl()\r\n{\r\n std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L\"\"));\r\n std::unique_ptr<TSessionData> SessionData(Clone());\r\n SessionData->FSProtocol = FactoryDefaults->FSProtocol;\r\n SessionData->HostName = FactoryDefaults->HostName;\r\n SessionData->PortNumber = FactoryDefaults->PortNumber;\r\n SessionData->UserName = FactoryDefaults->UserName;\r\n SessionData->Password = FactoryDefaults->Password;\r\n SessionData->Ftps = FactoryDefaults->Ftps;\r\n SessionData->HostKey = FactoryDefaults->HostKey;\r\n SessionData->CopyNonCoreData(FactoryDefaults.get());\r\n // Cannot be decided in SaveToOptions as it does not have HostName and UserName, so it cannot calculate DefaultSessionName.\r\n bool SaveName = HasSessionName() && (Name != DefaultSessionName);\r\n return SessionData->SaveToOptions(FactoryDefaults.get(), SaveName, false);\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::HasRawSettingsForUrl()\r\n{\r\n std::unique_ptr<TStrings> RawSettings(GetRawSettingsForUrl());\r\n return (RawSettings->Count > 0);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GenerateSessionUrl(unsigned int Flags)\r\n{\r\n UnicodeString Url;\r\n\r\n if (FLAGSET(Flags, sufSpecific))\r\n {\r\n Url += WinSCPProtocolPrefix;\r\n }\r\n\r\n Url += GetProtocolUrl(FLAGSET(Flags, sufHttpForWebDAV));\r\n\r\n if (FLAGSET(Flags, sufUserName) && !UserNameExpanded.IsEmpty())\r\n {\r\n Url += EncodeUrlString(UserNameExpanded);\r\n\r\n if (FLAGSET(Flags, sufPassword) && !Password.IsEmpty())\r\n {\r\n Url += L\":\" + EncodeUrlString(NormalizeString(Password));\r\n }\r\n\r\n if (FLAGSET(Flags, sufHostKey) && !HostKey.IsEmpty())\r\n {\r\n UnicodeString KeyName;\r\n UnicodeString Fingerprint = HostKey;\r\n NormalizeFingerprint(Fingerprint, KeyName);\r\n UnicodeString S = Fingerprint;\r\n if (!KeyName.IsEmpty())\r\n {\r\n S = KeyName + NormalizedFingerprintSeparator + S;\r\n }\r\n S = Base64ToUrlSafe(S); // Noop for MD5 (both in SSH host keys and TLS/SSL)\r\n S = MD5ToUrlSafe(S); // TLS/SSL fingerprints\r\n UnicodeString S2 = EncodeUrlString(S);\r\n DebugAssert(S2 == S2); // There should be nothing left for encoding\r\n\r\n Url +=\r\n UnicodeString(UrlParamSeparator) + UrlHostKeyParamName +\r\n UnicodeString(UrlParamValueSeparator) + S2;\r\n }\r\n\r\n if (FLAGSET(Flags, sufRawSettings))\r\n {\r\n std::unique_ptr<TStrings> RawSettings(GetRawSettingsForUrl());\r\n for (int Index = 0; Index < RawSettings->Count; Index++)\r\n {\r\n Url +=\r\n UnicodeString(UrlParamSeparator) +\r\n UrlRawSettingsParamNamePrefix + EncodeUrlString(LowerCase(RawSettings->Names[Index])) +\r\n UnicodeString(UrlParamValueSeparator) + EncodeUrlString(RawSettings->ValueFromIndex[Index]);\r\n }\r\n }\r\n\r\n Url += L\"@\";\r\n }\r\n\r\n DebugAssert(!HostNameExpanded.IsEmpty());\r\n if (IsIPv6Literal(HostNameExpanded))\r\n {\r\n Url += EscapeIPv6Literal(HostNameExpanded);\r\n }\r\n else\r\n {\r\n Url += EncodeUrlString(HostNameExpanded);\r\n }\r\n\r\n if (PortNumber != DefaultPort(FSProtocol, Ftps))\r\n {\r\n Url += L\":\" + IntToStr(PortNumber);\r\n }\r\n Url += L\"/\";\r\n\r\n return Url;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString ScriptCommandOpenLink(TraceInitStr(ScriptCommandLink(L\"open\")));\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::AddSwitch(\r\n UnicodeString & Result, const UnicodeString & Name, bool Rtf)\r\n{\r\n Result += RtfSwitch(Name, ScriptCommandOpenLink, Rtf);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::AddSwitch(\r\n UnicodeString & Result, const UnicodeString & Name, const UnicodeString & Value, bool Rtf)\r\n{\r\n Result += RtfSwitch(Name, ScriptCommandOpenLink, Value, Rtf);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::AddSwitch(\r\n UnicodeString & Result, const UnicodeString & Name, int Value, bool Rtf)\r\n{\r\n Result += RtfSwitch(Name, ScriptCommandOpenLink, Value, Rtf);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::LookupLastFingerprint()\r\n{\r\n UnicodeString FingerprintType;\r\n if (IsSshProtocol(FSProtocol))\r\n {\r\n FingerprintType = SshFingerprintType;\r\n }\r\n else if (Ftps != ftpsNone)\r\n {\r\n FingerprintType = TlsFingerprintType;\r\n }\r\n\r\n if (!FingerprintType.IsEmpty())\r\n {\r\n HostKey = Configuration->LastFingerprint(SiteKey, FingerprintType);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GenerateOpenCommandArgs(bool Rtf)\r\n{\r\n std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L\"\"));\r\n std::unique_ptr<TSessionData> SessionData(new TSessionData(L\"\"));\r\n\r\n SessionData->Assign(this);\r\n\r\n UnicodeString Result = SessionData->GenerateSessionUrl(sufOpen);\r\n\r\n // Before we reset the FSProtocol\r\n bool AUsesSsh = SessionData->UsesSsh;\r\n // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that\r\n if (SessionData->FSProtocol != fsSFTPonly)\r\n {\r\n SessionData->FSProtocol = FactoryDefaults->FSProtocol;\r\n }\r\n SessionData->HostName = FactoryDefaults->HostName;\r\n SessionData->PortNumber = FactoryDefaults->PortNumber;\r\n SessionData->UserName = FactoryDefaults->UserName;\r\n SessionData->Password = FactoryDefaults->Password;\r\n SessionData->CopyNonCoreData(FactoryDefaults.get());\r\n SessionData->Ftps = FactoryDefaults->Ftps;\r\n\r\n if (SessionData->HostKey != FactoryDefaults->HostKey)\r\n {\r\n UnicodeString SwitchName = AUsesSsh ? L\"hostkey\" : L\"certificate\";\r\n AddSwitch(Result, SwitchName, SessionData->HostKey, Rtf);\r\n SessionData->HostKey = FactoryDefaults->HostKey;\r\n }\r\n if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)\r\n {\r\n AddSwitch(Result, L\"privatekey\", SessionData->PublicKeyFile, Rtf);\r\n SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;\r\n }\r\n if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)\r\n {\r\n AddSwitch(Result, L\"clientcert\", SessionData->TlsCertificateFile, Rtf);\r\n SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;\r\n }\r\n if (SessionData->Passphrase != FactoryDefaults->Passphrase)\r\n {\r\n AddSwitch(Result, PassphraseOption, SessionData->Passphrase, Rtf);\r\n SessionData->Passphrase = FactoryDefaults->Passphrase;\r\n }\r\n if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)\r\n {\r\n AddSwitch(Result, L\"passive\", SessionData->FtpPasvMode ? 1 : 0, Rtf);\r\n SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;\r\n }\r\n if (SessionData->Timeout != FactoryDefaults->Timeout)\r\n {\r\n AddSwitch(Result, L\"timeout\", SessionData->Timeout, Rtf);\r\n SessionData->Timeout = FactoryDefaults->Timeout;\r\n }\r\n\r\n std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get(), false, false));\r\n\r\n if (RawSettings->Count > 0)\r\n {\r\n AddSwitch(Result, RawSettingsOption, Rtf);\r\n\r\n Result += StringsToParams(RawSettings.get());\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString SessionOptionsClassName(L\"SessionOptions\");\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::AddAssemblyProperty(\r\n UnicodeString & Result, TAssemblyLanguage Language,\r\n const UnicodeString & Name, const UnicodeString & Type,\r\n const UnicodeString & Member)\r\n{\r\n Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Type, Member, false);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::AddAssemblyProperty(\r\n UnicodeString & Result, TAssemblyLanguage Language,\r\n const UnicodeString & Name, const UnicodeString & Value)\r\n{\r\n Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::AddAssemblyProperty(\r\n UnicodeString & Result, TAssemblyLanguage Language,\r\n const UnicodeString & Name, int Value)\r\n{\r\n Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::AddAssemblyProperty(\r\n UnicodeString & Result, TAssemblyLanguage Language,\r\n const UnicodeString & Name, bool Value)\r\n{\r\n Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::GenerateAssemblyCode(\r\n TAssemblyLanguage Language, UnicodeString & Head, UnicodeString & Tail, int & Indent)\r\n{\r\n std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L\"\"));\r\n std::unique_ptr<TSessionData> SessionData(Clone());\r\n\r\n switch (Language)\r\n {\r\n case alCSharp:\r\n case alVBNET:\r\n // noop\r\n break;\r\n\r\n case alPowerShell:\r\n Head +=\r\n AssemblyCommentLine(Language, LoadStr(CODE_PS_ADD_TYPE)) +\r\n RtfKeyword(L\"Add-Type\") + RtfText(\" -Path \") + AssemblyString(Language, \"WinSCPnet.dll\") + RtfPara +\r\n RtfPara;\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n break;\r\n }\r\n\r\n Head +=\r\n AssemblyCommentLine(Language, LoadStr(CODE_SESSION_OPTIONS)) +\r\n AssemblyNewClassInstanceStart(Language, SessionOptionsClassName, false);\r\n\r\n UnicodeString ProtocolMember;\r\n switch (SessionData->FSProtocol)\r\n {\r\n case fsSCPonly:\r\n ProtocolMember = \"Scp\";\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n // fallback\r\n case fsSFTP:\r\n case fsSFTPonly:\r\n ProtocolMember = \"Sftp\";\r\n break;\r\n\r\n case fsFTP:\r\n ProtocolMember = \"Ftp\";\r\n break;\r\n\r\n case fsWebDAV:\r\n ProtocolMember = \"Webdav\";\r\n break;\r\n\r\n case fsS3:\r\n ProtocolMember = \"S3\";\r\n break;\r\n }\r\n\r\n // Before we reset the FSProtocol\r\n bool AUsesSsh = SessionData->UsesSsh;\r\n\r\n // Protocol is set unconditionally, we want even the default SFTP\r\n AddAssemblyProperty(Head, Language, L\"Protocol\", L\"Protocol\", ProtocolMember);\r\n // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that\r\n if (SessionData->FSProtocol != fsSFTPonly)\r\n {\r\n SessionData->FSProtocol = FactoryDefaults->FSProtocol;\r\n }\r\n if (SessionData->HostName != FactoryDefaults->HostName)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"HostName\", HostName);\r\n SessionData->HostName = FactoryDefaults->HostName;\r\n }\r\n int ADefaultPort = DefaultPort(FSProtocol, Ftps);\r\n if (SessionData->PortNumber != ADefaultPort)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"PortNumber\", PortNumber);\r\n }\r\n SessionData->PortNumber = FactoryDefaults->PortNumber;\r\n if (SessionData->UserName != FactoryDefaults->UserName)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"UserName\", UserName);\r\n SessionData->UserName = FactoryDefaults->UserName;\r\n }\r\n if (SessionData->Password != FactoryDefaults->Password)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"Password\", NormalizeString(Password));\r\n SessionData->Password = FactoryDefaults->Password;\r\n }\r\n\r\n SessionData->CopyNonCoreData(FactoryDefaults.get());\r\n\r\n if (SessionData->Ftps != FactoryDefaults->Ftps)\r\n {\r\n // SessionData->FSProtocol is reset already\r\n switch (FSProtocol)\r\n {\r\n case fsFTP:\r\n {\r\n UnicodeString FtpSecureMember;\r\n switch (SessionData->Ftps)\r\n {\r\n case ftpsNone:\r\n // noop\r\n break;\r\n\r\n case ftpsImplicit:\r\n FtpSecureMember = L\"Implicit\";\r\n break;\r\n\r\n case ftpsExplicitTls:\r\n case ftpsExplicitSsl:\r\n FtpSecureMember = L\"Explicit\";\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n break;\r\n }\r\n AddAssemblyProperty(Head, Language, L\"FtpSecure\", L\"FtpSecure\", FtpSecureMember);\r\n }\r\n break;\r\n\r\n case fsWebDAV:\r\n AddAssemblyProperty(Head, Language, L\"WebdavSecure\", (SessionData->Ftps != ftpsNone));\r\n break;\r\n\r\n case fsS3:\r\n // implicit\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n break;\r\n }\r\n SessionData->Ftps = FactoryDefaults->Ftps;\r\n }\r\n\r\n if (SessionData->HostKey != FactoryDefaults->HostKey)\r\n {\r\n UnicodeString PropertyName = AUsesSsh ? L\"SshHostKeyFingerprint\" : L\"TlsHostCertificateFingerprint\";\r\n AddAssemblyProperty(Head, Language, PropertyName, SessionData->HostKey);\r\n SessionData->HostKey = FactoryDefaults->HostKey;\r\n }\r\n if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"SshPrivateKeyPath\", SessionData->PublicKeyFile);\r\n SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;\r\n }\r\n if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"TlsClientCertificatePath\", SessionData->TlsCertificateFile);\r\n SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;\r\n }\r\n if (SessionData->Passphrase != FactoryDefaults->Passphrase)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"PrivateKeyPassphrase\", SessionData->Passphrase);\r\n SessionData->Passphrase = FactoryDefaults->Passphrase;\r\n }\r\n if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"FtpMode\", L\"FtpMode\", (SessionData->FtpPasvMode ? L\"Passive\" : L\"Active\"));\r\n SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;\r\n }\r\n if (SessionData->Timeout != FactoryDefaults->Timeout)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"TimeoutInMilliseconds\", SessionData->Timeout * 1000);\r\n SessionData->Timeout = FactoryDefaults->Timeout;\r\n }\r\n\r\n Head += AssemblyNewClassInstanceEnd(Language, false);\r\n\r\n std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get(), false, false));\r\n\r\n UnicodeString SessionOptionsVariableName = AssemblyVariableName(Language, SessionOptionsClassName);\r\n\r\n if (RawSettings->Count > 0)\r\n {\r\n Head +=\r\n RtfPara +\r\n AssemblyAddRawSettings(Language, RawSettings.get(), SessionOptionsClassName, L\"AddRawSettings\");\r\n }\r\n\r\n Head += RtfPara;\r\n\r\n UnicodeString Indentation = L\" \";\r\n UnicodeString SessionVariableName = AssemblyVariableName(Language, SessionClassName);\r\n UnicodeString RtfSessionClass = RtfLibraryClass(SessionClassName);\r\n UnicodeString RtfSessionOpenMethod = RtfLibraryMethod(SessionClassName, L\"Open\", false);\r\n\r\n UnicodeString NewSessionInstance = AssemblyNewClassInstance(Language, SessionClassName, false);\r\n UnicodeString OpenCall =\r\n Indentation + AssemblyCommentLine(Language, LoadStr(CODE_CONNECT)) +\r\n Indentation + RtfText(SessionVariableName + L\".\") + RtfSessionOpenMethod + RtfText(L\"(\" + SessionOptionsVariableName + L\")\") +\r\n AssemblyStatementSeparator(Language) + RtfPara;\r\n\r\n switch (Language)\r\n {\r\n case alCSharp:\r\n Head +=\r\n RtfKeyword(L\"using\") + RtfText(\" (\") + NewSessionInstance + RtfText(L\"())\") + RtfPara +\r\n RtfText(L\"{\") + RtfPara +\r\n OpenCall;\r\n\r\n Tail =\r\n RtfText(L\"}\") + RtfPara;\r\n break;\r\n\r\n case alVBNET:\r\n Head +=\r\n RtfKeyword(L\"Using\") + RtfText(L\" \") + NewSessionInstance + RtfPara +\r\n OpenCall;\r\n\r\n Tail =\r\n RtfKeyword(L\"End Using\") + RtfPara;\r\n break;\r\n\r\n case alPowerShell:\r\n Head +=\r\n NewSessionInstance + RtfPara +\r\n RtfPara +\r\n RtfKeyword(L\"try\") + RtfPara +\r\n RtfText(L\"{\") + RtfPara +\r\n OpenCall;\r\n\r\n Tail =\r\n RtfText(L\"}\") + RtfPara +\r\n RtfKeyword(L\"finally\") + RtfPara +\r\n RtfText(L\"{\") + RtfPara +\r\n RtfText(Indentation + SessionVariableName + L\".\") +\r\n RtfLibraryMethod(SessionClassName, L\"Dispose\", false) + RtfText(L\"()\") + RtfPara +\r\n RtfText(L\"}\") + RtfPara;\r\n break;\r\n }\r\n\r\n Head += RtfPara;\r\n\r\n Indent = 4; // the same for all languages so far\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTimeDifference(TDateTime value)\r\n{\r\n SET_SESSION_PROPERTY(TimeDifference);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTimeDifferenceAuto(bool value)\r\n{\r\n SET_SESSION_PROPERTY(TimeDifferenceAuto);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetLocalDirectory(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(LocalDirectory);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetLocalDirectoryExpanded()\r\n{\r\n return ExpandFileName(::ExpandEnvironmentVariables(LocalDirectory));\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetRemoteDirectory(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(RemoteDirectory);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSynchronizeBrowsing(bool value)\r\n{\r\n SET_SESSION_PROPERTY(SynchronizeBrowsing);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetUpdateDirectories(bool value)\r\n{\r\n SET_SESSION_PROPERTY(UpdateDirectories);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetCacheDirectories(bool value)\r\n{\r\n SET_SESSION_PROPERTY(CacheDirectories);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetCacheDirectoryChanges(bool value)\r\n{\r\n SET_SESSION_PROPERTY(CacheDirectoryChanges);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPreserveDirectoryChanges(bool value)\r\n{\r\n SET_SESSION_PROPERTY(PreserveDirectoryChanges);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetResolveSymlinks(bool value)\r\n{\r\n SET_SESSION_PROPERTY(ResolveSymlinks);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFollowDirectorySymlinks(bool value)\r\n{\r\n SET_SESSION_PROPERTY(FollowDirectorySymlinks);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetDSTMode(TDSTMode value)\r\n{\r\n SET_SESSION_PROPERTY(DSTMode);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetDeleteToRecycleBin(bool value)\r\n{\r\n SET_SESSION_PROPERTY(DeleteToRecycleBin);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetOverwrittenToRecycleBin(bool value)\r\n{\r\n SET_SESSION_PROPERTY(OverwrittenToRecycleBin);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetRecycleBinPath(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(RecycleBinPath);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPostLoginCommands(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(PostLoginCommands);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetLockInHome(bool value)\r\n{\r\n SET_SESSION_PROPERTY(LockInHome);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSpecial(bool value)\r\n{\r\n SET_SESSION_PROPERTY(Special);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetScp1Compatibility(bool value)\r\n{\r\n SET_SESSION_PROPERTY(Scp1Compatibility);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTcpNoDelay(bool value)\r\n{\r\n SET_SESSION_PROPERTY(TcpNoDelay);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSendBuf(int value)\r\n{\r\n SET_SESSION_PROPERTY(SendBuf);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSourceAddress(const UnicodeString & value)\r\n{\r\n SET_SESSION_PROPERTY(SourceAddress);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSshSimple(bool value)\r\n{\r\n SET_SESSION_PROPERTY(SshSimple);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyMethod(TProxyMethod value)\r\n{\r\n SET_SESSION_PROPERTY(ProxyMethod);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyHost(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(ProxyHost);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyPort(int value)\r\n{\r\n SET_SESSION_PROPERTY(ProxyPort);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyUsername(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(ProxyUsername);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyPassword(UnicodeString avalue)\r\n{\r\n RawByteString value = EncryptPassword(avalue, ProxyUsername+ProxyHost);\r\n SET_SESSION_PROPERTY(ProxyPassword);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetProxyPassword() const\r\n{\r\n return DecryptPassword(FProxyPassword, ProxyUsername+ProxyHost);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyTelnetCommand(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(ProxyTelnetCommand);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyLocalCommand(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(ProxyLocalCommand);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyDNS(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(ProxyDNS);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyLocalhost(bool value)\r\n{\r\n SET_SESSION_PROPERTY(ProxyLocalhost);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpProxyLogonType(int value)\r\n{\r\n SET_SESSION_PROPERTY(FtpProxyLogonType);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetBug(TSshBug Bug, TAutoSwitch value)\r\n{\r\n DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));\r\n SET_SESSION_PROPERTY(Bugs[Bug]);\r\n}\r\n//---------------------------------------------------------------------\r\nTAutoSwitch __fastcall TSessionData::GetBug(TSshBug Bug) const\r\n{\r\n DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));\r\n return FBugs[Bug];\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPuttySettings(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(PuttySettings);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetCustomParam1(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(CustomParam1);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetCustomParam2(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(CustomParam2);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSFTPDownloadQueue(int value)\r\n{\r\n SET_SESSION_PROPERTY(SFTPDownloadQueue);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSFTPUploadQueue(int value)\r\n{\r\n SET_SESSION_PROPERTY(SFTPUploadQueue);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSFTPListingQueue(int value)\r\n{\r\n SET_SESSION_PROPERTY(SFTPListingQueue);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSFTPMaxVersion(int value)\r\n{\r\n SET_SESSION_PROPERTY(SFTPMaxVersion);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSFTPMaxPacketSize(unsigned long value)\r\n{\r\n SET_SESSION_PROPERTY(SFTPMaxPacketSize);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSFTPBug(TSftpBug Bug, TAutoSwitch value)\r\n{\r\n DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));\r\n SET_SESSION_PROPERTY(SFTPBugs[Bug]);\r\n}\r\n//---------------------------------------------------------------------\r\nTAutoSwitch __fastcall TSessionData::GetSFTPBug(TSftpBug Bug) const\r\n{\r\n DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));\r\n return FSFTPBugs[Bug];\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSCPLsFullTime(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(SCPLsFullTime);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetColor(int value)\r\n{\r\n SET_SESSION_PROPERTY(Color);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnel(bool value)\r\n{\r\n SET_SESSION_PROPERTY(Tunnel);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnelHostName(UnicodeString value)\r\n{\r\n if (FTunnelHostName != value)\r\n {\r\n // HostName is key for password encryption\r\n UnicodeString XTunnelPassword = TunnelPassword;\r\n\r\n int P = value.LastDelimiter(L\"@\");\r\n if (P > 0)\r\n {\r\n TunnelUserName = value.SubString(1, P - 1);\r\n value = value.SubString(P + 1, value.Length() - P);\r\n }\r\n FTunnelHostName = value;\r\n Modify();\r\n\r\n TunnelPassword = XTunnelPassword;\r\n Shred(XTunnelPassword);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnelPortNumber(int value)\r\n{\r\n SET_SESSION_PROPERTY(TunnelPortNumber);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnelUserName(UnicodeString value)\r\n{\r\n // Avoid password recryption (what may popup master password prompt)\r\n if (FTunnelUserName != value)\r\n {\r\n // TunnelUserName is key for password encryption\r\n UnicodeString XTunnelPassword = TunnelPassword;\r\n SET_SESSION_PROPERTY(TunnelUserName);\r\n TunnelPassword = XTunnelPassword;\r\n Shred(XTunnelPassword);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnelPassword(UnicodeString avalue)\r\n{\r\n RawByteString value = EncryptPassword(avalue, TunnelUserName+TunnelHostName);\r\n SET_SESSION_PROPERTY(TunnelPassword);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetTunnelPassword() const\r\n{\r\n return DecryptPassword(FTunnelPassword, TunnelUserName+TunnelHostName);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnelPublicKeyFile(UnicodeString value)\r\n{\r\n if (FTunnelPublicKeyFile != value)\r\n {\r\n // StripPathQuotes should not be needed as we do not feed quotes anymore\r\n FTunnelPublicKeyFile = StripPathQuotes(value);\r\n Modify();\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnelLocalPortNumber(int value)\r\n{\r\n SET_SESSION_PROPERTY(TunnelLocalPortNumber);\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::GetTunnelAutoassignLocalPortNumber()\r\n{\r\n return (FTunnelLocalPortNumber <= 0);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnelPortFwd(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(TunnelPortFwd);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnelHostKey(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(TunnelHostKey);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpPasvMode(bool value)\r\n{\r\n SET_SESSION_PROPERTY(FtpPasvMode);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpForcePasvIp(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(FtpForcePasvIp);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpUseMlsd(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(FtpUseMlsd);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpAccount(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(FtpAccount);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpPingInterval(int value)\r\n{\r\n SET_SESSION_PROPERTY(FtpPingInterval);\r\n}\r\n//---------------------------------------------------------------------------\r\nTDateTime __fastcall TSessionData::GetFtpPingIntervalDT()\r\n{\r\n return SecToDateTime(FtpPingInterval);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpPingType(TPingType value)\r\n{\r\n SET_SESSION_PROPERTY(FtpPingType);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpTransferActiveImmediately(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(FtpTransferActiveImmediately);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtps(TFtps value)\r\n{\r\n SET_SESSION_PROPERTY(Ftps);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetMinTlsVersion(TTlsVersion value)\r\n{\r\n SET_SESSION_PROPERTY(MinTlsVersion);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetMaxTlsVersion(TTlsVersion value)\r\n{\r\n SET_SESSION_PROPERTY(MaxTlsVersion);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetLogicalHostName(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(LogicalHostName);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpListAll(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(FtpListAll);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpHost(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(FtpHost);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpDeleteFromCwd(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(FtpDeleteFromCwd);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSslSessionReuse(bool value)\r\n{\r\n SET_SESSION_PROPERTY(SslSessionReuse);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTlsCertificateFile(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(TlsCertificateFile);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetNotUtf(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(NotUtf);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetInternalEditorEncoding(int value)\r\n{\r\n SET_SESSION_PROPERTY(InternalEditorEncoding);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetS3DefaultRegion(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(S3DefaultRegion);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetS3UrlStyle(TS3UrlStyle value)\r\n{\r\n SET_SESSION_PROPERTY(S3UrlStyle);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetIsWorkspace(bool value)\r\n{\r\n SET_SESSION_PROPERTY(IsWorkspace);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetLink(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(Link);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetNameOverride(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(NameOverride);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetHostKey(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(HostKey);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetNote(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(Note);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetWinTitle(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(WinTitle);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetEncryptKey() const\r\n{\r\n return DecryptPassword(FEncryptKey, UserName+HostName);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetEncryptKey(UnicodeString avalue)\r\n{\r\n RawByteString value = EncryptPassword(avalue, UserName+HostName);\r\n SET_SESSION_PROPERTY(EncryptKey);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetInfoTip()\r\n{\r\n if (UsesSsh)\r\n {\r\n return FMTLOAD(SESSION_INFO_TIP2,\r\n (HostName, UserName,\r\n (PublicKeyFile.IsEmpty() ? LoadStr(NO_STR) : LoadStr(YES_STR)),\r\n FSProtocolStr));\r\n }\r\n else\r\n {\r\n return FMTLOAD(SESSION_INFO_TIP_NO_SSH,\r\n (HostName, UserName, FSProtocolStr));\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::ExtractLocalName(const UnicodeString & Name)\r\n{\r\n UnicodeString Result = Name;\r\n int P = Result.LastDelimiter(L\"/\");\r\n if (P > 0)\r\n {\r\n Result.Delete(1, P);\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetLocalName()\r\n{\r\n UnicodeString Result;\r\n if (HasSessionName())\r\n {\r\n Result = ExtractLocalName(Name);\r\n }\r\n else\r\n {\r\n Result = DefaultSessionName;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::ExtractFolderName(const UnicodeString & Name)\r\n{\r\n UnicodeString Result;\r\n int P = Name.LastDelimiter(L\"/\");\r\n if (P > 0)\r\n {\r\n Result = Name.SubString(1, P - 1);\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetFolderName()\r\n{\r\n UnicodeString Result;\r\n if (HasSessionName() || IsWorkspace)\r\n {\r\n Result = ExtractFolderName(Name);\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::ComposePath(\r\n const UnicodeString & Path, const UnicodeString & Name)\r\n{\r\n return UnixIncludeTrailingBackslash(Path) + Name;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::DisableAuthentationsExceptPassword()\r\n{\r\n SshNoUserAuth = false;\r\n AuthTIS = false;\r\n AuthKI = false;\r\n AuthKIPassword = false;\r\n AuthGSSAPI = false;\r\n PublicKeyFile = L\"\";\r\n TlsCertificateFile = L\"\";\r\n Passphrase = L\"\";\r\n TryAgent = false;\r\n}\r\n//---------------------------------------------------------------------\r\nTStrings * TSessionData::GetAllOptionNames(bool PuttyExport)\r\n{\r\n std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L\"\"));\r\n return FactoryDefaults->SaveToOptions(NULL, false, PuttyExport);\r\n}\r\n//=== TStoredSessionList ----------------------------------------------\r\n__fastcall TStoredSessionList::TStoredSessionList(bool aReadOnly):\r\n TNamedObjectList(), FReadOnly(aReadOnly)\r\n{\r\n DebugAssert(Configuration);\r\n FDefaultSettings = new TSessionData(DefaultName);\r\n FPendingRemovals.reset(new TStringList());\r\n}\r\n//---------------------------------------------------------------------\r\n__fastcall TStoredSessionList::~TStoredSessionList()\r\n{\r\n DebugAssert(Configuration);\r\n delete FDefaultSettings;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::Load(THierarchicalStorage * Storage,\r\n bool AsModified, bool UseDefaults, bool PuttyImport)\r\n{\r\n TStringList *SubKeys = new TStringList();\r\n TList * Loaded = new TList;\r\n try\r\n {\r\n DebugAssert(AutoSort);\r\n AutoSort = false;\r\n bool WasEmpty = (Count == 0);\r\n\r\n Storage->GetSubKeyNames(SubKeys);\r\n\r\n for (int Index = 0; Index < SubKeys->Count; Index++)\r\n {\r\n UnicodeString SessionName = SubKeys->Strings[Index];\r\n\r\n bool ValidName = true;\r\n try\r\n {\r\n TSessionData::ValidatePath(SessionName);\r\n }\r\n catch(...)\r\n {\r\n ValidName = false;\r\n }\r\n\r\n if (ValidName)\r\n {\r\n TSessionData * SessionData;\r\n if (SessionName == FDefaultSettings->Name)\r\n {\r\n SessionData = FDefaultSettings;\r\n }\r\n else\r\n {\r\n // if the list was empty before loading, do not waste time trying to\r\n // find existing sites to overwrite (we rely on underlying storage\r\n // to secure uniqueness of the key names)\r\n if (WasEmpty)\r\n {\r\n SessionData = NULL;\r\n }\r\n else\r\n {\r\n SessionData = (TSessionData*)FindByName(SessionName);\r\n }\r\n }\r\n\r\n if ((SessionData != FDefaultSettings) || !UseDefaults)\r\n {\r\n if (SessionData == NULL)\r\n {\r\n SessionData = new TSessionData(L\"\");\r\n if (UseDefaults)\r\n {\r\n SessionData->CopyData(DefaultSettings);\r\n }\r\n SessionData->Name = SessionName;\r\n Add(SessionData);\r\n }\r\n Loaded->Add(SessionData);\r\n SessionData->Load(Storage, PuttyImport);\r\n if (AsModified)\r\n {\r\n SessionData->Modified = true;\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (!AsModified)\r\n {\r\n for (int Index = 0; Index < TObjectList::Count; Index++)\r\n {\r\n if (Loaded->IndexOf(Items[Index]) < 0)\r\n {\r\n Delete(Index);\r\n Index--;\r\n }\r\n }\r\n }\r\n }\r\n __finally\r\n {\r\n AutoSort = true;\r\n AlphaSort();\r\n delete SubKeys;\r\n delete Loaded;\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::Reload()\r\n{\r\n if (Count <= Configuration->DontReloadMoreThanSessions)\r\n {\r\n bool SessionList = true;\r\n std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(SessionList));\r\n if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, False))\r\n {\r\n Load(Storage.get());\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,\r\n TSessionData * Data, bool All, bool RecryptPasswordOnly,\r\n TSessionData * FactoryDefaults)\r\n{\r\n if (All || Data->Modified)\r\n {\r\n if (RecryptPasswordOnly)\r\n {\r\n Data->SaveRecryptedPasswords(Storage);\r\n }\r\n else\r\n {\r\n Data->Save(Storage, false, FactoryDefaults);\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,\r\n bool All, bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)\r\n{\r\n TSessionData * FactoryDefaults = new TSessionData(L\"\");\r\n try\r\n {\r\n while (FPendingRemovals->Count > 0)\r\n {\r\n TSessionData::Remove(Storage, FPendingRemovals->Strings[0]);\r\n FPendingRemovals->Delete(0);\r\n }\r\n\r\n DoSave(Storage, FDefaultSettings, All, RecryptPasswordOnly, FactoryDefaults);\r\n for (int Index = 0; Index < CountIncludingHidden; Index++)\r\n {\r\n TSessionData * SessionData = (TSessionData *)Items[Index];\r\n try\r\n {\r\n DoSave(Storage, SessionData, All, RecryptPasswordOnly, FactoryDefaults);\r\n }\r\n catch (Exception & E)\r\n {\r\n UnicodeString Message;\r\n if (RecryptPasswordOnly && DebugAlwaysTrue(RecryptPasswordErrors != NULL) &&\r\n ExceptionMessage(&E, Message))\r\n {\r\n RecryptPasswordErrors->Add(FORMAT(\"%s: %s\", (SessionData->SessionName, Message)));\r\n }\r\n else\r\n {\r\n throw;\r\n }\r\n }\r\n }\r\n }\r\n __finally\r\n {\r\n delete FactoryDefaults;\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::Save(THierarchicalStorage * Storage, bool All)\r\n{\r\n DoSave(Storage, All, false, NULL);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::DoSave(bool All, bool Explicit,\r\n bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)\r\n{\r\n bool SessionList = true;\r\n THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);\r\n try\r\n {\r\n Storage->AccessMode = smReadWrite;\r\n Storage->Explicit = Explicit;\r\n if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))\r\n {\r\n DoSave(Storage, All, RecryptPasswordOnly, RecryptPasswordErrors);\r\n }\r\n }\r\n __finally\r\n {\r\n delete Storage;\r\n }\r\n\r\n Saved();\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::Save(bool All, bool Explicit)\r\n{\r\n DoSave(All, Explicit, false, NULL);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::RecryptPasswords(TStrings * RecryptPasswordErrors)\r\n{\r\n DoSave(true, true, true, RecryptPasswordErrors);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::Saved()\r\n{\r\n FDefaultSettings->Modified = false;\r\n for (int Index = 0; Index < CountIncludingHidden; Index++)\r\n {\r\n ((TSessionData *)Items[Index])->Modified = false;\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::ImportLevelFromFilezilla(\r\n _di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode)\r\n{\r\n for (int Index = 0; Index < Node->ChildNodes->Count; Index++)\r\n {\r\n _di_IXMLNode ChildNode = Node->ChildNodes->Get(Index);\r\n if (ChildNode->NodeName == L\"Server\")\r\n {\r\n std::unique_ptr<TSessionData> SessionData(new TSessionData(L\"\"));\r\n SessionData->CopyData(DefaultSettings);\r\n SessionData->ImportFromFilezilla(ChildNode, Path, SettingsNode);\r\n Add(SessionData.release());\r\n }\r\n else if (ChildNode->NodeName == L\"Folder\")\r\n {\r\n UnicodeString Name;\r\n\r\n for (int Index = 0; Index < ChildNode->ChildNodes->Count; Index++)\r\n {\r\n _di_IXMLNode PossibleTextMode = ChildNode->ChildNodes->Get(Index);\r\n if (PossibleTextMode->NodeType == ntText)\r\n {\r\n UnicodeString NodeValue = PossibleTextMode->NodeValue;\r\n AddToList(Name, NodeValue.Trim(), L\" \");\r\n }\r\n }\r\n\r\n Name = TSessionData::MakeValidName(Name).Trim();\r\n\r\n ImportLevelFromFilezilla(ChildNode, TSessionData::ComposePath(Path, Name), SettingsNode);\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::ImportFromFilezilla(\r\n const UnicodeString FileName, const UnicodeString ConfigurationFileName)\r\n{\r\n\r\n // not sure if the document must exists if we want to use its node\r\n _di_IXMLDocument ConfigurationDocument;\r\n _di_IXMLNode SettingsNode;\r\n\r\n if (FileExists(ApiPath(ConfigurationFileName)))\r\n {\r\n ConfigurationDocument = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));\r\n ConfigurationDocument->LoadFromFile(ConfigurationFileName);\r\n _di_IXMLNode FileZilla3Node = ConfigurationDocument->ChildNodes->FindNode(L\"FileZilla3\");\r\n if (FileZilla3Node != NULL)\r\n {\r\n SettingsNode = FileZilla3Node->ChildNodes->FindNode(L\"Settings\");\r\n }\r\n }\r\n\r\n const _di_IXMLDocument Document = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));\r\n Document->LoadFromFile(FileName);\r\n _di_IXMLNode FileZilla3Node = Document->ChildNodes->FindNode(L\"FileZilla3\");\r\n if (FileZilla3Node != NULL)\r\n {\r\n _di_IXMLNode ServersNode = FileZilla3Node->ChildNodes->FindNode(L\"Servers\");\r\n if (ServersNode != NULL)\r\n {\r\n ImportLevelFromFilezilla(ServersNode, L\"\", SettingsNode);\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::ImportFromKnownHosts(TStrings * Lines)\r\n{\r\n bool SessionList = false;\r\n std::unique_ptr<THierarchicalStorage> HostKeyStorage(Configuration->CreateScpStorage(SessionList));\r\n std::unique_ptr<TStrings> KeyList(new TStringList());\r\n if (OpenHostKeysSubKey(HostKeyStorage.get(), false))\r\n {\r\n HostKeyStorage->GetValueNames(KeyList.get());\r\n }\r\n HostKeyStorage.reset(NULL);\r\n\r\n UnicodeString FirstError;\r\n for (int Index = 0; Index < Lines->Count; Index++)\r\n {\r\n try\r\n {\r\n UnicodeString Line = Lines->Strings[Index];\r\n Line = Trim(Line);\r\n if (!Line.IsEmpty() && (Line[1] != L';'))\r\n {\r\n int P = Pos(L' ', Line);\r\n if (P > 0)\r\n {\r\n UnicodeString HostNameStr = Line.SubString(1, P - 1);\r\n Line = Line.SubString(P + 1, Line.Length() - P);\r\n\r\n P = Pos(L',', HostNameStr);\r\n if (P > 0)\r\n {\r\n HostNameStr.SetLength(P - 1);\r\n }\r\n P = Pos(L':', HostNameStr);\r\n int PortNumber = -1;\r\n if (P > 0)\r\n {\r\n UnicodeString PortNumberStr = HostNameStr.SubString(P + 1, HostNameStr.Length() - P);\r\n PortNumber = StrToInt(PortNumberStr);\r\n HostNameStr.SetLength(P - 1);\r\n }\r\n if ((HostNameStr.Length() >= 2) &&\r\n (HostNameStr[1] == L'[') && (HostNameStr[HostNameStr.Length()] == L']'))\r\n {\r\n HostNameStr = HostNameStr.SubString(2, HostNameStr.Length() - 2);\r\n }\r\n\r\n UnicodeString NameStr = HostNameStr;\r\n if (PortNumber >= 0)\r\n {\r\n NameStr = FORMAT(L\"%s:%d\", (NameStr, PortNumber));\r\n }\r\n\r\n std::unique_ptr<TSessionData> SessionDataOwner;\r\n TSessionData * SessionData = dynamic_cast<TSessionData *>(FindByName(NameStr));\r\n if (SessionData == NULL)\r\n {\r\n SessionData = new TSessionData(L\"\");\r\n SessionDataOwner.reset(SessionData);\r\n SessionData->CopyData(DefaultSettings);\r\n SessionData->Name = NameStr;\r\n SessionData->HostName = HostNameStr;\r\n if (PortNumber >= 0)\r\n {\r\n SessionData->PortNumber = PortNumber;\r\n }\r\n }\r\n\r\n const struct ssh_keyalg * Algorithm;\r\n UnicodeString Key = ParseOpenSshPubLine(Line, Algorithm);\r\n UnicodeString KeyKey =\r\n FORMAT(L\"%s@%d:%s\", (Algorithm->cache_id, SessionData->PortNumber, HostNameStr));\r\n UnicodeString HostKey =\r\n FORMAT(L\"%s:%s=%s\", (Algorithm->ssh_id, KeyKey, Key));\r\n UnicodeString HostKeyList = SessionData->HostKey;\r\n AddToList(HostKeyList, HostKey, L\";\");\r\n SessionData->HostKey = HostKeyList;\r\n // If there's at least one unknown key type for this host, select it\r\n if (KeyList->IndexOf(KeyKey) < 0)\r\n {\r\n SessionData->Selected = true;\r\n }\r\n\r\n if (SessionDataOwner.get() != NULL)\r\n {\r\n Add(SessionDataOwner.release());\r\n }\r\n }\r\n }\r\n }\r\n catch (Exception & E)\r\n {\r\n if (FirstError.IsEmpty())\r\n {\r\n FirstError = E.Message;\r\n }\r\n }\r\n }\r\n\r\n if (Count == 0)\r\n {\r\n UnicodeString Message = LoadStr(KNOWN_HOSTS_NO_SITES);\r\n if (!FirstError.IsEmpty())\r\n {\r\n Message = FORMAT(L\"%s\\n(%s)\", (Message, FirstError));\r\n }\r\n\r\n throw Exception(Message);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::Export(const UnicodeString FileName)\r\n{\r\n THierarchicalStorage * Storage = TIniFileStorage::CreateFromPath(FileName);\r\n try\r\n {\r\n Storage->AccessMode = smReadWrite;\r\n if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))\r\n {\r\n Save(Storage, true);\r\n }\r\n }\r\n __finally\r\n {\r\n delete Storage;\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::SelectAll(bool Select)\r\n{\r\n for (int Index = 0; Index < Count; Index++)\r\n Sessions[Index]->Selected = Select;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::Import(TStoredSessionList * From,\r\n bool OnlySelected, TList * Imported)\r\n{\r\n for (int Index = 0; Index < From->Count; Index++)\r\n {\r\n if (!OnlySelected || From->Sessions[Index]->Selected)\r\n {\r\n TSessionData *Session = new TSessionData(L\"\");\r\n Session->Assign(From->Sessions[Index]);\r\n Session->Modified = true;\r\n Session->MakeUniqueIn(this);\r\n Add(Session);\r\n if (Imported != NULL)\r\n {\r\n Imported->Add(Session);\r\n }\r\n }\r\n }\r\n // only modified, explicit\r\n Save(false, true);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::SelectSessionsToImport\r\n (TStoredSessionList * Dest, bool SSHOnly)\r\n{\r\n for (int Index = 0; Index < Count; Index++)\r\n {\r\n Sessions[Index]->Selected =\r\n (!SSHOnly || (Sessions[Index]->GetNormalizedPuttyProtocol() == PuttySshProtocol)) &&\r\n !Dest->FindByName(Sessions[Index]->Name);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::Cleanup()\r\n{\r\n try\r\n {\r\n if (Configuration->Storage == stRegistry) Clear();\r\n TRegistryStorage * Storage = new TRegistryStorage(Configuration->RegistryStorageKey);\r\n try\r\n {\r\n Storage->AccessMode = smReadWrite;\r\n if (Storage->OpenRootKey(False))\r\n Storage->RecursiveDeleteSubKey(Configuration->StoredSessionsSubKey);\r\n }\r\n __finally\r\n {\r\n delete Storage;\r\n }\r\n }\r\n catch (Exception &E)\r\n {\r\n throw ExtException(&E, LoadStr(CLEANUP_SESSIONS_ERROR));\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::UpdateStaticUsage()\r\n{\r\n int SCP = 0;\r\n int SFTP = 0;\r\n int FTP = 0;\r\n int FTPS = 0;\r\n int WebDAV = 0;\r\n int WebDAVS = 0;\r\n int S3 = 0;\r\n int Password = 0;\r\n int Advanced = 0;\r\n int Color = 0;\r\n int Note = 0;\r\n int Tunnel = 0;\r\n bool Folders = false;\r\n bool Workspaces = false;\r\n std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L\"\"));\r\n std::unique_ptr<TStringList> DifferentAdvancedProperties(CreateSortedStringList());\r\n for (int Index = 0; Index < Count; Index++)\r\n {\r\n TSessionData * Data = Sessions[Index];\r\n if (Data->IsWorkspace)\r\n {\r\n Workspaces = true;\r\n }\r\n else\r\n {\r\n switch (Data->FSProtocol)\r\n {\r\n case fsSCPonly:\r\n SCP++;\r\n break;\r\n\r\n case fsSFTP:\r\n case fsSFTPonly:\r\n SFTP++;\r\n break;\r\n\r\n case fsFTP:\r\n if (Data->Ftps == ftpsNone)\r\n {\r\n FTP++;\r\n }\r\n else\r\n {\r\n FTPS++;\r\n }\r\n break;\r\n\r\n case fsWebDAV:\r\n if (Data->Ftps == ftpsNone)\r\n {\r\n WebDAV++;\r\n }\r\n else\r\n {\r\n WebDAVS++;\r\n }\r\n break;\r\n\r\n case fsS3:\r\n S3++;\r\n break;\r\n }\r\n\r\n if (Data->HasAnySessionPassword())\r\n {\r\n Password++;\r\n }\r\n\r\n if (Data->Color != 0)\r\n {\r\n Color++;\r\n }\r\n\r\n if (!Data->Note.IsEmpty())\r\n {\r\n Note++;\r\n }\r\n\r\n // This would not work for passwords, as they are compared in their encrypted form.\r\n // But there are no passwords set in factory defaults anyway.\r\n if (!Data->IsSame(FactoryDefaults.get(), true, DifferentAdvancedProperties.get(), false))\r\n {\r\n Advanced++;\r\n }\r\n\r\n if (Data->Tunnel)\r\n {\r\n Tunnel++;\r\n }\r\n\r\n if (!Data->FolderName.IsEmpty())\r\n {\r\n Folders = true;\r\n }\r\n }\r\n }\r\n\r\n Configuration->Usage->Set(L\"StoredSessionsCountSCP\", SCP);\r\n Configuration->Usage->Set(L\"StoredSessionsCountSFTP\", SFTP);\r\n Configuration->Usage->Set(L\"StoredSessionsCountFTP\", FTP);\r\n Configuration->Usage->Set(L\"StoredSessionsCountFTPS\", FTPS);\r\n Configuration->Usage->Set(L\"StoredSessionsCountWebDAV\", WebDAV);\r\n Configuration->Usage->Set(L\"StoredSessionsCountWebDAVS\", WebDAVS);\r\n Configuration->Usage->Set(L\"StoredSessionsCountS3\", S3);\r\n Configuration->Usage->Set(L\"StoredSessionsCountPassword\", Password);\r\n Configuration->Usage->Set(L\"StoredSessionsCountColor\", Color);\r\n Configuration->Usage->Set(L\"StoredSessionsCountNote\", Note);\r\n Configuration->Usage->Set(L\"StoredSessionsCountAdvanced\", Advanced);\r\n DifferentAdvancedProperties->Delimiter = L',';\r\n Configuration->Usage->Set(L\"StoredSessionsAdvancedSettings\", DifferentAdvancedProperties->DelimitedText);\r\n Configuration->Usage->Set(L\"StoredSessionsCountTunnel\", Tunnel);\r\n\r\n // actually default might be true, see below for when the default is actually used\r\n bool CustomDefaultStoredSession = false;\r\n try\r\n {\r\n // this can throw, when the default session settings have password set\r\n // (and no other basic property, like hostname/username),\r\n // and master password is enabled as we are called before master password\r\n // handler is set\r\n CustomDefaultStoredSession = !FDefaultSettings->IsSame(FactoryDefaults.get(), false);\r\n }\r\n catch (...)\r\n {\r\n }\r\n Configuration->Usage->Set(L\"UsingDefaultStoredSession\", CustomDefaultStoredSession);\r\n\r\n Configuration->Usage->Set(L\"UsingStoredSessionsFolders\", Folders);\r\n Configuration->Usage->Set(L\"UsingWorkspaces\", Workspaces);\r\n}\r\n//---------------------------------------------------------------------------\r\nTSessionData * __fastcall TStoredSessionList::FindSame(TSessionData * Data)\r\n{\r\n TSessionData * Result;\r\n if (Data->Hidden || Data->Name.IsEmpty() || Data->IsWorkspace)\r\n {\r\n Result = NULL;\r\n }\r\n else\r\n {\r\n Result = dynamic_cast<TSessionData *>(FindByName(Data->Name));\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall TStoredSessionList::IndexOf(TSessionData * Data)\r\n{\r\n for (int Index = 0; Index < Count; Index++)\r\n if (Data == Sessions[Index]) return Index;\r\n return -1;\r\n}\r\n//---------------------------------------------------------------------------\r\nTSessionData * __fastcall TStoredSessionList::NewSession(\r\n UnicodeString SessionName, TSessionData * Session)\r\n{\r\n TSessionData * DuplicateSession = (TSessionData*)FindByName(SessionName);\r\n if (!DuplicateSession)\r\n {\r\n DuplicateSession = new TSessionData(L\"\");\r\n DuplicateSession->Assign(Session);\r\n DuplicateSession->Name = SessionName;\r\n // make sure, that new stored session is saved to registry\r\n DuplicateSession->Modified = true;\r\n Add(DuplicateSession);\r\n }\r\n else\r\n {\r\n DuplicateSession->Assign(Session);\r\n DuplicateSession->Name = SessionName;\r\n DuplicateSession->Modified = true;\r\n }\r\n // list was saved here before to default storage, but it would not allow\r\n // to work with special lists (export/import) not using default storage\r\n return DuplicateSession;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::SetDefaultSettings(TSessionData * value)\r\n{\r\n DebugAssert(FDefaultSettings);\r\n if (FDefaultSettings != value)\r\n {\r\n FDefaultSettings->Assign(value);\r\n // make sure default settings are saved\r\n FDefaultSettings->Modified = true;\r\n FDefaultSettings->Name = DefaultName;\r\n if (!FReadOnly)\r\n {\r\n // only modified, explicit\r\n Save(false, true);\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TStoredSessionList::OpenHostKeysSubKey(THierarchicalStorage * Storage, bool CanCreate)\r\n{\r\n return\r\n Storage->OpenRootKey(CanCreate) &&\r\n Storage->OpenSubKey(Configuration->SshHostKeysSubKey, CanCreate);\r\n}\r\n//---------------------------------------------------------------------------\r\nTHierarchicalStorage * __fastcall TStoredSessionList::CreateHostKeysStorageForWritting()\r\n{\r\n bool SessionList = false;\r\n std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(SessionList));\r\n Storage->Explicit = true;\r\n Storage->AccessMode = smReadWrite;\r\n return Storage.release();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::ImportHostKeys(\r\n THierarchicalStorage * SourceStorage, THierarchicalStorage * TargetStorage, TStoredSessionList * Sessions, bool OnlySelected)\r\n{\r\n if (OpenHostKeysSubKey(SourceStorage, false) &&\r\n OpenHostKeysSubKey(TargetStorage, true))\r\n {\r\n std::auto_ptr<TStringList> KeyList(new TStringList());\r\n SourceStorage->GetValueNames(KeyList.get());\r\n\r\n DebugAssert(Sessions != NULL);\r\n for (int Index = 0; Index < Sessions->Count; Index++)\r\n {\r\n TSessionData * Session = Sessions->Sessions[Index];\r\n if (!OnlySelected || Session->Selected)\r\n {\r\n UnicodeString HostKeyName = PuttyMungeStr(FORMAT(L\"@%d:%s\", (Session->PortNumber, Session->HostNameExpanded)));\r\n for (int KeyIndex = 0; KeyIndex < KeyList->Count; KeyIndex++)\r\n {\r\n UnicodeString KeyName = KeyList->Strings[KeyIndex];\r\n if (EndsText(HostKeyName, KeyName))\r\n {\r\n TargetStorage->WriteStringRaw(KeyName, SourceStorage->ReadStringRaw(KeyName, L\"\"));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::ImportHostKeys(\r\n const UnicodeString & SourceKey, TStoredSessionList * Sessions, bool OnlySelected)\r\n{\r\n std::auto_ptr<THierarchicalStorage> TargetStorage(CreateHostKeysStorageForWritting());\r\n std::auto_ptr<THierarchicalStorage> SourceStorage(new TRegistryStorage(SourceKey));\r\n\r\n ImportHostKeys(SourceStorage.get(), TargetStorage.get(), Sessions, OnlySelected);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::ImportSelectedKnownHosts(TStoredSessionList * Sessions)\r\n{\r\n std::unique_ptr<THierarchicalStorage> Storage(CreateHostKeysStorageForWritting());\r\n if (OpenHostKeysSubKey(Storage.get(), true))\r\n {\r\n for (int Index = 0; Index < Sessions->Count; Index++)\r\n {\r\n TSessionData * Session = Sessions->Sessions[Index];\r\n if (Session->Selected)\r\n {\r\n UnicodeString Algs;\r\n UnicodeString HostKeys = Session->HostKey;\r\n while (!HostKeys.IsEmpty())\r\n {\r\n UnicodeString HostKey = CutToChar(HostKeys, L';', true);\r\n // skip alg\r\n CutToChar(HostKey, L':', true);\r\n UnicodeString Key = CutToChar(HostKey, L'=', true);\r\n Storage->WriteStringRaw(Key, HostKey);\r\n }\r\n }\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TStoredSessionList::IsFolderOrWorkspace(\r\n const UnicodeString & Name, bool Workspace)\r\n{\r\n bool Result = false;\r\n TSessionData * FirstData = NULL;\r\n if (!Name.IsEmpty())\r\n {\r\n for (int Index = 0; !Result && (Index < Count); Index++)\r\n {\r\n Result = Sessions[Index]->IsInFolderOrWorkspace(Name);\r\n if (Result)\r\n {\r\n FirstData = Sessions[Index];\r\n }\r\n }\r\n }\r\n\r\n return\r\n Result &&\r\n DebugAlwaysTrue(FirstData != NULL) &&\r\n (FirstData->IsWorkspace == Workspace);\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TStoredSessionList::IsFolder(const UnicodeString & Name)\r\n{\r\n return IsFolderOrWorkspace(Name, false);\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TStoredSessionList::IsWorkspace(const UnicodeString & Name)\r\n{\r\n return IsFolderOrWorkspace(Name, true);\r\n}\r\n//---------------------------------------------------------------------------\r\nTSessionData * __fastcall TStoredSessionList::CheckIsInFolderOrWorkspaceAndResolve(\r\n TSessionData * Data, const UnicodeString & Name)\r\n{\r\n if (Data->IsInFolderOrWorkspace(Name))\r\n {\r\n Data = ResolveWorkspaceData(Data);\r\n\r\n if ((Data != NULL) && Data->CanLogin &&\r\n DebugAlwaysTrue(Data->Link.IsEmpty()))\r\n {\r\n return Data;\r\n }\r\n }\r\n return NULL;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::GetFolderOrWorkspace(const UnicodeString & Name, TList * List)\r\n{\r\n DoGetFolderOrWorkspace(Name, List, false);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::DoGetFolderOrWorkspace(const UnicodeString & Name, TList * List, bool NoRecrypt)\r\n{\r\n for (int Index = 0; (Index < Count); Index++)\r\n {\r\n TSessionData * RawData = Sessions[Index];\r\n TSessionData * Data =\r\n CheckIsInFolderOrWorkspaceAndResolve(RawData, Name);\r\n\r\n if (Data != NULL)\r\n {\r\n TSessionData * Data2 = new TSessionData(L\"\");\r\n if (NoRecrypt)\r\n {\r\n Data2->CopyDataNoRecrypt(Data);\r\n }\r\n else\r\n {\r\n Data2->Assign(Data);\r\n }\r\n\r\n if (!RawData->Link.IsEmpty() && (DebugAlwaysTrue(Data != RawData)) &&\r\n // BACKWARD COMPATIBILITY\r\n // When loading pre-5.6.4 workspace, that does not have state saved,\r\n // do not overwrite the site \"state\" defaults\r\n // with (empty) workspace state\r\n RawData->HasStateData())\r\n {\r\n Data2->CopyStateData(RawData);\r\n }\r\n\r\n if (!RawData->NameOverride.IsEmpty())\r\n {\r\n Data2->Name = RawData->NameOverride;\r\n }\r\n else if (RawData->Link.IsEmpty() && RawData->IsWorkspace)\r\n {\r\n // Newly opened ad-hoc session has no name, so restore the workspace that way too.\r\n // Otherwise we would persist the generated internal workspace name as a real name.\r\n Data2->Name = UnicodeString();\r\n }\r\n\r\n List->Add(Data2);\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nTStrings * __fastcall TStoredSessionList::GetFolderOrWorkspaceList(\r\n const UnicodeString & Name)\r\n{\r\n std::unique_ptr<TObjectList> DataList(new TObjectList());\r\n DoGetFolderOrWorkspace(Name, DataList.get(), true);\r\n\r\n std::unique_ptr<TStringList> Result(new TStringList());\r\n for (int Index = 0; (Index < DataList->Count); Index++)\r\n {\r\n Result->Add(dynamic_cast<TSessionData *>(DataList->Items[Index])->SessionName);\r\n }\r\n\r\n return Result.release();\r\n}\r\n//---------------------------------------------------------------------------\r\nTStrings * __fastcall TStoredSessionList::GetWorkspaces()\r\n{\r\n std::unique_ptr<TStringList> Result(CreateSortedStringList());\r\n\r\n for (int Index = 0; (Index < Count); Index++)\r\n {\r\n TSessionData * Data = Sessions[Index];\r\n if (Data->IsWorkspace)\r\n {\r\n Result->Add(Data->FolderName);\r\n }\r\n }\r\n\r\n return Result.release();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::NewWorkspace(\r\n UnicodeString Name, TList * DataList)\r\n{\r\n for (int Index = 0; (Index < Count); Index++)\r\n {\r\n TSessionData * Data = Sessions[Index];\r\n if (Data->IsInFolderOrWorkspace(Name))\r\n {\r\n FPendingRemovals->Add(Data->Name);\r\n Remove(Data);\r\n Index--;\r\n }\r\n }\r\n\r\n for (int Index = 0; (Index < DataList->Count); Index++)\r\n {\r\n TSessionData * Data = static_cast<TSessionData *>(DataList->Items[Index]);\r\n\r\n TSessionData * Data2 = new TSessionData(L\"\");\r\n Data2->Assign(Data);\r\n Data2->Name = TSessionData::ComposePath(Name, Data->Name);\r\n // make sure, that new stored session is saved to registry\r\n Data2->Modified = true;\r\n Add(Data2);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TStoredSessionList::HasAnyWorkspace()\r\n{\r\n bool Result = false;\r\n for (int Index = 0; !Result && (Index < Count); Index++)\r\n {\r\n TSessionData * Data = Sessions[Index];\r\n Result = Data->IsWorkspace;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nTSessionData * __fastcall TStoredSessionList::ParseUrl(UnicodeString Url,\r\n TOptions * Options, bool & DefaultsOnly, UnicodeString * FileName,\r\n bool * AProtocolDefined, UnicodeString * MaskedUrl, int Flags)\r\n{\r\n TSessionData * Data = new TSessionData(L\"\");\r\n try\r\n {\r\n Data->ParseUrl(Url, Options, this, DefaultsOnly, FileName, AProtocolDefined, MaskedUrl, Flags);\r\n }\r\n catch(...)\r\n {\r\n delete Data;\r\n throw;\r\n }\r\n\r\n return Data;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TStoredSessionList::IsUrl(UnicodeString Url)\r\n{\r\n bool DefaultsOnly;\r\n bool ProtocolDefined = false;\r\n std::unique_ptr<TSessionData> ParsedData(ParseUrl(Url, NULL, DefaultsOnly, NULL, &ProtocolDefined));\r\n bool Result = ProtocolDefined;\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nTSessionData * __fastcall TStoredSessionList::ResolveWorkspaceData(TSessionData * Data)\r\n{\r\n if (!Data->Link.IsEmpty())\r\n {\r\n Data = dynamic_cast<TSessionData *>(FindByName(Data->Link));\r\n if (Data != NULL)\r\n {\r\n Data = ResolveWorkspaceData(Data);\r\n }\r\n }\r\n return Data;\r\n}\r\n//---------------------------------------------------------------------\r\nTSessionData * __fastcall TStoredSessionList::SaveWorkspaceData(TSessionData * Data, int Index)\r\n{\r\n std::unique_ptr<TSessionData> Result(new TSessionData(L\"\"));\r\n\r\n TSessionData * SameData = StoredSessions->FindSame(Data);\r\n if (SameData != NULL)\r\n {\r\n Result->CopyStateData(Data);\r\n Result->Link = Data->Name;\r\n }\r\n else\r\n {\r\n Result->Assign(Data);\r\n Result->NameOverride = Data->Name;\r\n }\r\n\r\n Result->IsWorkspace = true;\r\n Result->Name = IntToHex(Index, 4); // See HasSessionName()\r\n\r\n return Result.release();\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TStoredSessionList::CanLogin(TSessionData * Data)\r\n{\r\n Data = ResolveWorkspaceData(Data);\r\n return (Data != NULL) && Data->CanLogin;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString GetExpandedLogFileName(UnicodeString LogFileName, TDateTime Started, TSessionData * SessionData)\r\n{\r\n // StripPathQuotes should not be needed as we do not feed quotes anymore\r\n UnicodeString ANewFileName = StripPathQuotes(ExpandEnvironmentVariables(LogFileName));\r\n for (int Index = 1; Index < ANewFileName.Length(); Index++)\r\n {\r\n if (ANewFileName[Index] == L'!')\r\n {\r\n UnicodeString Replacement;\r\n // keep consistent with TFileCustomCommand::PatternReplacement\r\n switch (tolower(ANewFileName[Index + 1]))\r\n {\r\n case L'y':\r\n Replacement = FormatDateTime(L\"yyyy\", Started);\r\n break;\r\n\r\n case L'm':\r\n Replacement = FormatDateTime(L\"mm\", Started);\r\n break;\r\n\r\n case L'd':\r\n Replacement = FormatDateTime(L\"dd\", Started);\r\n break;\r\n\r\n case L't':\r\n Replacement = FormatDateTime(L\"hhnnss\", Started);\r\n break;\r\n\r\n case 'p':\r\n Replacement = IntToStr(static_cast<int>(GetCurrentProcessId()));\r\n break;\r\n\r\n case L'@':\r\n if (SessionData != NULL)\r\n {\r\n Replacement = MakeValidFileName(SessionData->HostNameExpanded);\r\n }\r\n else\r\n {\r\n Replacement = L\"nohost\";\r\n }\r\n break;\r\n\r\n case L's':\r\n if (SessionData != NULL)\r\n {\r\n Replacement = MakeValidFileName(SessionData->SessionName);\r\n }\r\n else\r\n {\r\n Replacement = L\"nosession\";\r\n }\r\n break;\r\n\r\n case L'!':\r\n Replacement = L\"!\";\r\n break;\r\n\r\n default:\r\n Replacement = UnicodeString(L\"!\") + ANewFileName[Index + 1];\r\n break;\r\n }\r\n ANewFileName.Delete(Index, 2);\r\n ANewFileName.Insert(Replacement, Index);\r\n Index += Replacement.Length() - 1;\r\n }\r\n }\r\n return ANewFileName;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall IsSshProtocol(TFSProtocol FSProtocol)\r\n{\r\n return\r\n (FSProtocol == fsSFTPonly) || (FSProtocol == fsSFTP) ||\r\n (FSProtocol == fsSCPonly);\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall DefaultPort(TFSProtocol FSProtocol, TFtps Ftps)\r\n{\r\n int Result;\r\n switch (FSProtocol)\r\n {\r\n case fsFTP:\r\n if (Ftps == ftpsImplicit)\r\n {\r\n Result = FtpsImplicitPortNumber;\r\n }\r\n else\r\n {\r\n Result = FtpPortNumber;\r\n }\r\n break;\r\n\r\n case fsWebDAV:\r\n case fsS3:\r\n if (Ftps == ftpsNone)\r\n {\r\n Result = HTTPPortNumber;\r\n }\r\n else\r\n {\r\n Result = HTTPSPortNumber;\r\n }\r\n break;\r\n\r\n default:\r\n if (IsSshProtocol(FSProtocol))\r\n {\r\n Result = SshPortNumber;\r\n }\r\n else\r\n {\r\n DebugFail();\r\n Result = -1;\r\n }\r\n break;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------" ]
[ 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 53, 80, 2275, 473, 1511, 2372, 1100], "buggy_code_start_loc": [46, 52, 79, 599, 57, 1510, 2371, 1099], "filenames": ["source/Console.cbproj", "source/DragExt.cbproj", "source/WinSCP.cbproj", "source/core/SessionData.cpp", "source/core/SessionData.h", "source/forms/Custom.cpp", "source/windows/ConsoleRunner.cpp", "source/windows/WinMain.cpp"], "fixing_code_end_loc": [47, 53, 80, 2294, 474, 1511, 2372, 1103], "fixing_code_start_loc": [46, 52, 79, 599, 58, 1510, 2371, 1099], "message": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:winscp:winscp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C081564B-8EF8-4C8A-9EB0-1C50D5A8F18B", "versionEndExcluding": "5.17.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)"}, {"lang": "es", "value": "WinSCP anterior a la versi\u00f3n 5.17.10 permite a los atacantes remotos ejecutar programas arbitrarios cuando el manejador de URLs encuentra una URL manipulada que carga la configuraci\u00f3n de la sesi\u00f3n. (Por ejemplo, esto es explotable en una instalaci\u00f3n por defecto en la que WinSCP es el manejador de URLs sftp://)"}], "evaluatorComment": null, "id": "CVE-2021-3331", "lastModified": "2021-02-04T15:59:24.960", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-01-27T21:15:16.840", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://winscp.net/eng/docs/history#5.17.10"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://winscp.net/eng/docs/rawsettings"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://winscp.net/tracker/1943"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, "type": "NVD-CWE-Other"}
177
Determine whether the {function_name} code is vulnerable or not.
[ "//---------------------------------------------------------------------------\r\n#include <vcl.h>\r\n#pragma hdrstop\r\n\r\n#include \"SessionData.h\"\r\n\r\n#include \"Common.h\"\r\n#include \"Exceptions.h\"\r\n#include \"FileBuffer.h\"\r\n#include \"CoreMain.h\"\r\n#include \"TextsCore.h\"\r\n#include \"PuttyIntf.h\"\r\n#include \"RemoteFiles.h\"\r\n#include \"SFTPFileSystem.h\"\r\n#include \"S3FileSystem.h\"\r\n#include <Soap.EncdDecd.hpp>\r\n#include <StrUtils.hpp>\r\n#include <XMLDoc.hpp>\r\n#include <StrUtils.hpp>\r\n#include <algorithm>\r\n//---------------------------------------------------------------------------\r\n#pragma package(smart_init)\r\n//---------------------------------------------------------------------------\r\n#define SET_SESSION_PROPERTY_FROM(PROPERTY, FROM) \\\r\n if (F##PROPERTY != FROM) { F##PROPERTY = FROM; Modify(); }\r\n//---------------------------------------------------------------------------\r\n#define SET_SESSION_PROPERTY(PROPERTY) \\\r\n SET_SESSION_PROPERTY_FROM(PROPERTY, value)\r\n//---------------------------------------------------------------------------\r\nconst wchar_t * PingTypeNames = L\"Off;Null;Dummy\";\r\nconst wchar_t * ProxyMethodNames = L\"None;SOCKS4;SOCKS5;HTTP;Telnet;Cmd\";\r\nconst wchar_t * DefaultName = L\"Default Settings\";\r\nconst UnicodeString CipherNames[CIPHER_COUNT] = {L\"WARN\", L\"3des\", L\"blowfish\", L\"aes\", L\"des\", L\"arcfour\", L\"chacha20\"};\r\nconst UnicodeString KexNames[KEX_COUNT] = {L\"WARN\", L\"dh-group1-sha1\", L\"dh-group14-sha1\", L\"dh-gex-sha1\", L\"rsa\", L\"ecdh\"};\r\nconst UnicodeString HostKeyNames[HOSTKEY_COUNT] = {L\"WARN\", L\"rsa\", L\"dsa\", L\"ecdsa\", L\"ed25519\"};\r\nconst UnicodeString GssLibNames[GSSLIB_COUNT] = {L\"gssapi32\", L\"sspi\", L\"custom\"};\r\nconst wchar_t SshProtList[][10] = {L\"1\", L\"1>2\", L\"2>1\", L\"2\"};\r\n// Update also order in Ssh2CipherList()\r\nconst TCipher DefaultCipherList[CIPHER_COUNT] =\r\n { cipAES, cipChaCha20, cipBlowfish, cip3DES, cipWarn, cipArcfour, cipDES };\r\n// Update also order in SshKexList()\r\nconst TKex DefaultKexList[KEX_COUNT] =\r\n { kexECDH, kexDHGEx, kexDHGroup14, kexRSA, kexWarn, kexDHGroup1 };\r\nconst THostKey DefaultHostKeyList[HOSTKEY_COUNT] =\r\n { hkED25519, hkECDSA, hkRSA, hkDSA, hkWarn };\r\nconst TGssLib DefaultGssLibList[GSSLIB_COUNT] =\r\n { gssGssApi32, gssSspi, gssCustom };\r\nconst wchar_t FSProtocolNames[FSPROTOCOL_COUNT][16] = { L\"SCP\", L\"SFTP (SCP)\", L\"SFTP\", L\"\", L\"\", L\"FTP\", L\"WebDAV\", L\"S3\" };\r\nconst int SshPortNumber = 22;\r\nconst int FtpPortNumber = 21;\r\nconst int FtpsImplicitPortNumber = 990;\r\nconst int HTTPPortNumber = 80;\r\nconst int HTTPSPortNumber = 443;\r\nconst int TelnetPortNumber = 23;\r\nconst int DefaultSendBuf = 262144;\r\nconst int ProxyPortNumber = 80;\r\nconst UnicodeString AnonymousUserName(L\"anonymous\");\r\nconst UnicodeString AnonymousPassword(L\"anonymous@example.com\");\r\nconst UnicodeString PuttySshProtocol(L\"ssh\");\r\nconst UnicodeString PuttyTelnetProtocol(L\"telnet\");\r\nconst UnicodeString SftpProtocol(L\"sftp\");\r\nconst UnicodeString ScpProtocol(L\"scp\");\r\nconst UnicodeString FtpProtocol(L\"ftp\");\r\nconst UnicodeString FtpsProtocol(L\"ftps\");\r\nconst UnicodeString FtpesProtocol(L\"ftpes\");\r\nconst UnicodeString WebDAVProtocol(L\"dav\");\r\nconst UnicodeString WebDAVSProtocol(L\"davs\");\r\nconst UnicodeString S3Protocol(L\"s3\");\r\nconst UnicodeString SshProtocol(L\"ssh\");\r\nconst UnicodeString WinSCPProtocolPrefix(L\"winscp-\");\r\nconst wchar_t UrlParamSeparator = L';';\r\nconst wchar_t UrlParamValueSeparator = L'=';\r\nconst UnicodeString UrlHostKeyParamName(L\"fingerprint\");\r\nconst UnicodeString UrlSaveParamName(L\"save\");\r\nconst UnicodeString UrlRawSettingsParamNamePrefix(L\"x-\");\r\nconst UnicodeString PassphraseOption(L\"passphrase\");\r\nconst UnicodeString RawSettingsOption(L\"rawsettings\");\r\nconst UnicodeString S3HostName(S3LibDefaultHostName());\r\n//---------------------------------------------------------------------\r\nTDateTime __fastcall SecToDateTime(int Sec)\r\n{\r\n return TDateTime(double(Sec) / SecsPerDay);\r\n}\r\n//--- TSessionData ----------------------------------------------------\r\n__fastcall TSessionData::TSessionData(UnicodeString aName):\r\n TNamedObject(aName)\r\n{\r\n Default();\r\n FModified = true;\r\n}\r\n//---------------------------------------------------------------------\r\n_fastcall TSessionData::~TSessionData()\r\n{\r\n}\r\n//---------------------------------------------------------------------\r\nint __fastcall TSessionData::Compare(TNamedObject * Other)\r\n{\r\n int Result;\r\n // To avoid using CompareLogicalText on hex names of sessions in workspace.\r\n // The session 000A would be sorted before 0001.\r\n if (IsWorkspace && DebugNotNull(dynamic_cast<TSessionData *>(Other))->IsWorkspace)\r\n {\r\n Result = CompareText(Name, Other->Name);\r\n }\r\n else\r\n {\r\n Result = TNamedObject::Compare(Other);\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nTSessionData * __fastcall TSessionData::Clone()\r\n{\r\n std::unique_ptr<TSessionData> Data(new TSessionData(L\"\"));\r\n Data->Assign(this);\r\n return Data.release();\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::DefaultSettings()\r\n{\r\n HostName = L\"\";\r\n PortNumber = SshPortNumber;\r\n UserName = L\"\";\r\n Password = L\"\";\r\n NewPassword = L\"\";\r\n ChangePassword = false;\r\n PingInterval = 30;\r\n PingType = ptOff;\r\n Timeout = 15;\r\n TryAgent = true;\r\n AgentFwd = false;\r\n AuthTIS = false;\r\n AuthKI = true;\r\n AuthKIPassword = true;\r\n AuthGSSAPI = true;\r\n GSSAPIFwdTGT = false;\r\n LogicalHostName = L\"\";\r\n ChangeUsername = false;\r\n Compression = false;\r\n SshProt = ssh2only;\r\n Ssh2DES = false;\r\n SshNoUserAuth = false;\r\n for (int Index = 0; Index < CIPHER_COUNT; Index++)\r\n {\r\n Cipher[Index] = DefaultCipherList[Index];\r\n }\r\n for (int Index = 0; Index < KEX_COUNT; Index++)\r\n {\r\n Kex[Index] = DefaultKexList[Index];\r\n }\r\n for (int Index = 0; Index < HOSTKEY_COUNT; Index++)\r\n {\r\n HostKeys[Index] = DefaultHostKeyList[Index];\r\n }\r\n for (int Index = 0; Index < GSSLIB_COUNT; Index++)\r\n {\r\n GssLib[Index] = DefaultGssLibList[Index];\r\n }\r\n GssLibCustom = L\"\";\r\n PublicKeyFile = L\"\";\r\n Passphrase = L\"\";\r\n FPuttyProtocol = L\"\";\r\n TcpNoDelay = false;\r\n SendBuf = DefaultSendBuf;\r\n SourceAddress = L\"\";\r\n SshSimple = true;\r\n HostKey = L\"\";\r\n FingerprintScan = false;\r\n FOverrideCachedHostKey = true;\r\n Note = L\"\";\r\n WinTitle = L\"\";\r\n InternalEditorEncoding = -1;\r\n\r\n EncryptKey = UnicodeString();\r\n\r\n ProxyMethod = ::pmNone;\r\n ProxyHost = L\"proxy\";\r\n ProxyPort = ProxyPortNumber;\r\n ProxyUsername = L\"\";\r\n ProxyPassword = L\"\";\r\n ProxyTelnetCommand = L\"connect %host %port\\\\n\";\r\n ProxyLocalCommand = L\"\";\r\n ProxyDNS = asAuto;\r\n ProxyLocalhost = false;\r\n\r\n for (unsigned int Index = 0; Index < LENOF(FBugs); Index++)\r\n {\r\n Bug[(TSshBug)Index] = asAuto;\r\n }\r\n\r\n Special = false;\r\n FSProtocol = fsSFTP;\r\n AddressFamily = afAuto;\r\n RekeyData = L\"1G\";\r\n RekeyTime = MinsPerHour;\r\n\r\n // FS common\r\n LocalDirectory = L\"\";\r\n RemoteDirectory = L\"\";\r\n SynchronizeBrowsing = false;\r\n UpdateDirectories = true;\r\n CacheDirectories = true;\r\n CacheDirectoryChanges = true;\r\n PreserveDirectoryChanges = true;\r\n LockInHome = false;\r\n ResolveSymlinks = true;\r\n FollowDirectorySymlinks = false;\r\n DSTMode = dstmUnix;\r\n DeleteToRecycleBin = false;\r\n OverwrittenToRecycleBin = false;\r\n RecycleBinPath = L\"\";\r\n Color = 0;\r\n PostLoginCommands = L\"\";\r\n\r\n // SCP\r\n LookupUserGroups = asAuto;\r\n EOLType = eolLF;\r\n TrimVMSVersions = false;\r\n Shell = L\"\"; //default shell\r\n ReturnVar = L\"\";\r\n ExitCode1IsError = false;\r\n ClearAliases = true;\r\n UnsetNationalVars = true;\r\n ListingCommand = L\"ls -la\";\r\n IgnoreLsWarnings = true;\r\n Scp1Compatibility = false;\r\n TimeDifference = 0;\r\n TimeDifferenceAuto = true;\r\n SCPLsFullTime = asAuto;\r\n NotUtf = asAuto;\r\n\r\n S3DefaultRegion = L\"\";\r\n S3UrlStyle = s3usVirtualHost;\r\n\r\n // SFTP\r\n SftpServer = L\"\";\r\n SFTPDownloadQueue = 32;\r\n SFTPUploadQueue = 32;\r\n SFTPListingQueue = 2;\r\n SFTPMaxVersion = ::SFTPMaxVersion;\r\n SFTPMaxPacketSize = 0;\r\n\r\n for (unsigned int Index = 0; Index < LENOF(FSFTPBugs); Index++)\r\n {\r\n SFTPBug[(TSftpBug)Index] = asAuto;\r\n }\r\n\r\n Tunnel = false;\r\n TunnelHostName = L\"\";\r\n TunnelPortNumber = SshPortNumber;\r\n TunnelUserName = L\"\";\r\n TunnelPassword = L\"\";\r\n TunnelPublicKeyFile = L\"\";\r\n TunnelLocalPortNumber = 0;\r\n TunnelPortFwd = L\"\";\r\n TunnelHostKey = L\"\";\r\n\r\n // FTP\r\n FtpPasvMode = true;\r\n FtpForcePasvIp = asAuto;\r\n FtpUseMlsd = asAuto;\r\n FtpAccount = L\"\";\r\n FtpPingInterval = 30;\r\n FtpPingType = ptDummyCommand;\r\n FtpTransferActiveImmediately = asAuto;\r\n Ftps = ftpsNone;\r\n MinTlsVersion = tls10;\r\n MaxTlsVersion = tls12;\r\n FtpListAll = asAuto;\r\n FtpHost = asAuto;\r\n FtpDeleteFromCwd = asAuto;\r\n SslSessionReuse = true;\r\n TlsCertificateFile = L\"\";\r\n\r\n FtpProxyLogonType = 0; // none\r\n\r\n PuttySettings = UnicodeString();\r\n\r\n CustomParam1 = L\"\";\r\n CustomParam2 = L\"\";\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::Default()\r\n{\r\n DefaultSettings();\r\n\r\n IsWorkspace = false;\r\n Link = L\"\";\r\n NameOverride = L\"\";\r\n\r\n Selected = false;\r\n FModified = false;\r\n FSource = ::ssNone;\r\n FSaveOnly = false;\r\n\r\n // add also to TSessionLog::AddStartupInfo()\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::NonPersistant()\r\n{\r\n UpdateDirectories = false;\r\n PreserveDirectoryChanges = false;\r\n}\r\n//---------------------------------------------------------------------\r\n#define PROPERTY(P) PROPERTY_HANDLER(P, )\r\n#define BASE_PROPERTIES \\\r\n PROPERTY(HostName); \\\r\n PROPERTY(PortNumber); \\\r\n PROPERTY(UserName); \\\r\n PROPERTY_HANDLER(Password, F); \\\r\n PROPERTY(PublicKeyFile); \\\r\n PROPERTY_HANDLER(Passphrase, F); \\\r\n PROPERTY(FSProtocol); \\\r\n PROPERTY(Ftps); \\\r\n PROPERTY(LocalDirectory); \\\r\n PROPERTY(RemoteDirectory); \\\r\n PROPERTY(Color); \\\r\n PROPERTY(SynchronizeBrowsing); \\\r\n PROPERTY(Note);\r\n//---------------------------------------------------------------------\r\n#define ADVANCED_PROPERTIES \\\r\n PROPERTY_HANDLER(NewPassword, F); \\\r\n PROPERTY(ChangePassword); \\\r\n PROPERTY(PingInterval); \\\r\n PROPERTY(PingType); \\\r\n PROPERTY(Timeout); \\\r\n PROPERTY(TryAgent); \\\r\n PROPERTY(AgentFwd); \\\r\n PROPERTY(AuthTIS); \\\r\n PROPERTY(LogicalHostName); \\\r\n PROPERTY(ChangeUsername); \\\r\n PROPERTY(Compression); \\\r\n PROPERTY(SshProt); \\\r\n PROPERTY(Ssh2DES); \\\r\n PROPERTY(SshNoUserAuth); \\\r\n PROPERTY(CipherList); \\\r\n PROPERTY(KexList); \\\r\n PROPERTY(HostKeyList); \\\r\n PROPERTY(GssLibList); \\\r\n PROPERTY(GssLibCustom); \\\r\n PROPERTY(AddressFamily); \\\r\n PROPERTY(RekeyData); \\\r\n PROPERTY(RekeyTime); \\\r\n PROPERTY(HostKey); \\\r\n PROPERTY(FingerprintScan); \\\r\n PROPERTY(InternalEditorEncoding); \\\r\n \\\r\n PROPERTY(UpdateDirectories); \\\r\n PROPERTY(CacheDirectories); \\\r\n PROPERTY(CacheDirectoryChanges); \\\r\n PROPERTY(PreserveDirectoryChanges); \\\r\n \\\r\n PROPERTY(ResolveSymlinks); \\\r\n PROPERTY(FollowDirectorySymlinks); \\\r\n PROPERTY(DSTMode); \\\r\n PROPERTY(LockInHome); \\\r\n PROPERTY(Special); \\\r\n PROPERTY(Selected); \\\r\n PROPERTY(ReturnVar); \\\r\n PROPERTY(ExitCode1IsError); \\\r\n PROPERTY(LookupUserGroups); \\\r\n PROPERTY(EOLType); \\\r\n PROPERTY(TrimVMSVersions); \\\r\n PROPERTY(Shell); \\\r\n PROPERTY(ClearAliases); \\\r\n PROPERTY(Scp1Compatibility); \\\r\n PROPERTY(UnsetNationalVars); \\\r\n PROPERTY(ListingCommand); \\\r\n PROPERTY(IgnoreLsWarnings); \\\r\n PROPERTY(SCPLsFullTime); \\\r\n \\\r\n PROPERTY(TimeDifference); \\\r\n PROPERTY(TimeDifferenceAuto); \\\r\n PROPERTY(TcpNoDelay); \\\r\n PROPERTY(SendBuf); \\\r\n PROPERTY(SourceAddress); \\\r\n PROPERTY(SshSimple); \\\r\n PROPERTY(AuthKI); \\\r\n PROPERTY(AuthKIPassword); \\\r\n PROPERTY(AuthGSSAPI); \\\r\n PROPERTY(GSSAPIFwdTGT); \\\r\n PROPERTY(DeleteToRecycleBin); \\\r\n PROPERTY(OverwrittenToRecycleBin); \\\r\n PROPERTY(RecycleBinPath); \\\r\n PROPERTY(NotUtf); \\\r\n PROPERTY(PostLoginCommands); \\\r\n \\\r\n PROPERTY(S3DefaultRegion); \\\r\n PROPERTY(S3UrlStyle); \\\r\n \\\r\n PROPERTY(ProxyMethod); \\\r\n PROPERTY(ProxyHost); \\\r\n PROPERTY(ProxyPort); \\\r\n PROPERTY(ProxyUsername); \\\r\n PROPERTY_HANDLER(ProxyPassword, F); \\\r\n PROPERTY(ProxyTelnetCommand); \\\r\n PROPERTY(ProxyLocalCommand); \\\r\n PROPERTY(ProxyDNS); \\\r\n PROPERTY(ProxyLocalhost); \\\r\n \\\r\n for (unsigned int Index = 0; Index < LENOF(FBugs); Index++) \\\r\n { \\\r\n PROPERTY(Bug[(TSshBug)Index]); \\\r\n } \\\r\n \\\r\n PROPERTY(SftpServer); \\\r\n PROPERTY(SFTPDownloadQueue); \\\r\n PROPERTY(SFTPUploadQueue); \\\r\n PROPERTY(SFTPListingQueue); \\\r\n PROPERTY(SFTPMaxVersion); \\\r\n PROPERTY(SFTPMaxPacketSize); \\\r\n \\\r\n for (unsigned int Index = 0; Index < LENOF(FSFTPBugs); Index++) \\\r\n { \\\r\n PROPERTY(SFTPBug[(TSftpBug)Index]); \\\r\n } \\\r\n \\\r\n PROPERTY(Tunnel); \\\r\n PROPERTY(TunnelHostName); \\\r\n PROPERTY(TunnelPortNumber); \\\r\n PROPERTY(TunnelUserName); \\\r\n PROPERTY_HANDLER(TunnelPassword, F); \\\r\n PROPERTY(TunnelPublicKeyFile); \\\r\n PROPERTY(TunnelLocalPortNumber); \\\r\n PROPERTY(TunnelPortFwd); \\\r\n PROPERTY(TunnelHostKey); \\\r\n \\\r\n PROPERTY(FtpPasvMode); \\\r\n PROPERTY(FtpForcePasvIp); \\\r\n PROPERTY(FtpUseMlsd); \\\r\n PROPERTY(FtpAccount); \\\r\n PROPERTY(FtpPingInterval); \\\r\n PROPERTY(FtpPingType); \\\r\n PROPERTY(FtpTransferActiveImmediately); \\\r\n PROPERTY(FtpListAll); \\\r\n PROPERTY(FtpHost); \\\r\n PROPERTY(FtpDeleteFromCwd); \\\r\n PROPERTY(SslSessionReuse); \\\r\n PROPERTY(TlsCertificateFile); \\\r\n \\\r\n PROPERTY(FtpProxyLogonType); \\\r\n \\\r\n PROPERTY(MinTlsVersion); \\\r\n PROPERTY(MaxTlsVersion); \\\r\n \\\r\n PROPERTY(WinTitle); \\\r\n \\\r\n PROPERTY_HANDLER(EncryptKey, F); \\\r\n \\\r\n PROPERTY(PuttySettings); \\\r\n \\\r\n PROPERTY(CustomParam1); \\\r\n PROPERTY(CustomParam2);\r\n#define META_PROPERTIES \\\r\n PROPERTY(IsWorkspace); \\\r\n PROPERTY(Link); \\\r\n PROPERTY(NameOverride);\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::Assign(TPersistent * Source)\r\n{\r\n if (Source && Source->InheritsFrom(__classid(TSessionData)))\r\n {\r\n TSessionData * SourceData = (TSessionData *)Source;\r\n // Master password prompt shows implicitly here, when cloning the session data for a new terminal\r\n CopyData(SourceData);\r\n FSource = SourceData->FSource;\r\n }\r\n else\r\n {\r\n TNamedObject::Assign(Source);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::DoCopyData(TSessionData * SourceData, bool NoRecrypt)\r\n{\r\n #define PROPERTY_HANDLER(P, F) \\\r\n if (NoRecrypt) \\\r\n { \\\r\n F##P = SourceData->F##P; \\\r\n } \\\r\n else \\\r\n { \\\r\n P = SourceData->P; \\\r\n }\r\n PROPERTY(Name);\r\n BASE_PROPERTIES;\r\n ADVANCED_PROPERTIES;\r\n META_PROPERTIES;\r\n #undef PROPERTY_HANDLER\r\n FOverrideCachedHostKey = SourceData->FOverrideCachedHostKey;\r\n FModified = SourceData->Modified;\r\n FSaveOnly = SourceData->FSaveOnly;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::CopyData(TSessionData * SourceData)\r\n{\r\n DoCopyData(SourceData, false);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::CopyDataNoRecrypt(TSessionData * SourceData)\r\n{\r\n DoCopyData(SourceData, true);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::CopyDirectoriesStateData(TSessionData * SourceData)\r\n{\r\n RemoteDirectory = SourceData->RemoteDirectory;\r\n LocalDirectory = SourceData->LocalDirectory;\r\n SynchronizeBrowsing = SourceData->SynchronizeBrowsing;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::HasStateData()\r\n{\r\n return\r\n !RemoteDirectory.IsEmpty() ||\r\n !LocalDirectory.IsEmpty() ||\r\n (Color != 0);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::CopyStateData(TSessionData * SourceData)\r\n{\r\n // Keep in sync with TCustomScpExplorerForm::UpdateSessionData.\r\n CopyDirectoriesStateData(SourceData);\r\n Color = SourceData->Color;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::CopyNonCoreData(TSessionData * SourceData)\r\n{\r\n CopyStateData(SourceData);\r\n UpdateDirectories = SourceData->UpdateDirectories;\r\n Note = SourceData->Note;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsSame(\r\n const TSessionData * Default, bool AdvancedOnly, TStrings * DifferentProperties, bool Decrypted)\r\n{\r\n bool Result = true;\r\n #define PROPERTY_HANDLER(P, F) \\\r\n if ((Decrypted && (P != Default->P)) || \\\r\n (!Decrypted && (F##P != Default->F##P))) \\\r\n { \\\r\n Result = false; \\\r\n if (DifferentProperties != NULL) \\\r\n { \\\r\n DifferentProperties->Add(#P); \\\r\n } \\\r\n else \\\r\n { \\\r\n return Result; \\\r\n } \\\r\n }\r\n\r\n if (!AdvancedOnly)\r\n {\r\n BASE_PROPERTIES;\r\n META_PROPERTIES;\r\n }\r\n ADVANCED_PROPERTIES;\r\n #undef PROPERTY_HANDLER\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsSame(const TSessionData * Default, bool AdvancedOnly)\r\n{\r\n return IsSame(Default, AdvancedOnly, NULL, false);\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsSameDecrypted(const TSessionData * Default)\r\n{\r\n return IsSame(Default, false, NULL, true);\r\n}\r\n//---------------------------------------------------------------------\r\nTFSProtocol NormalizeFSProtocol(TFSProtocol FSProtocol)\r\n{\r\n if (FSProtocol == fsSFTPonly)\r\n {\r\n FSProtocol = fsSFTP;\r\n }\r\n return FSProtocol;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsSameSite(const TSessionData * Other)\r\n{\r\n return\r\n // Particularly when handling /refresh,\r\n // fsSFTPonly sites when compared against sftp:// URLs (fsSFTP) have to match.\r\n // But similarly also falled back SCP sites.\r\n (NormalizeFSProtocol(FSProtocol) == NormalizeFSProtocol(Other->FSProtocol)) &&\r\n (HostName == Other->HostName) &&\r\n (PortNumber == Other->PortNumber) &&\r\n (UserName == Other->UserName);\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsInFolderOrWorkspace(UnicodeString AFolder)\r\n{\r\n return StartsText(UnixIncludeTrailingBackslash(AFolder), Name);\r\n}\r\n//---------------------------------------------------------------------\r", "void __fastcall TSessionData::DoLoad(THierarchicalStorage * Storage, bool PuttyImport, bool & RewritePassword, bool Unsafe)\r", "{\r\n // Make sure we only ever use methods supported by TOptionsStorage\r\n // (implemented by TOptionsIniFile)\r\n\r\n PortNumber = Storage->ReadInteger(L\"PortNumber\", PortNumber);\r\n UserName = Storage->ReadString(L\"UserName\", UserName);\r\n // must be loaded after UserName, because HostName may be in format user@host\r\n HostName = Storage->ReadString(L\"HostName\", HostName);\r\n\r\n if (!Configuration->DisablePasswordStoring)\r\n {\r\n if (Storage->ValueExists(L\"PasswordPlain\"))\r\n {\r\n Password = Storage->ReadString(L\"PasswordPlain\", Password);\r\n RewritePassword = true;\r\n }\r\n else\r\n {\r\n RawByteString APassword = Storage->ReadStringAsBinaryData(L\"Password\", FPassword);\r\n SET_SESSION_PROPERTY_FROM(Password, APassword);\r\n }\r\n }\r\n HostKey = Storage->ReadString(L\"SshHostKey\", HostKey); // probably never used\r\n Note = Storage->ReadString(L\"Note\", Note);\r\n // Putty uses PingIntervalSecs\r\n int PingIntervalSecs = Storage->ReadInteger(L\"PingIntervalSecs\", -1);\r\n if (PingIntervalSecs < 0)\r\n {\r\n PingIntervalSecs = Storage->ReadInteger(L\"PingIntervalSec\", PingInterval%SecsPerMin);\r\n }\r\n PingInterval =\r\n Storage->ReadInteger(L\"PingInterval\", PingInterval/SecsPerMin)*SecsPerMin +\r\n PingIntervalSecs;\r\n if (PingInterval == 0)\r\n {\r\n PingInterval = 30;\r\n }\r\n PingType = static_cast<TPingType>(Storage->ReadInteger(L\"PingType\", PingType));\r\n Timeout = Storage->ReadInteger(L\"Timeout\", Timeout);\r\n TryAgent = Storage->ReadBool(L\"TryAgent\", TryAgent);\r\n AgentFwd = Storage->ReadBool(L\"AgentFwd\", AgentFwd);\r\n AuthTIS = Storage->ReadBool(L\"AuthTIS\", AuthTIS);\r\n AuthKI = Storage->ReadBool(L\"AuthKI\", AuthKI);\r\n AuthKIPassword = Storage->ReadBool(L\"AuthKIPassword\", AuthKIPassword);\r\n // Continue to use setting keys of previous kerberos implementation (vaclav tomec),\r\n // but fallback to keys of other implementations (official putty and vintela quest putty),\r\n // to allow imports from all putty versions.\r\n // Both vaclav tomec and official putty use AuthGSSAPI\r\n AuthGSSAPI = Storage->ReadBool(L\"AuthGSSAPI\", Storage->ReadBool(L\"AuthSSPI\", AuthGSSAPI));\r\n GSSAPIFwdTGT = Storage->ReadBool(L\"GSSAPIFwdTGT\", Storage->ReadBool(L\"GssapiFwd\", Storage->ReadBool(L\"SSPIFwdTGT\", GSSAPIFwdTGT)));\r\n // KerbPrincipal was used by Quest PuTTY\r\n // GSSAPIServerRealm was used by Vaclav Tomec\r\n LogicalHostName = Storage->ReadString(L\"LogicalHostName\", Storage->ReadString(L\"GSSAPIServerRealm\", Storage->ReadString(L\"KerbPrincipal\", LogicalHostName)));\r\n ChangeUsername = Storage->ReadBool(L\"ChangeUsername\", ChangeUsername);\r\n Compression = Storage->ReadBool(L\"Compression\", Compression);\r\n TSshProt ASshProt = (TSshProt)Storage->ReadInteger(L\"SshProt\", SshProt);\r\n // Old sessions may contain the values correponding to the fallbacks we used to allow; migrate them\r\n if (ASshProt == ssh2deprecated)\r\n {\r\n ASshProt = ssh2only;\r\n }\r\n else if (ASshProt == ssh1deprecated)\r\n {\r\n ASshProt = ssh1only;\r\n }\r\n SshProt = ASshProt;\r\n Ssh2DES = Storage->ReadBool(L\"Ssh2DES\", Ssh2DES);\r\n SshNoUserAuth = Storage->ReadBool(L\"SshNoUserAuth\", SshNoUserAuth);\r\n CipherList = Storage->ReadString(L\"Cipher\", CipherList);\r\n KexList = Storage->ReadString(L\"KEX\", KexList);\r\n HostKeyList = Storage->ReadString(L\"HostKey\", HostKeyList);\r", " if (!Unsafe)\r\n {\r\n GssLibList = Storage->ReadString(L\"GSSLibs\", GssLibList);\r\n }\r", " GssLibCustom = Storage->ReadString(L\"GSSCustom\", GssLibCustom);\r\n PublicKeyFile = Storage->ReadString(L\"PublicKeyFile\", PublicKeyFile);\r\n AddressFamily = static_cast<TAddressFamily>\r\n (Storage->ReadInteger(L\"AddressFamily\", AddressFamily));\r\n RekeyData = Storage->ReadString(L\"RekeyBytes\", RekeyData);\r\n RekeyTime = Storage->ReadInteger(L\"RekeyTime\", RekeyTime);\r\n\r\n FSProtocol = (TFSProtocol)Storage->ReadInteger(L\"FSProtocol\", FSProtocol);\r\n LocalDirectory = Storage->ReadString(L\"LocalDirectory\", LocalDirectory);\r\n RemoteDirectory = Storage->ReadString(L\"RemoteDirectory\", RemoteDirectory);\r\n SynchronizeBrowsing = Storage->ReadBool(L\"SynchronizeBrowsing\", SynchronizeBrowsing);\r\n UpdateDirectories = Storage->ReadBool(L\"UpdateDirectories\", UpdateDirectories);\r\n CacheDirectories = Storage->ReadBool(L\"CacheDirectories\", CacheDirectories);\r\n CacheDirectoryChanges = Storage->ReadBool(L\"CacheDirectoryChanges\", CacheDirectoryChanges);\r\n PreserveDirectoryChanges = Storage->ReadBool(L\"PreserveDirectoryChanges\", PreserveDirectoryChanges);\r\n\r\n ResolveSymlinks = Storage->ReadBool(L\"ResolveSymlinks\", ResolveSymlinks);\r\n FollowDirectorySymlinks = Storage->ReadBool(L\"FollowDirectorySymlinks\", FollowDirectorySymlinks);\r\n DSTMode = (TDSTMode)Storage->ReadInteger(L\"ConsiderDST\", DSTMode);\r\n LockInHome = Storage->ReadBool(L\"LockInHome\", LockInHome);\r\n Special = Storage->ReadBool(L\"Special\", Special);\r", " if (!Unsafe)\r\n {\r\n Shell = Storage->ReadString(L\"Shell\", Shell);\r\n }\r", " ClearAliases = Storage->ReadBool(L\"ClearAliases\", ClearAliases);\r\n UnsetNationalVars = Storage->ReadBool(L\"UnsetNationalVars\", UnsetNationalVars);\r", " if (!Unsafe)\r\n {\r\n ListingCommand = Storage->ReadString(L\"ListingCommand\",\r\n Storage->ReadBool(L\"AliasGroupList\", false) ? UnicodeString(L\"ls -gla\") : ListingCommand);\r\n }\r", " IgnoreLsWarnings = Storage->ReadBool(L\"IgnoreLsWarnings\", IgnoreLsWarnings);\r\n SCPLsFullTime = TAutoSwitch(Storage->ReadInteger(L\"SCPLsFullTime\", SCPLsFullTime));\r\n Scp1Compatibility = Storage->ReadBool(L\"Scp1Compatibility\", Scp1Compatibility);\r\n TimeDifference = Storage->ReadFloat(L\"TimeDifference\", TimeDifference);\r\n TimeDifferenceAuto = Storage->ReadBool(L\"TimeDifferenceAuto\", (TimeDifference == TDateTime()));\r", " if (!Unsafe)\r\n {\r\n DeleteToRecycleBin = Storage->ReadBool(L\"DeleteToRecycleBin\", DeleteToRecycleBin);\r\n OverwrittenToRecycleBin = Storage->ReadBool(L\"OverwrittenToRecycleBin\", OverwrittenToRecycleBin);\r\n RecycleBinPath = Storage->ReadString(L\"RecycleBinPath\", RecycleBinPath);\r\n PostLoginCommands = Storage->ReadString(L\"PostLoginCommands\", PostLoginCommands);\r\n ReturnVar = Storage->ReadString(L\"ReturnVar\", ReturnVar);\r\n }\r\n\r", " ExitCode1IsError = Storage->ReadBool(L\"ExitCode1IsError\", ExitCode1IsError);\r\n LookupUserGroups = TAutoSwitch(Storage->ReadInteger(L\"LookupUserGroups2\", LookupUserGroups));\r\n EOLType = (TEOLType)Storage->ReadInteger(L\"EOLType\", EOLType);\r\n TrimVMSVersions = Storage->ReadBool(L\"TrimVMSVersions\", TrimVMSVersions);\r\n NotUtf = TAutoSwitch(Storage->ReadInteger(L\"Utf\", Storage->ReadInteger(L\"SFTPUtfBug\", NotUtf)));\r\n InternalEditorEncoding = Storage->ReadInteger(L\"InternalEditorEncoding\", InternalEditorEncoding);\r\n\r\n S3DefaultRegion = Storage->ReadString(L\"S3DefaultRegion\", S3DefaultRegion);\r\n S3UrlStyle = (TS3UrlStyle)Storage->ReadInteger(L\"S3UrlStyle\", S3UrlStyle);\r\n\r\n // PuTTY defaults to TcpNoDelay, but the psftp/pscp ignores this preference, and always set this to off (what is our default too)\r\n if (!PuttyImport)\r\n {\r\n TcpNoDelay = Storage->ReadBool(L\"TcpNoDelay\", TcpNoDelay);\r\n }\r\n SendBuf = Storage->ReadInteger(L\"SendBuf\", Storage->ReadInteger(\"SshSendBuf\", SendBuf));\r\n SourceAddress = Storage->ReadString(L\"SourceAddress\", SourceAddress);\r\n SshSimple = Storage->ReadBool(L\"SshSimple\", SshSimple);\r\n\r\n ProxyMethod = (TProxyMethod)Storage->ReadInteger(L\"ProxyMethod\", ProxyMethod);\r\n ProxyHost = Storage->ReadString(L\"ProxyHost\", ProxyHost);\r\n ProxyPort = Storage->ReadInteger(L\"ProxyPort\", ProxyPort);\r\n ProxyUsername = Storage->ReadString(L\"ProxyUsername\", ProxyUsername);\r\n if (Storage->ValueExists(L\"ProxyPassword\"))\r\n {\r\n // encrypt unencrypted password\r\n ProxyPassword = Storage->ReadString(L\"ProxyPassword\", L\"\");\r\n }\r\n else\r\n {\r\n // load encrypted password\r\n RawByteString AProxyPassword = Storage->ReadStringAsBinaryData(L\"ProxyPasswordEnc\", FProxyPassword);\r\n SET_SESSION_PROPERTY_FROM(ProxyPassword, AProxyPassword);\r\n }\r", " if (!Unsafe)\r\n {\r\n if (ProxyMethod == pmCmd)\r\n {\r\n ProxyLocalCommand = Storage->ReadStringRaw(L\"ProxyTelnetCommand\", ProxyLocalCommand);\r\n }\r\n else\r\n {\r\n ProxyTelnetCommand = Storage->ReadStringRaw(L\"ProxyTelnetCommand\", ProxyTelnetCommand);\r\n }\r", " }\r\n ProxyDNS = TAutoSwitch((Storage->ReadInteger(L\"ProxyDNS\", (ProxyDNS + 2) % 3) + 1) % 3);\r\n ProxyLocalhost = Storage->ReadBool(L\"ProxyLocalhost\", ProxyLocalhost);\r\n\r\n #define READ_BUG(BUG) \\\r\n Bug[sb##BUG] = TAutoSwitch(2 - Storage->ReadInteger(L\"Bug\"#BUG, \\\r\n 2 - Bug[sb##BUG]));\r\n READ_BUG(Ignore1);\r\n READ_BUG(PlainPW1);\r\n READ_BUG(RSA1);\r\n READ_BUG(HMAC2);\r\n READ_BUG(DeriveKey2);\r\n READ_BUG(RSAPad2);\r\n READ_BUG(PKSessID2);\r\n READ_BUG(Rekey2);\r\n READ_BUG(MaxPkt2);\r\n READ_BUG(Ignore2);\r\n READ_BUG(OldGex2);\r\n READ_BUG(WinAdj);\r\n READ_BUG(ChanReq);\r\n #undef READ_BUG\r\n\r\n if ((Bug[sbHMAC2] == asAuto) &&\r\n Storage->ReadBool(L\"BuggyMAC\", false))\r\n {\r\n Bug[sbHMAC2] = asOn;\r\n }\r\n\r", " if (!Unsafe)\r\n {\r\n SftpServer = Storage->ReadString(L\"SftpServer\", SftpServer);\r\n }\r", " #define READ_SFTP_BUG(BUG) \\\r\n SFTPBug[sb##BUG] = TAutoSwitch(Storage->ReadInteger(L\"SFTP\" #BUG \"Bug\", SFTPBug[sb##BUG]));\r\n READ_SFTP_BUG(Symlink);\r\n READ_SFTP_BUG(SignedTS);\r\n #undef READ_SFTP_BUG\r\n\r\n SFTPMaxVersion = Storage->ReadInteger(L\"SFTPMaxVersion\", SFTPMaxVersion);\r\n SFTPMaxPacketSize = Storage->ReadInteger(L\"SFTPMaxPacketSize\", SFTPMaxPacketSize);\r\n SFTPDownloadQueue = Storage->ReadInteger(L\"SFTPDownloadQueue\", SFTPDownloadQueue);\r\n SFTPUploadQueue = Storage->ReadInteger(L\"SFTPUploadQueue\", SFTPUploadQueue);\r\n SFTPListingQueue = Storage->ReadInteger(L\"SFTPListingQueue\", SFTPListingQueue);\r\n\r\n Color = Storage->ReadInteger(L\"Color\", Color);\r\n\r\n PuttyProtocol = Storage->ReadString(L\"Protocol\", PuttyProtocol);\r\n\r\n Tunnel = Storage->ReadBool(L\"Tunnel\", Tunnel);\r\n TunnelPortNumber = Storage->ReadInteger(L\"TunnelPortNumber\", TunnelPortNumber);\r\n TunnelUserName = Storage->ReadString(L\"TunnelUserName\", TunnelUserName);\r\n // must be loaded after TunnelUserName,\r\n // because TunnelHostName may be in format user@host\r\n TunnelHostName = Storage->ReadString(L\"TunnelHostName\", TunnelHostName);\r\n if (!Configuration->DisablePasswordStoring)\r\n {\r\n if (Storage->ValueExists(L\"TunnelPasswordPlain\"))\r\n {\r\n TunnelPassword = Storage->ReadString(L\"TunnelPasswordPlain\", TunnelPassword);\r\n RewritePassword = true;\r\n }\r\n else\r\n {\r\n RawByteString ATunnelPassword = Storage->ReadStringAsBinaryData(L\"TunnelPassword\", FTunnelPassword);\r\n SET_SESSION_PROPERTY_FROM(TunnelPassword, ATunnelPassword);\r\n }\r\n }\r\n TunnelPublicKeyFile = Storage->ReadString(L\"TunnelPublicKeyFile\", TunnelPublicKeyFile);\r\n TunnelLocalPortNumber = Storage->ReadInteger(L\"TunnelLocalPortNumber\", TunnelLocalPortNumber);\r\n TunnelHostKey = Storage->ReadString(L\"TunnelHostKey\", TunnelHostKey);\r\n\r\n // Ftp prefix\r\n FtpPasvMode = Storage->ReadBool(L\"FtpPasvMode\", FtpPasvMode);\r\n FtpForcePasvIp = TAutoSwitch(Storage->ReadInteger(L\"FtpForcePasvIp2\", FtpForcePasvIp));\r\n FtpUseMlsd = TAutoSwitch(Storage->ReadInteger(L\"FtpUseMlsd\", FtpUseMlsd));\r\n FtpAccount = Storage->ReadString(L\"FtpAccount\", FtpAccount);\r\n FtpPingInterval = Storage->ReadInteger(L\"FtpPingInterval\", FtpPingInterval);\r\n FtpPingType = static_cast<TPingType>(Storage->ReadInteger(L\"FtpPingType\", FtpPingType));\r\n FtpTransferActiveImmediately = static_cast<TAutoSwitch>(Storage->ReadInteger(L\"FtpTransferActiveImmediately2\", FtpTransferActiveImmediately));\r\n Ftps = static_cast<TFtps>(Storage->ReadInteger(L\"Ftps\", Ftps));\r\n FtpListAll = TAutoSwitch(Storage->ReadInteger(L\"FtpListAll\", FtpListAll));\r\n FtpHost = TAutoSwitch(Storage->ReadInteger(L\"FtpHost\", FtpHost));\r\n FtpDeleteFromCwd = TAutoSwitch(Storage->ReadInteger(L\"FtpDeleteFromCwd\", FtpDeleteFromCwd));\r\n SslSessionReuse = Storage->ReadBool(L\"SslSessionReuse\", SslSessionReuse);\r\n TlsCertificateFile = Storage->ReadString(L\"TlsCertificateFile\", TlsCertificateFile);\r\n\r\n FtpProxyLogonType = Storage->ReadInteger(L\"FtpProxyLogonType\", FtpProxyLogonType);\r\n\r\n MinTlsVersion = static_cast<TTlsVersion>(Storage->ReadInteger(L\"MinTlsVersion\", MinTlsVersion));\r\n MaxTlsVersion = static_cast<TTlsVersion>(Storage->ReadInteger(L\"MaxTlsVersion\", MaxTlsVersion));\r\n\r\n if (Storage->ValueExists(L\"EncryptKeyPlain\"))\r\n {\r\n EncryptKey = Storage->ReadString(L\"EncryptKeyPlain\", EncryptKey);\r\n RewritePassword = true;\r\n }\r\n else\r\n {\r\n RawByteString AEncryptKey = Storage->ReadStringAsBinaryData(L\"EncryptKey\", FEncryptKey);\r\n SET_SESSION_PROPERTY_FROM(EncryptKey, AEncryptKey);\r\n }\r\n\r\n IsWorkspace = Storage->ReadBool(L\"IsWorkspace\", IsWorkspace);\r\n Link = Storage->ReadString(L\"Link\", Link);\r\n NameOverride = Storage->ReadString(L\"NameOverride\", NameOverride);\r\n\r\n PuttySettings = Storage->ReadString(L\"PuttySettings\", PuttySettings);\r\n\r\n CustomParam1 = Storage->ReadString(L\"CustomParam1\", CustomParam1);\r\n CustomParam2 = Storage->ReadString(L\"CustomParam2\", CustomParam2);\r\n\r\n#ifdef TEST\r\n #define KEX_TEST(VALUE, EXPECTED) KexList = VALUE; DebugAssert(KexList == EXPECTED);\r\n #define KEX_DEFAULT L\"ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN,dh-group1-sha1\"\r\n // Empty source should result in default list\r\n KEX_TEST(L\"\", KEX_DEFAULT);\r\n // Default of pre 5.8.1\r\n KEX_TEST(L\"dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN\", L\"ecdh,dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN\");\r\n // Missing first two priority algos, and last non-priority algo\r\n KEX_TEST(L\"dh-group14-sha1,dh-group1-sha1,WARN\", L\"ecdh,dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN\");\r\n // Missing first two priority algos, last non-priority algo and WARN\r\n KEX_TEST(L\"dh-group14-sha1,dh-group1-sha1\", L\"ecdh,dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN\");\r\n // Old algos, with all but the first below WARN\r\n KEX_TEST(L\"dh-gex-sha1,WARN,dh-group14-sha1,dh-group1-sha1,rsa\", L\"ecdh,dh-gex-sha1,WARN,dh-group14-sha1,dh-group1-sha1,rsa\");\r\n // Unknown algo at front\r\n KEX_TEST(L\"unknown,ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN,dh-group1-sha1\", KEX_DEFAULT);\r\n // Unknown algo at back\r\n KEX_TEST(L\"ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN,dh-group1-sha1,unknown\", KEX_DEFAULT);\r\n // Unknown algo in the middle\r\n KEX_TEST(L\"ecdh,dh-gex-sha1,dh-group14-sha1,unknown,rsa,WARN,dh-group1-sha1\", KEX_DEFAULT);\r\n #undef KEX_DEFAULT\r\n #undef KEX_TEST\r\n\r\n #define CIPHER_TEST(VALUE, EXPECTED) CipherList = VALUE; DebugAssert(CipherList == EXPECTED);\r\n #define CIPHER_DEFAULT L\"aes,chacha20,blowfish,3des,WARN,arcfour,des\"\r\n // Empty source should result in default list\r\n CIPHER_TEST(L\"\", CIPHER_DEFAULT);\r\n // Default of pre 5.8.1\r\n CIPHER_TEST(L\"aes,blowfish,3des,WARN,arcfour,des\", L\"aes,blowfish,3des,chacha20,WARN,arcfour,des\");\r\n // Missing priority algo\r\n CIPHER_TEST(L\"chacha20,blowfish,3des,WARN,arcfour,des\", CIPHER_DEFAULT);\r\n // Missing non-priority algo\r\n CIPHER_TEST(L\"aes,chacha20,3des,WARN,arcfour,des\", L\"aes,chacha20,3des,blowfish,WARN,arcfour,des\");\r\n // Missing last warn algo\r\n CIPHER_TEST(L\"aes,blowfish,chacha20,3des,WARN,arcfour\", L\"aes,blowfish,chacha20,3des,WARN,arcfour,des\");\r\n // Missing first warn algo\r\n CIPHER_TEST(L\"aes,blowfish,chacha20,3des,WARN,des\", L\"aes,blowfish,chacha20,3des,WARN,des,arcfour\");\r\n #undef CIPHER_DEFAULT\r\n #undef CIPHER_TEST\r\n\r\n #define HOSTKEY_TEST(VALUE, EXPECTED) HostKeyList = VALUE; DebugAssert(HostKeyList == EXPECTED);\r\n #define HOSTKEY_DEFAULT L\"ed25519,ecdsa,rsa,dsa,WARN\"\r\n // Empty source should result in default list\r\n HOSTKEY_TEST(L\"\", HOSTKEY_DEFAULT);\r\n // Missing priority algo\r\n HOSTKEY_TEST(L\"ecdsa,rsa,dsa,WARN\", HOSTKEY_DEFAULT);\r\n // Missing non-priority algo\r\n HOSTKEY_TEST(L\"ed25519,ecdsa,dsa,WARN\", L\"ed25519,ecdsa,dsa,rsa,WARN\");\r\n #undef HOSTKEY_DEFAULT\r\n #undef HOSTKEY_TEST\r\n#endif\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::Load(THierarchicalStorage * Storage, bool PuttyImport)\r\n{\r\n bool RewritePassword = false;\r\n if (Storage->OpenSubKey(InternalStorageKey, False))\r\n {\r\n // In case we are re-loading, reset passwords, to avoid pointless\r\n // re-cryption, while loading username/hostname. And moreover, when\r\n // the password is wrongly encrypted (using a different master password),\r\n // this breaks sites reload and consequently an overal operation,\r\n // such as opening Sites menu\r\n ClearSessionPasswords();\r\n FProxyPassword = L\"\";\r\n\r", " DoLoad(Storage, PuttyImport, RewritePassword, false);\r", "\r\n Storage->CloseSubKey();\r\n }\r\n\r\n if (RewritePassword)\r\n {\r\n TStorageAccessMode AccessMode = Storage->AccessMode;\r\n Storage->AccessMode = smReadWrite;\r\n\r\n try\r\n {\r\n if (Storage->OpenSubKey(InternalStorageKey, true))\r\n {\r\n Storage->DeleteValue(L\"PasswordPlain\");\r\n if (!Password.IsEmpty())\r\n {\r\n Storage->WriteBinaryDataAsString(L\"Password\", FPassword);\r\n }\r\n Storage->DeleteValue(L\"TunnelPasswordPlain\");\r\n if (!TunnelPassword.IsEmpty())\r\n {\r\n Storage->WriteBinaryDataAsString(L\"TunnelPassword\", FTunnelPassword);\r\n }\r\n Storage->DeleteValue(L\"EncryptKeyPlain\");\r\n if (!EncryptKey.IsEmpty())\r\n {\r\n Storage->WriteBinaryDataAsString(L\"EncryptKey\", FEncryptKey);\r\n }\r\n Storage->CloseSubKey();\r\n }\r\n }\r\n catch(...)\r\n {\r\n // ignore errors (like read-only INI file)\r\n }\r\n\r\n Storage->AccessMode = AccessMode;\r\n }\r\n\r\n FModified = false;\r\n FSource = ssStored;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::DoSave(THierarchicalStorage * Storage,\r\n bool PuttyExport, const TSessionData * Default, bool DoNotEncryptPasswords)\r\n{\r\n // Same as in TCopyParamType::Save\r\n #define WRITE_DATA_EX(TYPE, NAME, PROPERTY, CONV) \\\r\n if ((Default != NULL) && (CONV(Default->PROPERTY) == CONV(PROPERTY))) \\\r\n { \\\r\n Storage->DeleteValue(NAME); \\\r\n } \\\r\n else \\\r\n { \\\r\n Storage->Write ## TYPE(NAME, CONV(PROPERTY)); \\\r\n }\r\n #define WRITE_DATA_CONV(TYPE, NAME, PROPERTY) WRITE_DATA_EX(TYPE, NAME, PROPERTY, WRITE_DATA_CONV_FUNC)\r\n #define WRITE_DATA(TYPE, PROPERTY) WRITE_DATA_EX(TYPE, TEXT(#PROPERTY), PROPERTY, )\r\n\r\n WRITE_DATA(String, HostName);\r\n WRITE_DATA(Integer, PortNumber);\r\n WRITE_DATA_EX(Integer, L\"PingInterval\", PingInterval / SecsPerMin, );\r\n WRITE_DATA_EX(Integer, L\"PingIntervalSecs\", PingInterval % SecsPerMin, );\r\n Storage->DeleteValue(L\"PingIntervalSec\"); // obsolete\r\n WRITE_DATA(Integer, PingType);\r\n WRITE_DATA(Integer, Timeout);\r\n WRITE_DATA(Bool, TryAgent);\r\n WRITE_DATA(Bool, AgentFwd);\r\n WRITE_DATA(Bool, AuthTIS);\r\n WRITE_DATA(Bool, AuthKI);\r\n WRITE_DATA(Bool, AuthKIPassword);\r\n WRITE_DATA(String, Note);\r\n\r\n WRITE_DATA(Bool, AuthGSSAPI);\r\n WRITE_DATA(Bool, GSSAPIFwdTGT);\r\n Storage->DeleteValue(L\"TryGSSKEX\");\r\n Storage->DeleteValue(L\"UserNameFromEnvironment\");\r\n Storage->DeleteValue(\"GSSAPIServerChoosesUserName\");\r\n Storage->DeleteValue(L\"GSSAPITrustDNS\");\r\n WRITE_DATA(String, LogicalHostName);\r\n if (PuttyExport)\r\n {\r\n // duplicate kerberos setting with keys of the vintela quest putty\r\n WRITE_DATA_EX(Bool, L\"AuthSSPI\", AuthGSSAPI, );\r\n WRITE_DATA_EX(Bool, L\"SSPIFwdTGT\", GSSAPIFwdTGT, );\r\n WRITE_DATA_EX(String, L\"KerbPrincipal\", LogicalHostName, );\r\n // duplicate kerberos setting with keys of the official putty\r\n WRITE_DATA_EX(Bool, L\"GssapiFwd\", GSSAPIFwdTGT, );\r\n }\r\n\r\n WRITE_DATA(Bool, ChangeUsername);\r\n WRITE_DATA(Bool, Compression);\r\n WRITE_DATA(Integer, SshProt);\r\n WRITE_DATA(Bool, Ssh2DES);\r\n WRITE_DATA(Bool, SshNoUserAuth);\r\n WRITE_DATA_EX(String, L\"Cipher\", CipherList, );\r\n WRITE_DATA_EX(String, L\"KEX\", KexList, );\r\n WRITE_DATA_EX(String, L\"HostKey\", HostKeyList, );\r\n WRITE_DATA_EX(String, L\"GSSLibs\", GssLibList, );\r\n WRITE_DATA_EX(String, L\"GSSCustom\", GssLibCustom, );\r\n WRITE_DATA(Integer, AddressFamily);\r\n WRITE_DATA_EX(String, L\"RekeyBytes\", RekeyData, );\r\n WRITE_DATA(Integer, RekeyTime);\r\n\r\n WRITE_DATA(Bool, TcpNoDelay);\r\n\r\n if (PuttyExport)\r\n {\r\n WRITE_DATA(StringRaw, UserName);\r\n // PuTTY is started in its binary directory to allow relative paths when opening PuTTY's own stored session.\r\n // To allow relative paths in our sessions, we have to expand them for PuTTY.\r\n WRITE_DATA_EX(StringRaw, L\"PublicKeyFile\", PublicKeyFile, ExpandFileName);\r\n }\r\n else\r\n {\r\n WRITE_DATA(String, UserName);\r\n WRITE_DATA(String, PublicKeyFile);\r\n WRITE_DATA(Integer, FSProtocol);\r\n WRITE_DATA(String, LocalDirectory);\r\n WRITE_DATA(String, RemoteDirectory);\r\n WRITE_DATA(Bool, SynchronizeBrowsing);\r\n WRITE_DATA(Bool, UpdateDirectories);\r\n WRITE_DATA(Bool, CacheDirectories);\r\n WRITE_DATA(Bool, CacheDirectoryChanges);\r\n WRITE_DATA(Bool, PreserveDirectoryChanges);\r\n\r\n WRITE_DATA(Bool, ResolveSymlinks);\r\n WRITE_DATA(Bool, FollowDirectorySymlinks);\r\n WRITE_DATA_EX(Integer, L\"ConsiderDST\", DSTMode, );\r\n WRITE_DATA(Bool, LockInHome);\r\n // Special is never stored (if it would, login dialog must be modified not to\r\n // duplicate Special parameter when Special session is loaded and then stored\r\n // under different name)\r\n // WRITE_DATA(Bool, Special);\r\n WRITE_DATA(String, Shell);\r\n WRITE_DATA(Bool, ClearAliases);\r\n WRITE_DATA(Bool, UnsetNationalVars);\r\n WRITE_DATA(String, ListingCommand);\r\n WRITE_DATA(Bool, IgnoreLsWarnings);\r\n WRITE_DATA(Integer, SCPLsFullTime);\r\n WRITE_DATA(Bool, Scp1Compatibility);\r\n // TimeDifferenceAuto is valid for FTP protocol only.\r\n // For other protocols it's typically true (default value),\r\n // but ignored so TimeDifference is still taken into account (SCP only actually)\r\n if (TimeDifferenceAuto && (FSProtocol == fsFTP))\r\n {\r\n // Have to delete it as TimeDifferenceAuto is not saved when enabled,\r\n // but the default is derived from value of TimeDifference.\r\n Storage->DeleteValue(L\"TimeDifference\");\r\n }\r\n else\r\n {\r\n WRITE_DATA(Float, TimeDifference);\r\n }\r\n WRITE_DATA(Bool, TimeDifferenceAuto);\r\n WRITE_DATA(Bool, DeleteToRecycleBin);\r\n WRITE_DATA(Bool, OverwrittenToRecycleBin);\r\n WRITE_DATA(String, RecycleBinPath);\r\n WRITE_DATA(String, PostLoginCommands);\r\n\r\n WRITE_DATA(String, ReturnVar);\r\n WRITE_DATA(Bool, ExitCode1IsError);\r\n WRITE_DATA_EX(Integer, L\"LookupUserGroups2\", LookupUserGroups, );\r\n WRITE_DATA(Integer, EOLType);\r\n WRITE_DATA(Bool, TrimVMSVersions);\r\n Storage->DeleteValue(L\"SFTPUtfBug\");\r\n WRITE_DATA_EX(Integer, L\"Utf\", NotUtf, );\r\n WRITE_DATA(Integer, InternalEditorEncoding);\r\n WRITE_DATA(String, S3DefaultRegion);\r\n WRITE_DATA(Integer, S3UrlStyle);\r\n WRITE_DATA(Integer, SendBuf);\r\n WRITE_DATA(String, SourceAddress);\r\n WRITE_DATA(Bool, SshSimple);\r\n }\r\n\r\n WRITE_DATA(Integer, ProxyMethod);\r\n WRITE_DATA(String, ProxyHost);\r\n WRITE_DATA(Integer, ProxyPort);\r\n WRITE_DATA(String, ProxyUsername);\r\n if (ProxyMethod == pmCmd)\r\n {\r\n WRITE_DATA_EX(StringRaw, L\"ProxyTelnetCommand\", ProxyLocalCommand, );\r\n }\r\n else\r\n {\r\n WRITE_DATA(StringRaw, ProxyTelnetCommand);\r\n }\r\n #define WRITE_DATA_CONV_FUNC(X) (((X) + 2) % 3)\r\n WRITE_DATA_CONV(Integer, L\"ProxyDNS\", ProxyDNS);\r\n #undef WRITE_DATA_CONV_FUNC\r\n WRITE_DATA(Bool, ProxyLocalhost);\r\n\r\n #define WRITE_DATA_CONV_FUNC(X) (2 - (X))\r\n #define WRITE_BUG(BUG) WRITE_DATA_CONV(Integer, L\"Bug\" #BUG, Bug[sb##BUG]);\r\n WRITE_BUG(Ignore1);\r\n WRITE_BUG(PlainPW1);\r\n WRITE_BUG(RSA1);\r\n WRITE_BUG(HMAC2);\r\n WRITE_BUG(DeriveKey2);\r\n WRITE_BUG(RSAPad2);\r\n WRITE_BUG(PKSessID2);\r\n WRITE_BUG(Rekey2);\r\n WRITE_BUG(MaxPkt2);\r\n WRITE_BUG(Ignore2);\r\n WRITE_BUG(OldGex2);\r\n WRITE_BUG(WinAdj);\r\n WRITE_BUG(ChanReq);\r\n #undef WRITE_BUG\r\n #undef WRITE_DATA_CONV_FUNC\r\n\r\n Storage->DeleteValue(L\"BuggyMAC\");\r\n Storage->DeleteValue(L\"AliasGroupList\");\r\n\r\n if (PuttyExport)\r\n {\r\n WRITE_DATA_EX(String, L\"Protocol\", GetNormalizedPuttyProtocol(), );\r\n WRITE_DATA(String, WinTitle);\r\n }\r\n\r\n if (!PuttyExport)\r\n {\r\n WRITE_DATA(String, SftpServer);\r\n\r\n #define WRITE_SFTP_BUG(BUG) WRITE_DATA_EX(Integer, L\"SFTP\" #BUG \"Bug\", SFTPBug[sb##BUG], );\r\n WRITE_SFTP_BUG(Symlink);\r\n WRITE_SFTP_BUG(SignedTS);\r\n #undef WRITE_SFTP_BUG\r\n\r\n WRITE_DATA(Integer, SFTPMaxVersion);\r\n WRITE_DATA(Integer, SFTPMaxPacketSize);\r\n WRITE_DATA(Integer, SFTPDownloadQueue);\r\n WRITE_DATA(Integer, SFTPUploadQueue);\r\n WRITE_DATA(Integer, SFTPListingQueue);\r\n\r\n WRITE_DATA(Integer, Color);\r\n\r\n WRITE_DATA(Bool, Tunnel);\r\n WRITE_DATA(String, TunnelHostName);\r\n WRITE_DATA(Integer, TunnelPortNumber);\r\n WRITE_DATA(String, TunnelUserName);\r\n WRITE_DATA(String, TunnelPublicKeyFile);\r\n WRITE_DATA(Integer, TunnelLocalPortNumber);\r\n\r\n WRITE_DATA(Bool, FtpPasvMode);\r\n WRITE_DATA_EX(Integer, L\"FtpForcePasvIp2\", FtpForcePasvIp, );\r\n WRITE_DATA(Integer, FtpUseMlsd);\r\n WRITE_DATA(String, FtpAccount);\r\n WRITE_DATA(Integer, FtpPingInterval);\r\n WRITE_DATA(Integer, FtpPingType);\r\n WRITE_DATA_EX(Integer, L\"FtpTransferActiveImmediately2\", FtpTransferActiveImmediately, );\r\n WRITE_DATA(Integer, Ftps);\r\n WRITE_DATA(Integer, FtpListAll);\r\n WRITE_DATA(Integer, FtpHost);\r\n WRITE_DATA(Integer, FtpDeleteFromCwd);\r\n WRITE_DATA(Bool, SslSessionReuse);\r\n WRITE_DATA(String, TlsCertificateFile);\r\n\r\n WRITE_DATA(Integer, FtpProxyLogonType);\r\n\r\n WRITE_DATA(Integer, MinTlsVersion);\r\n WRITE_DATA(Integer, MaxTlsVersion);\r\n\r\n WRITE_DATA(Bool, IsWorkspace);\r\n WRITE_DATA(String, Link);\r\n WRITE_DATA(String, NameOverride);\r\n\r\n WRITE_DATA(String, PuttySettings);\r\n\r\n WRITE_DATA(String, CustomParam1);\r\n WRITE_DATA(String, CustomParam2);\r\n }\r\n\r\n // This is for collecting all keys for TSiteRawDialog::AddButtonClick.\r\n // It should be enough to test for (Default == NULL),\r\n // the DoNotEncryptPasswords and PuttyExport were added to limit a possible unintended impact.\r\n bool SaveAll = (Default == NULL) && DoNotEncryptPasswords && !PuttyExport;\r\n\r\n SavePasswords(Storage, PuttyExport, DoNotEncryptPasswords, SaveAll);\r\n\r\n if (PuttyExport)\r\n {\r\n WritePuttySettings(Storage, PuttySettings);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nTStrings * __fastcall TSessionData::SaveToOptions(const TSessionData * Default, bool SaveName, bool PuttyExport)\r\n{\r\n std::unique_ptr<TStringList> Options(new TStringList());\r\n std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));\r\n if (SaveName)\r\n {\r\n OptionsStorage->WriteString(L\"Name\", Name);\r\n }\r\n DoSave(OptionsStorage.get(), PuttyExport, Default, true);\r\n return Options.release();\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::Save(THierarchicalStorage * Storage,\r\n bool PuttyExport, const TSessionData * Default)\r\n{\r\n if (Storage->OpenSubKey(InternalStorageKey, true))\r\n {\r\n DoSave(Storage, PuttyExport, Default, false);\r\n\r\n Storage->CloseSubKey();\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::ReadXmlNode(_di_IXMLNode Node, const UnicodeString & Name, const UnicodeString & Default)\r\n{\r\n _di_IXMLNode TheNode = Node->ChildNodes->FindNode(Name);\r\n UnicodeString Result;\r\n if (TheNode != NULL)\r\n {\r\n Result = TheNode->Text.Trim();\r\n }\r\n\r\n if (Result.IsEmpty())\r\n {\r\n Result = Default;\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nint __fastcall TSessionData::ReadXmlNode(_di_IXMLNode Node, const UnicodeString & Name, int Default)\r\n{\r\n _di_IXMLNode TheNode = Node->ChildNodes->FindNode(Name);\r\n int Result;\r\n if (TheNode != NULL)\r\n {\r\n Result = StrToIntDef(TheNode->Text.Trim(), Default);\r\n }\r\n else\r\n {\r\n Result = Default;\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\n_di_IXMLNode __fastcall TSessionData::FindSettingsNode(_di_IXMLNode Node, const UnicodeString & Name)\r\n{\r\n for (int Index = 0; Index < Node->ChildNodes->Count; Index++)\r\n {\r\n _di_IXMLNode ChildNode = Node->ChildNodes->Get(Index);\r\n if (ChildNode->NodeName == L\"Setting\")\r\n {\r\n OleVariant SettingName = ChildNode->GetAttribute(L\"name\");\r\n if (SettingName == Name)\r\n {\r\n return ChildNode;\r\n }\r\n }\r\n }\r\n\r\n return NULL;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::ReadSettingsNode(_di_IXMLNode Node, const UnicodeString & Name, const UnicodeString & Default)\r\n{\r\n _di_IXMLNode TheNode = FindSettingsNode(Node, Name);\r\n UnicodeString Result;\r\n if (TheNode != NULL)\r\n {\r\n Result = TheNode->Text.Trim();\r\n }\r\n\r\n if (Result.IsEmpty())\r\n {\r\n Result = Default;\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nint __fastcall TSessionData::ReadSettingsNode(_di_IXMLNode Node, const UnicodeString & Name, int Default)\r\n{\r\n _di_IXMLNode TheNode = FindSettingsNode(Node, Name);\r\n int Result;\r\n if (TheNode != NULL)\r\n {\r\n Result = StrToIntDef(TheNode->Text.Trim(), Default);\r\n }\r\n else\r\n {\r\n Result = Default;\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::ImportFromFilezilla(\r\n _di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode)\r\n{\r\n Name = UnixIncludeTrailingBackslash(Path) + MakeValidName(ReadXmlNode(Node, L\"Name\", Name));\r\n HostName = ReadXmlNode(Node, L\"Host\", HostName);\r\n PortNumber = ReadXmlNode(Node, L\"Port\", PortNumber);\r\n\r\n int AProtocol = ReadXmlNode(Node, L\"Protocol\", 0);\r\n // ServerProtocol enum\r\n switch (AProtocol)\r\n {\r\n case 0: // FTP\r\n default: // UNKNOWN, HTTP, HTTPS, INSECURE_FTP\r\n FSProtocol = fsFTP;\r\n break;\r\n\r\n case 1: // SFTP\r\n FSProtocol = fsSFTP;\r\n break;\r\n\r\n case 3: // FTPS\r\n FSProtocol = fsFTP;\r\n Ftps = ftpsImplicit;\r\n break;\r\n\r\n case 4: // FTPES\r\n FSProtocol = fsFTP;\r\n Ftps = ftpsExplicitTls;\r\n break;\r\n }\r\n\r\n // LogonType enum\r\n int LogonType = ReadXmlNode(Node, L\"Logontype\", 0);\r\n if (LogonType == 0) // ANONYMOUS\r\n {\r\n UserName = AnonymousUserName;\r\n Password = AnonymousPassword;\r\n }\r\n else\r\n {\r\n UserName = ReadXmlNode(Node, L\"User\", UserName);\r\n FtpAccount = ReadXmlNode(Node, L\"Account\", FtpAccount);\r\n\r\n _di_IXMLNode PassNode = Node->ChildNodes->FindNode(L\"Pass\");\r\n if (PassNode != NULL)\r\n {\r\n UnicodeString APassword = PassNode->Text.Trim();\r\n OleVariant EncodingValue = PassNode->GetAttribute(L\"encoding\");\r\n if (!EncodingValue.IsNull())\r\n {\r\n UnicodeString EncodingValueStr = EncodingValue;\r\n if (SameText(EncodingValueStr, L\"base64\"))\r\n {\r\n TBytes Bytes = DecodeBase64(APassword);\r\n APassword = TEncoding::UTF8->GetString(Bytes);\r\n }\r\n }\r\n Password = APassword;\r\n }\r\n }\r\n\r\n PublicKeyFile = ReadXmlNode(Node, L\"Keyfile\", PublicKeyFile);\r\n\r\n int DefaultTimeDifference = TimeToSeconds(TimeDifference);\r\n TimeDifference =\r\n (double(ReadXmlNode(Node, L\"TimezoneOffset\", DefaultTimeDifference) / SecsPerDay));\r\n TimeDifferenceAuto = (TimeDifference == TDateTime());\r\n\r\n UnicodeString PasvMode = ReadXmlNode(Node, L\"PasvMode\", L\"\");\r\n if (SameText(PasvMode, L\"MODE_PASSIVE\"))\r\n {\r\n FtpPasvMode = true;\r\n }\r\n else if (SameText(PasvMode, L\"MODE_ACTIVE\"))\r\n {\r\n FtpPasvMode = false;\r\n }\r\n\r\n UnicodeString EncodingType = ReadXmlNode(Node, L\"EncodingType\", L\"\");\r\n if (SameText(EncodingType, L\"Auto\"))\r\n {\r\n NotUtf = asAuto;\r\n }\r\n else if (SameText(EncodingType, L\"UTF-8\"))\r\n {\r\n NotUtf = asOff;\r\n }\r\n\r\n // todo PostLoginCommands\r\n\r\n Note = ReadXmlNode(Node, L\"Comments\", Note);\r\n\r\n LocalDirectory = ReadXmlNode(Node, L\"LocalDir\", LocalDirectory);\r\n\r\n UnicodeString RemoteDir = ReadXmlNode(Node, L\"RemoteDir\", L\"\");\r\n if (!RemoteDir.IsEmpty())\r\n {\r\n CutToChar(RemoteDir, L' ', false); // type\r\n int PrefixSize = StrToIntDef(CutToChar(RemoteDir, L' ', false), 0); // prefix size\r\n if (PrefixSize > 0)\r\n {\r\n RemoteDir.Delete(1, PrefixSize);\r\n }\r\n RemoteDirectory = L\"/\";\r\n while (!RemoteDir.IsEmpty())\r\n {\r\n int SegmentSize = StrToIntDef(CutToChar(RemoteDir, L' ', false), 0);\r\n UnicodeString Segment = RemoteDir.SubString(1, SegmentSize);\r\n RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory) + Segment;\r\n RemoteDir.Delete(1, SegmentSize + 1);\r\n }\r\n }\r\n\r\n SynchronizeBrowsing = (ReadXmlNode(Node, L\"SyncBrowsing\", SynchronizeBrowsing ? 1 : 0) != 0);\r\n\r\n if (SettingsNode != NULL)\r\n {\r\n if (UsesSsh && PublicKeyFile.IsEmpty())\r\n {\r\n UnicodeString KeyFiles = ReadSettingsNode(SettingsNode, L\"SFTP keyfiles\", UnicodeString());\r\n UnicodeString KeyFile = CutToChar(KeyFiles, L'\\n', true).Trim();\r\n KeyFiles = KeyFiles.Trim();\r\n // If there are more keys, ignore them, as we do not know which one to use\r\n if (!KeyFile.IsEmpty() && KeyFiles.IsEmpty())\r\n {\r\n PublicKeyFile = KeyFile;\r\n }\r\n }\r\n\r\n bool BypassProxy = (ReadXmlNode(Node, L\"BypassProxy\", 0) != 0);\r\n if (!BypassProxy)\r\n {\r\n int FtpProxyType = ReadSettingsNode(SettingsNode, L\"FTP Proxy type\", -1);\r\n if (FtpProxyType > 0)\r\n {\r\n switch (FtpProxyType)\r\n {\r\n case 1:\r\n FtpProxyLogonType = 2;\r\n break;\r\n case 2:\r\n FtpProxyLogonType = 1;\r\n break;\r\n case 3:\r\n FtpProxyLogonType = 3;\r\n break;\r\n case 4:\r\n // custom\r\n // TODO: map known sequences to our enumeration\r\n FtpProxyLogonType = 0;\r\n break;\r\n default:\r\n DebugFail();\r\n FtpProxyLogonType = 0;\r\n break;\r\n }\r\n\r\n ProxyHost = ReadSettingsNode(SettingsNode, L\"FTP Proxy host\", ProxyHost);\r\n ProxyUsername = ReadSettingsNode(SettingsNode, L\"FTP Proxy user\", ProxyUsername);\r\n ProxyPassword = ReadSettingsNode(SettingsNode, L\"FTP Proxy password\", ProxyPassword);\r\n // ProxyPort is not used with FtpProxyLogonType\r\n }\r\n else\r\n {\r\n int ProxyType = ReadSettingsNode(SettingsNode, L\"Proxy type\", -1);\r\n if (ProxyType >= 0)\r\n {\r\n switch (ProxyType)\r\n {\r\n case 0:\r\n ProxyMethod = ::pmNone;\r\n break;\r\n\r\n case 1:\r\n ProxyMethod = pmHTTP;\r\n break;\r\n\r\n case 2:\r\n ProxyMethod = pmSocks5;\r\n break;\r\n\r\n case 3:\r\n ProxyMethod = pmSocks4;\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n ProxyMethod = ::pmNone;\r\n break;\r\n }\r\n\r\n ProxyHost = ReadSettingsNode(SettingsNode, L\"Proxy host\", ProxyHost);\r\n ProxyPort = ReadSettingsNode(SettingsNode, L\"Proxy port\", ProxyPort);\r\n ProxyUsername = ReadSettingsNode(SettingsNode, L\"Proxy user\", ProxyUsername);\r\n ProxyPassword = ReadSettingsNode(SettingsNode, L\"Proxy password\", ProxyPassword);\r\n }\r\n }\r\n }\r\n }\r\n\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SavePasswords(THierarchicalStorage * Storage, bool PuttyExport, bool DoNotEncryptPasswords, bool SaveAll)\r\n{\r\n if (!Configuration->DisablePasswordStoring && !PuttyExport && (!FPassword.IsEmpty() || SaveAll))\r\n {\r\n if (DoNotEncryptPasswords)\r\n {\r\n Storage->WriteString(L\"PasswordPlain\", Password);\r\n Storage->DeleteValue(L\"Password\");\r\n }\r\n else\r\n {\r\n Storage->WriteBinaryDataAsString(L\"Password\", StronglyRecryptPassword(FPassword, UserName+HostName));\r\n Storage->DeleteValue(L\"PasswordPlain\");\r\n }\r\n }\r\n else\r\n {\r\n Storage->DeleteValue(L\"Password\");\r\n Storage->DeleteValue(L\"PasswordPlain\");\r\n }\r\n\r\n if (PuttyExport)\r\n {\r\n // save password unencrypted\r\n Storage->WriteString(L\"ProxyPassword\", ProxyPassword);\r\n }\r\n else\r\n {\r\n if (DoNotEncryptPasswords)\r\n {\r\n if (!FProxyPassword.IsEmpty() || SaveAll)\r\n {\r\n Storage->WriteString(L\"ProxyPassword\", ProxyPassword);\r\n }\r\n else\r\n {\r\n Storage->DeleteValue(L\"ProxyPassword\");\r\n }\r\n Storage->DeleteValue(L\"ProxyPasswordEnc\");\r\n }\r\n else\r\n {\r\n // save password encrypted\r\n if (!FProxyPassword.IsEmpty() || SaveAll)\r\n {\r\n Storage->WriteBinaryDataAsString(L\"ProxyPasswordEnc\", StronglyRecryptPassword(FProxyPassword, ProxyUsername+ProxyHost));\r\n }\r\n else\r\n {\r\n Storage->DeleteValue(L\"ProxyPasswordEnc\");\r\n }\r\n Storage->DeleteValue(L\"ProxyPassword\");\r\n }\r\n\r\n if (DoNotEncryptPasswords)\r\n {\r\n if (!FTunnelPassword.IsEmpty() || SaveAll)\r\n {\r\n Storage->WriteString(L\"TunnelPasswordPlain\", TunnelPassword);\r\n }\r\n else\r\n {\r\n Storage->DeleteValue(L\"TunnelPasswordPlain\");\r\n }\r\n }\r\n else\r\n {\r\n if (!Configuration->DisablePasswordStoring && (!FTunnelPassword.IsEmpty() || SaveAll))\r\n {\r\n Storage->WriteBinaryDataAsString(L\"TunnelPassword\", StronglyRecryptPassword(FTunnelPassword, TunnelUserName+TunnelHostName));\r\n }\r\n else\r\n {\r\n Storage->DeleteValue(L\"TunnelPassword\");\r\n }\r\n }\r\n\r\n if (DoNotEncryptPasswords)\r\n {\r\n if (!FEncryptKey.IsEmpty() || SaveAll)\r\n {\r\n Storage->WriteString(L\"EncryptKeyPlain\", EncryptKey);\r\n }\r\n else\r\n {\r\n Storage->DeleteValue(L\"EncryptKeyPlain\");\r\n }\r\n Storage->DeleteValue(L\"EncryptKey\");\r\n }\r\n else\r\n {\r\n if (!FEncryptKey.IsEmpty() || SaveAll)\r\n {\r\n Storage->WriteBinaryDataAsString(L\"EncryptKey\", StronglyRecryptPassword(FEncryptKey, UserName+HostName));\r\n }\r\n else\r\n {\r\n Storage->DeleteValue(L\"EncryptKey\");\r\n }\r\n Storage->DeleteValue(L\"EncryptKeyPlain\");\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::RecryptPasswords()\r\n{\r\n Password = Password;\r\n NewPassword = NewPassword;\r\n ProxyPassword = ProxyPassword;\r\n TunnelPassword = TunnelPassword;\r\n Passphrase = Passphrase;\r\n EncryptKey = EncryptKey;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::HasPassword()\r\n{\r\n return !FPassword.IsEmpty();\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::HasAnySessionPassword()\r\n{\r\n // Keep in sync with ClearSessionPasswords\r\n return\r\n HasPassword() ||\r\n !FTunnelPassword.IsEmpty() ||\r\n // will probably be never used\r\n !FNewPassword.IsEmpty();\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::HasAnyPassword()\r\n{\r\n // Keep in sync with MaskPasswords\r\n return\r\n HasAnySessionPassword() ||\r\n !FProxyPassword.IsEmpty() ||\r\n !FEncryptKey.IsEmpty() ||\r\n !FPassphrase.IsEmpty();\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::ClearSessionPasswords()\r\n{\r\n // Keep in sync with HasAnySessionPassword\r\n FPassword = L\"\";\r\n FNewPassword = L\"\";\r\n FTunnelPassword = L\"\";\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::Modify()\r\n{\r\n FModified = true;\r\n if (FSource == ssStored)\r\n {\r\n FSource = ssStoredModified;\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetSource()\r\n{\r\n switch (FSource)\r\n {\r\n case ::ssNone:\r\n return L\"Ad-Hoc site\";\r\n\r\n case ssStored:\r\n return L\"Site\";\r\n\r\n case ssStoredModified:\r\n return L\"Modified site\";\r\n\r\n default:\r\n DebugFail();\r\n return L\"\";\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SaveRecryptedPasswords(THierarchicalStorage * Storage)\r\n{\r\n if (Storage->OpenSubKey(InternalStorageKey, true))\r\n {\r\n try\r\n {\r\n RecryptPasswords();\r\n\r\n SavePasswords(Storage, false, false, false);\r\n }\r\n __finally\r\n {\r\n Storage->CloseSubKey();\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::Remove(THierarchicalStorage * Storage, const UnicodeString & Name)\r\n{\r\n Storage->RecursiveDeleteSubKey(Name);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::Remove()\r\n{\r\n bool SessionList = true;\r\n THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);\r\n try\r\n {\r\n Storage->Explicit = true;\r\n if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, false))\r\n {\r\n Remove(Storage, InternalStorageKey);\r\n }\r\n }\r\n __finally\r\n {\r\n delete Storage;\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::CacheHostKeyIfNotCached()\r\n{\r\n UnicodeString KeyType = KeyTypeFromFingerprint(HostKey);\r\n\r\n // Should allow importing to INI file as ImportHostKeys\r\n UnicodeString TargetKey = Configuration->RegistryStorageKey + L\"\\\\\" + Configuration->SshHostKeysSubKey;\r\n std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(TargetKey));\r\n Storage->AccessMode = smReadWrite;\r\n if (Storage->OpenRootKey(true))\r\n {\r\n UnicodeString HostKeyName = PuttyMungeStr(FORMAT(L\"%s@%d:%s\", (KeyType, PortNumber, HostName)));\r\n if (!Storage->ValueExists(HostKeyName))\r\n {\r\n // fingerprint is a checksum of a host key, so it cannot be translated back to host key,\r\n // so we store fingerprint and TSecureShell::VerifyHostKey was\r\n // modified to accept also fingerprint\r\n Storage->WriteString(HostKeyName, HostKey);\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\ninline void __fastcall MoveStr(UnicodeString & Source, UnicodeString * Dest, int Count)\r\n{\r\n if (Dest != NULL)\r\n {\r\n (*Dest) += Source.SubString(1, Count);\r\n }\r\n\r\n Source.Delete(1, Count);\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::DoIsProtocolUrl(\r\n const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen)\r\n{\r\n bool Result = SameText(Url.SubString(1, Protocol.Length() + 1), Protocol + L\":\");\r\n if (Result)\r\n {\r\n ProtocolLen = Protocol.Length() + 1;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsProtocolUrl(\r\n const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen)\r\n{\r\n return\r\n DoIsProtocolUrl(Url, Protocol, ProtocolLen) ||\r\n DoIsProtocolUrl(Url, WinSCPProtocolPrefix + Protocol, ProtocolLen);\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsSensitiveOption(const UnicodeString & Option)\r\n{\r\n return\r\n SameText(Option, PassphraseOption) ||\r\n SameText(Option, NEWPASSWORD_SWITCH);\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsOptionWithParameters(const UnicodeString & Option)\r\n{\r\n return SameText(Option, RawSettingsOption);\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::MaskPasswordInOptionParameter(const UnicodeString & Option, UnicodeString & Param)\r\n{\r\n bool Result = false;\r\n if (SameText(Option, RawSettingsOption))\r\n {\r\n int P = Param.Pos(L\"=\");\r\n if (P > 0)\r\n {\r\n // TStrings.IndexOfName does not trim\r\n UnicodeString Key = Param.SubString(1, P - 1);\r\n\r\n if (SameText(Key, L\"ProxyPassword\") ||\r\n SameText(Key, L\"ProxyPasswordEnc\") ||\r\n SameText(Key, L\"TunnelPassword\") ||\r\n SameText(Key, L\"TunnelPasswordPlain\") ||\r\n SameText(Key, L\"EncryptKey\"))\r\n {\r\n Param = Key + L\"=\" + PasswordMask;\r\n Result = true;\r\n }\r\n }\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::MaskPasswords()\r\n{\r\n // Keep in sync with HasAnyPassword\r\n if (!Password.IsEmpty())\r\n {\r\n Password = PasswordMask;\r\n }\r\n if (!NewPassword.IsEmpty())\r\n {\r\n NewPassword = PasswordMask;\r\n }\r\n if (!ProxyPassword.IsEmpty())\r\n {\r\n ProxyPassword = PasswordMask;\r\n }\r\n if (!TunnelPassword.IsEmpty())\r\n {\r\n TunnelPassword = PasswordMask;\r\n }\r\n if (!EncryptKey.IsEmpty())\r\n {\r\n EncryptKey = PasswordMask;\r\n }\r\n if (!Passphrase.IsEmpty())\r\n {\r\n Passphrase = PasswordMask;\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::ParseUrl(UnicodeString Url, TOptions * Options,\r\n TStoredSessionList * StoredSessions, bool & DefaultsOnly, UnicodeString * FileName,\r\n bool * AProtocolDefined, UnicodeString * MaskedUrl, int Flags)\r\n{\r\n bool ProtocolDefined = false;\r\n bool PortNumberDefined = false;\r\n TFSProtocol AFSProtocol;\r\n int APortNumber;\r\n TFtps AFtps = ftpsNone;\r\n int ProtocolLen = 0;\r\n if (IsProtocolUrl(Url, ScpProtocol, ProtocolLen))\r\n {\r\n AFSProtocol = fsSCPonly;\r\n APortNumber = SshPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n else if (IsProtocolUrl(Url, SftpProtocol, ProtocolLen))\r\n {\r\n AFSProtocol = fsSFTPonly;\r\n APortNumber = SshPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n else if (IsProtocolUrl(Url, FtpProtocol, ProtocolLen))\r\n {\r\n AFSProtocol = fsFTP;\r\n Ftps = ftpsNone;\r\n APortNumber = FtpPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n else if (IsProtocolUrl(Url, FtpsProtocol, ProtocolLen))\r\n {\r\n AFSProtocol = fsFTP;\r\n AFtps = ftpsImplicit;\r\n APortNumber = FtpsImplicitPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n else if (IsProtocolUrl(Url, FtpesProtocol, ProtocolLen))\r\n {\r\n AFSProtocol = fsFTP;\r\n AFtps = ftpsExplicitTls;\r\n APortNumber = FtpPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n else if (IsProtocolUrl(Url, WebDAVProtocol, ProtocolLen) ||\r\n IsProtocolUrl(Url, HttpProtocol, ProtocolLen))\r\n {\r\n AFSProtocol = fsWebDAV;\r\n AFtps = ftpsNone;\r\n APortNumber = HTTPPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n else if (IsProtocolUrl(Url, WebDAVSProtocol, ProtocolLen) ||\r\n IsProtocolUrl(Url, HttpsProtocol, ProtocolLen))\r\n {\r\n AFSProtocol = fsWebDAV;\r\n AFtps = ftpsImplicit;\r\n APortNumber = HTTPSPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n else if (IsProtocolUrl(Url, S3Protocol, ProtocolLen))\r\n {\r\n AFSProtocol = fsS3;\r\n AFtps = ftpsImplicit;\r\n APortNumber = HTTPSPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n else if (IsProtocolUrl(Url, SshProtocol, ProtocolLen))\r\n {\r\n // For most uses, handling ssh:// the same way as sftp://\r\n // The only place where a difference is made is GetLoginData() in WinMain.cpp\r\n AFSProtocol = fsSFTPonly;\r\n PuttyProtocol = PuttySshProtocol;\r\n APortNumber = SshPortNumber;\r\n MoveStr(Url, MaskedUrl, ProtocolLen);\r\n ProtocolDefined = true;\r\n }\r\n\r\n if (ProtocolDefined && (Url.SubString(1, 2) == L\"//\"))\r\n {\r\n MoveStr(Url, MaskedUrl, 2);\r\n }\r\n\r\n if (AProtocolDefined != NULL)\r\n {\r\n *AProtocolDefined = ProtocolDefined;\r\n }\r\n\r", " bool Unsafe = FLAGSET(Flags, pufUnsafe);\r", " if (!Url.IsEmpty())\r\n {\r\n UnicodeString DecodedUrl = DecodeUrlChars(Url);\r\n // lookup stored session even if protocol was defined\r\n // (this allows setting for example default username for host\r\n // by creating stored session named by host)\r\n TSessionData * Data = NULL;\r\n // When using to paste URL on Login dialog, we do not want to lookup the stored sites\r\n if ((StoredSessions != NULL) &&\r\n (!ProtocolDefined || FLAGSET(Flags, pufAllowStoredSiteWithProtocol)))\r\n {\r\n // this can be optimized as the list is sorted\r\n for (Integer Index = 0; Index < StoredSessions->CountIncludingHidden; Index++)\r\n {\r\n TSessionData * AData = (TSessionData *)StoredSessions->Items[Index];\r\n if (!AData->IsWorkspace)\r\n {\r\n bool Match = false;\r\n // Comparison optimizations as this is called many times\r\n // e.g. when updating jumplist\r\n if ((AData->Name.Length() == DecodedUrl.Length()) &&\r\n SameText(AData->Name, DecodedUrl))\r\n {\r\n Match = true;\r\n }\r\n else if ((AData->Name.Length() < DecodedUrl.Length()) &&\r\n (DecodedUrl[AData->Name.Length() + 1] == L'/') &&\r\n // StrLIComp is an equivalent of SameText\r\n (StrLIComp(AData->Name.c_str(), DecodedUrl.c_str(), AData->Name.Length()) == 0))\r\n {\r\n Match = true;\r\n }\r\n\r\n if (Match)\r\n {\r\n Data = AData;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n UnicodeString ARemoteDirectory;\r\n\r\n if (Data != NULL)\r\n {\r\n Assign(Data);\r\n int P = 1;\r\n while (!AnsiSameText(DecodeUrlChars(Url.SubString(1, P)), Data->Name))\r\n {\r\n P++;\r\n DebugAssert(P <= Url.Length());\r\n }\r\n ARemoteDirectory = Url.SubString(P + 1, Url.Length() - P);\r\n\r\n if (Data->Hidden)\r\n {\r\n Data->Remove();\r\n StoredSessions->Remove(Data);\r\n // only modified, implicit\r\n StoredSessions->Save(false, false);\r\n }\r\n\r\n if (MaskedUrl != NULL)\r\n {\r\n (*MaskedUrl) += Url;\r\n }\r\n }\r\n else\r\n {\r\n // This happens when pasting URL on Login dialog\r\n if (StoredSessions != NULL)\r\n {\r\n CopyData(StoredSessions->DefaultSettings);\r\n }\r\n Name = L\"\";\r\n\r\n int PSlash = Url.Pos(L\"/\");\r\n if (PSlash == 0)\r\n {\r\n PSlash = Url.Length() + 1;\r\n }\r\n\r\n UnicodeString ConnectInfo = Url.SubString(1, PSlash - 1);\r\n\r\n int P = ConnectInfo.LastDelimiter(L\"@\");\r\n\r\n UnicodeString UserInfo;\r\n UnicodeString HostInfo;\r\n\r\n if (P > 0)\r\n {\r\n UserInfo = ConnectInfo.SubString(1, P - 1);\r\n HostInfo = ConnectInfo.SubString(P + 1, ConnectInfo.Length() - P);\r\n }\r\n else\r\n {\r\n HostInfo = ConnectInfo;\r\n }\r\n\r\n UnicodeString OrigHostInfo = HostInfo;\r\n if ((HostInfo.Length() >= 2) && (HostInfo[1] == L'[') && ((P = HostInfo.Pos(L\"]\")) > 0))\r\n {\r\n HostName = HostInfo.SubString(2, P - 2);\r\n HostInfo.Delete(1, P);\r\n if (!HostInfo.IsEmpty() && (HostInfo[1] == L':'))\r\n {\r\n HostInfo.Delete(1, 1);\r\n }\r\n }\r\n else\r\n {\r\n HostName = DecodeUrlChars(CutToChar(HostInfo, L':', true));\r\n }\r\n\r\n // expanded from ?: operator, as it caused strange \"access violation\" errors\r\n if (!HostInfo.IsEmpty())\r\n {\r\n PortNumber = StrToIntDef(DecodeUrlChars(HostInfo), -1);\r\n PortNumberDefined = true;\r\n }\r\n else if (ProtocolDefined)\r\n {\r\n PortNumber = APortNumber;\r\n }\r\n\r\n if (ProtocolDefined)\r\n {\r\n Ftps = AFtps;\r\n }\r\n\r\n UnicodeString UserInfoWithoutConnectionParams = CutToChar(UserInfo, UrlParamSeparator, false);\r\n UnicodeString ConnectionParams = UserInfo;\r\n UserInfo = UserInfoWithoutConnectionParams;\r\n\r\n std::unique_ptr<TStrings> RawSettings(new TStringList());\r\n\r\n while (!ConnectionParams.IsEmpty())\r\n {\r\n UnicodeString ConnectionParam = CutToChar(ConnectionParams, UrlParamSeparator, false);\r\n UnicodeString ConnectionParamName = CutToChar(ConnectionParam, UrlParamValueSeparator, false);\r\n if (SameText(ConnectionParamName, UrlHostKeyParamName))\r\n {\r\n HostKey = DecodeUrlChars(ConnectionParam);\r\n FOverrideCachedHostKey = false;\r\n }\r\n else if (StartsText(UrlRawSettingsParamNamePrefix, ConnectionParamName))\r\n {\r\n UnicodeString AName = RightStr(ConnectionParamName, ConnectionParamName.Length() - UrlRawSettingsParamNamePrefix.Length());\r\n AName = DecodeUrlChars(AName);\r\n UnicodeString Value = DecodeUrlChars(ConnectionParam);\r\n if (SameText(AName, L\"Name\"))\r\n {\r\n Name = Value;\r\n }\r\n else\r\n {\r\n RawSettings->Values[AName] = Value;\r\n }\r\n }\r\n }\r\n\r\n if (RawSettings->Count > 0) // optimization\r\n {\r", " ApplyRawSettings(RawSettings.get(), FLAGSET(Flags, pufUnsafe));\r", " }\r\n\r\n bool HasPassword = (UserInfo.Pos(L':') > 0);\r\n UnicodeString RawUserName = CutToChar(UserInfo, L':', false);\r\n UserName = DecodeUrlChars(RawUserName);\r\n\r\n Password = DecodeUrlChars(UserInfo);\r\n if (HasPassword && Password.IsEmpty())\r\n {\r\n Password = EmptyString;\r\n }\r\n\r\n UnicodeString RemoteDirectoryWithSessionParams = Url.SubString(PSlash, Url.Length() - PSlash + 1);\r\n ARemoteDirectory = CutToChar(RemoteDirectoryWithSessionParams, UrlParamSeparator, false);\r\n UnicodeString SessionParams = RemoteDirectoryWithSessionParams;\r\n\r\n // We should handle session params in \"stored session\" branch too.\r\n // And particularly if there's a \"save\" param, we should actually not try to match the\r\n // URL against site names\r\n while (!SessionParams.IsEmpty())\r\n {\r\n UnicodeString SessionParam = CutToChar(SessionParams, UrlParamSeparator, false);\r\n UnicodeString SessionParamName = CutToChar(SessionParam, UrlParamValueSeparator, false);\r\n if (SameText(SessionParamName, UrlSaveParamName))\r\n {\r\n FSaveOnly = (StrToIntDef(SessionParam, 1) != 0);\r\n }\r\n }\r\n\r\n if (MaskedUrl != NULL)\r\n {\r\n (*MaskedUrl) += RawUserName;\r\n if (HasPassword)\r\n {\r\n (*MaskedUrl) += L\":\" + PasswordMask;\r\n }\r\n if (!RawUserName.IsEmpty() || HasPassword)\r\n {\r\n (*MaskedUrl) += L\"@\";\r\n }\r\n (*MaskedUrl) += OrigHostInfo + ARemoteDirectory;\r\n }\r\n }\r\n\r\n if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory != L\"/\"))\r\n {\r\n if ((ARemoteDirectory[ARemoteDirectory.Length()] != L'/') &&\r\n (FileName != NULL))\r\n {\r\n *FileName = DecodeUrlChars(UnixExtractFileName(ARemoteDirectory));\r\n ARemoteDirectory = UnixExtractFilePath(ARemoteDirectory);\r\n }\r\n RemoteDirectory = DecodeUrlChars(ARemoteDirectory);\r\n }\r\n\r\n DefaultsOnly = false;\r\n }\r\n else\r\n {\r\n // This happens when pasting URL on Login dialog\r\n if (StoredSessions != NULL)\r\n {\r\n CopyData(StoredSessions->DefaultSettings);\r\n }\r\n\r\n DefaultsOnly = true;\r\n }\r\n\r\n if (ProtocolDefined)\r\n {\r\n FSProtocol = AFSProtocol;\r\n }\r\n\r\n if (Options != NULL)\r\n {\r\n // we deliberately do keep defaultonly to false, in presence of any option,\r\n // as the option should not make session \"connectable\"\r\n\r\n UnicodeString Value;\r\n if (Options->FindSwitch(SESSIONNAME_SWICH, Value))\r\n {\r\n Name = Value;\r\n }\r\n if (Options->FindSwitch(NEWPASSWORD_SWITCH, Value))\r\n {\r\n ChangePassword = true;\r\n NewPassword = Value;\r\n }\r\n if (Options->FindSwitch(L\"privatekey\", Value))\r\n {\r\n PublicKeyFile = Value;\r\n }\r\n if (Options->FindSwitch(L\"clientcert\", Value))\r\n {\r\n TlsCertificateFile = Value;\r\n }\r\n if (Options->FindSwitch(PassphraseOption, Value))\r\n {\r\n Passphrase = Value;\r\n }\r\n if (Options->FindSwitch(L\"timeout\", Value))\r\n {\r\n Timeout = StrToInt(Value);\r\n }\r\n if (Options->FindSwitch(L\"hostkey\", Value) ||\r\n Options->FindSwitch(L\"certificate\", Value))\r\n {\r\n HostKey = Value;\r\n FOverrideCachedHostKey = true;\r\n }\r\n FtpPasvMode = Options->SwitchValue(L\"passive\", FtpPasvMode);\r\n if (Options->FindSwitch(L\"implicit\"))\r\n {\r\n bool Enabled = Options->SwitchValue(L\"implicit\", true);\r\n Ftps = Enabled ? ftpsImplicit : ftpsNone;\r\n if (!PortNumberDefined && Enabled)\r\n {\r\n PortNumber = FtpsImplicitPortNumber;\r\n }\r\n }\r\n // BACKWARD COMPATIBILITY with 5.5.x\r\n if (Options->FindSwitch(L\"explicitssl\"))\r\n {\r\n bool Enabled = Options->SwitchValue(L\"explicitssl\", true);\r\n Ftps = Enabled ? ftpsExplicitSsl : ftpsNone;\r\n if (!PortNumberDefined && Enabled)\r\n {\r\n PortNumber = FtpPortNumber;\r\n }\r\n }\r\n if (Options->FindSwitch(L\"explicit\") ||\r\n // BACKWARD COMPATIBILITY with 5.5.x\r\n Options->FindSwitch(L\"explicittls\"))\r\n {\r\n UnicodeString SwitchName =\r\n Options->FindSwitch(L\"explicit\") ? L\"explicit\" : L\"explicittls\";\r\n bool Enabled = Options->SwitchValue(SwitchName, true);\r\n Ftps = Enabled ? ftpsExplicitTls : ftpsNone;\r\n if (!PortNumberDefined && Enabled)\r\n {\r\n PortNumber = FtpPortNumber;\r\n }\r\n }\r\n if (Options->FindSwitch(RawSettingsOption))\r\n {\r\n std::unique_ptr<TStrings> RawSettings(new TStringList());\r\n if (Options->FindSwitch(RawSettingsOption, RawSettings.get()))\r\n {\r", " ApplyRawSettings(RawSettings.get(), Unsafe);\r", " }\r\n }\r\n }\r\n\r\n return true;\r\n}\r\n//---------------------------------------------------------------------\r", "void __fastcall TSessionData::ApplyRawSettings(TStrings * RawSettings, bool Unsafe)\r", "{\r\n std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings, false));\r", " ApplyRawSettings(OptionsStorage.get(), Unsafe);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::ApplyRawSettings(THierarchicalStorage * Storage, bool Unsafe)\r", "{\r\n bool Dummy;\r", " DoLoad(Storage, false, Dummy, Unsafe);\r", "}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::ConfigureTunnel(int APortNumber)\r\n{\r\n FOrigHostName = HostName;\r\n FOrigPortNumber = PortNumber;\r\n FOrigProxyMethod = ProxyMethod;\r\n\r\n HostName = L\"127.0.0.1\";\r\n PortNumber = APortNumber;\r\n // proxy settings is used for tunnel\r\n ProxyMethod = ::pmNone;\r\n FLogicalHostName = FOrigHostName;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::RollbackTunnel()\r\n{\r\n HostName = FOrigHostName;\r\n PortNumber = FOrigPortNumber;\r\n ProxyMethod = FOrigProxyMethod;\r\n FLogicalHostName = L\"\";\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::ExpandEnvironmentVariables()\r\n{\r\n HostName = HostNameExpanded;\r\n UserName = UserNameExpanded;\r\n PublicKeyFile = ::ExpandEnvironmentVariables(PublicKeyFile);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::ValidatePath(const UnicodeString Path)\r\n{\r\n // noop\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::ValidateName(const UnicodeString Name)\r\n{\r\n // keep consistent with MakeValidName\r\n if (Name.LastDelimiter(L\"/\") > 0)\r\n {\r\n throw Exception(FMTLOAD(ITEM_NAME_INVALID, (Name, L\"/\")));\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::MakeValidName(const UnicodeString & Name)\r\n{\r\n // keep consistent with ValidateName\r\n return ReplaceStr(Name, L\"/\", L\"\\\\\");\r\n}\r\n//---------------------------------------------------------------------\r\nRawByteString __fastcall TSessionData::EncryptPassword(const UnicodeString & Password, UnicodeString Key)\r\n{\r\n return Configuration->EncryptPassword(Password, Key);\r\n}\r\n//---------------------------------------------------------------------\r\nRawByteString __fastcall TSessionData::StronglyRecryptPassword(const RawByteString & Password, UnicodeString Key)\r\n{\r\n return Configuration->StronglyRecryptPassword(Password, Key);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::DecryptPassword(const RawByteString & Password, UnicodeString Key)\r\n{\r\n UnicodeString Result;\r\n try\r\n {\r\n Result = Configuration->DecryptPassword(Password, Key);\r\n }\r\n catch(EAbort &)\r\n {\r\n // silently ignore aborted prompts for master password and return empty password\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::GetCanLogin()\r\n{\r\n return !FHostName.IsEmpty();\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetSessionKey()\r\n{\r\n UnicodeString Result = FORMAT(L\"%s@%s\", (UserName, HostName));\r\n if (PortNumber != DefaultPort(FSProtocol, Ftps))\r\n {\r\n Result += FORMAT(L\":%d\", (PortNumber));\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetInternalStorageKey()\r\n{\r\n // This is probably useless remnant of previous use of this method from OpenSessionInPutty\r\n // that needs the method to return something even for ad-hoc sessions\r\n if (Name.IsEmpty())\r\n {\r\n return SessionKey;\r\n }\r\n else\r\n {\r\n return Name;\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetStorageKey()\r\n{\r\n return SessionName;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::FormatSiteKey(const UnicodeString & HostName, int PortNumber)\r\n{\r\n return FORMAT(L\"%s:%d\", (HostName, PortNumber));\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetSiteKey()\r\n{\r\n return FormatSiteKey(HostNameExpanded, PortNumber);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetHostName(UnicodeString value)\r\n{\r\n if (FHostName != value)\r\n {\r\n // HostName is key for password encryption\r\n UnicodeString XPassword = Password;\r\n UnicodeString XNewPassword = Password;\r\n UnicodeString XEncryptKey = EncryptKey;\r\n\r\n // This is now hardly used as hostname is parsed directly on login dialog.\r\n // But can be used when importing sites from PuTTY, as it allows same format too.\r\n int P = value.LastDelimiter(L\"@\");\r\n if (P > 0)\r\n {\r\n UserName = value.SubString(1, P - 1);\r\n value = value.SubString(P + 1, value.Length() - P);\r\n }\r\n FHostName = value;\r\n Modify();\r\n\r\n Password = XPassword;\r\n NewPassword = XNewPassword;\r\n EncryptKey = XEncryptKey;\r\n Shred(XPassword);\r\n Shred(XNewPassword);\r\n Shred(XEncryptKey);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetHostNameExpanded()\r\n{\r\n return ::ExpandEnvironmentVariables(HostName);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPortNumber(int value)\r\n{\r\n SET_SESSION_PROPERTY(PortNumber);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetShell(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(Shell);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSftpServer(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(SftpServer);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetClearAliases(bool value)\r\n{\r\n SET_SESSION_PROPERTY(ClearAliases);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetListingCommand(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(ListingCommand);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetIgnoreLsWarnings(bool value)\r\n{\r\n SET_SESSION_PROPERTY(IgnoreLsWarnings);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetUnsetNationalVars(bool value)\r\n{\r\n SET_SESSION_PROPERTY(UnsetNationalVars);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetUserName(UnicodeString value)\r\n{\r\n // Avoid password recryption (what may popup master password prompt)\r\n if (FUserName != value)\r\n {\r\n // UserName is key for password encryption\r\n UnicodeString XPassword = Password;\r\n UnicodeString XNewPassword = NewPassword;\r\n UnicodeString XEncryptKey = EncryptKey;\r\n SET_SESSION_PROPERTY(UserName);\r\n Password = XPassword;\r\n NewPassword = XNewPassword;\r\n EncryptKey = XEncryptKey;\r\n Shred(XPassword);\r\n Shred(XNewPassword);\r\n Shred(XEncryptKey);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetUserNameExpanded()\r\n{\r\n return ::ExpandEnvironmentVariables(UserName);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPassword(UnicodeString avalue)\r\n{\r\n RawByteString value = EncryptPassword(avalue, UserName+HostName);\r\n SET_SESSION_PROPERTY(Password);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetPassword() const\r\n{\r\n return DecryptPassword(FPassword, UserName+HostName);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetNewPassword(UnicodeString avalue)\r\n{\r\n RawByteString value = EncryptPassword(avalue, UserName+HostName);\r\n SET_SESSION_PROPERTY(NewPassword);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetNewPassword() const\r\n{\r\n return DecryptPassword(FNewPassword, UserName+HostName);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetChangePassword(bool value)\r\n{\r\n SET_SESSION_PROPERTY(ChangePassword);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPingInterval(int value)\r\n{\r\n SET_SESSION_PROPERTY(PingInterval);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTryAgent(bool value)\r\n{\r\n SET_SESSION_PROPERTY(TryAgent);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetAgentFwd(bool value)\r\n{\r\n SET_SESSION_PROPERTY(AgentFwd);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetAuthTIS(bool value)\r\n{\r\n SET_SESSION_PROPERTY(AuthTIS);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetAuthKI(bool value)\r\n{\r\n SET_SESSION_PROPERTY(AuthKI);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetAuthKIPassword(bool value)\r\n{\r\n SET_SESSION_PROPERTY(AuthKIPassword);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetAuthGSSAPI(bool value)\r\n{\r\n SET_SESSION_PROPERTY(AuthGSSAPI);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetGSSAPIFwdTGT(bool value)\r\n{\r\n SET_SESSION_PROPERTY(GSSAPIFwdTGT);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetChangeUsername(bool value)\r\n{\r\n SET_SESSION_PROPERTY(ChangeUsername);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetCompression(bool value)\r\n{\r\n SET_SESSION_PROPERTY(Compression);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSshProt(TSshProt value)\r\n{\r\n SET_SESSION_PROPERTY(SshProt);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSsh2DES(bool value)\r\n{\r\n SET_SESSION_PROPERTY(Ssh2DES);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSshNoUserAuth(bool value)\r\n{\r\n SET_SESSION_PROPERTY(SshNoUserAuth);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetSshProtStr()\r\n{\r\n return SshProtList[FSshProt];\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::GetUsesSsh()\r\n{\r\n return IsSshProtocol(FSProtocol);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetCipher(int Index, TCipher value)\r\n{\r\n DebugAssert(Index >= 0 && Index < CIPHER_COUNT);\r\n SET_SESSION_PROPERTY(Ciphers[Index]);\r\n}\r\n//---------------------------------------------------------------------\r\nTCipher __fastcall TSessionData::GetCipher(int Index) const\r\n{\r\n DebugAssert(Index >= 0 && Index < CIPHER_COUNT);\r\n return FCiphers[Index];\r\n}\r\n//---------------------------------------------------------------------\r\ntemplate<class AlgoT>\r\nvoid __fastcall TSessionData::SetAlgoList(AlgoT * List, const AlgoT * DefaultList, const UnicodeString * Names,\r\n int Count, AlgoT WarnAlgo, UnicodeString value)\r\n{\r\n std::vector<bool> Used(Count); // initialized to false\r\n std::vector<AlgoT> NewList(Count);\r\n\r\n bool HasWarnAlgo = (WarnAlgo >= AlgoT());\r\n const AlgoT * WarnPtr;\r\n int WarnDefaultIndex;\r\n if (!HasWarnAlgo)\r\n {\r\n WarnPtr = NULL;\r\n WarnDefaultIndex = -1;\r\n }\r\n else\r\n {\r\n WarnPtr = std::find(DefaultList, DefaultList + Count, WarnAlgo);\r\n DebugAssert(WarnPtr != NULL);\r\n WarnDefaultIndex = (WarnPtr - DefaultList);\r\n }\r\n\r\n int Index = 0;\r\n while (!value.IsEmpty())\r\n {\r\n UnicodeString AlgoStr = CutToChar(value, L',', true);\r\n for (int Algo = 0; Algo < Count; Algo++)\r\n {\r\n if (!AlgoStr.CompareIC(Names[Algo]) &&\r\n !Used[Algo] && DebugAlwaysTrue(Index < Count))\r\n {\r\n NewList[Index] = (AlgoT)Algo;\r\n Used[Algo] = true;\r\n Index++;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (HasWarnAlgo && !Used[WarnAlgo] && DebugAlwaysTrue(Index < Count))\r\n {\r\n NewList[Index] = WarnAlgo;\r\n Used[WarnAlgo] = true;\r\n Index++;\r\n }\r\n\r\n int WarnIndex = -1;\r\n if (HasWarnAlgo)\r\n {\r\n WarnIndex = std::find(NewList.begin(), NewList.end(), WarnAlgo) - NewList.begin();\r\n }\r\n\r\n bool Priority = true;\r\n for (int DefaultIndex = 0; (DefaultIndex < Count); DefaultIndex++)\r\n {\r\n AlgoT DefaultAlgo = DefaultList[DefaultIndex];\r\n if (!Used[DefaultAlgo] && DebugAlwaysTrue(Index < Count))\r\n {\r\n int TargetIndex;\r\n // Unused algs that are prioritized in the default list,\r\n // should be merged before the existing custom list\r\n if (Priority)\r\n {\r\n TargetIndex = DefaultIndex;\r\n }\r\n else\r\n {\r\n if (HasWarnAlgo && (DefaultIndex < WarnDefaultIndex))\r\n {\r\n TargetIndex = WarnIndex;\r\n }\r\n else\r\n {\r\n TargetIndex = Index;\r\n }\r\n }\r\n\r\n NewList.insert(NewList.begin() + TargetIndex, DefaultAlgo);\r\n DebugAssert(NewList.back() == AlgoT());\r\n NewList.pop_back();\r\n\r\n if (HasWarnAlgo && (TargetIndex <= WarnIndex))\r\n {\r\n WarnIndex++;\r\n }\r\n\r\n Index++;\r\n }\r\n else\r\n {\r\n Priority = false;\r\n }\r\n }\r\n\r\n if (!std::equal(NewList.begin(), NewList.end(), List))\r\n {\r\n std::copy(NewList.begin(), NewList.end(), List);\r\n Modify();\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetCipherList(UnicodeString value)\r\n{\r\n SetAlgoList(FCiphers, DefaultCipherList, CipherNames, CIPHER_COUNT, cipWarn, value);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetCipherList() const\r\n{\r\n UnicodeString Result;\r\n for (int Index = 0; Index < CIPHER_COUNT; Index++)\r\n {\r\n Result += UnicodeString(Index ? L\",\" : L\"\") + CipherNames[Cipher[Index]];\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetKex(int Index, TKex value)\r\n{\r\n DebugAssert(Index >= 0 && Index < KEX_COUNT);\r\n SET_SESSION_PROPERTY(Kex[Index]);\r\n}\r\n//---------------------------------------------------------------------\r\nTKex __fastcall TSessionData::GetKex(int Index) const\r\n{\r\n DebugAssert(Index >= 0 && Index < KEX_COUNT);\r\n return FKex[Index];\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetKexList(UnicodeString value)\r\n{\r\n SetAlgoList(FKex, DefaultKexList, KexNames, KEX_COUNT, kexWarn, value);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetKexList() const\r\n{\r\n UnicodeString Result;\r\n for (int Index = 0; Index < KEX_COUNT; Index++)\r\n {\r\n Result += UnicodeString(Index ? L\",\" : L\"\") + KexNames[Kex[Index]];\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetHostKeys(int Index, THostKey value)\r\n{\r\n DebugAssert(Index >= 0 && Index < HOSTKEY_COUNT);\r\n SET_SESSION_PROPERTY(HostKeys[Index]);\r\n}\r\n//---------------------------------------------------------------------\r\nTHostKey __fastcall TSessionData::GetHostKeys(int Index) const\r\n{\r\n DebugAssert(Index >= 0 && Index < HOSTKEY_COUNT);\r\n return FHostKeys[Index];\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetHostKeyList(UnicodeString value)\r\n{\r\n SetAlgoList(FHostKeys, DefaultHostKeyList, HostKeyNames, HOSTKEY_COUNT, hkWarn, value);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetHostKeyList() const\r\n{\r\n UnicodeString Result;\r\n for (int Index = 0; Index < HOSTKEY_COUNT; Index++)\r\n {\r\n Result += UnicodeString(Index ? L\",\" : L\"\") + HostKeyNames[HostKeys[Index]];\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetGssLib(int Index, TGssLib value)\r\n{\r\n DebugAssert(Index >= 0 && Index < GSSLIB_COUNT);\r\n SET_SESSION_PROPERTY(GssLib[Index]);\r\n}\r\n//---------------------------------------------------------------------\r\nTGssLib __fastcall TSessionData::GetGssLib(int Index) const\r\n{\r\n DebugAssert(Index >= 0 && Index < GSSLIB_COUNT);\r\n return FGssLib[Index];\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetGssLibList(UnicodeString value)\r\n{\r\n SetAlgoList(FGssLib, DefaultGssLibList, GssLibNames, GSSLIB_COUNT, TGssLib(-1), value);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetGssLibList() const\r\n{\r\n UnicodeString Result;\r\n for (int Index = 0; Index < GSSLIB_COUNT; Index++)\r\n {\r\n Result += UnicodeString(Index ? L\",\" : L\"\") + GssLibNames[GssLib[Index]];\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetGssLibCustom(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(GssLibCustom);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPublicKeyFile(UnicodeString value)\r\n{\r\n if (FPublicKeyFile != value)\r\n {\r\n // PublicKeyFile is key for Passphrase encryption\r\n UnicodeString XPassphrase = Passphrase;\r\n\r\n // StripPathQuotes should not be needed as we do not feed quotes anymore\r\n FPublicKeyFile = StripPathQuotes(value);\r\n Modify();\r\n\r\n Passphrase = XPassphrase;\r\n Shred(XPassphrase);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPassphrase(UnicodeString avalue)\r\n{\r\n RawByteString value = EncryptPassword(avalue, PublicKeyFile);\r\n SET_SESSION_PROPERTY(Passphrase);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetPassphrase() const\r\n{\r\n return DecryptPassword(FPassphrase, PublicKeyFile);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetReturnVar(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(ReturnVar);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetExitCode1IsError(bool value)\r\n{\r\n SET_SESSION_PROPERTY(ExitCode1IsError);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetLookupUserGroups(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(LookupUserGroups);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetEOLType(TEOLType value)\r\n{\r\n SET_SESSION_PROPERTY(EOLType);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTrimVMSVersions(bool value)\r\n{\r\n SET_SESSION_PROPERTY(TrimVMSVersions);\r\n}\r\n//---------------------------------------------------------------------------\r\nTDateTime __fastcall TSessionData::GetTimeoutDT()\r\n{\r\n return SecToDateTime(Timeout);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTimeout(int value)\r\n{\r\n SET_SESSION_PROPERTY(Timeout);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFSProtocol(TFSProtocol value)\r\n{\r\n SET_SESSION_PROPERTY(FSProtocol);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetFSProtocolStr()\r\n{\r\n DebugAssert(FSProtocol >= 0 && FSProtocol < FSPROTOCOL_COUNT);\r\n return FSProtocolNames[FSProtocol];\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetDetectReturnVar(bool value)\r\n{\r\n if (value != DetectReturnVar)\r\n {\r\n ReturnVar = value ? L\"\" : L\"$?\";\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TSessionData::GetDetectReturnVar()\r\n{\r\n return ReturnVar.IsEmpty();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetDefaultShell(bool value)\r\n{\r\n if (value != DefaultShell)\r\n {\r\n Shell = value ? L\"\" : L\"/bin/bash\";\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TSessionData::GetDefaultShell()\r\n{\r\n return Shell.IsEmpty();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPuttyProtocol(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(PuttyProtocol);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetNormalizedPuttyProtocol() const\r\n{\r\n return DefaultStr(PuttyProtocol, PuttySshProtocol);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPingIntervalDT(TDateTime value)\r\n{\r\n unsigned short hour, min, sec, msec;\r\n\r\n value.DecodeTime(&hour, &min, &sec, &msec);\r\n PingInterval = ((int)hour)*SecsPerHour + ((int)min)*SecsPerMin + sec;\r\n}\r\n//---------------------------------------------------------------------------\r\nTDateTime __fastcall TSessionData::GetPingIntervalDT()\r\n{\r\n return SecToDateTime(PingInterval);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPingType(TPingType value)\r\n{\r\n SET_SESSION_PROPERTY(PingType);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetAddressFamily(TAddressFamily value)\r\n{\r\n SET_SESSION_PROPERTY(AddressFamily);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetRekeyData(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(RekeyData);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetRekeyTime(unsigned int value)\r\n{\r\n SET_SESSION_PROPERTY(RekeyTime);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetDefaultSessionName()\r\n{\r\n if (!HostName.IsEmpty() && !UserName.IsEmpty())\r\n {\r\n // If we ever choose to include port number,\r\n // we have to escape IPv6 literals in HostName\r\n return FORMAT(L\"%s@%s\", (UserName, HostName));\r\n }\r\n else if (!HostName.IsEmpty())\r\n {\r\n return HostName;\r\n }\r\n else\r\n {\r\n return L\"session\";\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetNameWithoutHiddenPrefix()\r\n{\r\n UnicodeString Result = Name;\r\n if (Hidden)\r\n {\r\n Result = Result.SubString(TNamedObjectList::HiddenPrefix.Length() + 1, Result.Length() - TNamedObjectList::HiddenPrefix.Length());\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::HasSessionName()\r\n{\r\n return (!GetNameWithoutHiddenPrefix().IsEmpty() && (Name != DefaultName));\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetSessionName()\r\n{\r\n UnicodeString Result;\r\n if (HasSessionName())\r\n {\r\n Result = GetNameWithoutHiddenPrefix();\r\n }\r\n else\r\n {\r\n Result = DefaultSessionName;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::IsSecure()\r\n{\r\n bool Result;\r\n switch (FSProtocol)\r\n {\r\n case fsSCPonly:\r\n case fsSFTP:\r\n case fsSFTPonly:\r\n Result = true;\r\n break;\r\n\r\n case fsFTP:\r\n case fsWebDAV:\r\n case fsS3:\r\n Result = (Ftps != ftpsNone);\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n break;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetProtocolUrl(bool HttpForWebDAV)\r\n{\r\n UnicodeString Url;\r\n switch (FSProtocol)\r\n {\r\n case fsSCPonly:\r\n Url = ScpProtocol;\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n // fallback\r\n case fsSFTP:\r\n case fsSFTPonly:\r\n Url = SftpProtocol;\r\n break;\r\n\r\n case fsFTP:\r\n if (Ftps == ftpsImplicit)\r\n {\r\n Url = FtpsProtocol;\r\n }\r\n else if ((Ftps == ftpsExplicitTls) || (Ftps == ftpsExplicitSsl))\r\n {\r\n Url = FtpesProtocol;\r\n }\r\n else\r\n {\r\n Url = FtpProtocol;\r\n }\r\n break;\r\n\r\n case fsWebDAV:\r\n if (HttpForWebDAV)\r\n {\r\n if (Ftps == ftpsImplicit)\r\n {\r\n Url = HttpsProtocol;\r\n }\r\n else\r\n {\r\n Url = HttpProtocol;\r\n }\r\n }\r\n else\r\n {\r\n if (Ftps == ftpsImplicit)\r\n {\r\n Url = WebDAVSProtocol;\r\n }\r\n else\r\n {\r\n Url = WebDAVProtocol;\r\n }\r\n }\r\n break;\r\n\r\n case fsS3:\r\n Url = S3Protocol;\r\n break;\r\n }\r\n\r\n Url += ProtocolSeparator;\r\n\r\n return Url;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall IsIPv6Literal(const UnicodeString & HostName)\r\n{\r\n bool Result = (HostName.Pos(L\":\") > 0);\r\n if (Result)\r\n {\r\n for (int Index = 1; Result && (Index <= HostName.Length()); Index++)\r\n {\r\n wchar_t C = HostName[Index];\r\n Result = IsHex(C) || (C == L':');\r\n }\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall EscapeIPv6Literal(const UnicodeString & IP)\r\n{\r\n return L\"[\" + IP + L\"]\";\r\n}\r\n//---------------------------------------------------------------------\r\nTStrings * __fastcall TSessionData::GetRawSettingsForUrl()\r\n{\r\n std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L\"\"));\r\n std::unique_ptr<TSessionData> SessionData(Clone());\r\n SessionData->FSProtocol = FactoryDefaults->FSProtocol;\r\n SessionData->HostName = FactoryDefaults->HostName;\r\n SessionData->PortNumber = FactoryDefaults->PortNumber;\r\n SessionData->UserName = FactoryDefaults->UserName;\r\n SessionData->Password = FactoryDefaults->Password;\r\n SessionData->Ftps = FactoryDefaults->Ftps;\r\n SessionData->HostKey = FactoryDefaults->HostKey;\r\n SessionData->CopyNonCoreData(FactoryDefaults.get());\r\n // Cannot be decided in SaveToOptions as it does not have HostName and UserName, so it cannot calculate DefaultSessionName.\r\n bool SaveName = HasSessionName() && (Name != DefaultSessionName);\r\n return SessionData->SaveToOptions(FactoryDefaults.get(), SaveName, false);\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::HasRawSettingsForUrl()\r\n{\r\n std::unique_ptr<TStrings> RawSettings(GetRawSettingsForUrl());\r\n return (RawSettings->Count > 0);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GenerateSessionUrl(unsigned int Flags)\r\n{\r\n UnicodeString Url;\r\n\r\n if (FLAGSET(Flags, sufSpecific))\r\n {\r\n Url += WinSCPProtocolPrefix;\r\n }\r\n\r\n Url += GetProtocolUrl(FLAGSET(Flags, sufHttpForWebDAV));\r\n\r\n if (FLAGSET(Flags, sufUserName) && !UserNameExpanded.IsEmpty())\r\n {\r\n Url += EncodeUrlString(UserNameExpanded);\r\n\r\n if (FLAGSET(Flags, sufPassword) && !Password.IsEmpty())\r\n {\r\n Url += L\":\" + EncodeUrlString(NormalizeString(Password));\r\n }\r\n\r\n if (FLAGSET(Flags, sufHostKey) && !HostKey.IsEmpty())\r\n {\r\n UnicodeString KeyName;\r\n UnicodeString Fingerprint = HostKey;\r\n NormalizeFingerprint(Fingerprint, KeyName);\r\n UnicodeString S = Fingerprint;\r\n if (!KeyName.IsEmpty())\r\n {\r\n S = KeyName + NormalizedFingerprintSeparator + S;\r\n }\r\n S = Base64ToUrlSafe(S); // Noop for MD5 (both in SSH host keys and TLS/SSL)\r\n S = MD5ToUrlSafe(S); // TLS/SSL fingerprints\r\n UnicodeString S2 = EncodeUrlString(S);\r\n DebugAssert(S2 == S2); // There should be nothing left for encoding\r\n\r\n Url +=\r\n UnicodeString(UrlParamSeparator) + UrlHostKeyParamName +\r\n UnicodeString(UrlParamValueSeparator) + S2;\r\n }\r\n\r\n if (FLAGSET(Flags, sufRawSettings))\r\n {\r\n std::unique_ptr<TStrings> RawSettings(GetRawSettingsForUrl());\r\n for (int Index = 0; Index < RawSettings->Count; Index++)\r\n {\r\n Url +=\r\n UnicodeString(UrlParamSeparator) +\r\n UrlRawSettingsParamNamePrefix + EncodeUrlString(LowerCase(RawSettings->Names[Index])) +\r\n UnicodeString(UrlParamValueSeparator) + EncodeUrlString(RawSettings->ValueFromIndex[Index]);\r\n }\r\n }\r\n\r\n Url += L\"@\";\r\n }\r\n\r\n DebugAssert(!HostNameExpanded.IsEmpty());\r\n if (IsIPv6Literal(HostNameExpanded))\r\n {\r\n Url += EscapeIPv6Literal(HostNameExpanded);\r\n }\r\n else\r\n {\r\n Url += EncodeUrlString(HostNameExpanded);\r\n }\r\n\r\n if (PortNumber != DefaultPort(FSProtocol, Ftps))\r\n {\r\n Url += L\":\" + IntToStr(PortNumber);\r\n }\r\n Url += L\"/\";\r\n\r\n return Url;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString ScriptCommandOpenLink(TraceInitStr(ScriptCommandLink(L\"open\")));\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::AddSwitch(\r\n UnicodeString & Result, const UnicodeString & Name, bool Rtf)\r\n{\r\n Result += RtfSwitch(Name, ScriptCommandOpenLink, Rtf);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::AddSwitch(\r\n UnicodeString & Result, const UnicodeString & Name, const UnicodeString & Value, bool Rtf)\r\n{\r\n Result += RtfSwitch(Name, ScriptCommandOpenLink, Value, Rtf);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::AddSwitch(\r\n UnicodeString & Result, const UnicodeString & Name, int Value, bool Rtf)\r\n{\r\n Result += RtfSwitch(Name, ScriptCommandOpenLink, Value, Rtf);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::LookupLastFingerprint()\r\n{\r\n UnicodeString FingerprintType;\r\n if (IsSshProtocol(FSProtocol))\r\n {\r\n FingerprintType = SshFingerprintType;\r\n }\r\n else if (Ftps != ftpsNone)\r\n {\r\n FingerprintType = TlsFingerprintType;\r\n }\r\n\r\n if (!FingerprintType.IsEmpty())\r\n {\r\n HostKey = Configuration->LastFingerprint(SiteKey, FingerprintType);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GenerateOpenCommandArgs(bool Rtf)\r\n{\r\n std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L\"\"));\r\n std::unique_ptr<TSessionData> SessionData(new TSessionData(L\"\"));\r\n\r\n SessionData->Assign(this);\r\n\r\n UnicodeString Result = SessionData->GenerateSessionUrl(sufOpen);\r\n\r\n // Before we reset the FSProtocol\r\n bool AUsesSsh = SessionData->UsesSsh;\r\n // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that\r\n if (SessionData->FSProtocol != fsSFTPonly)\r\n {\r\n SessionData->FSProtocol = FactoryDefaults->FSProtocol;\r\n }\r\n SessionData->HostName = FactoryDefaults->HostName;\r\n SessionData->PortNumber = FactoryDefaults->PortNumber;\r\n SessionData->UserName = FactoryDefaults->UserName;\r\n SessionData->Password = FactoryDefaults->Password;\r\n SessionData->CopyNonCoreData(FactoryDefaults.get());\r\n SessionData->Ftps = FactoryDefaults->Ftps;\r\n\r\n if (SessionData->HostKey != FactoryDefaults->HostKey)\r\n {\r\n UnicodeString SwitchName = AUsesSsh ? L\"hostkey\" : L\"certificate\";\r\n AddSwitch(Result, SwitchName, SessionData->HostKey, Rtf);\r\n SessionData->HostKey = FactoryDefaults->HostKey;\r\n }\r\n if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)\r\n {\r\n AddSwitch(Result, L\"privatekey\", SessionData->PublicKeyFile, Rtf);\r\n SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;\r\n }\r\n if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)\r\n {\r\n AddSwitch(Result, L\"clientcert\", SessionData->TlsCertificateFile, Rtf);\r\n SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;\r\n }\r\n if (SessionData->Passphrase != FactoryDefaults->Passphrase)\r\n {\r\n AddSwitch(Result, PassphraseOption, SessionData->Passphrase, Rtf);\r\n SessionData->Passphrase = FactoryDefaults->Passphrase;\r\n }\r\n if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)\r\n {\r\n AddSwitch(Result, L\"passive\", SessionData->FtpPasvMode ? 1 : 0, Rtf);\r\n SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;\r\n }\r\n if (SessionData->Timeout != FactoryDefaults->Timeout)\r\n {\r\n AddSwitch(Result, L\"timeout\", SessionData->Timeout, Rtf);\r\n SessionData->Timeout = FactoryDefaults->Timeout;\r\n }\r\n\r\n std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get(), false, false));\r\n\r\n if (RawSettings->Count > 0)\r\n {\r\n AddSwitch(Result, RawSettingsOption, Rtf);\r\n\r\n Result += StringsToParams(RawSettings.get());\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString SessionOptionsClassName(L\"SessionOptions\");\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::AddAssemblyProperty(\r\n UnicodeString & Result, TAssemblyLanguage Language,\r\n const UnicodeString & Name, const UnicodeString & Type,\r\n const UnicodeString & Member)\r\n{\r\n Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Type, Member, false);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::AddAssemblyProperty(\r\n UnicodeString & Result, TAssemblyLanguage Language,\r\n const UnicodeString & Name, const UnicodeString & Value)\r\n{\r\n Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::AddAssemblyProperty(\r\n UnicodeString & Result, TAssemblyLanguage Language,\r\n const UnicodeString & Name, int Value)\r\n{\r\n Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::AddAssemblyProperty(\r\n UnicodeString & Result, TAssemblyLanguage Language,\r\n const UnicodeString & Name, bool Value)\r\n{\r\n Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::GenerateAssemblyCode(\r\n TAssemblyLanguage Language, UnicodeString & Head, UnicodeString & Tail, int & Indent)\r\n{\r\n std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L\"\"));\r\n std::unique_ptr<TSessionData> SessionData(Clone());\r\n\r\n switch (Language)\r\n {\r\n case alCSharp:\r\n case alVBNET:\r\n // noop\r\n break;\r\n\r\n case alPowerShell:\r\n Head +=\r\n AssemblyCommentLine(Language, LoadStr(CODE_PS_ADD_TYPE)) +\r\n RtfKeyword(L\"Add-Type\") + RtfText(\" -Path \") + AssemblyString(Language, \"WinSCPnet.dll\") + RtfPara +\r\n RtfPara;\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n break;\r\n }\r\n\r\n Head +=\r\n AssemblyCommentLine(Language, LoadStr(CODE_SESSION_OPTIONS)) +\r\n AssemblyNewClassInstanceStart(Language, SessionOptionsClassName, false);\r\n\r\n UnicodeString ProtocolMember;\r\n switch (SessionData->FSProtocol)\r\n {\r\n case fsSCPonly:\r\n ProtocolMember = \"Scp\";\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n // fallback\r\n case fsSFTP:\r\n case fsSFTPonly:\r\n ProtocolMember = \"Sftp\";\r\n break;\r\n\r\n case fsFTP:\r\n ProtocolMember = \"Ftp\";\r\n break;\r\n\r\n case fsWebDAV:\r\n ProtocolMember = \"Webdav\";\r\n break;\r\n\r\n case fsS3:\r\n ProtocolMember = \"S3\";\r\n break;\r\n }\r\n\r\n // Before we reset the FSProtocol\r\n bool AUsesSsh = SessionData->UsesSsh;\r\n\r\n // Protocol is set unconditionally, we want even the default SFTP\r\n AddAssemblyProperty(Head, Language, L\"Protocol\", L\"Protocol\", ProtocolMember);\r\n // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that\r\n if (SessionData->FSProtocol != fsSFTPonly)\r\n {\r\n SessionData->FSProtocol = FactoryDefaults->FSProtocol;\r\n }\r\n if (SessionData->HostName != FactoryDefaults->HostName)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"HostName\", HostName);\r\n SessionData->HostName = FactoryDefaults->HostName;\r\n }\r\n int ADefaultPort = DefaultPort(FSProtocol, Ftps);\r\n if (SessionData->PortNumber != ADefaultPort)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"PortNumber\", PortNumber);\r\n }\r\n SessionData->PortNumber = FactoryDefaults->PortNumber;\r\n if (SessionData->UserName != FactoryDefaults->UserName)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"UserName\", UserName);\r\n SessionData->UserName = FactoryDefaults->UserName;\r\n }\r\n if (SessionData->Password != FactoryDefaults->Password)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"Password\", NormalizeString(Password));\r\n SessionData->Password = FactoryDefaults->Password;\r\n }\r\n\r\n SessionData->CopyNonCoreData(FactoryDefaults.get());\r\n\r\n if (SessionData->Ftps != FactoryDefaults->Ftps)\r\n {\r\n // SessionData->FSProtocol is reset already\r\n switch (FSProtocol)\r\n {\r\n case fsFTP:\r\n {\r\n UnicodeString FtpSecureMember;\r\n switch (SessionData->Ftps)\r\n {\r\n case ftpsNone:\r\n // noop\r\n break;\r\n\r\n case ftpsImplicit:\r\n FtpSecureMember = L\"Implicit\";\r\n break;\r\n\r\n case ftpsExplicitTls:\r\n case ftpsExplicitSsl:\r\n FtpSecureMember = L\"Explicit\";\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n break;\r\n }\r\n AddAssemblyProperty(Head, Language, L\"FtpSecure\", L\"FtpSecure\", FtpSecureMember);\r\n }\r\n break;\r\n\r\n case fsWebDAV:\r\n AddAssemblyProperty(Head, Language, L\"WebdavSecure\", (SessionData->Ftps != ftpsNone));\r\n break;\r\n\r\n case fsS3:\r\n // implicit\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n break;\r\n }\r\n SessionData->Ftps = FactoryDefaults->Ftps;\r\n }\r\n\r\n if (SessionData->HostKey != FactoryDefaults->HostKey)\r\n {\r\n UnicodeString PropertyName = AUsesSsh ? L\"SshHostKeyFingerprint\" : L\"TlsHostCertificateFingerprint\";\r\n AddAssemblyProperty(Head, Language, PropertyName, SessionData->HostKey);\r\n SessionData->HostKey = FactoryDefaults->HostKey;\r\n }\r\n if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"SshPrivateKeyPath\", SessionData->PublicKeyFile);\r\n SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;\r\n }\r\n if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"TlsClientCertificatePath\", SessionData->TlsCertificateFile);\r\n SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;\r\n }\r\n if (SessionData->Passphrase != FactoryDefaults->Passphrase)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"PrivateKeyPassphrase\", SessionData->Passphrase);\r\n SessionData->Passphrase = FactoryDefaults->Passphrase;\r\n }\r\n if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"FtpMode\", L\"FtpMode\", (SessionData->FtpPasvMode ? L\"Passive\" : L\"Active\"));\r\n SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;\r\n }\r\n if (SessionData->Timeout != FactoryDefaults->Timeout)\r\n {\r\n AddAssemblyProperty(Head, Language, L\"TimeoutInMilliseconds\", SessionData->Timeout * 1000);\r\n SessionData->Timeout = FactoryDefaults->Timeout;\r\n }\r\n\r\n Head += AssemblyNewClassInstanceEnd(Language, false);\r\n\r\n std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get(), false, false));\r\n\r\n UnicodeString SessionOptionsVariableName = AssemblyVariableName(Language, SessionOptionsClassName);\r\n\r\n if (RawSettings->Count > 0)\r\n {\r\n Head +=\r\n RtfPara +\r\n AssemblyAddRawSettings(Language, RawSettings.get(), SessionOptionsClassName, L\"AddRawSettings\");\r\n }\r\n\r\n Head += RtfPara;\r\n\r\n UnicodeString Indentation = L\" \";\r\n UnicodeString SessionVariableName = AssemblyVariableName(Language, SessionClassName);\r\n UnicodeString RtfSessionClass = RtfLibraryClass(SessionClassName);\r\n UnicodeString RtfSessionOpenMethod = RtfLibraryMethod(SessionClassName, L\"Open\", false);\r\n\r\n UnicodeString NewSessionInstance = AssemblyNewClassInstance(Language, SessionClassName, false);\r\n UnicodeString OpenCall =\r\n Indentation + AssemblyCommentLine(Language, LoadStr(CODE_CONNECT)) +\r\n Indentation + RtfText(SessionVariableName + L\".\") + RtfSessionOpenMethod + RtfText(L\"(\" + SessionOptionsVariableName + L\")\") +\r\n AssemblyStatementSeparator(Language) + RtfPara;\r\n\r\n switch (Language)\r\n {\r\n case alCSharp:\r\n Head +=\r\n RtfKeyword(L\"using\") + RtfText(\" (\") + NewSessionInstance + RtfText(L\"())\") + RtfPara +\r\n RtfText(L\"{\") + RtfPara +\r\n OpenCall;\r\n\r\n Tail =\r\n RtfText(L\"}\") + RtfPara;\r\n break;\r\n\r\n case alVBNET:\r\n Head +=\r\n RtfKeyword(L\"Using\") + RtfText(L\" \") + NewSessionInstance + RtfPara +\r\n OpenCall;\r\n\r\n Tail =\r\n RtfKeyword(L\"End Using\") + RtfPara;\r\n break;\r\n\r\n case alPowerShell:\r\n Head +=\r\n NewSessionInstance + RtfPara +\r\n RtfPara +\r\n RtfKeyword(L\"try\") + RtfPara +\r\n RtfText(L\"{\") + RtfPara +\r\n OpenCall;\r\n\r\n Tail =\r\n RtfText(L\"}\") + RtfPara +\r\n RtfKeyword(L\"finally\") + RtfPara +\r\n RtfText(L\"{\") + RtfPara +\r\n RtfText(Indentation + SessionVariableName + L\".\") +\r\n RtfLibraryMethod(SessionClassName, L\"Dispose\", false) + RtfText(L\"()\") + RtfPara +\r\n RtfText(L\"}\") + RtfPara;\r\n break;\r\n }\r\n\r\n Head += RtfPara;\r\n\r\n Indent = 4; // the same for all languages so far\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTimeDifference(TDateTime value)\r\n{\r\n SET_SESSION_PROPERTY(TimeDifference);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTimeDifferenceAuto(bool value)\r\n{\r\n SET_SESSION_PROPERTY(TimeDifferenceAuto);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetLocalDirectory(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(LocalDirectory);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetLocalDirectoryExpanded()\r\n{\r\n return ExpandFileName(::ExpandEnvironmentVariables(LocalDirectory));\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetRemoteDirectory(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(RemoteDirectory);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSynchronizeBrowsing(bool value)\r\n{\r\n SET_SESSION_PROPERTY(SynchronizeBrowsing);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetUpdateDirectories(bool value)\r\n{\r\n SET_SESSION_PROPERTY(UpdateDirectories);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetCacheDirectories(bool value)\r\n{\r\n SET_SESSION_PROPERTY(CacheDirectories);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetCacheDirectoryChanges(bool value)\r\n{\r\n SET_SESSION_PROPERTY(CacheDirectoryChanges);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPreserveDirectoryChanges(bool value)\r\n{\r\n SET_SESSION_PROPERTY(PreserveDirectoryChanges);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetResolveSymlinks(bool value)\r\n{\r\n SET_SESSION_PROPERTY(ResolveSymlinks);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFollowDirectorySymlinks(bool value)\r\n{\r\n SET_SESSION_PROPERTY(FollowDirectorySymlinks);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetDSTMode(TDSTMode value)\r\n{\r\n SET_SESSION_PROPERTY(DSTMode);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetDeleteToRecycleBin(bool value)\r\n{\r\n SET_SESSION_PROPERTY(DeleteToRecycleBin);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetOverwrittenToRecycleBin(bool value)\r\n{\r\n SET_SESSION_PROPERTY(OverwrittenToRecycleBin);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetRecycleBinPath(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(RecycleBinPath);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPostLoginCommands(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(PostLoginCommands);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetLockInHome(bool value)\r\n{\r\n SET_SESSION_PROPERTY(LockInHome);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSpecial(bool value)\r\n{\r\n SET_SESSION_PROPERTY(Special);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetScp1Compatibility(bool value)\r\n{\r\n SET_SESSION_PROPERTY(Scp1Compatibility);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTcpNoDelay(bool value)\r\n{\r\n SET_SESSION_PROPERTY(TcpNoDelay);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSendBuf(int value)\r\n{\r\n SET_SESSION_PROPERTY(SendBuf);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSourceAddress(const UnicodeString & value)\r\n{\r\n SET_SESSION_PROPERTY(SourceAddress);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSshSimple(bool value)\r\n{\r\n SET_SESSION_PROPERTY(SshSimple);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyMethod(TProxyMethod value)\r\n{\r\n SET_SESSION_PROPERTY(ProxyMethod);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyHost(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(ProxyHost);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyPort(int value)\r\n{\r\n SET_SESSION_PROPERTY(ProxyPort);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyUsername(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(ProxyUsername);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyPassword(UnicodeString avalue)\r\n{\r\n RawByteString value = EncryptPassword(avalue, ProxyUsername+ProxyHost);\r\n SET_SESSION_PROPERTY(ProxyPassword);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetProxyPassword() const\r\n{\r\n return DecryptPassword(FProxyPassword, ProxyUsername+ProxyHost);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyTelnetCommand(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(ProxyTelnetCommand);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyLocalCommand(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(ProxyLocalCommand);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyDNS(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(ProxyDNS);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetProxyLocalhost(bool value)\r\n{\r\n SET_SESSION_PROPERTY(ProxyLocalhost);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpProxyLogonType(int value)\r\n{\r\n SET_SESSION_PROPERTY(FtpProxyLogonType);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetBug(TSshBug Bug, TAutoSwitch value)\r\n{\r\n DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));\r\n SET_SESSION_PROPERTY(Bugs[Bug]);\r\n}\r\n//---------------------------------------------------------------------\r\nTAutoSwitch __fastcall TSessionData::GetBug(TSshBug Bug) const\r\n{\r\n DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));\r\n return FBugs[Bug];\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetPuttySettings(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(PuttySettings);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetCustomParam1(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(CustomParam1);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetCustomParam2(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(CustomParam2);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSFTPDownloadQueue(int value)\r\n{\r\n SET_SESSION_PROPERTY(SFTPDownloadQueue);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSFTPUploadQueue(int value)\r\n{\r\n SET_SESSION_PROPERTY(SFTPUploadQueue);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSFTPListingQueue(int value)\r\n{\r\n SET_SESSION_PROPERTY(SFTPListingQueue);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSFTPMaxVersion(int value)\r\n{\r\n SET_SESSION_PROPERTY(SFTPMaxVersion);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSFTPMaxPacketSize(unsigned long value)\r\n{\r\n SET_SESSION_PROPERTY(SFTPMaxPacketSize);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSFTPBug(TSftpBug Bug, TAutoSwitch value)\r\n{\r\n DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));\r\n SET_SESSION_PROPERTY(SFTPBugs[Bug]);\r\n}\r\n//---------------------------------------------------------------------\r\nTAutoSwitch __fastcall TSessionData::GetSFTPBug(TSftpBug Bug) const\r\n{\r\n DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));\r\n return FSFTPBugs[Bug];\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSCPLsFullTime(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(SCPLsFullTime);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetColor(int value)\r\n{\r\n SET_SESSION_PROPERTY(Color);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnel(bool value)\r\n{\r\n SET_SESSION_PROPERTY(Tunnel);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnelHostName(UnicodeString value)\r\n{\r\n if (FTunnelHostName != value)\r\n {\r\n // HostName is key for password encryption\r\n UnicodeString XTunnelPassword = TunnelPassword;\r\n\r\n int P = value.LastDelimiter(L\"@\");\r\n if (P > 0)\r\n {\r\n TunnelUserName = value.SubString(1, P - 1);\r\n value = value.SubString(P + 1, value.Length() - P);\r\n }\r\n FTunnelHostName = value;\r\n Modify();\r\n\r\n TunnelPassword = XTunnelPassword;\r\n Shred(XTunnelPassword);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnelPortNumber(int value)\r\n{\r\n SET_SESSION_PROPERTY(TunnelPortNumber);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnelUserName(UnicodeString value)\r\n{\r\n // Avoid password recryption (what may popup master password prompt)\r\n if (FTunnelUserName != value)\r\n {\r\n // TunnelUserName is key for password encryption\r\n UnicodeString XTunnelPassword = TunnelPassword;\r\n SET_SESSION_PROPERTY(TunnelUserName);\r\n TunnelPassword = XTunnelPassword;\r\n Shred(XTunnelPassword);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnelPassword(UnicodeString avalue)\r\n{\r\n RawByteString value = EncryptPassword(avalue, TunnelUserName+TunnelHostName);\r\n SET_SESSION_PROPERTY(TunnelPassword);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetTunnelPassword() const\r\n{\r\n return DecryptPassword(FTunnelPassword, TunnelUserName+TunnelHostName);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnelPublicKeyFile(UnicodeString value)\r\n{\r\n if (FTunnelPublicKeyFile != value)\r\n {\r\n // StripPathQuotes should not be needed as we do not feed quotes anymore\r\n FTunnelPublicKeyFile = StripPathQuotes(value);\r\n Modify();\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnelLocalPortNumber(int value)\r\n{\r\n SET_SESSION_PROPERTY(TunnelLocalPortNumber);\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TSessionData::GetTunnelAutoassignLocalPortNumber()\r\n{\r\n return (FTunnelLocalPortNumber <= 0);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnelPortFwd(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(TunnelPortFwd);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTunnelHostKey(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(TunnelHostKey);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpPasvMode(bool value)\r\n{\r\n SET_SESSION_PROPERTY(FtpPasvMode);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpForcePasvIp(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(FtpForcePasvIp);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpUseMlsd(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(FtpUseMlsd);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpAccount(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(FtpAccount);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpPingInterval(int value)\r\n{\r\n SET_SESSION_PROPERTY(FtpPingInterval);\r\n}\r\n//---------------------------------------------------------------------------\r\nTDateTime __fastcall TSessionData::GetFtpPingIntervalDT()\r\n{\r\n return SecToDateTime(FtpPingInterval);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpPingType(TPingType value)\r\n{\r\n SET_SESSION_PROPERTY(FtpPingType);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpTransferActiveImmediately(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(FtpTransferActiveImmediately);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtps(TFtps value)\r\n{\r\n SET_SESSION_PROPERTY(Ftps);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetMinTlsVersion(TTlsVersion value)\r\n{\r\n SET_SESSION_PROPERTY(MinTlsVersion);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetMaxTlsVersion(TTlsVersion value)\r\n{\r\n SET_SESSION_PROPERTY(MaxTlsVersion);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetLogicalHostName(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(LogicalHostName);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpListAll(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(FtpListAll);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpHost(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(FtpHost);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetFtpDeleteFromCwd(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(FtpDeleteFromCwd);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetSslSessionReuse(bool value)\r\n{\r\n SET_SESSION_PROPERTY(SslSessionReuse);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetTlsCertificateFile(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(TlsCertificateFile);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetNotUtf(TAutoSwitch value)\r\n{\r\n SET_SESSION_PROPERTY(NotUtf);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetInternalEditorEncoding(int value)\r\n{\r\n SET_SESSION_PROPERTY(InternalEditorEncoding);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetS3DefaultRegion(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(S3DefaultRegion);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetS3UrlStyle(TS3UrlStyle value)\r\n{\r\n SET_SESSION_PROPERTY(S3UrlStyle);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetIsWorkspace(bool value)\r\n{\r\n SET_SESSION_PROPERTY(IsWorkspace);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetLink(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(Link);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetNameOverride(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(NameOverride);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetHostKey(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(HostKey);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetNote(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(Note);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetWinTitle(UnicodeString value)\r\n{\r\n SET_SESSION_PROPERTY(WinTitle);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetEncryptKey() const\r\n{\r\n return DecryptPassword(FEncryptKey, UserName+HostName);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::SetEncryptKey(UnicodeString avalue)\r\n{\r\n RawByteString value = EncryptPassword(avalue, UserName+HostName);\r\n SET_SESSION_PROPERTY(EncryptKey);\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetInfoTip()\r\n{\r\n if (UsesSsh)\r\n {\r\n return FMTLOAD(SESSION_INFO_TIP2,\r\n (HostName, UserName,\r\n (PublicKeyFile.IsEmpty() ? LoadStr(NO_STR) : LoadStr(YES_STR)),\r\n FSProtocolStr));\r\n }\r\n else\r\n {\r\n return FMTLOAD(SESSION_INFO_TIP_NO_SSH,\r\n (HostName, UserName, FSProtocolStr));\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::ExtractLocalName(const UnicodeString & Name)\r\n{\r\n UnicodeString Result = Name;\r\n int P = Result.LastDelimiter(L\"/\");\r\n if (P > 0)\r\n {\r\n Result.Delete(1, P);\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetLocalName()\r\n{\r\n UnicodeString Result;\r\n if (HasSessionName())\r\n {\r\n Result = ExtractLocalName(Name);\r\n }\r\n else\r\n {\r\n Result = DefaultSessionName;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::ExtractFolderName(const UnicodeString & Name)\r\n{\r\n UnicodeString Result;\r\n int P = Name.LastDelimiter(L\"/\");\r\n if (P > 0)\r\n {\r\n Result = Name.SubString(1, P - 1);\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::GetFolderName()\r\n{\r\n UnicodeString Result;\r\n if (HasSessionName() || IsWorkspace)\r\n {\r\n Result = ExtractFolderName(Name);\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString __fastcall TSessionData::ComposePath(\r\n const UnicodeString & Path, const UnicodeString & Name)\r\n{\r\n return UnixIncludeTrailingBackslash(Path) + Name;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TSessionData::DisableAuthentationsExceptPassword()\r\n{\r\n SshNoUserAuth = false;\r\n AuthTIS = false;\r\n AuthKI = false;\r\n AuthKIPassword = false;\r\n AuthGSSAPI = false;\r\n PublicKeyFile = L\"\";\r\n TlsCertificateFile = L\"\";\r\n Passphrase = L\"\";\r\n TryAgent = false;\r\n}\r\n//---------------------------------------------------------------------\r\nTStrings * TSessionData::GetAllOptionNames(bool PuttyExport)\r\n{\r\n std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L\"\"));\r\n return FactoryDefaults->SaveToOptions(NULL, false, PuttyExport);\r\n}\r\n//=== TStoredSessionList ----------------------------------------------\r\n__fastcall TStoredSessionList::TStoredSessionList(bool aReadOnly):\r\n TNamedObjectList(), FReadOnly(aReadOnly)\r\n{\r\n DebugAssert(Configuration);\r\n FDefaultSettings = new TSessionData(DefaultName);\r\n FPendingRemovals.reset(new TStringList());\r\n}\r\n//---------------------------------------------------------------------\r\n__fastcall TStoredSessionList::~TStoredSessionList()\r\n{\r\n DebugAssert(Configuration);\r\n delete FDefaultSettings;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::Load(THierarchicalStorage * Storage,\r\n bool AsModified, bool UseDefaults, bool PuttyImport)\r\n{\r\n TStringList *SubKeys = new TStringList();\r\n TList * Loaded = new TList;\r\n try\r\n {\r\n DebugAssert(AutoSort);\r\n AutoSort = false;\r\n bool WasEmpty = (Count == 0);\r\n\r\n Storage->GetSubKeyNames(SubKeys);\r\n\r\n for (int Index = 0; Index < SubKeys->Count; Index++)\r\n {\r\n UnicodeString SessionName = SubKeys->Strings[Index];\r\n\r\n bool ValidName = true;\r\n try\r\n {\r\n TSessionData::ValidatePath(SessionName);\r\n }\r\n catch(...)\r\n {\r\n ValidName = false;\r\n }\r\n\r\n if (ValidName)\r\n {\r\n TSessionData * SessionData;\r\n if (SessionName == FDefaultSettings->Name)\r\n {\r\n SessionData = FDefaultSettings;\r\n }\r\n else\r\n {\r\n // if the list was empty before loading, do not waste time trying to\r\n // find existing sites to overwrite (we rely on underlying storage\r\n // to secure uniqueness of the key names)\r\n if (WasEmpty)\r\n {\r\n SessionData = NULL;\r\n }\r\n else\r\n {\r\n SessionData = (TSessionData*)FindByName(SessionName);\r\n }\r\n }\r\n\r\n if ((SessionData != FDefaultSettings) || !UseDefaults)\r\n {\r\n if (SessionData == NULL)\r\n {\r\n SessionData = new TSessionData(L\"\");\r\n if (UseDefaults)\r\n {\r\n SessionData->CopyData(DefaultSettings);\r\n }\r\n SessionData->Name = SessionName;\r\n Add(SessionData);\r\n }\r\n Loaded->Add(SessionData);\r\n SessionData->Load(Storage, PuttyImport);\r\n if (AsModified)\r\n {\r\n SessionData->Modified = true;\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (!AsModified)\r\n {\r\n for (int Index = 0; Index < TObjectList::Count; Index++)\r\n {\r\n if (Loaded->IndexOf(Items[Index]) < 0)\r\n {\r\n Delete(Index);\r\n Index--;\r\n }\r\n }\r\n }\r\n }\r\n __finally\r\n {\r\n AutoSort = true;\r\n AlphaSort();\r\n delete SubKeys;\r\n delete Loaded;\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::Reload()\r\n{\r\n if (Count <= Configuration->DontReloadMoreThanSessions)\r\n {\r\n bool SessionList = true;\r\n std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(SessionList));\r\n if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, False))\r\n {\r\n Load(Storage.get());\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,\r\n TSessionData * Data, bool All, bool RecryptPasswordOnly,\r\n TSessionData * FactoryDefaults)\r\n{\r\n if (All || Data->Modified)\r\n {\r\n if (RecryptPasswordOnly)\r\n {\r\n Data->SaveRecryptedPasswords(Storage);\r\n }\r\n else\r\n {\r\n Data->Save(Storage, false, FactoryDefaults);\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,\r\n bool All, bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)\r\n{\r\n TSessionData * FactoryDefaults = new TSessionData(L\"\");\r\n try\r\n {\r\n while (FPendingRemovals->Count > 0)\r\n {\r\n TSessionData::Remove(Storage, FPendingRemovals->Strings[0]);\r\n FPendingRemovals->Delete(0);\r\n }\r\n\r\n DoSave(Storage, FDefaultSettings, All, RecryptPasswordOnly, FactoryDefaults);\r\n for (int Index = 0; Index < CountIncludingHidden; Index++)\r\n {\r\n TSessionData * SessionData = (TSessionData *)Items[Index];\r\n try\r\n {\r\n DoSave(Storage, SessionData, All, RecryptPasswordOnly, FactoryDefaults);\r\n }\r\n catch (Exception & E)\r\n {\r\n UnicodeString Message;\r\n if (RecryptPasswordOnly && DebugAlwaysTrue(RecryptPasswordErrors != NULL) &&\r\n ExceptionMessage(&E, Message))\r\n {\r\n RecryptPasswordErrors->Add(FORMAT(\"%s: %s\", (SessionData->SessionName, Message)));\r\n }\r\n else\r\n {\r\n throw;\r\n }\r\n }\r\n }\r\n }\r\n __finally\r\n {\r\n delete FactoryDefaults;\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::Save(THierarchicalStorage * Storage, bool All)\r\n{\r\n DoSave(Storage, All, false, NULL);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::DoSave(bool All, bool Explicit,\r\n bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)\r\n{\r\n bool SessionList = true;\r\n THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);\r\n try\r\n {\r\n Storage->AccessMode = smReadWrite;\r\n Storage->Explicit = Explicit;\r\n if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))\r\n {\r\n DoSave(Storage, All, RecryptPasswordOnly, RecryptPasswordErrors);\r\n }\r\n }\r\n __finally\r\n {\r\n delete Storage;\r\n }\r\n\r\n Saved();\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::Save(bool All, bool Explicit)\r\n{\r\n DoSave(All, Explicit, false, NULL);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::RecryptPasswords(TStrings * RecryptPasswordErrors)\r\n{\r\n DoSave(true, true, true, RecryptPasswordErrors);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::Saved()\r\n{\r\n FDefaultSettings->Modified = false;\r\n for (int Index = 0; Index < CountIncludingHidden; Index++)\r\n {\r\n ((TSessionData *)Items[Index])->Modified = false;\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::ImportLevelFromFilezilla(\r\n _di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode)\r\n{\r\n for (int Index = 0; Index < Node->ChildNodes->Count; Index++)\r\n {\r\n _di_IXMLNode ChildNode = Node->ChildNodes->Get(Index);\r\n if (ChildNode->NodeName == L\"Server\")\r\n {\r\n std::unique_ptr<TSessionData> SessionData(new TSessionData(L\"\"));\r\n SessionData->CopyData(DefaultSettings);\r\n SessionData->ImportFromFilezilla(ChildNode, Path, SettingsNode);\r\n Add(SessionData.release());\r\n }\r\n else if (ChildNode->NodeName == L\"Folder\")\r\n {\r\n UnicodeString Name;\r\n\r\n for (int Index = 0; Index < ChildNode->ChildNodes->Count; Index++)\r\n {\r\n _di_IXMLNode PossibleTextMode = ChildNode->ChildNodes->Get(Index);\r\n if (PossibleTextMode->NodeType == ntText)\r\n {\r\n UnicodeString NodeValue = PossibleTextMode->NodeValue;\r\n AddToList(Name, NodeValue.Trim(), L\" \");\r\n }\r\n }\r\n\r\n Name = TSessionData::MakeValidName(Name).Trim();\r\n\r\n ImportLevelFromFilezilla(ChildNode, TSessionData::ComposePath(Path, Name), SettingsNode);\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::ImportFromFilezilla(\r\n const UnicodeString FileName, const UnicodeString ConfigurationFileName)\r\n{\r\n\r\n // not sure if the document must exists if we want to use its node\r\n _di_IXMLDocument ConfigurationDocument;\r\n _di_IXMLNode SettingsNode;\r\n\r\n if (FileExists(ApiPath(ConfigurationFileName)))\r\n {\r\n ConfigurationDocument = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));\r\n ConfigurationDocument->LoadFromFile(ConfigurationFileName);\r\n _di_IXMLNode FileZilla3Node = ConfigurationDocument->ChildNodes->FindNode(L\"FileZilla3\");\r\n if (FileZilla3Node != NULL)\r\n {\r\n SettingsNode = FileZilla3Node->ChildNodes->FindNode(L\"Settings\");\r\n }\r\n }\r\n\r\n const _di_IXMLDocument Document = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));\r\n Document->LoadFromFile(FileName);\r\n _di_IXMLNode FileZilla3Node = Document->ChildNodes->FindNode(L\"FileZilla3\");\r\n if (FileZilla3Node != NULL)\r\n {\r\n _di_IXMLNode ServersNode = FileZilla3Node->ChildNodes->FindNode(L\"Servers\");\r\n if (ServersNode != NULL)\r\n {\r\n ImportLevelFromFilezilla(ServersNode, L\"\", SettingsNode);\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::ImportFromKnownHosts(TStrings * Lines)\r\n{\r\n bool SessionList = false;\r\n std::unique_ptr<THierarchicalStorage> HostKeyStorage(Configuration->CreateScpStorage(SessionList));\r\n std::unique_ptr<TStrings> KeyList(new TStringList());\r\n if (OpenHostKeysSubKey(HostKeyStorage.get(), false))\r\n {\r\n HostKeyStorage->GetValueNames(KeyList.get());\r\n }\r\n HostKeyStorage.reset(NULL);\r\n\r\n UnicodeString FirstError;\r\n for (int Index = 0; Index < Lines->Count; Index++)\r\n {\r\n try\r\n {\r\n UnicodeString Line = Lines->Strings[Index];\r\n Line = Trim(Line);\r\n if (!Line.IsEmpty() && (Line[1] != L';'))\r\n {\r\n int P = Pos(L' ', Line);\r\n if (P > 0)\r\n {\r\n UnicodeString HostNameStr = Line.SubString(1, P - 1);\r\n Line = Line.SubString(P + 1, Line.Length() - P);\r\n\r\n P = Pos(L',', HostNameStr);\r\n if (P > 0)\r\n {\r\n HostNameStr.SetLength(P - 1);\r\n }\r\n P = Pos(L':', HostNameStr);\r\n int PortNumber = -1;\r\n if (P > 0)\r\n {\r\n UnicodeString PortNumberStr = HostNameStr.SubString(P + 1, HostNameStr.Length() - P);\r\n PortNumber = StrToInt(PortNumberStr);\r\n HostNameStr.SetLength(P - 1);\r\n }\r\n if ((HostNameStr.Length() >= 2) &&\r\n (HostNameStr[1] == L'[') && (HostNameStr[HostNameStr.Length()] == L']'))\r\n {\r\n HostNameStr = HostNameStr.SubString(2, HostNameStr.Length() - 2);\r\n }\r\n\r\n UnicodeString NameStr = HostNameStr;\r\n if (PortNumber >= 0)\r\n {\r\n NameStr = FORMAT(L\"%s:%d\", (NameStr, PortNumber));\r\n }\r\n\r\n std::unique_ptr<TSessionData> SessionDataOwner;\r\n TSessionData * SessionData = dynamic_cast<TSessionData *>(FindByName(NameStr));\r\n if (SessionData == NULL)\r\n {\r\n SessionData = new TSessionData(L\"\");\r\n SessionDataOwner.reset(SessionData);\r\n SessionData->CopyData(DefaultSettings);\r\n SessionData->Name = NameStr;\r\n SessionData->HostName = HostNameStr;\r\n if (PortNumber >= 0)\r\n {\r\n SessionData->PortNumber = PortNumber;\r\n }\r\n }\r\n\r\n const struct ssh_keyalg * Algorithm;\r\n UnicodeString Key = ParseOpenSshPubLine(Line, Algorithm);\r\n UnicodeString KeyKey =\r\n FORMAT(L\"%s@%d:%s\", (Algorithm->cache_id, SessionData->PortNumber, HostNameStr));\r\n UnicodeString HostKey =\r\n FORMAT(L\"%s:%s=%s\", (Algorithm->ssh_id, KeyKey, Key));\r\n UnicodeString HostKeyList = SessionData->HostKey;\r\n AddToList(HostKeyList, HostKey, L\";\");\r\n SessionData->HostKey = HostKeyList;\r\n // If there's at least one unknown key type for this host, select it\r\n if (KeyList->IndexOf(KeyKey) < 0)\r\n {\r\n SessionData->Selected = true;\r\n }\r\n\r\n if (SessionDataOwner.get() != NULL)\r\n {\r\n Add(SessionDataOwner.release());\r\n }\r\n }\r\n }\r\n }\r\n catch (Exception & E)\r\n {\r\n if (FirstError.IsEmpty())\r\n {\r\n FirstError = E.Message;\r\n }\r\n }\r\n }\r\n\r\n if (Count == 0)\r\n {\r\n UnicodeString Message = LoadStr(KNOWN_HOSTS_NO_SITES);\r\n if (!FirstError.IsEmpty())\r\n {\r\n Message = FORMAT(L\"%s\\n(%s)\", (Message, FirstError));\r\n }\r\n\r\n throw Exception(Message);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::Export(const UnicodeString FileName)\r\n{\r\n THierarchicalStorage * Storage = TIniFileStorage::CreateFromPath(FileName);\r\n try\r\n {\r\n Storage->AccessMode = smReadWrite;\r\n if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))\r\n {\r\n Save(Storage, true);\r\n }\r\n }\r\n __finally\r\n {\r\n delete Storage;\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::SelectAll(bool Select)\r\n{\r\n for (int Index = 0; Index < Count; Index++)\r\n Sessions[Index]->Selected = Select;\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::Import(TStoredSessionList * From,\r\n bool OnlySelected, TList * Imported)\r\n{\r\n for (int Index = 0; Index < From->Count; Index++)\r\n {\r\n if (!OnlySelected || From->Sessions[Index]->Selected)\r\n {\r\n TSessionData *Session = new TSessionData(L\"\");\r\n Session->Assign(From->Sessions[Index]);\r\n Session->Modified = true;\r\n Session->MakeUniqueIn(this);\r\n Add(Session);\r\n if (Imported != NULL)\r\n {\r\n Imported->Add(Session);\r\n }\r\n }\r\n }\r\n // only modified, explicit\r\n Save(false, true);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::SelectSessionsToImport\r\n (TStoredSessionList * Dest, bool SSHOnly)\r\n{\r\n for (int Index = 0; Index < Count; Index++)\r\n {\r\n Sessions[Index]->Selected =\r\n (!SSHOnly || (Sessions[Index]->GetNormalizedPuttyProtocol() == PuttySshProtocol)) &&\r\n !Dest->FindByName(Sessions[Index]->Name);\r\n }\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::Cleanup()\r\n{\r\n try\r\n {\r\n if (Configuration->Storage == stRegistry) Clear();\r\n TRegistryStorage * Storage = new TRegistryStorage(Configuration->RegistryStorageKey);\r\n try\r\n {\r\n Storage->AccessMode = smReadWrite;\r\n if (Storage->OpenRootKey(False))\r\n Storage->RecursiveDeleteSubKey(Configuration->StoredSessionsSubKey);\r\n }\r\n __finally\r\n {\r\n delete Storage;\r\n }\r\n }\r\n catch (Exception &E)\r\n {\r\n throw ExtException(&E, LoadStr(CLEANUP_SESSIONS_ERROR));\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::UpdateStaticUsage()\r\n{\r\n int SCP = 0;\r\n int SFTP = 0;\r\n int FTP = 0;\r\n int FTPS = 0;\r\n int WebDAV = 0;\r\n int WebDAVS = 0;\r\n int S3 = 0;\r\n int Password = 0;\r\n int Advanced = 0;\r\n int Color = 0;\r\n int Note = 0;\r\n int Tunnel = 0;\r\n bool Folders = false;\r\n bool Workspaces = false;\r\n std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L\"\"));\r\n std::unique_ptr<TStringList> DifferentAdvancedProperties(CreateSortedStringList());\r\n for (int Index = 0; Index < Count; Index++)\r\n {\r\n TSessionData * Data = Sessions[Index];\r\n if (Data->IsWorkspace)\r\n {\r\n Workspaces = true;\r\n }\r\n else\r\n {\r\n switch (Data->FSProtocol)\r\n {\r\n case fsSCPonly:\r\n SCP++;\r\n break;\r\n\r\n case fsSFTP:\r\n case fsSFTPonly:\r\n SFTP++;\r\n break;\r\n\r\n case fsFTP:\r\n if (Data->Ftps == ftpsNone)\r\n {\r\n FTP++;\r\n }\r\n else\r\n {\r\n FTPS++;\r\n }\r\n break;\r\n\r\n case fsWebDAV:\r\n if (Data->Ftps == ftpsNone)\r\n {\r\n WebDAV++;\r\n }\r\n else\r\n {\r\n WebDAVS++;\r\n }\r\n break;\r\n\r\n case fsS3:\r\n S3++;\r\n break;\r\n }\r\n\r\n if (Data->HasAnySessionPassword())\r\n {\r\n Password++;\r\n }\r\n\r\n if (Data->Color != 0)\r\n {\r\n Color++;\r\n }\r\n\r\n if (!Data->Note.IsEmpty())\r\n {\r\n Note++;\r\n }\r\n\r\n // This would not work for passwords, as they are compared in their encrypted form.\r\n // But there are no passwords set in factory defaults anyway.\r\n if (!Data->IsSame(FactoryDefaults.get(), true, DifferentAdvancedProperties.get(), false))\r\n {\r\n Advanced++;\r\n }\r\n\r\n if (Data->Tunnel)\r\n {\r\n Tunnel++;\r\n }\r\n\r\n if (!Data->FolderName.IsEmpty())\r\n {\r\n Folders = true;\r\n }\r\n }\r\n }\r\n\r\n Configuration->Usage->Set(L\"StoredSessionsCountSCP\", SCP);\r\n Configuration->Usage->Set(L\"StoredSessionsCountSFTP\", SFTP);\r\n Configuration->Usage->Set(L\"StoredSessionsCountFTP\", FTP);\r\n Configuration->Usage->Set(L\"StoredSessionsCountFTPS\", FTPS);\r\n Configuration->Usage->Set(L\"StoredSessionsCountWebDAV\", WebDAV);\r\n Configuration->Usage->Set(L\"StoredSessionsCountWebDAVS\", WebDAVS);\r\n Configuration->Usage->Set(L\"StoredSessionsCountS3\", S3);\r\n Configuration->Usage->Set(L\"StoredSessionsCountPassword\", Password);\r\n Configuration->Usage->Set(L\"StoredSessionsCountColor\", Color);\r\n Configuration->Usage->Set(L\"StoredSessionsCountNote\", Note);\r\n Configuration->Usage->Set(L\"StoredSessionsCountAdvanced\", Advanced);\r\n DifferentAdvancedProperties->Delimiter = L',';\r\n Configuration->Usage->Set(L\"StoredSessionsAdvancedSettings\", DifferentAdvancedProperties->DelimitedText);\r\n Configuration->Usage->Set(L\"StoredSessionsCountTunnel\", Tunnel);\r\n\r\n // actually default might be true, see below for when the default is actually used\r\n bool CustomDefaultStoredSession = false;\r\n try\r\n {\r\n // this can throw, when the default session settings have password set\r\n // (and no other basic property, like hostname/username),\r\n // and master password is enabled as we are called before master password\r\n // handler is set\r\n CustomDefaultStoredSession = !FDefaultSettings->IsSame(FactoryDefaults.get(), false);\r\n }\r\n catch (...)\r\n {\r\n }\r\n Configuration->Usage->Set(L\"UsingDefaultStoredSession\", CustomDefaultStoredSession);\r\n\r\n Configuration->Usage->Set(L\"UsingStoredSessionsFolders\", Folders);\r\n Configuration->Usage->Set(L\"UsingWorkspaces\", Workspaces);\r\n}\r\n//---------------------------------------------------------------------------\r\nTSessionData * __fastcall TStoredSessionList::FindSame(TSessionData * Data)\r\n{\r\n TSessionData * Result;\r\n if (Data->Hidden || Data->Name.IsEmpty() || Data->IsWorkspace)\r\n {\r\n Result = NULL;\r\n }\r\n else\r\n {\r\n Result = dynamic_cast<TSessionData *>(FindByName(Data->Name));\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall TStoredSessionList::IndexOf(TSessionData * Data)\r\n{\r\n for (int Index = 0; Index < Count; Index++)\r\n if (Data == Sessions[Index]) return Index;\r\n return -1;\r\n}\r\n//---------------------------------------------------------------------------\r\nTSessionData * __fastcall TStoredSessionList::NewSession(\r\n UnicodeString SessionName, TSessionData * Session)\r\n{\r\n TSessionData * DuplicateSession = (TSessionData*)FindByName(SessionName);\r\n if (!DuplicateSession)\r\n {\r\n DuplicateSession = new TSessionData(L\"\");\r\n DuplicateSession->Assign(Session);\r\n DuplicateSession->Name = SessionName;\r\n // make sure, that new stored session is saved to registry\r\n DuplicateSession->Modified = true;\r\n Add(DuplicateSession);\r\n }\r\n else\r\n {\r\n DuplicateSession->Assign(Session);\r\n DuplicateSession->Name = SessionName;\r\n DuplicateSession->Modified = true;\r\n }\r\n // list was saved here before to default storage, but it would not allow\r\n // to work with special lists (export/import) not using default storage\r\n return DuplicateSession;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::SetDefaultSettings(TSessionData * value)\r\n{\r\n DebugAssert(FDefaultSettings);\r\n if (FDefaultSettings != value)\r\n {\r\n FDefaultSettings->Assign(value);\r\n // make sure default settings are saved\r\n FDefaultSettings->Modified = true;\r\n FDefaultSettings->Name = DefaultName;\r\n if (!FReadOnly)\r\n {\r\n // only modified, explicit\r\n Save(false, true);\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TStoredSessionList::OpenHostKeysSubKey(THierarchicalStorage * Storage, bool CanCreate)\r\n{\r\n return\r\n Storage->OpenRootKey(CanCreate) &&\r\n Storage->OpenSubKey(Configuration->SshHostKeysSubKey, CanCreate);\r\n}\r\n//---------------------------------------------------------------------------\r\nTHierarchicalStorage * __fastcall TStoredSessionList::CreateHostKeysStorageForWritting()\r\n{\r\n bool SessionList = false;\r\n std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(SessionList));\r\n Storage->Explicit = true;\r\n Storage->AccessMode = smReadWrite;\r\n return Storage.release();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::ImportHostKeys(\r\n THierarchicalStorage * SourceStorage, THierarchicalStorage * TargetStorage, TStoredSessionList * Sessions, bool OnlySelected)\r\n{\r\n if (OpenHostKeysSubKey(SourceStorage, false) &&\r\n OpenHostKeysSubKey(TargetStorage, true))\r\n {\r\n std::auto_ptr<TStringList> KeyList(new TStringList());\r\n SourceStorage->GetValueNames(KeyList.get());\r\n\r\n DebugAssert(Sessions != NULL);\r\n for (int Index = 0; Index < Sessions->Count; Index++)\r\n {\r\n TSessionData * Session = Sessions->Sessions[Index];\r\n if (!OnlySelected || Session->Selected)\r\n {\r\n UnicodeString HostKeyName = PuttyMungeStr(FORMAT(L\"@%d:%s\", (Session->PortNumber, Session->HostNameExpanded)));\r\n for (int KeyIndex = 0; KeyIndex < KeyList->Count; KeyIndex++)\r\n {\r\n UnicodeString KeyName = KeyList->Strings[KeyIndex];\r\n if (EndsText(HostKeyName, KeyName))\r\n {\r\n TargetStorage->WriteStringRaw(KeyName, SourceStorage->ReadStringRaw(KeyName, L\"\"));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::ImportHostKeys(\r\n const UnicodeString & SourceKey, TStoredSessionList * Sessions, bool OnlySelected)\r\n{\r\n std::auto_ptr<THierarchicalStorage> TargetStorage(CreateHostKeysStorageForWritting());\r\n std::auto_ptr<THierarchicalStorage> SourceStorage(new TRegistryStorage(SourceKey));\r\n\r\n ImportHostKeys(SourceStorage.get(), TargetStorage.get(), Sessions, OnlySelected);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::ImportSelectedKnownHosts(TStoredSessionList * Sessions)\r\n{\r\n std::unique_ptr<THierarchicalStorage> Storage(CreateHostKeysStorageForWritting());\r\n if (OpenHostKeysSubKey(Storage.get(), true))\r\n {\r\n for (int Index = 0; Index < Sessions->Count; Index++)\r\n {\r\n TSessionData * Session = Sessions->Sessions[Index];\r\n if (Session->Selected)\r\n {\r\n UnicodeString Algs;\r\n UnicodeString HostKeys = Session->HostKey;\r\n while (!HostKeys.IsEmpty())\r\n {\r\n UnicodeString HostKey = CutToChar(HostKeys, L';', true);\r\n // skip alg\r\n CutToChar(HostKey, L':', true);\r\n UnicodeString Key = CutToChar(HostKey, L'=', true);\r\n Storage->WriteStringRaw(Key, HostKey);\r\n }\r\n }\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TStoredSessionList::IsFolderOrWorkspace(\r\n const UnicodeString & Name, bool Workspace)\r\n{\r\n bool Result = false;\r\n TSessionData * FirstData = NULL;\r\n if (!Name.IsEmpty())\r\n {\r\n for (int Index = 0; !Result && (Index < Count); Index++)\r\n {\r\n Result = Sessions[Index]->IsInFolderOrWorkspace(Name);\r\n if (Result)\r\n {\r\n FirstData = Sessions[Index];\r\n }\r\n }\r\n }\r\n\r\n return\r\n Result &&\r\n DebugAlwaysTrue(FirstData != NULL) &&\r\n (FirstData->IsWorkspace == Workspace);\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TStoredSessionList::IsFolder(const UnicodeString & Name)\r\n{\r\n return IsFolderOrWorkspace(Name, false);\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TStoredSessionList::IsWorkspace(const UnicodeString & Name)\r\n{\r\n return IsFolderOrWorkspace(Name, true);\r\n}\r\n//---------------------------------------------------------------------------\r\nTSessionData * __fastcall TStoredSessionList::CheckIsInFolderOrWorkspaceAndResolve(\r\n TSessionData * Data, const UnicodeString & Name)\r\n{\r\n if (Data->IsInFolderOrWorkspace(Name))\r\n {\r\n Data = ResolveWorkspaceData(Data);\r\n\r\n if ((Data != NULL) && Data->CanLogin &&\r\n DebugAlwaysTrue(Data->Link.IsEmpty()))\r\n {\r\n return Data;\r\n }\r\n }\r\n return NULL;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::GetFolderOrWorkspace(const UnicodeString & Name, TList * List)\r\n{\r\n DoGetFolderOrWorkspace(Name, List, false);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::DoGetFolderOrWorkspace(const UnicodeString & Name, TList * List, bool NoRecrypt)\r\n{\r\n for (int Index = 0; (Index < Count); Index++)\r\n {\r\n TSessionData * RawData = Sessions[Index];\r\n TSessionData * Data =\r\n CheckIsInFolderOrWorkspaceAndResolve(RawData, Name);\r\n\r\n if (Data != NULL)\r\n {\r\n TSessionData * Data2 = new TSessionData(L\"\");\r\n if (NoRecrypt)\r\n {\r\n Data2->CopyDataNoRecrypt(Data);\r\n }\r\n else\r\n {\r\n Data2->Assign(Data);\r\n }\r\n\r\n if (!RawData->Link.IsEmpty() && (DebugAlwaysTrue(Data != RawData)) &&\r\n // BACKWARD COMPATIBILITY\r\n // When loading pre-5.6.4 workspace, that does not have state saved,\r\n // do not overwrite the site \"state\" defaults\r\n // with (empty) workspace state\r\n RawData->HasStateData())\r\n {\r\n Data2->CopyStateData(RawData);\r\n }\r\n\r\n if (!RawData->NameOverride.IsEmpty())\r\n {\r\n Data2->Name = RawData->NameOverride;\r\n }\r\n else if (RawData->Link.IsEmpty() && RawData->IsWorkspace)\r\n {\r\n // Newly opened ad-hoc session has no name, so restore the workspace that way too.\r\n // Otherwise we would persist the generated internal workspace name as a real name.\r\n Data2->Name = UnicodeString();\r\n }\r\n\r\n List->Add(Data2);\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nTStrings * __fastcall TStoredSessionList::GetFolderOrWorkspaceList(\r\n const UnicodeString & Name)\r\n{\r\n std::unique_ptr<TObjectList> DataList(new TObjectList());\r\n DoGetFolderOrWorkspace(Name, DataList.get(), true);\r\n\r\n std::unique_ptr<TStringList> Result(new TStringList());\r\n for (int Index = 0; (Index < DataList->Count); Index++)\r\n {\r\n Result->Add(dynamic_cast<TSessionData *>(DataList->Items[Index])->SessionName);\r\n }\r\n\r\n return Result.release();\r\n}\r\n//---------------------------------------------------------------------------\r\nTStrings * __fastcall TStoredSessionList::GetWorkspaces()\r\n{\r\n std::unique_ptr<TStringList> Result(CreateSortedStringList());\r\n\r\n for (int Index = 0; (Index < Count); Index++)\r\n {\r\n TSessionData * Data = Sessions[Index];\r\n if (Data->IsWorkspace)\r\n {\r\n Result->Add(Data->FolderName);\r\n }\r\n }\r\n\r\n return Result.release();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TStoredSessionList::NewWorkspace(\r\n UnicodeString Name, TList * DataList)\r\n{\r\n for (int Index = 0; (Index < Count); Index++)\r\n {\r\n TSessionData * Data = Sessions[Index];\r\n if (Data->IsInFolderOrWorkspace(Name))\r\n {\r\n FPendingRemovals->Add(Data->Name);\r\n Remove(Data);\r\n Index--;\r\n }\r\n }\r\n\r\n for (int Index = 0; (Index < DataList->Count); Index++)\r\n {\r\n TSessionData * Data = static_cast<TSessionData *>(DataList->Items[Index]);\r\n\r\n TSessionData * Data2 = new TSessionData(L\"\");\r\n Data2->Assign(Data);\r\n Data2->Name = TSessionData::ComposePath(Name, Data->Name);\r\n // make sure, that new stored session is saved to registry\r\n Data2->Modified = true;\r\n Add(Data2);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TStoredSessionList::HasAnyWorkspace()\r\n{\r\n bool Result = false;\r\n for (int Index = 0; !Result && (Index < Count); Index++)\r\n {\r\n TSessionData * Data = Sessions[Index];\r\n Result = Data->IsWorkspace;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nTSessionData * __fastcall TStoredSessionList::ParseUrl(UnicodeString Url,\r\n TOptions * Options, bool & DefaultsOnly, UnicodeString * FileName,\r\n bool * AProtocolDefined, UnicodeString * MaskedUrl, int Flags)\r\n{\r\n TSessionData * Data = new TSessionData(L\"\");\r\n try\r\n {\r\n Data->ParseUrl(Url, Options, this, DefaultsOnly, FileName, AProtocolDefined, MaskedUrl, Flags);\r\n }\r\n catch(...)\r\n {\r\n delete Data;\r\n throw;\r\n }\r\n\r\n return Data;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TStoredSessionList::IsUrl(UnicodeString Url)\r\n{\r\n bool DefaultsOnly;\r\n bool ProtocolDefined = false;\r\n std::unique_ptr<TSessionData> ParsedData(ParseUrl(Url, NULL, DefaultsOnly, NULL, &ProtocolDefined));\r\n bool Result = ProtocolDefined;\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------\r\nTSessionData * __fastcall TStoredSessionList::ResolveWorkspaceData(TSessionData * Data)\r\n{\r\n if (!Data->Link.IsEmpty())\r\n {\r\n Data = dynamic_cast<TSessionData *>(FindByName(Data->Link));\r\n if (Data != NULL)\r\n {\r\n Data = ResolveWorkspaceData(Data);\r\n }\r\n }\r\n return Data;\r\n}\r\n//---------------------------------------------------------------------\r\nTSessionData * __fastcall TStoredSessionList::SaveWorkspaceData(TSessionData * Data, int Index)\r\n{\r\n std::unique_ptr<TSessionData> Result(new TSessionData(L\"\"));\r\n\r\n TSessionData * SameData = StoredSessions->FindSame(Data);\r\n if (SameData != NULL)\r\n {\r\n Result->CopyStateData(Data);\r\n Result->Link = Data->Name;\r\n }\r\n else\r\n {\r\n Result->Assign(Data);\r\n Result->NameOverride = Data->Name;\r\n }\r\n\r\n Result->IsWorkspace = true;\r\n Result->Name = IntToHex(Index, 4); // See HasSessionName()\r\n\r\n return Result.release();\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TStoredSessionList::CanLogin(TSessionData * Data)\r\n{\r\n Data = ResolveWorkspaceData(Data);\r\n return (Data != NULL) && Data->CanLogin;\r\n}\r\n//---------------------------------------------------------------------\r\nUnicodeString GetExpandedLogFileName(UnicodeString LogFileName, TDateTime Started, TSessionData * SessionData)\r\n{\r\n // StripPathQuotes should not be needed as we do not feed quotes anymore\r\n UnicodeString ANewFileName = StripPathQuotes(ExpandEnvironmentVariables(LogFileName));\r\n for (int Index = 1; Index < ANewFileName.Length(); Index++)\r\n {\r\n if (ANewFileName[Index] == L'!')\r\n {\r\n UnicodeString Replacement;\r\n // keep consistent with TFileCustomCommand::PatternReplacement\r\n switch (tolower(ANewFileName[Index + 1]))\r\n {\r\n case L'y':\r\n Replacement = FormatDateTime(L\"yyyy\", Started);\r\n break;\r\n\r\n case L'm':\r\n Replacement = FormatDateTime(L\"mm\", Started);\r\n break;\r\n\r\n case L'd':\r\n Replacement = FormatDateTime(L\"dd\", Started);\r\n break;\r\n\r\n case L't':\r\n Replacement = FormatDateTime(L\"hhnnss\", Started);\r\n break;\r\n\r\n case 'p':\r\n Replacement = IntToStr(static_cast<int>(GetCurrentProcessId()));\r\n break;\r\n\r\n case L'@':\r\n if (SessionData != NULL)\r\n {\r\n Replacement = MakeValidFileName(SessionData->HostNameExpanded);\r\n }\r\n else\r\n {\r\n Replacement = L\"nohost\";\r\n }\r\n break;\r\n\r\n case L's':\r\n if (SessionData != NULL)\r\n {\r\n Replacement = MakeValidFileName(SessionData->SessionName);\r\n }\r\n else\r\n {\r\n Replacement = L\"nosession\";\r\n }\r\n break;\r\n\r\n case L'!':\r\n Replacement = L\"!\";\r\n break;\r\n\r\n default:\r\n Replacement = UnicodeString(L\"!\") + ANewFileName[Index + 1];\r\n break;\r\n }\r\n ANewFileName.Delete(Index, 2);\r\n ANewFileName.Insert(Replacement, Index);\r\n Index += Replacement.Length() - 1;\r\n }\r\n }\r\n return ANewFileName;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall IsSshProtocol(TFSProtocol FSProtocol)\r\n{\r\n return\r\n (FSProtocol == fsSFTPonly) || (FSProtocol == fsSFTP) ||\r\n (FSProtocol == fsSCPonly);\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall DefaultPort(TFSProtocol FSProtocol, TFtps Ftps)\r\n{\r\n int Result;\r\n switch (FSProtocol)\r\n {\r\n case fsFTP:\r\n if (Ftps == ftpsImplicit)\r\n {\r\n Result = FtpsImplicitPortNumber;\r\n }\r\n else\r\n {\r\n Result = FtpPortNumber;\r\n }\r\n break;\r\n\r\n case fsWebDAV:\r\n case fsS3:\r\n if (Ftps == ftpsNone)\r\n {\r\n Result = HTTPPortNumber;\r\n }\r\n else\r\n {\r\n Result = HTTPSPortNumber;\r\n }\r\n break;\r\n\r\n default:\r\n if (IsSshProtocol(FSProtocol))\r\n {\r\n Result = SshPortNumber;\r\n }\r\n else\r\n {\r\n DebugFail();\r\n Result = -1;\r\n }\r\n break;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------" ]
[ 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 ]
PreciseBugs
{"buggy_code_end_loc": [47, 53, 80, 2275, 473, 1511, 2372, 1100], "buggy_code_start_loc": [46, 52, 79, 599, 57, 1510, 2371, 1099], "filenames": ["source/Console.cbproj", "source/DragExt.cbproj", "source/WinSCP.cbproj", "source/core/SessionData.cpp", "source/core/SessionData.h", "source/forms/Custom.cpp", "source/windows/ConsoleRunner.cpp", "source/windows/WinMain.cpp"], "fixing_code_end_loc": [47, 53, 80, 2294, 474, 1511, 2372, 1103], "fixing_code_start_loc": [46, 52, 79, 599, 58, 1510, 2371, 1099], "message": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:winscp:winscp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C081564B-8EF8-4C8A-9EB0-1C50D5A8F18B", "versionEndExcluding": "5.17.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)"}, {"lang": "es", "value": "WinSCP anterior a la versi\u00f3n 5.17.10 permite a los atacantes remotos ejecutar programas arbitrarios cuando el manejador de URLs encuentra una URL manipulada que carga la configuraci\u00f3n de la sesi\u00f3n. (Por ejemplo, esto es explotable en una instalaci\u00f3n por defecto en la que WinSCP es el manejador de URLs sftp://)"}], "evaluatorComment": null, "id": "CVE-2021-3331", "lastModified": "2021-02-04T15:59:24.960", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-01-27T21:15:16.840", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://winscp.net/eng/docs/history#5.17.10"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://winscp.net/eng/docs/rawsettings"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://winscp.net/tracker/1943"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, "type": "NVD-CWE-Other"}
177
Determine whether the {function_name} code is vulnerable or not.
[ "//---------------------------------------------------------------------------\r\n#ifndef SessionDataH\r\n#define SessionDataH\r\n\r\n#include \"Common.h\"\r\n#include \"Option.h\"\r\n#include \"FileBuffer.h\"\r\n#include \"NamedObjs.h\"\r\n#include \"HierarchicalStorage.h\"\r\n#include \"Configuration.h\"\r\n#include <Xml.XMLIntf.hpp>\r\n//---------------------------------------------------------------------------\r\nenum TCipher { cipWarn, cip3DES, cipBlowfish, cipAES, cipDES, cipArcfour, cipChaCha20 };\r\n#define CIPHER_COUNT (cipChaCha20+1)\r\n// explicit values to skip obsoleted fsExternalSSH, fsExternalSFTP\r\nenum TFSProtocol { fsSCPonly = 0, fsSFTP = 1, fsSFTPonly = 2, fsFTP = 5, fsWebDAV = 6, fsS3 = 7 };\r\n#define FSPROTOCOL_COUNT (fsS3+1)\r\nextern const wchar_t * ProxyMethodNames;\r\nenum TProxyMethod { pmNone, pmSocks4, pmSocks5, pmHTTP, pmTelnet, pmCmd };\r\nenum TSshProt { ssh1only, ssh1deprecated, ssh2deprecated, ssh2only };\r\nenum TKex { kexWarn, kexDHGroup1, kexDHGroup14, kexDHGEx, kexRSA, kexECDH };\r\n#define KEX_COUNT (kexECDH+1)\r\nenum THostKey { hkWarn, hkRSA, hkDSA, hkECDSA, hkED25519, hkMax };\r\n#define HOSTKEY_COUNT (hkMax)\r\nenum TGssLib { gssGssApi32, gssSspi, gssCustom };\r\n#define GSSLIB_COUNT (gssCustom+1)\r\n// names have to match PuTTY registry entries (see settings.c)\r\nenum TSshBug { sbIgnore1, sbPlainPW1, sbRSA1, sbHMAC2, sbDeriveKey2, sbRSAPad2,\r\n sbPKSessID2, sbRekey2, sbMaxPkt2, sbIgnore2, sbOldGex2, sbWinAdj, sbChanReq };\r\n#define BUG_COUNT (sbChanReq+1)\r\nenum TSftpBug { sbSymlink, sbSignedTS };\r\n#define SFTP_BUG_COUNT (sbSignedTS+1)\r\nextern const wchar_t * PingTypeNames;\r\nenum TPingType { ptOff, ptNullPacket, ptDummyCommand };\r\nenum TAddressFamily { afAuto, afIPv4, afIPv6 };\r\nenum TFtps { ftpsNone, ftpsImplicit, ftpsExplicitSsl, ftpsExplicitTls };\r\n// has to match SSL_VERSION_XXX constants in AsyncSslSocketLayer.h\r\n// ssl2 has no effect now\r\nenum TTlsVersion { ssl2 = 2, ssl3 = 3, tls10 = 10, tls11 = 11, tls12 = 12, tls13 = 13 };\r\n// has to match libs3 S3UriStyle\r\nenum TS3UrlStyle { s3usVirtualHost, s3usPath };\r\nenum TSessionSource { ssNone, ssStored, ssStoredModified };\r\nenum TSessionUrlFlags\r\n{\r\n sufSpecific = 0x01,\r\n sufUserName = 0x02,\r\n sufPassword = 0x04,\r\n sufHostKey = 0x08,\r\n sufRawSettings = 0x10,\r\n sufHttpForWebDAV = 0x20,\r\n sufSession = sufUserName | sufPassword | sufHostKey,\r\n sufComplete = sufSession | sufRawSettings,\r\n sufOpen = sufUserName | sufPassword\r\n};\r\nenum TParseUrlFlags\r\n{\r\n pufAllowStoredSiteWithProtocol = 0x01,\r", "", "};\r\n//---------------------------------------------------------------------------\r\nextern const UnicodeString CipherNames[CIPHER_COUNT];\r\nextern const UnicodeString KexNames[KEX_COUNT];\r\nextern const UnicodeString HostKeyNames[HOSTKEY_COUNT];\r\nextern const UnicodeString GssLibNames[GSSLIB_COUNT];\r\nextern const wchar_t SshProtList[][10];\r\nextern const TCipher DefaultCipherList[CIPHER_COUNT];\r\nextern const TKex DefaultKexList[KEX_COUNT];\r\nextern const THostKey DefaultHostKeyList[HOSTKEY_COUNT];\r\nextern const TGssLib DefaultGssLibList[GSSLIB_COUNT];\r\nextern const wchar_t FSProtocolNames[FSPROTOCOL_COUNT][16];\r\nextern const int DefaultSendBuf;\r\nextern const UnicodeString AnonymousUserName;\r\nextern const UnicodeString AnonymousPassword;\r\nextern const int SshPortNumber;\r\nextern const int FtpPortNumber;\r\nextern const int FtpsImplicitPortNumber;\r\nextern const int HTTPPortNumber;\r\nextern const int HTTPSPortNumber;\r\nextern const int TelnetPortNumber;\r\nextern const int ProxyPortNumber;\r\nextern const UnicodeString PuttySshProtocol;\r\nextern const UnicodeString PuttyTelnetProtocol;\r\nextern const UnicodeString SftpProtocol;\r\nextern const UnicodeString ScpProtocol;\r\nextern const UnicodeString FtpProtocol;\r\nextern const UnicodeString FtpsProtocol;\r\nextern const UnicodeString FtpesProtocol;\r\nextern const UnicodeString WebDAVProtocol;\r\nextern const UnicodeString WebDAVSProtocol;\r\nextern const UnicodeString S3Protocol;\r\nextern const UnicodeString SshProtocol;\r\nextern const UnicodeString WinSCPProtocolPrefix;\r\nextern const wchar_t UrlParamSeparator;\r\nextern const wchar_t UrlParamValueSeparator;\r\nextern const UnicodeString UrlHostKeyParamName;\r\nextern const UnicodeString UrlSaveParamName;\r\nextern const UnicodeString PassphraseOption;\r\nextern const UnicodeString S3HostName;\r\n//---------------------------------------------------------------------------\r\nclass TStoredSessionList;\r\n//---------------------------------------------------------------------------\r\nclass TSessionData : public TNamedObject\r\n{\r\nfriend class TStoredSessionList;\r\n\r\nprivate:\r\n UnicodeString FHostName;\r\n int FPortNumber;\r\n UnicodeString FUserName;\r\n RawByteString FPassword;\r\n RawByteString FNewPassword;\r\n bool FChangePassword;\r\n int FPingInterval;\r\n TPingType FPingType;\r\n bool FTryAgent;\r\n bool FAgentFwd;\r\n UnicodeString FListingCommand;\r\n bool FAuthTIS;\r\n bool FAuthKI;\r\n bool FAuthKIPassword;\r\n bool FAuthGSSAPI;\r\n bool FGSSAPIFwdTGT;\r\n bool FChangeUsername;\r\n bool FCompression;\r\n TSshProt FSshProt;\r\n bool FSsh2DES;\r\n bool FSshNoUserAuth;\r\n TCipher FCiphers[CIPHER_COUNT];\r\n TKex FKex[KEX_COUNT];\r\n THostKey FHostKeys[HOSTKEY_COUNT];\r\n TGssLib FGssLib[GSSLIB_COUNT];\r\n UnicodeString FGssLibCustom;\r\n bool FClearAliases;\r\n TEOLType FEOLType;\r\n bool FTrimVMSVersions;\r\n UnicodeString FPublicKeyFile;\r\n UnicodeString FPassphrase;\r\n UnicodeString FPuttyProtocol;\r\n TFSProtocol FFSProtocol;\r\n bool FModified;\r\n UnicodeString FLocalDirectory;\r\n UnicodeString FRemoteDirectory;\r\n bool FLockInHome;\r\n bool FSpecial;\r\n bool FSynchronizeBrowsing;\r\n bool FUpdateDirectories;\r\n bool FCacheDirectories;\r\n bool FCacheDirectoryChanges;\r\n bool FPreserveDirectoryChanges;\r\n bool FSelected;\r\n TAutoSwitch FLookupUserGroups;\r\n UnicodeString FReturnVar;\r\n bool FExitCode1IsError;\r\n bool FScp1Compatibility;\r\n UnicodeString FShell;\r\n UnicodeString FSftpServer;\r\n int FTimeout;\r\n bool FUnsetNationalVars;\r\n bool FIgnoreLsWarnings;\r\n bool FTcpNoDelay;\r\n int FSendBuf;\r\n UnicodeString FSourceAddress;\r\n bool FSshSimple;\r\n TProxyMethod FProxyMethod;\r\n UnicodeString FProxyHost;\r\n int FProxyPort;\r\n UnicodeString FProxyUsername;\r\n RawByteString FProxyPassword;\r\n UnicodeString FProxyTelnetCommand;\r\n UnicodeString FProxyLocalCommand;\r\n TAutoSwitch FProxyDNS;\r\n bool FProxyLocalhost;\r\n int FFtpProxyLogonType;\r\n TAutoSwitch FBugs[BUG_COUNT];\r\n UnicodeString FPuttySettings;\r\n UnicodeString FCustomParam1;\r\n UnicodeString FCustomParam2;\r\n bool FResolveSymlinks;\r\n bool FFollowDirectorySymlinks;\r\n TDateTime FTimeDifference;\r\n bool FTimeDifferenceAuto;\r\n int FSFTPDownloadQueue;\r\n int FSFTPUploadQueue;\r\n int FSFTPListingQueue;\r\n int FSFTPMaxVersion;\r\n unsigned long FSFTPMaxPacketSize;\r\n TDSTMode FDSTMode;\r\n TAutoSwitch FSFTPBugs[SFTP_BUG_COUNT];\r\n bool FDeleteToRecycleBin;\r\n bool FOverwrittenToRecycleBin;\r\n UnicodeString FRecycleBinPath;\r\n UnicodeString FPostLoginCommands;\r\n TAutoSwitch FSCPLsFullTime;\r\n TAutoSwitch FFtpListAll;\r\n TAutoSwitch FFtpHost;\r\n TAutoSwitch FFtpDeleteFromCwd;\r\n bool FSslSessionReuse;\r\n UnicodeString FTlsCertificateFile;\r\n TAddressFamily FAddressFamily;\r\n UnicodeString FRekeyData;\r\n unsigned int FRekeyTime;\r\n int FColor;\r\n bool FTunnel;\r\n UnicodeString FTunnelHostName;\r\n int FTunnelPortNumber;\r\n UnicodeString FTunnelUserName;\r\n RawByteString FTunnelPassword;\r\n UnicodeString FTunnelPublicKeyFile;\r\n int FTunnelLocalPortNumber;\r\n UnicodeString FTunnelPortFwd;\r\n UnicodeString FTunnelHostKey;\r\n bool FFtpPasvMode;\r\n TAutoSwitch FFtpForcePasvIp;\r\n TAutoSwitch FFtpUseMlsd;\r\n UnicodeString FFtpAccount;\r\n int FFtpPingInterval;\r\n TPingType FFtpPingType;\r\n TAutoSwitch FFtpTransferActiveImmediately;\r\n TFtps FFtps;\r\n TTlsVersion FMinTlsVersion;\r\n TTlsVersion FMaxTlsVersion;\r\n TAutoSwitch FNotUtf;\r\n int FInternalEditorEncoding;\r\n UnicodeString FS3DefaultRegion;\r\n TS3UrlStyle FS3UrlStyle;\r\n bool FIsWorkspace;\r\n UnicodeString FLink;\r\n UnicodeString FNameOverride;\r\n UnicodeString FHostKey;\r\n bool FFingerprintScan;\r\n bool FOverrideCachedHostKey;\r\n UnicodeString FNote;\r\n UnicodeString FWinTitle;\r\n RawByteString FEncryptKey;\r\n\r\n UnicodeString FOrigHostName;\r\n int FOrigPortNumber;\r\n TProxyMethod FOrigProxyMethod;\r\n TSessionSource FSource;\r\n bool FSaveOnly;\r\n UnicodeString FLogicalHostName;\r\n\r\n void __fastcall SetHostName(UnicodeString value);\r\n UnicodeString __fastcall GetHostNameExpanded();\r\n void __fastcall SetPortNumber(int value);\r\n void __fastcall SetUserName(UnicodeString value);\r\n UnicodeString __fastcall GetUserNameExpanded();\r\n void __fastcall SetPassword(UnicodeString value);\r\n UnicodeString __fastcall GetPassword() const;\r\n void __fastcall SetNewPassword(UnicodeString value);\r\n UnicodeString __fastcall GetNewPassword() const;\r\n void __fastcall SetChangePassword(bool value);\r\n void __fastcall SetPingInterval(int value);\r\n void __fastcall SetTryAgent(bool value);\r\n void __fastcall SetAgentFwd(bool value);\r\n void __fastcall SetAuthTIS(bool value);\r\n void __fastcall SetAuthKI(bool value);\r\n void __fastcall SetAuthKIPassword(bool value);\r\n void __fastcall SetAuthGSSAPI(bool value);\r\n void __fastcall SetGSSAPIFwdTGT(bool value);\r\n void __fastcall SetChangeUsername(bool value);\r\n void __fastcall SetCompression(bool value);\r\n void __fastcall SetSshProt(TSshProt value);\r\n void __fastcall SetSsh2DES(bool value);\r\n void __fastcall SetSshNoUserAuth(bool value);\r\n void __fastcall SetCipher(int Index, TCipher value);\r\n TCipher __fastcall GetCipher(int Index) const;\r\n void __fastcall SetKex(int Index, TKex value);\r\n TKex __fastcall GetKex(int Index) const;\r\n void __fastcall SetHostKeys(int Index, THostKey value);\r\n THostKey __fastcall GetHostKeys(int Index) const;\r\n void __fastcall SetGssLib(int Index, TGssLib value);\r\n TGssLib __fastcall GetGssLib(int Index) const;\r\n void __fastcall SetGssLibCustom(UnicodeString value);\r\n void __fastcall SetPublicKeyFile(UnicodeString value);\r\n UnicodeString __fastcall GetPassphrase() const;\r\n void __fastcall SetPassphrase(UnicodeString value);\r\n\r\n void __fastcall SetPuttyProtocol(UnicodeString value);\r\n bool __fastcall GetCanLogin();\r\n void __fastcall SetPingIntervalDT(TDateTime value);\r\n TDateTime __fastcall GetPingIntervalDT();\r\n TDateTime __fastcall GetFtpPingIntervalDT();\r\n void __fastcall SetTimeDifference(TDateTime value);\r\n void __fastcall SetTimeDifferenceAuto(bool value);\r\n void __fastcall SetPingType(TPingType value);\r\n UnicodeString __fastcall GetSessionName();\r\n UnicodeString __fastcall GetDefaultSessionName();\r\n UnicodeString __fastcall GetProtocolUrl(bool HttpForWebDAV);\r\n void __fastcall SetFSProtocol(TFSProtocol value);\r\n UnicodeString __fastcall GetFSProtocolStr();\r\n void __fastcall SetLocalDirectory(UnicodeString value);\r\n UnicodeString __fastcall GetLocalDirectoryExpanded();\r\n void __fastcall SetRemoteDirectory(UnicodeString value);\r\n void __fastcall SetSynchronizeBrowsing(bool value);\r\n void __fastcall SetUpdateDirectories(bool value);\r\n void __fastcall SetCacheDirectories(bool value);\r\n void __fastcall SetCacheDirectoryChanges(bool value);\r\n void __fastcall SetPreserveDirectoryChanges(bool value);\r\n void __fastcall SetLockInHome(bool value);\r\n void __fastcall SetSpecial(bool value);\r\n UnicodeString __fastcall GetInfoTip();\r\n bool __fastcall GetDefaultShell();\r\n void __fastcall SetDetectReturnVar(bool value);\r\n bool __fastcall GetDetectReturnVar();\r\n void __fastcall SetListingCommand(UnicodeString value);\r\n void __fastcall SetClearAliases(bool value);\r\n void __fastcall SetDefaultShell(bool value);\r\n void __fastcall SetEOLType(TEOLType value);\r\n void __fastcall SetTrimVMSVersions(bool value);\r\n void __fastcall SetLookupUserGroups(TAutoSwitch value);\r\n void __fastcall SetReturnVar(UnicodeString value);\r\n void __fastcall SetExitCode1IsError(bool value);\r\n void __fastcall SetScp1Compatibility(bool value);\r\n void __fastcall SetShell(UnicodeString value);\r\n void __fastcall SetSftpServer(UnicodeString value);\r\n void __fastcall SetTimeout(int value);\r\n void __fastcall SetUnsetNationalVars(bool value);\r\n void __fastcall SetIgnoreLsWarnings(bool value);\r\n void __fastcall SetTcpNoDelay(bool value);\r\n void __fastcall SetSendBuf(int value);\r\n void __fastcall SetSourceAddress(const UnicodeString & value);\r\n void __fastcall SetSshSimple(bool value);\r\n UnicodeString __fastcall GetSshProtStr();\r\n bool __fastcall GetUsesSsh();\r\n void __fastcall SetCipherList(UnicodeString value);\r\n UnicodeString __fastcall GetCipherList() const;\r\n void __fastcall SetKexList(UnicodeString value);\r\n UnicodeString __fastcall GetKexList() const;\r\n void __fastcall SetHostKeyList(UnicodeString value);\r\n UnicodeString __fastcall GetHostKeyList() const;\r\n void __fastcall SetGssLibList(UnicodeString value);\r\n UnicodeString __fastcall GetGssLibList() const;\r\n void __fastcall SetProxyMethod(TProxyMethod value);\r\n void __fastcall SetProxyHost(UnicodeString value);\r\n void __fastcall SetProxyPort(int value);\r\n void __fastcall SetProxyUsername(UnicodeString value);\r\n void __fastcall SetProxyPassword(UnicodeString value);\r\n void __fastcall SetProxyTelnetCommand(UnicodeString value);\r\n void __fastcall SetProxyLocalCommand(UnicodeString value);\r\n void __fastcall SetProxyDNS(TAutoSwitch value);\r\n void __fastcall SetProxyLocalhost(bool value);\r\n UnicodeString __fastcall GetProxyPassword() const;\r\n void __fastcall SetFtpProxyLogonType(int value);\r\n void __fastcall SetBug(TSshBug Bug, TAutoSwitch value);\r\n TAutoSwitch __fastcall GetBug(TSshBug Bug) const;\r\n UnicodeString __fastcall GetSessionKey();\r\n void __fastcall SetPuttySettings(UnicodeString value);\r\n void __fastcall SetCustomParam1(UnicodeString value);\r\n void __fastcall SetCustomParam2(UnicodeString value);\r\n void __fastcall SetResolveSymlinks(bool value);\r\n void __fastcall SetFollowDirectorySymlinks(bool value);\r\n void __fastcall SetSFTPDownloadQueue(int value);\r\n void __fastcall SetSFTPUploadQueue(int value);\r\n void __fastcall SetSFTPListingQueue(int value);\r\n void __fastcall SetSFTPMaxVersion(int value);\r\n void __fastcall SetSFTPMaxPacketSize(unsigned long value);\r\n void __fastcall SetSFTPBug(TSftpBug Bug, TAutoSwitch value);\r\n TAutoSwitch __fastcall GetSFTPBug(TSftpBug Bug) const;\r\n void __fastcall SetSCPLsFullTime(TAutoSwitch value);\r\n void __fastcall SetFtpListAll(TAutoSwitch value);\r\n void __fastcall SetFtpHost(TAutoSwitch value);\r\n void __fastcall SetFtpDeleteFromCwd(TAutoSwitch value);\r\n void __fastcall SetSslSessionReuse(bool value);\r\n void __fastcall SetTlsCertificateFile(UnicodeString value);\r\n UnicodeString __fastcall GetStorageKey();\r\n UnicodeString __fastcall GetInternalStorageKey();\r\n UnicodeString __fastcall GetSiteKey();\r\n void __fastcall SetDSTMode(TDSTMode value);\r\n void __fastcall SetDeleteToRecycleBin(bool value);\r\n void __fastcall SetOverwrittenToRecycleBin(bool value);\r\n void __fastcall SetRecycleBinPath(UnicodeString value);\r\n void __fastcall SetPostLoginCommands(UnicodeString value);\r\n void __fastcall SetAddressFamily(TAddressFamily value);\r\n void __fastcall SetRekeyData(UnicodeString value);\r\n void __fastcall SetRekeyTime(unsigned int value);\r\n void __fastcall SetColor(int value);\r\n void __fastcall SetTunnel(bool value);\r\n void __fastcall SetTunnelHostName(UnicodeString value);\r\n void __fastcall SetTunnelPortNumber(int value);\r\n void __fastcall SetTunnelUserName(UnicodeString value);\r\n void __fastcall SetTunnelPassword(UnicodeString value);\r\n UnicodeString __fastcall GetTunnelPassword() const;\r\n void __fastcall SetTunnelPublicKeyFile(UnicodeString value);\r\n void __fastcall SetTunnelPortFwd(UnicodeString value);\r\n void __fastcall SetTunnelLocalPortNumber(int value);\r\n bool __fastcall GetTunnelAutoassignLocalPortNumber();\r\n void __fastcall SetTunnelHostKey(UnicodeString value);\r\n void __fastcall SetFtpPasvMode(bool value);\r\n void __fastcall SetFtpForcePasvIp(TAutoSwitch value);\r\n void __fastcall SetFtpUseMlsd(TAutoSwitch value);\r\n void __fastcall SetFtpAccount(UnicodeString value);\r\n void __fastcall SetFtpPingInterval(int value);\r\n void __fastcall SetFtpPingType(TPingType value);\r\n void __fastcall SetFtpTransferActiveImmediately(TAutoSwitch value);\r\n void __fastcall SetFtps(TFtps value);\r\n void __fastcall SetMinTlsVersion(TTlsVersion value);\r\n void __fastcall SetMaxTlsVersion(TTlsVersion value);\r\n void __fastcall SetNotUtf(TAutoSwitch value);\r\n void __fastcall SetInternalEditorEncoding(int value);\r\n void __fastcall SetS3DefaultRegion(UnicodeString value);\r\n void __fastcall SetS3UrlStyle(TS3UrlStyle value);\r\n void __fastcall SetLogicalHostName(UnicodeString value);\r\n void __fastcall SetIsWorkspace(bool value);\r\n void __fastcall SetLink(UnicodeString value);\r\n void __fastcall SetNameOverride(UnicodeString value);\r\n void __fastcall SetHostKey(UnicodeString value);\r\n void __fastcall SetNote(UnicodeString value);\r\n void __fastcall SetWinTitle(UnicodeString value);\r\n UnicodeString __fastcall GetEncryptKey() const;\r\n void __fastcall SetEncryptKey(UnicodeString value);\r\n\r\n TDateTime __fastcall GetTimeoutDT();\r\n void __fastcall SavePasswords(THierarchicalStorage * Storage, bool PuttyExport, bool DoNotEncryptPasswords, bool SaveAll);\r\n UnicodeString __fastcall GetLocalName();\r\n UnicodeString __fastcall GetFolderName();\r\n void __fastcall Modify();\r\n UnicodeString __fastcall GetSource();\r", " void __fastcall DoLoad(THierarchicalStorage * Storage, bool PuttyImport, bool & RewritePassword);\r", " void __fastcall DoSave(THierarchicalStorage * Storage,\r\n bool PuttyExport, const TSessionData * Default, bool DoNotEncryptPasswords);\r\n UnicodeString __fastcall ReadXmlNode(_di_IXMLNode Node, const UnicodeString & Name, const UnicodeString & Default);\r\n int __fastcall ReadXmlNode(_di_IXMLNode Node, const UnicodeString & Name, int Default);\r\n _di_IXMLNode __fastcall FindSettingsNode(_di_IXMLNode Node, const UnicodeString & Name);\r\n UnicodeString __fastcall ReadSettingsNode(_di_IXMLNode Node, const UnicodeString & Name, const UnicodeString & Default);\r\n int __fastcall ReadSettingsNode(_di_IXMLNode Node, const UnicodeString & Name, int Default);\r\n bool __fastcall IsSame(const TSessionData * Default, bool AdvancedOnly, TStrings * DifferentProperties, bool Decrypted);\r\n UnicodeString __fastcall GetNameWithoutHiddenPrefix();\r\n bool __fastcall HasStateData();\r\n void __fastcall CopyStateData(TSessionData * SourceData);\r\n void __fastcall CopyNonCoreData(TSessionData * SourceData);\r\n UnicodeString __fastcall GetNormalizedPuttyProtocol() const;\r\n static RawByteString __fastcall EncryptPassword(const UnicodeString & Password, UnicodeString Key);\r\n static UnicodeString __fastcall DecryptPassword(const RawByteString & Password, UnicodeString Key);\r\n static RawByteString __fastcall StronglyRecryptPassword(const RawByteString & Password, UnicodeString Key);\r\n static bool __fastcall DoIsProtocolUrl(const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen);\r\n static bool __fastcall IsProtocolUrl(const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen);\r\n static void __fastcall AddSwitch(UnicodeString & Result, const UnicodeString & Name, bool Rtf);\r\n static void __fastcall AddSwitch(\r\n UnicodeString & Result, const UnicodeString & Name, const UnicodeString & Value, bool Rtf);\r\n static void __fastcall AddSwitch(UnicodeString & Result, const UnicodeString & Name, int Value, bool Rtf);\r\n static void __fastcall AddAssemblyProperty(\r\n UnicodeString & Result, TAssemblyLanguage Language,\r\n const UnicodeString & Name, const UnicodeString & Value);\r\n static void __fastcall AddAssemblyProperty(\r\n UnicodeString & Result, TAssemblyLanguage Language,\r\n const UnicodeString & Name, const UnicodeString & Type,\r\n const UnicodeString & Member);\r\n static void __fastcall AddAssemblyProperty(\r\n UnicodeString & Result, TAssemblyLanguage Language,\r\n const UnicodeString & Name, int Value);\r\n void __fastcall AddAssemblyProperty(\r\n UnicodeString & Result, TAssemblyLanguage Language,\r\n const UnicodeString & Name, bool Value);\r\n TStrings * __fastcall GetRawSettingsForUrl();\r\n void __fastcall DoCopyData(TSessionData * SourceData, bool NoRecrypt);\r\n template<class AlgoT>\r\n void __fastcall SetAlgoList(AlgoT * List, const AlgoT * DefaultList, const UnicodeString * Names,\r\n int Count, AlgoT WarnAlgo, UnicodeString value);\r\n static void __fastcall Remove(THierarchicalStorage * Storage, const UnicodeString & Name);\r\n\r\n __property UnicodeString InternalStorageKey = { read = GetInternalStorageKey };\r\n\r\npublic:\r\n __fastcall TSessionData(UnicodeString aName);\r\n virtual __fastcall ~TSessionData();\r\n TSessionData * __fastcall Clone();\r\n void __fastcall Default();\r\n void __fastcall DefaultSettings();\r\n void __fastcall NonPersistant();\r\n void __fastcall Load(THierarchicalStorage * Storage, bool PuttyImport);\r", " void __fastcall ApplyRawSettings(TStrings * RawSettings);\r\n void __fastcall ApplyRawSettings(THierarchicalStorage * Storage);\r", " void __fastcall ImportFromFilezilla(_di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode);\r\n void __fastcall Save(THierarchicalStorage * Storage, bool PuttyExport,\r\n const TSessionData * Default = NULL);\r\n void __fastcall SaveRecryptedPasswords(THierarchicalStorage * Storage);\r\n void __fastcall RecryptPasswords();\r\n bool __fastcall HasPassword();\r\n bool __fastcall HasAnySessionPassword();\r\n bool __fastcall HasAnyPassword();\r\n void __fastcall ClearSessionPasswords();\r\n void __fastcall MaskPasswords();\r\n void __fastcall Remove();\r\n void __fastcall CacheHostKeyIfNotCached();\r\n virtual void __fastcall Assign(TPersistent * Source);\r\n virtual int __fastcall Compare(TNamedObject * Other);\r\n void __fastcall CopyData(TSessionData * Source);\r\n void __fastcall CopyDataNoRecrypt(TSessionData * SourceData);\r\n void __fastcall CopyDirectoriesStateData(TSessionData * SourceData);\r\n bool __fastcall ParseUrl(UnicodeString Url, TOptions * Options,\r\n TStoredSessionList * StoredSessions, bool & DefaultsOnly,\r\n UnicodeString * FileName, bool * AProtocolDefined, UnicodeString * MaskedUrl, int Flags);\r\n TStrings * __fastcall SaveToOptions(const TSessionData * Default, bool SaveName, bool PuttyExport);\r\n void __fastcall ConfigureTunnel(int PortNumber);\r\n void __fastcall RollbackTunnel();\r\n void __fastcall ExpandEnvironmentVariables();\r\n void __fastcall DisableAuthentationsExceptPassword();\r\n bool __fastcall IsSame(const TSessionData * Default, bool AdvancedOnly);\r\n bool __fastcall IsSameDecrypted(const TSessionData * Default);\r\n bool __fastcall IsSameSite(const TSessionData * Default);\r\n bool __fastcall IsInFolderOrWorkspace(UnicodeString Name);\r\n UnicodeString __fastcall GenerateSessionUrl(unsigned int Flags);\r\n bool __fastcall HasRawSettingsForUrl();\r\n bool __fastcall HasSessionName();\r\n\r\n UnicodeString __fastcall GenerateOpenCommandArgs(bool Rtf);\r\n void __fastcall GenerateAssemblyCode(TAssemblyLanguage Language, UnicodeString & Head, UnicodeString & Tail, int & Indent);\r\n void __fastcall LookupLastFingerprint();\r\n bool __fastcall IsSecure();\r\n static void __fastcall ValidatePath(const UnicodeString Path);\r\n static void __fastcall ValidateName(const UnicodeString Name);\r\n static UnicodeString __fastcall MakeValidName(const UnicodeString & Name);\r\n static UnicodeString __fastcall ExtractLocalName(const UnicodeString & Name);\r\n static UnicodeString __fastcall ExtractFolderName(const UnicodeString & Name);\r\n static UnicodeString __fastcall ComposePath(const UnicodeString & Path, const UnicodeString & Name);\r\n static bool __fastcall IsSensitiveOption(const UnicodeString & Option);\r\n static bool __fastcall IsOptionWithParameters(const UnicodeString & Option);\r\n static bool __fastcall MaskPasswordInOptionParameter(const UnicodeString & Option, UnicodeString & Param);\r\n static UnicodeString __fastcall FormatSiteKey(const UnicodeString & HostName, int PortNumber);\r\n static TStrings * GetAllOptionNames(bool PuttyExport);\r\n\r\n __property UnicodeString HostName = { read=FHostName, write=SetHostName };\r\n __property UnicodeString HostNameExpanded = { read=GetHostNameExpanded };\r\n __property int PortNumber = { read=FPortNumber, write=SetPortNumber };\r\n __property UnicodeString UserName = { read=FUserName, write=SetUserName };\r\n __property UnicodeString UserNameExpanded = { read=GetUserNameExpanded };\r\n __property UnicodeString Password = { read=GetPassword, write=SetPassword };\r\n __property UnicodeString NewPassword = { read=GetNewPassword, write=SetNewPassword };\r\n __property bool ChangePassword = { read=FChangePassword, write=SetChangePassword };\r\n __property int PingInterval = { read=FPingInterval, write=SetPingInterval };\r\n __property bool TryAgent = { read=FTryAgent, write=SetTryAgent };\r\n __property bool AgentFwd = { read=FAgentFwd, write=SetAgentFwd };\r\n __property UnicodeString ListingCommand = { read = FListingCommand, write = SetListingCommand };\r\n __property bool AuthTIS = { read=FAuthTIS, write=SetAuthTIS };\r\n __property bool AuthKI = { read=FAuthKI, write=SetAuthKI };\r\n __property bool AuthKIPassword = { read=FAuthKIPassword, write=SetAuthKIPassword };\r\n __property bool AuthGSSAPI = { read=FAuthGSSAPI, write=SetAuthGSSAPI };\r\n __property bool GSSAPIFwdTGT = { read=FGSSAPIFwdTGT, write=SetGSSAPIFwdTGT };\r\n __property bool ChangeUsername = { read=FChangeUsername, write=SetChangeUsername };\r\n __property bool Compression = { read=FCompression, write=SetCompression };\r\n __property TSshProt SshProt = { read=FSshProt, write=SetSshProt };\r\n __property bool UsesSsh = { read = GetUsesSsh };\r\n __property bool Ssh2DES = { read=FSsh2DES, write=SetSsh2DES };\r\n __property bool SshNoUserAuth = { read=FSshNoUserAuth, write=SetSshNoUserAuth };\r\n __property TCipher Cipher[int Index] = { read=GetCipher, write=SetCipher };\r\n __property TKex Kex[int Index] = { read=GetKex, write=SetKex };\r\n __property THostKey HostKeys[int Index] = { read=GetHostKeys, write=SetHostKeys };\r\n __property TGssLib GssLib[int Index] = { read=GetGssLib, write=SetGssLib };\r\n __property UnicodeString GssLibCustom = { read=FGssLibCustom, write=SetGssLibCustom };\r\n __property UnicodeString PublicKeyFile = { read=FPublicKeyFile, write=SetPublicKeyFile };\r\n __property UnicodeString Passphrase = { read=GetPassphrase, write=SetPassphrase };\r\n __property UnicodeString PuttyProtocol = { read=FPuttyProtocol, write=SetPuttyProtocol };\r\n __property TFSProtocol FSProtocol = { read=FFSProtocol, write=SetFSProtocol };\r\n __property UnicodeString FSProtocolStr = { read=GetFSProtocolStr };\r\n __property bool Modified = { read=FModified, write=FModified };\r\n __property bool CanLogin = { read=GetCanLogin };\r\n __property bool ClearAliases = { read = FClearAliases, write = SetClearAliases };\r\n __property TDateTime PingIntervalDT = { read = GetPingIntervalDT, write = SetPingIntervalDT };\r\n __property TDateTime TimeDifference = { read = FTimeDifference, write = SetTimeDifference };\r\n __property bool TimeDifferenceAuto = { read = FTimeDifferenceAuto, write = SetTimeDifferenceAuto };\r\n __property TPingType PingType = { read = FPingType, write = SetPingType };\r\n __property UnicodeString SessionName = { read=GetSessionName };\r\n __property UnicodeString DefaultSessionName = { read=GetDefaultSessionName };\r\n __property UnicodeString LocalDirectory = { read=FLocalDirectory, write=SetLocalDirectory };\r\n __property UnicodeString LocalDirectoryExpanded = { read = GetLocalDirectoryExpanded };\r\n __property UnicodeString RemoteDirectory = { read=FRemoteDirectory, write=SetRemoteDirectory };\r\n __property bool SynchronizeBrowsing = { read=FSynchronizeBrowsing, write=SetSynchronizeBrowsing };\r\n __property bool UpdateDirectories = { read=FUpdateDirectories, write=SetUpdateDirectories };\r\n __property bool CacheDirectories = { read=FCacheDirectories, write=SetCacheDirectories };\r\n __property bool CacheDirectoryChanges = { read=FCacheDirectoryChanges, write=SetCacheDirectoryChanges };\r\n __property bool PreserveDirectoryChanges = { read=FPreserveDirectoryChanges, write=SetPreserveDirectoryChanges };\r\n __property bool LockInHome = { read=FLockInHome, write=SetLockInHome };\r\n __property bool Special = { read=FSpecial, write=SetSpecial };\r\n __property bool Selected = { read=FSelected, write=FSelected };\r\n __property UnicodeString InfoTip = { read=GetInfoTip };\r\n __property bool DefaultShell = { read = GetDefaultShell, write = SetDefaultShell };\r\n __property bool DetectReturnVar = { read = GetDetectReturnVar, write = SetDetectReturnVar };\r\n __property TEOLType EOLType = { read = FEOLType, write = SetEOLType };\r\n __property bool TrimVMSVersions = { read = FTrimVMSVersions, write = SetTrimVMSVersions };\r\n __property TAutoSwitch LookupUserGroups = { read = FLookupUserGroups, write = SetLookupUserGroups };\r\n __property UnicodeString ReturnVar = { read = FReturnVar, write = SetReturnVar };\r\n __property bool ExitCode1IsError = { read = FExitCode1IsError, write = SetExitCode1IsError };\r\n __property bool Scp1Compatibility = { read = FScp1Compatibility, write = SetScp1Compatibility };\r\n __property UnicodeString Shell = { read = FShell, write = SetShell };\r\n __property UnicodeString SftpServer = { read = FSftpServer, write = SetSftpServer };\r\n __property int Timeout = { read = FTimeout, write = SetTimeout };\r\n __property TDateTime TimeoutDT = { read = GetTimeoutDT };\r\n __property bool UnsetNationalVars = { read = FUnsetNationalVars, write = SetUnsetNationalVars };\r\n __property bool IgnoreLsWarnings = { read=FIgnoreLsWarnings, write=SetIgnoreLsWarnings };\r\n __property bool TcpNoDelay = { read=FTcpNoDelay, write=SetTcpNoDelay };\r\n __property int SendBuf = { read=FSendBuf, write=SetSendBuf };\r\n __property UnicodeString SourceAddress = { read=FSourceAddress, write=SetSourceAddress };\r\n __property bool SshSimple = { read=FSshSimple, write=SetSshSimple };\r\n __property UnicodeString SshProtStr = { read=GetSshProtStr };\r\n __property UnicodeString CipherList = { read=GetCipherList, write=SetCipherList };\r\n __property UnicodeString KexList = { read=GetKexList, write=SetKexList };\r\n __property UnicodeString HostKeyList = { read=GetHostKeyList, write=SetHostKeyList };\r\n __property UnicodeString GssLibList = { read=GetGssLibList, write=SetGssLibList };\r\n __property TProxyMethod ProxyMethod = { read=FProxyMethod, write=SetProxyMethod };\r\n __property UnicodeString ProxyHost = { read=FProxyHost, write=SetProxyHost };\r\n __property int ProxyPort = { read=FProxyPort, write=SetProxyPort };\r\n __property UnicodeString ProxyUsername = { read=FProxyUsername, write=SetProxyUsername };\r\n __property UnicodeString ProxyPassword = { read=GetProxyPassword, write=SetProxyPassword };\r\n __property UnicodeString ProxyTelnetCommand = { read=FProxyTelnetCommand, write=SetProxyTelnetCommand };\r\n __property UnicodeString ProxyLocalCommand = { read=FProxyLocalCommand, write=SetProxyLocalCommand };\r\n __property TAutoSwitch ProxyDNS = { read=FProxyDNS, write=SetProxyDNS };\r\n __property bool ProxyLocalhost = { read=FProxyLocalhost, write=SetProxyLocalhost };\r\n __property int FtpProxyLogonType = { read=FFtpProxyLogonType, write=SetFtpProxyLogonType };\r\n __property TAutoSwitch Bug[TSshBug Bug] = { read=GetBug, write=SetBug };\r\n __property UnicodeString PuttySettings = { read = FPuttySettings, write = SetPuttySettings };\r\n __property UnicodeString CustomParam1 = { read = FCustomParam1, write = SetCustomParam1 };\r\n __property UnicodeString CustomParam2 = { read = FCustomParam2, write = SetCustomParam2 };\r\n __property UnicodeString SessionKey = { read = GetSessionKey };\r\n __property bool ResolveSymlinks = { read = FResolveSymlinks, write = SetResolveSymlinks };\r\n __property bool FollowDirectorySymlinks = { read = FFollowDirectorySymlinks, write = SetFollowDirectorySymlinks };\r\n __property int SFTPDownloadQueue = { read = FSFTPDownloadQueue, write = SetSFTPDownloadQueue };\r\n __property int SFTPUploadQueue = { read = FSFTPUploadQueue, write = SetSFTPUploadQueue };\r\n __property int SFTPListingQueue = { read = FSFTPListingQueue, write = SetSFTPListingQueue };\r\n __property int SFTPMaxVersion = { read = FSFTPMaxVersion, write = SetSFTPMaxVersion };\r\n __property unsigned long SFTPMaxPacketSize = { read = FSFTPMaxPacketSize, write = SetSFTPMaxPacketSize };\r\n __property TAutoSwitch SFTPBug[TSftpBug Bug] = { read=GetSFTPBug, write=SetSFTPBug };\r\n __property TAutoSwitch SCPLsFullTime = { read = FSCPLsFullTime, write = SetSCPLsFullTime };\r\n __property TAutoSwitch FtpListAll = { read = FFtpListAll, write = SetFtpListAll };\r\n __property TAutoSwitch FtpHost = { read = FFtpHost, write = SetFtpHost };\r\n __property TAutoSwitch FtpDeleteFromCwd = { read = FFtpDeleteFromCwd, write = SetFtpDeleteFromCwd };\r\n __property bool SslSessionReuse = { read = FSslSessionReuse, write = SetSslSessionReuse };\r\n __property UnicodeString TlsCertificateFile = { read=FTlsCertificateFile, write=SetTlsCertificateFile };\r\n __property TDSTMode DSTMode = { read = FDSTMode, write = SetDSTMode };\r\n __property bool DeleteToRecycleBin = { read = FDeleteToRecycleBin, write = SetDeleteToRecycleBin };\r\n __property bool OverwrittenToRecycleBin = { read = FOverwrittenToRecycleBin, write = SetOverwrittenToRecycleBin };\r\n __property UnicodeString RecycleBinPath = { read = FRecycleBinPath, write = SetRecycleBinPath };\r\n __property UnicodeString PostLoginCommands = { read = FPostLoginCommands, write = SetPostLoginCommands };\r\n __property TAddressFamily AddressFamily = { read = FAddressFamily, write = SetAddressFamily };\r\n __property UnicodeString RekeyData = { read = FRekeyData, write = SetRekeyData };\r\n __property unsigned int RekeyTime = { read = FRekeyTime, write = SetRekeyTime };\r\n __property int Color = { read = FColor, write = SetColor };\r\n __property bool Tunnel = { read = FTunnel, write = SetTunnel };\r\n __property UnicodeString TunnelHostName = { read = FTunnelHostName, write = SetTunnelHostName };\r\n __property int TunnelPortNumber = { read = FTunnelPortNumber, write = SetTunnelPortNumber };\r\n __property UnicodeString TunnelUserName = { read = FTunnelUserName, write = SetTunnelUserName };\r\n __property UnicodeString TunnelPassword = { read = GetTunnelPassword, write = SetTunnelPassword };\r\n __property UnicodeString TunnelPublicKeyFile = { read = FTunnelPublicKeyFile, write = SetTunnelPublicKeyFile };\r\n __property bool TunnelAutoassignLocalPortNumber = { read = GetTunnelAutoassignLocalPortNumber };\r\n __property int TunnelLocalPortNumber = { read = FTunnelLocalPortNumber, write = SetTunnelLocalPortNumber };\r\n __property UnicodeString TunnelPortFwd = { read = FTunnelPortFwd, write = SetTunnelPortFwd };\r\n __property UnicodeString TunnelHostKey = { read = FTunnelHostKey, write = SetTunnelHostKey };\r\n __property bool FtpPasvMode = { read = FFtpPasvMode, write = SetFtpPasvMode };\r\n __property TAutoSwitch FtpForcePasvIp = { read = FFtpForcePasvIp, write = SetFtpForcePasvIp };\r\n __property TAutoSwitch FtpUseMlsd = { read = FFtpUseMlsd, write = SetFtpUseMlsd };\r\n __property UnicodeString FtpAccount = { read = FFtpAccount, write = SetFtpAccount };\r\n __property int FtpPingInterval = { read=FFtpPingInterval, write=SetFtpPingInterval };\r\n __property TDateTime FtpPingIntervalDT = { read=GetFtpPingIntervalDT };\r\n __property TPingType FtpPingType = { read = FFtpPingType, write = SetFtpPingType };\r\n __property TAutoSwitch FtpTransferActiveImmediately = { read = FFtpTransferActiveImmediately, write = SetFtpTransferActiveImmediately };\r\n __property TFtps Ftps = { read = FFtps, write = SetFtps };\r\n __property TTlsVersion MinTlsVersion = { read = FMinTlsVersion, write = SetMinTlsVersion };\r\n __property TTlsVersion MaxTlsVersion = { read = FMaxTlsVersion, write = SetMaxTlsVersion };\r\n __property UnicodeString LogicalHostName = { read = FLogicalHostName, write = SetLogicalHostName };\r\n __property TAutoSwitch NotUtf = { read = FNotUtf, write = SetNotUtf };\r\n __property int InternalEditorEncoding = { read = FInternalEditorEncoding, write = SetInternalEditorEncoding };\r\n __property UnicodeString S3DefaultRegion = { read = FS3DefaultRegion, write = SetS3DefaultRegion };\r\n __property TS3UrlStyle S3UrlStyle = { read = FS3UrlStyle, write = SetS3UrlStyle };\r\n __property bool IsWorkspace = { read = FIsWorkspace, write = SetIsWorkspace };\r\n __property UnicodeString Link = { read = FLink, write = SetLink };\r\n __property UnicodeString NameOverride = { read = FNameOverride, write = SetNameOverride };\r\n __property UnicodeString HostKey = { read = FHostKey, write = SetHostKey };\r\n __property bool FingerprintScan = { read = FFingerprintScan, write = FFingerprintScan };\r\n __property bool OverrideCachedHostKey = { read = FOverrideCachedHostKey };\r\n __property UnicodeString Note = { read = FNote, write = SetNote };\r\n __property UnicodeString WinTitle = { read = FWinTitle, write = SetWinTitle };\r\n __property UnicodeString EncryptKey = { read = GetEncryptKey, write = SetEncryptKey };\r\n\r\n __property UnicodeString StorageKey = { read = GetStorageKey };\r\n __property UnicodeString SiteKey = { read = GetSiteKey };\r\n __property UnicodeString OrigHostName = { read = FOrigHostName };\r\n __property int OrigPortNumber = { read = FOrigPortNumber };\r\n __property UnicodeString LocalName = { read = GetLocalName };\r\n __property UnicodeString FolderName = { read = GetFolderName };\r\n __property UnicodeString Source = { read = GetSource };\r\n __property bool SaveOnly = { read = FSaveOnly };\r\n};\r\n//---------------------------------------------------------------------------\r\nclass TStoredSessionList : public TNamedObjectList\r\n{\r\npublic:\r\n __fastcall TStoredSessionList(bool aReadOnly = false);\r\n void __fastcall Reload();\r\n void __fastcall Save(bool All, bool Explicit);\r\n void __fastcall Saved();\r\n void __fastcall ImportFromFilezilla(const UnicodeString FileName, const UnicodeString ConfigurationFileName);\r\n void __fastcall ImportFromKnownHosts(TStrings * Lines);\r\n void __fastcall Export(const UnicodeString FileName);\r\n void __fastcall Load(THierarchicalStorage * Storage, bool AsModified = false,\r\n bool UseDefaults = false, bool PuttyImport = false);\r\n void __fastcall Save(THierarchicalStorage * Storage, bool All = false);\r\n void __fastcall SelectAll(bool Select);\r\n void __fastcall Import(TStoredSessionList * From, bool OnlySelected, TList * Imported);\r\n void __fastcall RecryptPasswords(TStrings * RecryptPasswordErrors);\r\n TSessionData * __fastcall AtSession(int Index)\r\n { return (TSessionData*)AtObject(Index); }\r\n void __fastcall SelectSessionsToImport(TStoredSessionList * Dest, bool SSHOnly);\r\n void __fastcall Cleanup();\r\n void __fastcall UpdateStaticUsage();\r\n int __fastcall IndexOf(TSessionData * Data);\r\n TSessionData * __fastcall FindSame(TSessionData * Data);\r\n TSessionData * __fastcall NewSession(UnicodeString SessionName, TSessionData * Session);\r\n void __fastcall NewWorkspace(UnicodeString Name, TList * DataList);\r\n bool __fastcall IsFolder(const UnicodeString & Name);\r\n bool __fastcall IsWorkspace(const UnicodeString & Name);\r\n TSessionData * __fastcall ParseUrl(UnicodeString Url, TOptions * Options, bool & DefaultsOnly,\r\n UnicodeString * FileName = NULL, bool * ProtocolDefined = NULL, UnicodeString * MaskedUrl = NULL, int Flags = 0);\r\n bool __fastcall IsUrl(UnicodeString Url);\r\n bool __fastcall CanLogin(TSessionData * Data);\r\n void __fastcall GetFolderOrWorkspace(const UnicodeString & Name, TList * List);\r\n TStrings * __fastcall GetFolderOrWorkspaceList(const UnicodeString & Name);\r\n TStrings * __fastcall GetWorkspaces();\r\n bool __fastcall HasAnyWorkspace();\r\n TSessionData * __fastcall SaveWorkspaceData(TSessionData * Data, int Index);\r\n virtual __fastcall ~TStoredSessionList();\r\n __property TSessionData * Sessions[int Index] = { read=AtSession };\r\n __property TSessionData * DefaultSettings = { read=FDefaultSettings, write=SetDefaultSettings };\r\n\r\n static void __fastcall ImportHostKeys(\r\n THierarchicalStorage * SourceStorage, THierarchicalStorage * TargetStorage, TStoredSessionList * Sessions, bool OnlySelected);\r\n static void __fastcall ImportHostKeys(\r\n const UnicodeString & SourceKey, TStoredSessionList * Sessions, bool OnlySelected);\r\n static void __fastcall ImportSelectedKnownHosts(TStoredSessionList * Sessions);\r\n static bool __fastcall OpenHostKeysSubKey(THierarchicalStorage * Storage, bool CanCreate);\r\n\r\nprivate:\r\n TSessionData * FDefaultSettings;\r\n bool FReadOnly;\r\n std::unique_ptr<TStrings> FPendingRemovals;\r\n void __fastcall SetDefaultSettings(TSessionData * value);\r\n void __fastcall DoSave(THierarchicalStorage * Storage, bool All,\r\n bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors);\r\n void __fastcall DoSave(bool All, bool Explicit, bool RecryptPasswordOnly,\r\n TStrings * RecryptPasswordErrors);\r\n void __fastcall DoSave(THierarchicalStorage * Storage,\r\n TSessionData * Data, bool All, bool RecryptPasswordOnly,\r\n TSessionData * FactoryDefaults);\r\n TSessionData * __fastcall ResolveWorkspaceData(TSessionData * Data);\r\n bool __fastcall IsFolderOrWorkspace(const UnicodeString & Name, bool Workspace);\r\n TSessionData * __fastcall CheckIsInFolderOrWorkspaceAndResolve(\r\n TSessionData * Data, const UnicodeString & Name);\r\n void __fastcall ImportLevelFromFilezilla(_di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode);\r\n void __fastcall DoGetFolderOrWorkspace(const UnicodeString & Name, TList * List, bool NoRecrypt);\r\n static THierarchicalStorage * __fastcall CreateHostKeysStorageForWritting();\r\n};\r\n//---------------------------------------------------------------------------\r\nUnicodeString GetExpandedLogFileName(UnicodeString LogFileName, TDateTime Started, TSessionData * SessionData);\r\nbool __fastcall IsSshProtocol(TFSProtocol FSProtocol);\r\nint __fastcall DefaultPort(TFSProtocol FSProtocol, TFtps Ftps);\r\nbool __fastcall IsIPv6Literal(const UnicodeString & HostName);\r\nUnicodeString __fastcall EscapeIPv6Literal(const UnicodeString & IP);\r\nTFSProtocol NormalizeFSProtocol(TFSProtocol FSProtocol);\r\n//---------------------------------------------------------------------------\r\n#endif" ]
[ 1, 0, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 53, 80, 2275, 473, 1511, 2372, 1100], "buggy_code_start_loc": [46, 52, 79, 599, 57, 1510, 2371, 1099], "filenames": ["source/Console.cbproj", "source/DragExt.cbproj", "source/WinSCP.cbproj", "source/core/SessionData.cpp", "source/core/SessionData.h", "source/forms/Custom.cpp", "source/windows/ConsoleRunner.cpp", "source/windows/WinMain.cpp"], "fixing_code_end_loc": [47, 53, 80, 2294, 474, 1511, 2372, 1103], "fixing_code_start_loc": [46, 52, 79, 599, 58, 1510, 2371, 1099], "message": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:winscp:winscp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C081564B-8EF8-4C8A-9EB0-1C50D5A8F18B", "versionEndExcluding": "5.17.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)"}, {"lang": "es", "value": "WinSCP anterior a la versi\u00f3n 5.17.10 permite a los atacantes remotos ejecutar programas arbitrarios cuando el manejador de URLs encuentra una URL manipulada que carga la configuraci\u00f3n de la sesi\u00f3n. (Por ejemplo, esto es explotable en una instalaci\u00f3n por defecto en la que WinSCP es el manejador de URLs sftp://)"}], "evaluatorComment": null, "id": "CVE-2021-3331", "lastModified": "2021-02-04T15:59:24.960", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-01-27T21:15:16.840", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://winscp.net/eng/docs/history#5.17.10"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://winscp.net/eng/docs/rawsettings"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://winscp.net/tracker/1943"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, "type": "NVD-CWE-Other"}
177
Determine whether the {function_name} code is vulnerable or not.
[ "//---------------------------------------------------------------------------\r\n#ifndef SessionDataH\r\n#define SessionDataH\r\n\r\n#include \"Common.h\"\r\n#include \"Option.h\"\r\n#include \"FileBuffer.h\"\r\n#include \"NamedObjs.h\"\r\n#include \"HierarchicalStorage.h\"\r\n#include \"Configuration.h\"\r\n#include <Xml.XMLIntf.hpp>\r\n//---------------------------------------------------------------------------\r\nenum TCipher { cipWarn, cip3DES, cipBlowfish, cipAES, cipDES, cipArcfour, cipChaCha20 };\r\n#define CIPHER_COUNT (cipChaCha20+1)\r\n// explicit values to skip obsoleted fsExternalSSH, fsExternalSFTP\r\nenum TFSProtocol { fsSCPonly = 0, fsSFTP = 1, fsSFTPonly = 2, fsFTP = 5, fsWebDAV = 6, fsS3 = 7 };\r\n#define FSPROTOCOL_COUNT (fsS3+1)\r\nextern const wchar_t * ProxyMethodNames;\r\nenum TProxyMethod { pmNone, pmSocks4, pmSocks5, pmHTTP, pmTelnet, pmCmd };\r\nenum TSshProt { ssh1only, ssh1deprecated, ssh2deprecated, ssh2only };\r\nenum TKex { kexWarn, kexDHGroup1, kexDHGroup14, kexDHGEx, kexRSA, kexECDH };\r\n#define KEX_COUNT (kexECDH+1)\r\nenum THostKey { hkWarn, hkRSA, hkDSA, hkECDSA, hkED25519, hkMax };\r\n#define HOSTKEY_COUNT (hkMax)\r\nenum TGssLib { gssGssApi32, gssSspi, gssCustom };\r\n#define GSSLIB_COUNT (gssCustom+1)\r\n// names have to match PuTTY registry entries (see settings.c)\r\nenum TSshBug { sbIgnore1, sbPlainPW1, sbRSA1, sbHMAC2, sbDeriveKey2, sbRSAPad2,\r\n sbPKSessID2, sbRekey2, sbMaxPkt2, sbIgnore2, sbOldGex2, sbWinAdj, sbChanReq };\r\n#define BUG_COUNT (sbChanReq+1)\r\nenum TSftpBug { sbSymlink, sbSignedTS };\r\n#define SFTP_BUG_COUNT (sbSignedTS+1)\r\nextern const wchar_t * PingTypeNames;\r\nenum TPingType { ptOff, ptNullPacket, ptDummyCommand };\r\nenum TAddressFamily { afAuto, afIPv4, afIPv6 };\r\nenum TFtps { ftpsNone, ftpsImplicit, ftpsExplicitSsl, ftpsExplicitTls };\r\n// has to match SSL_VERSION_XXX constants in AsyncSslSocketLayer.h\r\n// ssl2 has no effect now\r\nenum TTlsVersion { ssl2 = 2, ssl3 = 3, tls10 = 10, tls11 = 11, tls12 = 12, tls13 = 13 };\r\n// has to match libs3 S3UriStyle\r\nenum TS3UrlStyle { s3usVirtualHost, s3usPath };\r\nenum TSessionSource { ssNone, ssStored, ssStoredModified };\r\nenum TSessionUrlFlags\r\n{\r\n sufSpecific = 0x01,\r\n sufUserName = 0x02,\r\n sufPassword = 0x04,\r\n sufHostKey = 0x08,\r\n sufRawSettings = 0x10,\r\n sufHttpForWebDAV = 0x20,\r\n sufSession = sufUserName | sufPassword | sufHostKey,\r\n sufComplete = sufSession | sufRawSettings,\r\n sufOpen = sufUserName | sufPassword\r\n};\r\nenum TParseUrlFlags\r\n{\r\n pufAllowStoredSiteWithProtocol = 0x01,\r", " pufUnsafe = 0x02,\r", "};\r\n//---------------------------------------------------------------------------\r\nextern const UnicodeString CipherNames[CIPHER_COUNT];\r\nextern const UnicodeString KexNames[KEX_COUNT];\r\nextern const UnicodeString HostKeyNames[HOSTKEY_COUNT];\r\nextern const UnicodeString GssLibNames[GSSLIB_COUNT];\r\nextern const wchar_t SshProtList[][10];\r\nextern const TCipher DefaultCipherList[CIPHER_COUNT];\r\nextern const TKex DefaultKexList[KEX_COUNT];\r\nextern const THostKey DefaultHostKeyList[HOSTKEY_COUNT];\r\nextern const TGssLib DefaultGssLibList[GSSLIB_COUNT];\r\nextern const wchar_t FSProtocolNames[FSPROTOCOL_COUNT][16];\r\nextern const int DefaultSendBuf;\r\nextern const UnicodeString AnonymousUserName;\r\nextern const UnicodeString AnonymousPassword;\r\nextern const int SshPortNumber;\r\nextern const int FtpPortNumber;\r\nextern const int FtpsImplicitPortNumber;\r\nextern const int HTTPPortNumber;\r\nextern const int HTTPSPortNumber;\r\nextern const int TelnetPortNumber;\r\nextern const int ProxyPortNumber;\r\nextern const UnicodeString PuttySshProtocol;\r\nextern const UnicodeString PuttyTelnetProtocol;\r\nextern const UnicodeString SftpProtocol;\r\nextern const UnicodeString ScpProtocol;\r\nextern const UnicodeString FtpProtocol;\r\nextern const UnicodeString FtpsProtocol;\r\nextern const UnicodeString FtpesProtocol;\r\nextern const UnicodeString WebDAVProtocol;\r\nextern const UnicodeString WebDAVSProtocol;\r\nextern const UnicodeString S3Protocol;\r\nextern const UnicodeString SshProtocol;\r\nextern const UnicodeString WinSCPProtocolPrefix;\r\nextern const wchar_t UrlParamSeparator;\r\nextern const wchar_t UrlParamValueSeparator;\r\nextern const UnicodeString UrlHostKeyParamName;\r\nextern const UnicodeString UrlSaveParamName;\r\nextern const UnicodeString PassphraseOption;\r\nextern const UnicodeString S3HostName;\r\n//---------------------------------------------------------------------------\r\nclass TStoredSessionList;\r\n//---------------------------------------------------------------------------\r\nclass TSessionData : public TNamedObject\r\n{\r\nfriend class TStoredSessionList;\r\n\r\nprivate:\r\n UnicodeString FHostName;\r\n int FPortNumber;\r\n UnicodeString FUserName;\r\n RawByteString FPassword;\r\n RawByteString FNewPassword;\r\n bool FChangePassword;\r\n int FPingInterval;\r\n TPingType FPingType;\r\n bool FTryAgent;\r\n bool FAgentFwd;\r\n UnicodeString FListingCommand;\r\n bool FAuthTIS;\r\n bool FAuthKI;\r\n bool FAuthKIPassword;\r\n bool FAuthGSSAPI;\r\n bool FGSSAPIFwdTGT;\r\n bool FChangeUsername;\r\n bool FCompression;\r\n TSshProt FSshProt;\r\n bool FSsh2DES;\r\n bool FSshNoUserAuth;\r\n TCipher FCiphers[CIPHER_COUNT];\r\n TKex FKex[KEX_COUNT];\r\n THostKey FHostKeys[HOSTKEY_COUNT];\r\n TGssLib FGssLib[GSSLIB_COUNT];\r\n UnicodeString FGssLibCustom;\r\n bool FClearAliases;\r\n TEOLType FEOLType;\r\n bool FTrimVMSVersions;\r\n UnicodeString FPublicKeyFile;\r\n UnicodeString FPassphrase;\r\n UnicodeString FPuttyProtocol;\r\n TFSProtocol FFSProtocol;\r\n bool FModified;\r\n UnicodeString FLocalDirectory;\r\n UnicodeString FRemoteDirectory;\r\n bool FLockInHome;\r\n bool FSpecial;\r\n bool FSynchronizeBrowsing;\r\n bool FUpdateDirectories;\r\n bool FCacheDirectories;\r\n bool FCacheDirectoryChanges;\r\n bool FPreserveDirectoryChanges;\r\n bool FSelected;\r\n TAutoSwitch FLookupUserGroups;\r\n UnicodeString FReturnVar;\r\n bool FExitCode1IsError;\r\n bool FScp1Compatibility;\r\n UnicodeString FShell;\r\n UnicodeString FSftpServer;\r\n int FTimeout;\r\n bool FUnsetNationalVars;\r\n bool FIgnoreLsWarnings;\r\n bool FTcpNoDelay;\r\n int FSendBuf;\r\n UnicodeString FSourceAddress;\r\n bool FSshSimple;\r\n TProxyMethod FProxyMethod;\r\n UnicodeString FProxyHost;\r\n int FProxyPort;\r\n UnicodeString FProxyUsername;\r\n RawByteString FProxyPassword;\r\n UnicodeString FProxyTelnetCommand;\r\n UnicodeString FProxyLocalCommand;\r\n TAutoSwitch FProxyDNS;\r\n bool FProxyLocalhost;\r\n int FFtpProxyLogonType;\r\n TAutoSwitch FBugs[BUG_COUNT];\r\n UnicodeString FPuttySettings;\r\n UnicodeString FCustomParam1;\r\n UnicodeString FCustomParam2;\r\n bool FResolveSymlinks;\r\n bool FFollowDirectorySymlinks;\r\n TDateTime FTimeDifference;\r\n bool FTimeDifferenceAuto;\r\n int FSFTPDownloadQueue;\r\n int FSFTPUploadQueue;\r\n int FSFTPListingQueue;\r\n int FSFTPMaxVersion;\r\n unsigned long FSFTPMaxPacketSize;\r\n TDSTMode FDSTMode;\r\n TAutoSwitch FSFTPBugs[SFTP_BUG_COUNT];\r\n bool FDeleteToRecycleBin;\r\n bool FOverwrittenToRecycleBin;\r\n UnicodeString FRecycleBinPath;\r\n UnicodeString FPostLoginCommands;\r\n TAutoSwitch FSCPLsFullTime;\r\n TAutoSwitch FFtpListAll;\r\n TAutoSwitch FFtpHost;\r\n TAutoSwitch FFtpDeleteFromCwd;\r\n bool FSslSessionReuse;\r\n UnicodeString FTlsCertificateFile;\r\n TAddressFamily FAddressFamily;\r\n UnicodeString FRekeyData;\r\n unsigned int FRekeyTime;\r\n int FColor;\r\n bool FTunnel;\r\n UnicodeString FTunnelHostName;\r\n int FTunnelPortNumber;\r\n UnicodeString FTunnelUserName;\r\n RawByteString FTunnelPassword;\r\n UnicodeString FTunnelPublicKeyFile;\r\n int FTunnelLocalPortNumber;\r\n UnicodeString FTunnelPortFwd;\r\n UnicodeString FTunnelHostKey;\r\n bool FFtpPasvMode;\r\n TAutoSwitch FFtpForcePasvIp;\r\n TAutoSwitch FFtpUseMlsd;\r\n UnicodeString FFtpAccount;\r\n int FFtpPingInterval;\r\n TPingType FFtpPingType;\r\n TAutoSwitch FFtpTransferActiveImmediately;\r\n TFtps FFtps;\r\n TTlsVersion FMinTlsVersion;\r\n TTlsVersion FMaxTlsVersion;\r\n TAutoSwitch FNotUtf;\r\n int FInternalEditorEncoding;\r\n UnicodeString FS3DefaultRegion;\r\n TS3UrlStyle FS3UrlStyle;\r\n bool FIsWorkspace;\r\n UnicodeString FLink;\r\n UnicodeString FNameOverride;\r\n UnicodeString FHostKey;\r\n bool FFingerprintScan;\r\n bool FOverrideCachedHostKey;\r\n UnicodeString FNote;\r\n UnicodeString FWinTitle;\r\n RawByteString FEncryptKey;\r\n\r\n UnicodeString FOrigHostName;\r\n int FOrigPortNumber;\r\n TProxyMethod FOrigProxyMethod;\r\n TSessionSource FSource;\r\n bool FSaveOnly;\r\n UnicodeString FLogicalHostName;\r\n\r\n void __fastcall SetHostName(UnicodeString value);\r\n UnicodeString __fastcall GetHostNameExpanded();\r\n void __fastcall SetPortNumber(int value);\r\n void __fastcall SetUserName(UnicodeString value);\r\n UnicodeString __fastcall GetUserNameExpanded();\r\n void __fastcall SetPassword(UnicodeString value);\r\n UnicodeString __fastcall GetPassword() const;\r\n void __fastcall SetNewPassword(UnicodeString value);\r\n UnicodeString __fastcall GetNewPassword() const;\r\n void __fastcall SetChangePassword(bool value);\r\n void __fastcall SetPingInterval(int value);\r\n void __fastcall SetTryAgent(bool value);\r\n void __fastcall SetAgentFwd(bool value);\r\n void __fastcall SetAuthTIS(bool value);\r\n void __fastcall SetAuthKI(bool value);\r\n void __fastcall SetAuthKIPassword(bool value);\r\n void __fastcall SetAuthGSSAPI(bool value);\r\n void __fastcall SetGSSAPIFwdTGT(bool value);\r\n void __fastcall SetChangeUsername(bool value);\r\n void __fastcall SetCompression(bool value);\r\n void __fastcall SetSshProt(TSshProt value);\r\n void __fastcall SetSsh2DES(bool value);\r\n void __fastcall SetSshNoUserAuth(bool value);\r\n void __fastcall SetCipher(int Index, TCipher value);\r\n TCipher __fastcall GetCipher(int Index) const;\r\n void __fastcall SetKex(int Index, TKex value);\r\n TKex __fastcall GetKex(int Index) const;\r\n void __fastcall SetHostKeys(int Index, THostKey value);\r\n THostKey __fastcall GetHostKeys(int Index) const;\r\n void __fastcall SetGssLib(int Index, TGssLib value);\r\n TGssLib __fastcall GetGssLib(int Index) const;\r\n void __fastcall SetGssLibCustom(UnicodeString value);\r\n void __fastcall SetPublicKeyFile(UnicodeString value);\r\n UnicodeString __fastcall GetPassphrase() const;\r\n void __fastcall SetPassphrase(UnicodeString value);\r\n\r\n void __fastcall SetPuttyProtocol(UnicodeString value);\r\n bool __fastcall GetCanLogin();\r\n void __fastcall SetPingIntervalDT(TDateTime value);\r\n TDateTime __fastcall GetPingIntervalDT();\r\n TDateTime __fastcall GetFtpPingIntervalDT();\r\n void __fastcall SetTimeDifference(TDateTime value);\r\n void __fastcall SetTimeDifferenceAuto(bool value);\r\n void __fastcall SetPingType(TPingType value);\r\n UnicodeString __fastcall GetSessionName();\r\n UnicodeString __fastcall GetDefaultSessionName();\r\n UnicodeString __fastcall GetProtocolUrl(bool HttpForWebDAV);\r\n void __fastcall SetFSProtocol(TFSProtocol value);\r\n UnicodeString __fastcall GetFSProtocolStr();\r\n void __fastcall SetLocalDirectory(UnicodeString value);\r\n UnicodeString __fastcall GetLocalDirectoryExpanded();\r\n void __fastcall SetRemoteDirectory(UnicodeString value);\r\n void __fastcall SetSynchronizeBrowsing(bool value);\r\n void __fastcall SetUpdateDirectories(bool value);\r\n void __fastcall SetCacheDirectories(bool value);\r\n void __fastcall SetCacheDirectoryChanges(bool value);\r\n void __fastcall SetPreserveDirectoryChanges(bool value);\r\n void __fastcall SetLockInHome(bool value);\r\n void __fastcall SetSpecial(bool value);\r\n UnicodeString __fastcall GetInfoTip();\r\n bool __fastcall GetDefaultShell();\r\n void __fastcall SetDetectReturnVar(bool value);\r\n bool __fastcall GetDetectReturnVar();\r\n void __fastcall SetListingCommand(UnicodeString value);\r\n void __fastcall SetClearAliases(bool value);\r\n void __fastcall SetDefaultShell(bool value);\r\n void __fastcall SetEOLType(TEOLType value);\r\n void __fastcall SetTrimVMSVersions(bool value);\r\n void __fastcall SetLookupUserGroups(TAutoSwitch value);\r\n void __fastcall SetReturnVar(UnicodeString value);\r\n void __fastcall SetExitCode1IsError(bool value);\r\n void __fastcall SetScp1Compatibility(bool value);\r\n void __fastcall SetShell(UnicodeString value);\r\n void __fastcall SetSftpServer(UnicodeString value);\r\n void __fastcall SetTimeout(int value);\r\n void __fastcall SetUnsetNationalVars(bool value);\r\n void __fastcall SetIgnoreLsWarnings(bool value);\r\n void __fastcall SetTcpNoDelay(bool value);\r\n void __fastcall SetSendBuf(int value);\r\n void __fastcall SetSourceAddress(const UnicodeString & value);\r\n void __fastcall SetSshSimple(bool value);\r\n UnicodeString __fastcall GetSshProtStr();\r\n bool __fastcall GetUsesSsh();\r\n void __fastcall SetCipherList(UnicodeString value);\r\n UnicodeString __fastcall GetCipherList() const;\r\n void __fastcall SetKexList(UnicodeString value);\r\n UnicodeString __fastcall GetKexList() const;\r\n void __fastcall SetHostKeyList(UnicodeString value);\r\n UnicodeString __fastcall GetHostKeyList() const;\r\n void __fastcall SetGssLibList(UnicodeString value);\r\n UnicodeString __fastcall GetGssLibList() const;\r\n void __fastcall SetProxyMethod(TProxyMethod value);\r\n void __fastcall SetProxyHost(UnicodeString value);\r\n void __fastcall SetProxyPort(int value);\r\n void __fastcall SetProxyUsername(UnicodeString value);\r\n void __fastcall SetProxyPassword(UnicodeString value);\r\n void __fastcall SetProxyTelnetCommand(UnicodeString value);\r\n void __fastcall SetProxyLocalCommand(UnicodeString value);\r\n void __fastcall SetProxyDNS(TAutoSwitch value);\r\n void __fastcall SetProxyLocalhost(bool value);\r\n UnicodeString __fastcall GetProxyPassword() const;\r\n void __fastcall SetFtpProxyLogonType(int value);\r\n void __fastcall SetBug(TSshBug Bug, TAutoSwitch value);\r\n TAutoSwitch __fastcall GetBug(TSshBug Bug) const;\r\n UnicodeString __fastcall GetSessionKey();\r\n void __fastcall SetPuttySettings(UnicodeString value);\r\n void __fastcall SetCustomParam1(UnicodeString value);\r\n void __fastcall SetCustomParam2(UnicodeString value);\r\n void __fastcall SetResolveSymlinks(bool value);\r\n void __fastcall SetFollowDirectorySymlinks(bool value);\r\n void __fastcall SetSFTPDownloadQueue(int value);\r\n void __fastcall SetSFTPUploadQueue(int value);\r\n void __fastcall SetSFTPListingQueue(int value);\r\n void __fastcall SetSFTPMaxVersion(int value);\r\n void __fastcall SetSFTPMaxPacketSize(unsigned long value);\r\n void __fastcall SetSFTPBug(TSftpBug Bug, TAutoSwitch value);\r\n TAutoSwitch __fastcall GetSFTPBug(TSftpBug Bug) const;\r\n void __fastcall SetSCPLsFullTime(TAutoSwitch value);\r\n void __fastcall SetFtpListAll(TAutoSwitch value);\r\n void __fastcall SetFtpHost(TAutoSwitch value);\r\n void __fastcall SetFtpDeleteFromCwd(TAutoSwitch value);\r\n void __fastcall SetSslSessionReuse(bool value);\r\n void __fastcall SetTlsCertificateFile(UnicodeString value);\r\n UnicodeString __fastcall GetStorageKey();\r\n UnicodeString __fastcall GetInternalStorageKey();\r\n UnicodeString __fastcall GetSiteKey();\r\n void __fastcall SetDSTMode(TDSTMode value);\r\n void __fastcall SetDeleteToRecycleBin(bool value);\r\n void __fastcall SetOverwrittenToRecycleBin(bool value);\r\n void __fastcall SetRecycleBinPath(UnicodeString value);\r\n void __fastcall SetPostLoginCommands(UnicodeString value);\r\n void __fastcall SetAddressFamily(TAddressFamily value);\r\n void __fastcall SetRekeyData(UnicodeString value);\r\n void __fastcall SetRekeyTime(unsigned int value);\r\n void __fastcall SetColor(int value);\r\n void __fastcall SetTunnel(bool value);\r\n void __fastcall SetTunnelHostName(UnicodeString value);\r\n void __fastcall SetTunnelPortNumber(int value);\r\n void __fastcall SetTunnelUserName(UnicodeString value);\r\n void __fastcall SetTunnelPassword(UnicodeString value);\r\n UnicodeString __fastcall GetTunnelPassword() const;\r\n void __fastcall SetTunnelPublicKeyFile(UnicodeString value);\r\n void __fastcall SetTunnelPortFwd(UnicodeString value);\r\n void __fastcall SetTunnelLocalPortNumber(int value);\r\n bool __fastcall GetTunnelAutoassignLocalPortNumber();\r\n void __fastcall SetTunnelHostKey(UnicodeString value);\r\n void __fastcall SetFtpPasvMode(bool value);\r\n void __fastcall SetFtpForcePasvIp(TAutoSwitch value);\r\n void __fastcall SetFtpUseMlsd(TAutoSwitch value);\r\n void __fastcall SetFtpAccount(UnicodeString value);\r\n void __fastcall SetFtpPingInterval(int value);\r\n void __fastcall SetFtpPingType(TPingType value);\r\n void __fastcall SetFtpTransferActiveImmediately(TAutoSwitch value);\r\n void __fastcall SetFtps(TFtps value);\r\n void __fastcall SetMinTlsVersion(TTlsVersion value);\r\n void __fastcall SetMaxTlsVersion(TTlsVersion value);\r\n void __fastcall SetNotUtf(TAutoSwitch value);\r\n void __fastcall SetInternalEditorEncoding(int value);\r\n void __fastcall SetS3DefaultRegion(UnicodeString value);\r\n void __fastcall SetS3UrlStyle(TS3UrlStyle value);\r\n void __fastcall SetLogicalHostName(UnicodeString value);\r\n void __fastcall SetIsWorkspace(bool value);\r\n void __fastcall SetLink(UnicodeString value);\r\n void __fastcall SetNameOverride(UnicodeString value);\r\n void __fastcall SetHostKey(UnicodeString value);\r\n void __fastcall SetNote(UnicodeString value);\r\n void __fastcall SetWinTitle(UnicodeString value);\r\n UnicodeString __fastcall GetEncryptKey() const;\r\n void __fastcall SetEncryptKey(UnicodeString value);\r\n\r\n TDateTime __fastcall GetTimeoutDT();\r\n void __fastcall SavePasswords(THierarchicalStorage * Storage, bool PuttyExport, bool DoNotEncryptPasswords, bool SaveAll);\r\n UnicodeString __fastcall GetLocalName();\r\n UnicodeString __fastcall GetFolderName();\r\n void __fastcall Modify();\r\n UnicodeString __fastcall GetSource();\r", " void __fastcall DoLoad(THierarchicalStorage * Storage, bool PuttyImport, bool & RewritePassword, bool Unsafe);\r", " void __fastcall DoSave(THierarchicalStorage * Storage,\r\n bool PuttyExport, const TSessionData * Default, bool DoNotEncryptPasswords);\r\n UnicodeString __fastcall ReadXmlNode(_di_IXMLNode Node, const UnicodeString & Name, const UnicodeString & Default);\r\n int __fastcall ReadXmlNode(_di_IXMLNode Node, const UnicodeString & Name, int Default);\r\n _di_IXMLNode __fastcall FindSettingsNode(_di_IXMLNode Node, const UnicodeString & Name);\r\n UnicodeString __fastcall ReadSettingsNode(_di_IXMLNode Node, const UnicodeString & Name, const UnicodeString & Default);\r\n int __fastcall ReadSettingsNode(_di_IXMLNode Node, const UnicodeString & Name, int Default);\r\n bool __fastcall IsSame(const TSessionData * Default, bool AdvancedOnly, TStrings * DifferentProperties, bool Decrypted);\r\n UnicodeString __fastcall GetNameWithoutHiddenPrefix();\r\n bool __fastcall HasStateData();\r\n void __fastcall CopyStateData(TSessionData * SourceData);\r\n void __fastcall CopyNonCoreData(TSessionData * SourceData);\r\n UnicodeString __fastcall GetNormalizedPuttyProtocol() const;\r\n static RawByteString __fastcall EncryptPassword(const UnicodeString & Password, UnicodeString Key);\r\n static UnicodeString __fastcall DecryptPassword(const RawByteString & Password, UnicodeString Key);\r\n static RawByteString __fastcall StronglyRecryptPassword(const RawByteString & Password, UnicodeString Key);\r\n static bool __fastcall DoIsProtocolUrl(const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen);\r\n static bool __fastcall IsProtocolUrl(const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen);\r\n static void __fastcall AddSwitch(UnicodeString & Result, const UnicodeString & Name, bool Rtf);\r\n static void __fastcall AddSwitch(\r\n UnicodeString & Result, const UnicodeString & Name, const UnicodeString & Value, bool Rtf);\r\n static void __fastcall AddSwitch(UnicodeString & Result, const UnicodeString & Name, int Value, bool Rtf);\r\n static void __fastcall AddAssemblyProperty(\r\n UnicodeString & Result, TAssemblyLanguage Language,\r\n const UnicodeString & Name, const UnicodeString & Value);\r\n static void __fastcall AddAssemblyProperty(\r\n UnicodeString & Result, TAssemblyLanguage Language,\r\n const UnicodeString & Name, const UnicodeString & Type,\r\n const UnicodeString & Member);\r\n static void __fastcall AddAssemblyProperty(\r\n UnicodeString & Result, TAssemblyLanguage Language,\r\n const UnicodeString & Name, int Value);\r\n void __fastcall AddAssemblyProperty(\r\n UnicodeString & Result, TAssemblyLanguage Language,\r\n const UnicodeString & Name, bool Value);\r\n TStrings * __fastcall GetRawSettingsForUrl();\r\n void __fastcall DoCopyData(TSessionData * SourceData, bool NoRecrypt);\r\n template<class AlgoT>\r\n void __fastcall SetAlgoList(AlgoT * List, const AlgoT * DefaultList, const UnicodeString * Names,\r\n int Count, AlgoT WarnAlgo, UnicodeString value);\r\n static void __fastcall Remove(THierarchicalStorage * Storage, const UnicodeString & Name);\r\n\r\n __property UnicodeString InternalStorageKey = { read = GetInternalStorageKey };\r\n\r\npublic:\r\n __fastcall TSessionData(UnicodeString aName);\r\n virtual __fastcall ~TSessionData();\r\n TSessionData * __fastcall Clone();\r\n void __fastcall Default();\r\n void __fastcall DefaultSettings();\r\n void __fastcall NonPersistant();\r\n void __fastcall Load(THierarchicalStorage * Storage, bool PuttyImport);\r", " void __fastcall ApplyRawSettings(TStrings * RawSettings, bool Unsafe);\r\n void __fastcall ApplyRawSettings(THierarchicalStorage * Storage, bool Unsafe);\r", " void __fastcall ImportFromFilezilla(_di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode);\r\n void __fastcall Save(THierarchicalStorage * Storage, bool PuttyExport,\r\n const TSessionData * Default = NULL);\r\n void __fastcall SaveRecryptedPasswords(THierarchicalStorage * Storage);\r\n void __fastcall RecryptPasswords();\r\n bool __fastcall HasPassword();\r\n bool __fastcall HasAnySessionPassword();\r\n bool __fastcall HasAnyPassword();\r\n void __fastcall ClearSessionPasswords();\r\n void __fastcall MaskPasswords();\r\n void __fastcall Remove();\r\n void __fastcall CacheHostKeyIfNotCached();\r\n virtual void __fastcall Assign(TPersistent * Source);\r\n virtual int __fastcall Compare(TNamedObject * Other);\r\n void __fastcall CopyData(TSessionData * Source);\r\n void __fastcall CopyDataNoRecrypt(TSessionData * SourceData);\r\n void __fastcall CopyDirectoriesStateData(TSessionData * SourceData);\r\n bool __fastcall ParseUrl(UnicodeString Url, TOptions * Options,\r\n TStoredSessionList * StoredSessions, bool & DefaultsOnly,\r\n UnicodeString * FileName, bool * AProtocolDefined, UnicodeString * MaskedUrl, int Flags);\r\n TStrings * __fastcall SaveToOptions(const TSessionData * Default, bool SaveName, bool PuttyExport);\r\n void __fastcall ConfigureTunnel(int PortNumber);\r\n void __fastcall RollbackTunnel();\r\n void __fastcall ExpandEnvironmentVariables();\r\n void __fastcall DisableAuthentationsExceptPassword();\r\n bool __fastcall IsSame(const TSessionData * Default, bool AdvancedOnly);\r\n bool __fastcall IsSameDecrypted(const TSessionData * Default);\r\n bool __fastcall IsSameSite(const TSessionData * Default);\r\n bool __fastcall IsInFolderOrWorkspace(UnicodeString Name);\r\n UnicodeString __fastcall GenerateSessionUrl(unsigned int Flags);\r\n bool __fastcall HasRawSettingsForUrl();\r\n bool __fastcall HasSessionName();\r\n\r\n UnicodeString __fastcall GenerateOpenCommandArgs(bool Rtf);\r\n void __fastcall GenerateAssemblyCode(TAssemblyLanguage Language, UnicodeString & Head, UnicodeString & Tail, int & Indent);\r\n void __fastcall LookupLastFingerprint();\r\n bool __fastcall IsSecure();\r\n static void __fastcall ValidatePath(const UnicodeString Path);\r\n static void __fastcall ValidateName(const UnicodeString Name);\r\n static UnicodeString __fastcall MakeValidName(const UnicodeString & Name);\r\n static UnicodeString __fastcall ExtractLocalName(const UnicodeString & Name);\r\n static UnicodeString __fastcall ExtractFolderName(const UnicodeString & Name);\r\n static UnicodeString __fastcall ComposePath(const UnicodeString & Path, const UnicodeString & Name);\r\n static bool __fastcall IsSensitiveOption(const UnicodeString & Option);\r\n static bool __fastcall IsOptionWithParameters(const UnicodeString & Option);\r\n static bool __fastcall MaskPasswordInOptionParameter(const UnicodeString & Option, UnicodeString & Param);\r\n static UnicodeString __fastcall FormatSiteKey(const UnicodeString & HostName, int PortNumber);\r\n static TStrings * GetAllOptionNames(bool PuttyExport);\r\n\r\n __property UnicodeString HostName = { read=FHostName, write=SetHostName };\r\n __property UnicodeString HostNameExpanded = { read=GetHostNameExpanded };\r\n __property int PortNumber = { read=FPortNumber, write=SetPortNumber };\r\n __property UnicodeString UserName = { read=FUserName, write=SetUserName };\r\n __property UnicodeString UserNameExpanded = { read=GetUserNameExpanded };\r\n __property UnicodeString Password = { read=GetPassword, write=SetPassword };\r\n __property UnicodeString NewPassword = { read=GetNewPassword, write=SetNewPassword };\r\n __property bool ChangePassword = { read=FChangePassword, write=SetChangePassword };\r\n __property int PingInterval = { read=FPingInterval, write=SetPingInterval };\r\n __property bool TryAgent = { read=FTryAgent, write=SetTryAgent };\r\n __property bool AgentFwd = { read=FAgentFwd, write=SetAgentFwd };\r\n __property UnicodeString ListingCommand = { read = FListingCommand, write = SetListingCommand };\r\n __property bool AuthTIS = { read=FAuthTIS, write=SetAuthTIS };\r\n __property bool AuthKI = { read=FAuthKI, write=SetAuthKI };\r\n __property bool AuthKIPassword = { read=FAuthKIPassword, write=SetAuthKIPassword };\r\n __property bool AuthGSSAPI = { read=FAuthGSSAPI, write=SetAuthGSSAPI };\r\n __property bool GSSAPIFwdTGT = { read=FGSSAPIFwdTGT, write=SetGSSAPIFwdTGT };\r\n __property bool ChangeUsername = { read=FChangeUsername, write=SetChangeUsername };\r\n __property bool Compression = { read=FCompression, write=SetCompression };\r\n __property TSshProt SshProt = { read=FSshProt, write=SetSshProt };\r\n __property bool UsesSsh = { read = GetUsesSsh };\r\n __property bool Ssh2DES = { read=FSsh2DES, write=SetSsh2DES };\r\n __property bool SshNoUserAuth = { read=FSshNoUserAuth, write=SetSshNoUserAuth };\r\n __property TCipher Cipher[int Index] = { read=GetCipher, write=SetCipher };\r\n __property TKex Kex[int Index] = { read=GetKex, write=SetKex };\r\n __property THostKey HostKeys[int Index] = { read=GetHostKeys, write=SetHostKeys };\r\n __property TGssLib GssLib[int Index] = { read=GetGssLib, write=SetGssLib };\r\n __property UnicodeString GssLibCustom = { read=FGssLibCustom, write=SetGssLibCustom };\r\n __property UnicodeString PublicKeyFile = { read=FPublicKeyFile, write=SetPublicKeyFile };\r\n __property UnicodeString Passphrase = { read=GetPassphrase, write=SetPassphrase };\r\n __property UnicodeString PuttyProtocol = { read=FPuttyProtocol, write=SetPuttyProtocol };\r\n __property TFSProtocol FSProtocol = { read=FFSProtocol, write=SetFSProtocol };\r\n __property UnicodeString FSProtocolStr = { read=GetFSProtocolStr };\r\n __property bool Modified = { read=FModified, write=FModified };\r\n __property bool CanLogin = { read=GetCanLogin };\r\n __property bool ClearAliases = { read = FClearAliases, write = SetClearAliases };\r\n __property TDateTime PingIntervalDT = { read = GetPingIntervalDT, write = SetPingIntervalDT };\r\n __property TDateTime TimeDifference = { read = FTimeDifference, write = SetTimeDifference };\r\n __property bool TimeDifferenceAuto = { read = FTimeDifferenceAuto, write = SetTimeDifferenceAuto };\r\n __property TPingType PingType = { read = FPingType, write = SetPingType };\r\n __property UnicodeString SessionName = { read=GetSessionName };\r\n __property UnicodeString DefaultSessionName = { read=GetDefaultSessionName };\r\n __property UnicodeString LocalDirectory = { read=FLocalDirectory, write=SetLocalDirectory };\r\n __property UnicodeString LocalDirectoryExpanded = { read = GetLocalDirectoryExpanded };\r\n __property UnicodeString RemoteDirectory = { read=FRemoteDirectory, write=SetRemoteDirectory };\r\n __property bool SynchronizeBrowsing = { read=FSynchronizeBrowsing, write=SetSynchronizeBrowsing };\r\n __property bool UpdateDirectories = { read=FUpdateDirectories, write=SetUpdateDirectories };\r\n __property bool CacheDirectories = { read=FCacheDirectories, write=SetCacheDirectories };\r\n __property bool CacheDirectoryChanges = { read=FCacheDirectoryChanges, write=SetCacheDirectoryChanges };\r\n __property bool PreserveDirectoryChanges = { read=FPreserveDirectoryChanges, write=SetPreserveDirectoryChanges };\r\n __property bool LockInHome = { read=FLockInHome, write=SetLockInHome };\r\n __property bool Special = { read=FSpecial, write=SetSpecial };\r\n __property bool Selected = { read=FSelected, write=FSelected };\r\n __property UnicodeString InfoTip = { read=GetInfoTip };\r\n __property bool DefaultShell = { read = GetDefaultShell, write = SetDefaultShell };\r\n __property bool DetectReturnVar = { read = GetDetectReturnVar, write = SetDetectReturnVar };\r\n __property TEOLType EOLType = { read = FEOLType, write = SetEOLType };\r\n __property bool TrimVMSVersions = { read = FTrimVMSVersions, write = SetTrimVMSVersions };\r\n __property TAutoSwitch LookupUserGroups = { read = FLookupUserGroups, write = SetLookupUserGroups };\r\n __property UnicodeString ReturnVar = { read = FReturnVar, write = SetReturnVar };\r\n __property bool ExitCode1IsError = { read = FExitCode1IsError, write = SetExitCode1IsError };\r\n __property bool Scp1Compatibility = { read = FScp1Compatibility, write = SetScp1Compatibility };\r\n __property UnicodeString Shell = { read = FShell, write = SetShell };\r\n __property UnicodeString SftpServer = { read = FSftpServer, write = SetSftpServer };\r\n __property int Timeout = { read = FTimeout, write = SetTimeout };\r\n __property TDateTime TimeoutDT = { read = GetTimeoutDT };\r\n __property bool UnsetNationalVars = { read = FUnsetNationalVars, write = SetUnsetNationalVars };\r\n __property bool IgnoreLsWarnings = { read=FIgnoreLsWarnings, write=SetIgnoreLsWarnings };\r\n __property bool TcpNoDelay = { read=FTcpNoDelay, write=SetTcpNoDelay };\r\n __property int SendBuf = { read=FSendBuf, write=SetSendBuf };\r\n __property UnicodeString SourceAddress = { read=FSourceAddress, write=SetSourceAddress };\r\n __property bool SshSimple = { read=FSshSimple, write=SetSshSimple };\r\n __property UnicodeString SshProtStr = { read=GetSshProtStr };\r\n __property UnicodeString CipherList = { read=GetCipherList, write=SetCipherList };\r\n __property UnicodeString KexList = { read=GetKexList, write=SetKexList };\r\n __property UnicodeString HostKeyList = { read=GetHostKeyList, write=SetHostKeyList };\r\n __property UnicodeString GssLibList = { read=GetGssLibList, write=SetGssLibList };\r\n __property TProxyMethod ProxyMethod = { read=FProxyMethod, write=SetProxyMethod };\r\n __property UnicodeString ProxyHost = { read=FProxyHost, write=SetProxyHost };\r\n __property int ProxyPort = { read=FProxyPort, write=SetProxyPort };\r\n __property UnicodeString ProxyUsername = { read=FProxyUsername, write=SetProxyUsername };\r\n __property UnicodeString ProxyPassword = { read=GetProxyPassword, write=SetProxyPassword };\r\n __property UnicodeString ProxyTelnetCommand = { read=FProxyTelnetCommand, write=SetProxyTelnetCommand };\r\n __property UnicodeString ProxyLocalCommand = { read=FProxyLocalCommand, write=SetProxyLocalCommand };\r\n __property TAutoSwitch ProxyDNS = { read=FProxyDNS, write=SetProxyDNS };\r\n __property bool ProxyLocalhost = { read=FProxyLocalhost, write=SetProxyLocalhost };\r\n __property int FtpProxyLogonType = { read=FFtpProxyLogonType, write=SetFtpProxyLogonType };\r\n __property TAutoSwitch Bug[TSshBug Bug] = { read=GetBug, write=SetBug };\r\n __property UnicodeString PuttySettings = { read = FPuttySettings, write = SetPuttySettings };\r\n __property UnicodeString CustomParam1 = { read = FCustomParam1, write = SetCustomParam1 };\r\n __property UnicodeString CustomParam2 = { read = FCustomParam2, write = SetCustomParam2 };\r\n __property UnicodeString SessionKey = { read = GetSessionKey };\r\n __property bool ResolveSymlinks = { read = FResolveSymlinks, write = SetResolveSymlinks };\r\n __property bool FollowDirectorySymlinks = { read = FFollowDirectorySymlinks, write = SetFollowDirectorySymlinks };\r\n __property int SFTPDownloadQueue = { read = FSFTPDownloadQueue, write = SetSFTPDownloadQueue };\r\n __property int SFTPUploadQueue = { read = FSFTPUploadQueue, write = SetSFTPUploadQueue };\r\n __property int SFTPListingQueue = { read = FSFTPListingQueue, write = SetSFTPListingQueue };\r\n __property int SFTPMaxVersion = { read = FSFTPMaxVersion, write = SetSFTPMaxVersion };\r\n __property unsigned long SFTPMaxPacketSize = { read = FSFTPMaxPacketSize, write = SetSFTPMaxPacketSize };\r\n __property TAutoSwitch SFTPBug[TSftpBug Bug] = { read=GetSFTPBug, write=SetSFTPBug };\r\n __property TAutoSwitch SCPLsFullTime = { read = FSCPLsFullTime, write = SetSCPLsFullTime };\r\n __property TAutoSwitch FtpListAll = { read = FFtpListAll, write = SetFtpListAll };\r\n __property TAutoSwitch FtpHost = { read = FFtpHost, write = SetFtpHost };\r\n __property TAutoSwitch FtpDeleteFromCwd = { read = FFtpDeleteFromCwd, write = SetFtpDeleteFromCwd };\r\n __property bool SslSessionReuse = { read = FSslSessionReuse, write = SetSslSessionReuse };\r\n __property UnicodeString TlsCertificateFile = { read=FTlsCertificateFile, write=SetTlsCertificateFile };\r\n __property TDSTMode DSTMode = { read = FDSTMode, write = SetDSTMode };\r\n __property bool DeleteToRecycleBin = { read = FDeleteToRecycleBin, write = SetDeleteToRecycleBin };\r\n __property bool OverwrittenToRecycleBin = { read = FOverwrittenToRecycleBin, write = SetOverwrittenToRecycleBin };\r\n __property UnicodeString RecycleBinPath = { read = FRecycleBinPath, write = SetRecycleBinPath };\r\n __property UnicodeString PostLoginCommands = { read = FPostLoginCommands, write = SetPostLoginCommands };\r\n __property TAddressFamily AddressFamily = { read = FAddressFamily, write = SetAddressFamily };\r\n __property UnicodeString RekeyData = { read = FRekeyData, write = SetRekeyData };\r\n __property unsigned int RekeyTime = { read = FRekeyTime, write = SetRekeyTime };\r\n __property int Color = { read = FColor, write = SetColor };\r\n __property bool Tunnel = { read = FTunnel, write = SetTunnel };\r\n __property UnicodeString TunnelHostName = { read = FTunnelHostName, write = SetTunnelHostName };\r\n __property int TunnelPortNumber = { read = FTunnelPortNumber, write = SetTunnelPortNumber };\r\n __property UnicodeString TunnelUserName = { read = FTunnelUserName, write = SetTunnelUserName };\r\n __property UnicodeString TunnelPassword = { read = GetTunnelPassword, write = SetTunnelPassword };\r\n __property UnicodeString TunnelPublicKeyFile = { read = FTunnelPublicKeyFile, write = SetTunnelPublicKeyFile };\r\n __property bool TunnelAutoassignLocalPortNumber = { read = GetTunnelAutoassignLocalPortNumber };\r\n __property int TunnelLocalPortNumber = { read = FTunnelLocalPortNumber, write = SetTunnelLocalPortNumber };\r\n __property UnicodeString TunnelPortFwd = { read = FTunnelPortFwd, write = SetTunnelPortFwd };\r\n __property UnicodeString TunnelHostKey = { read = FTunnelHostKey, write = SetTunnelHostKey };\r\n __property bool FtpPasvMode = { read = FFtpPasvMode, write = SetFtpPasvMode };\r\n __property TAutoSwitch FtpForcePasvIp = { read = FFtpForcePasvIp, write = SetFtpForcePasvIp };\r\n __property TAutoSwitch FtpUseMlsd = { read = FFtpUseMlsd, write = SetFtpUseMlsd };\r\n __property UnicodeString FtpAccount = { read = FFtpAccount, write = SetFtpAccount };\r\n __property int FtpPingInterval = { read=FFtpPingInterval, write=SetFtpPingInterval };\r\n __property TDateTime FtpPingIntervalDT = { read=GetFtpPingIntervalDT };\r\n __property TPingType FtpPingType = { read = FFtpPingType, write = SetFtpPingType };\r\n __property TAutoSwitch FtpTransferActiveImmediately = { read = FFtpTransferActiveImmediately, write = SetFtpTransferActiveImmediately };\r\n __property TFtps Ftps = { read = FFtps, write = SetFtps };\r\n __property TTlsVersion MinTlsVersion = { read = FMinTlsVersion, write = SetMinTlsVersion };\r\n __property TTlsVersion MaxTlsVersion = { read = FMaxTlsVersion, write = SetMaxTlsVersion };\r\n __property UnicodeString LogicalHostName = { read = FLogicalHostName, write = SetLogicalHostName };\r\n __property TAutoSwitch NotUtf = { read = FNotUtf, write = SetNotUtf };\r\n __property int InternalEditorEncoding = { read = FInternalEditorEncoding, write = SetInternalEditorEncoding };\r\n __property UnicodeString S3DefaultRegion = { read = FS3DefaultRegion, write = SetS3DefaultRegion };\r\n __property TS3UrlStyle S3UrlStyle = { read = FS3UrlStyle, write = SetS3UrlStyle };\r\n __property bool IsWorkspace = { read = FIsWorkspace, write = SetIsWorkspace };\r\n __property UnicodeString Link = { read = FLink, write = SetLink };\r\n __property UnicodeString NameOverride = { read = FNameOverride, write = SetNameOverride };\r\n __property UnicodeString HostKey = { read = FHostKey, write = SetHostKey };\r\n __property bool FingerprintScan = { read = FFingerprintScan, write = FFingerprintScan };\r\n __property bool OverrideCachedHostKey = { read = FOverrideCachedHostKey };\r\n __property UnicodeString Note = { read = FNote, write = SetNote };\r\n __property UnicodeString WinTitle = { read = FWinTitle, write = SetWinTitle };\r\n __property UnicodeString EncryptKey = { read = GetEncryptKey, write = SetEncryptKey };\r\n\r\n __property UnicodeString StorageKey = { read = GetStorageKey };\r\n __property UnicodeString SiteKey = { read = GetSiteKey };\r\n __property UnicodeString OrigHostName = { read = FOrigHostName };\r\n __property int OrigPortNumber = { read = FOrigPortNumber };\r\n __property UnicodeString LocalName = { read = GetLocalName };\r\n __property UnicodeString FolderName = { read = GetFolderName };\r\n __property UnicodeString Source = { read = GetSource };\r\n __property bool SaveOnly = { read = FSaveOnly };\r\n};\r\n//---------------------------------------------------------------------------\r\nclass TStoredSessionList : public TNamedObjectList\r\n{\r\npublic:\r\n __fastcall TStoredSessionList(bool aReadOnly = false);\r\n void __fastcall Reload();\r\n void __fastcall Save(bool All, bool Explicit);\r\n void __fastcall Saved();\r\n void __fastcall ImportFromFilezilla(const UnicodeString FileName, const UnicodeString ConfigurationFileName);\r\n void __fastcall ImportFromKnownHosts(TStrings * Lines);\r\n void __fastcall Export(const UnicodeString FileName);\r\n void __fastcall Load(THierarchicalStorage * Storage, bool AsModified = false,\r\n bool UseDefaults = false, bool PuttyImport = false);\r\n void __fastcall Save(THierarchicalStorage * Storage, bool All = false);\r\n void __fastcall SelectAll(bool Select);\r\n void __fastcall Import(TStoredSessionList * From, bool OnlySelected, TList * Imported);\r\n void __fastcall RecryptPasswords(TStrings * RecryptPasswordErrors);\r\n TSessionData * __fastcall AtSession(int Index)\r\n { return (TSessionData*)AtObject(Index); }\r\n void __fastcall SelectSessionsToImport(TStoredSessionList * Dest, bool SSHOnly);\r\n void __fastcall Cleanup();\r\n void __fastcall UpdateStaticUsage();\r\n int __fastcall IndexOf(TSessionData * Data);\r\n TSessionData * __fastcall FindSame(TSessionData * Data);\r\n TSessionData * __fastcall NewSession(UnicodeString SessionName, TSessionData * Session);\r\n void __fastcall NewWorkspace(UnicodeString Name, TList * DataList);\r\n bool __fastcall IsFolder(const UnicodeString & Name);\r\n bool __fastcall IsWorkspace(const UnicodeString & Name);\r\n TSessionData * __fastcall ParseUrl(UnicodeString Url, TOptions * Options, bool & DefaultsOnly,\r\n UnicodeString * FileName = NULL, bool * ProtocolDefined = NULL, UnicodeString * MaskedUrl = NULL, int Flags = 0);\r\n bool __fastcall IsUrl(UnicodeString Url);\r\n bool __fastcall CanLogin(TSessionData * Data);\r\n void __fastcall GetFolderOrWorkspace(const UnicodeString & Name, TList * List);\r\n TStrings * __fastcall GetFolderOrWorkspaceList(const UnicodeString & Name);\r\n TStrings * __fastcall GetWorkspaces();\r\n bool __fastcall HasAnyWorkspace();\r\n TSessionData * __fastcall SaveWorkspaceData(TSessionData * Data, int Index);\r\n virtual __fastcall ~TStoredSessionList();\r\n __property TSessionData * Sessions[int Index] = { read=AtSession };\r\n __property TSessionData * DefaultSettings = { read=FDefaultSettings, write=SetDefaultSettings };\r\n\r\n static void __fastcall ImportHostKeys(\r\n THierarchicalStorage * SourceStorage, THierarchicalStorage * TargetStorage, TStoredSessionList * Sessions, bool OnlySelected);\r\n static void __fastcall ImportHostKeys(\r\n const UnicodeString & SourceKey, TStoredSessionList * Sessions, bool OnlySelected);\r\n static void __fastcall ImportSelectedKnownHosts(TStoredSessionList * Sessions);\r\n static bool __fastcall OpenHostKeysSubKey(THierarchicalStorage * Storage, bool CanCreate);\r\n\r\nprivate:\r\n TSessionData * FDefaultSettings;\r\n bool FReadOnly;\r\n std::unique_ptr<TStrings> FPendingRemovals;\r\n void __fastcall SetDefaultSettings(TSessionData * value);\r\n void __fastcall DoSave(THierarchicalStorage * Storage, bool All,\r\n bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors);\r\n void __fastcall DoSave(bool All, bool Explicit, bool RecryptPasswordOnly,\r\n TStrings * RecryptPasswordErrors);\r\n void __fastcall DoSave(THierarchicalStorage * Storage,\r\n TSessionData * Data, bool All, bool RecryptPasswordOnly,\r\n TSessionData * FactoryDefaults);\r\n TSessionData * __fastcall ResolveWorkspaceData(TSessionData * Data);\r\n bool __fastcall IsFolderOrWorkspace(const UnicodeString & Name, bool Workspace);\r\n TSessionData * __fastcall CheckIsInFolderOrWorkspaceAndResolve(\r\n TSessionData * Data, const UnicodeString & Name);\r\n void __fastcall ImportLevelFromFilezilla(_di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode);\r\n void __fastcall DoGetFolderOrWorkspace(const UnicodeString & Name, TList * List, bool NoRecrypt);\r\n static THierarchicalStorage * __fastcall CreateHostKeysStorageForWritting();\r\n};\r\n//---------------------------------------------------------------------------\r\nUnicodeString GetExpandedLogFileName(UnicodeString LogFileName, TDateTime Started, TSessionData * SessionData);\r\nbool __fastcall IsSshProtocol(TFSProtocol FSProtocol);\r\nint __fastcall DefaultPort(TFSProtocol FSProtocol, TFtps Ftps);\r\nbool __fastcall IsIPv6Literal(const UnicodeString & HostName);\r\nUnicodeString __fastcall EscapeIPv6Literal(const UnicodeString & IP);\r\nTFSProtocol NormalizeFSProtocol(TFSProtocol FSProtocol);\r\n//---------------------------------------------------------------------------\r\n#endif" ]
[ 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 53, 80, 2275, 473, 1511, 2372, 1100], "buggy_code_start_loc": [46, 52, 79, 599, 57, 1510, 2371, 1099], "filenames": ["source/Console.cbproj", "source/DragExt.cbproj", "source/WinSCP.cbproj", "source/core/SessionData.cpp", "source/core/SessionData.h", "source/forms/Custom.cpp", "source/windows/ConsoleRunner.cpp", "source/windows/WinMain.cpp"], "fixing_code_end_loc": [47, 53, 80, 2294, 474, 1511, 2372, 1103], "fixing_code_start_loc": [46, 52, 79, 599, 58, 1510, 2371, 1099], "message": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:winscp:winscp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C081564B-8EF8-4C8A-9EB0-1C50D5A8F18B", "versionEndExcluding": "5.17.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)"}, {"lang": "es", "value": "WinSCP anterior a la versi\u00f3n 5.17.10 permite a los atacantes remotos ejecutar programas arbitrarios cuando el manejador de URLs encuentra una URL manipulada que carga la configuraci\u00f3n de la sesi\u00f3n. (Por ejemplo, esto es explotable en una instalaci\u00f3n por defecto en la que WinSCP es el manejador de URLs sftp://)"}], "evaluatorComment": null, "id": "CVE-2021-3331", "lastModified": "2021-02-04T15:59:24.960", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-01-27T21:15:16.840", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://winscp.net/eng/docs/history#5.17.10"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://winscp.net/eng/docs/rawsettings"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://winscp.net/tracker/1943"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, "type": "NVD-CWE-Other"}
177
Determine whether the {function_name} code is vulnerable or not.
[ "//---------------------------------------------------------------------\r\n#include <vcl.h>\r\n#pragma hdrstop\r\n\r\n#include <Dialogs.hpp>\r\n//---------------------------------------------------------------------\r\n#include <Common.h>\r\n#include <CustomWinConfiguration.h>\r\n#include <WinInterface.h>\r\n#include <VCLCommon.h>\r\n#include <TextsWin.h>\r\n#include <HelpWin.h>\r\n#include <CoreMain.h>\r\n#include <PasTools.hpp>\r\n#include <ProgParams.h>\r\n#include <Tools.h>\r\n#include <GUITools.h>\r\n#include <HistoryComboBox.hpp>\r\n#include <Math.hpp>\r\n\r\n#include \"Custom.h\"\r\n//---------------------------------------------------------------------\r\n#pragma link \"PasswordEdit\"\r\n#pragma resource \"*.dfm\"\r\n//---------------------------------------------------------------------\r\n__fastcall TCustomDialog::TCustomDialog(UnicodeString AHelpKeyword)\r\n : TForm(GetFormOwner())\r\n{\r\n UseSystemSettings(this);\r\n\r\n FControlPadding = ScaleByTextHeight(this, 8);\r\n FPos = ScaleByTextHeight(this, 8);\r\n FPrePos = FPos;\r\n FHorizontalMargin = ScaleByTextHeight(this, 8);\r\n FIndent = FHorizontalMargin;\r\n FGroupBox = NULL;\r\n\r\n HelpKeyword = AHelpKeyword;\r\n\r\n TBorderIcons BI = BorderIcons;\r\n if (HelpKeyword.IsEmpty())\r\n {\r\n BI >> biHelp;\r\n\r\n OKButton->Left = CancelButton->Left;\r\n CancelButton->Left = HelpButton->Left;\r\n HelpButton->Visible = false;\r\n }\r\n else\r\n {\r\n BI << biHelp;\r\n }\r\n BorderIcons = BI;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TCustomDialog::Execute()\r\n{\r\n Changed();\r\n return (ShowModal() == DefaultResult(this));\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::DoChange(bool & /*CanSubmit*/)\r\n{\r\n // noop\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::Changed()\r\n{\r\n bool CanSubmit = true;\r\n DoChange(CanSubmit);\r\n EnableControl(OKButton, CanSubmit);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::Change(TObject * /*Sender*/)\r\n{\r\n Changed();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::DoHelp()\r\n{\r\n FormHelp(this);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::HelpButtonClick(TObject * /*Sender*/)\r\n{\r\n DoHelp();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::DoShow()\r\n{\r\n OKButton->TabOrder = FCount;\r\n CancelButton->TabOrder = static_cast<short>(FCount + 1);\r\n HelpButton->TabOrder = static_cast<short>(FCount + 2);\r\n Changed();\r\n TForm::DoShow();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::DoValidate()\r\n{\r\n // noop\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TCustomDialog::CloseQuery()\r\n{\r\n if (ModalResult == DefaultResult(this))\r\n {\r\n DoValidate();\r\n }\r\n return TForm::CloseQuery();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::RemoveCancelButton()\r\n{\r\n CancelButton->Visible = false;\r\n OKButton->Left = CancelButton->Left;\r\n OKButton->Cancel = true;\r\n DebugAssert(OKButton->Width == CancelButton->Width);\r\n DebugAssert(OKButton->Top == CancelButton->Top);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddDialogButton(TButton * Button)\r\n{\r\n Button->Parent = this;\r\n Button->Top = OKButton->Top;\r\n Button->Left = FHorizontalMargin;\r\n Button->Height = OKButton->Height;\r\n AddWinControl(Button);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddImage(const UnicodeString & ImageName)\r\n{\r\n TImage * Image = new TImage(this);\r\n Image->Name = L\"Image\";\r\n Image->Parent = GetDefaultParent();\r\n LoadDialogImage(Image, ImageName);\r\n Image->SetBounds(FIndent, FPos + ScaleByTextHeight(this, 3), Image->Picture->Width, Image->Picture->Height);\r\n FIndent += Image->Width + ScaleByTextHeight(this, 12);\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall TCustomDialog::GetMaxControlWidth(TControl * Control)\r\n{\r\n return GetDefaultParent()->ClientWidth - Control->Left - FHorizontalMargin;\r\n}\r\n//---------------------------------------------------------------------------\r\nTWinControl * __fastcall TCustomDialog::GetDefaultParent()\r\n{\r\n return (FGroupBox != NULL) ? FGroupBox : static_cast<TWinControl *>(this);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AdjustHeight(TControl * Control)\r\n{\r\n FPos = Control->Top + Control->Height + FControlPadding;\r\n int Delta = (FPos - FPrePos);\r\n ClientHeight = ClientHeight + Delta;\r\n if (FGroupBox != NULL)\r\n {\r\n FGroupBox->Height = FGroupBox->Height + Delta;\r\n }\r\n FPrePos = FPos;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddWinControl(TWinControl * Control)\r\n{\r\n Control->TabOrder = FCount;\r\n FCount++;\r\n}\r\n//---------------------------------------------------------------------------\r\nTCheckBox * __fastcall TCustomDialog::CreateAndAddCheckBox(const UnicodeString & Caption)\r\n{\r\n TCheckBox * CheckBox = new TCheckBox(this);\r\n CheckBox->Caption = Caption;\r\n AddButtonControl(CheckBox);\r\n return CheckBox;\r\n}\r\n//---------------------------------------------------------------------------\r\nTLabel * __fastcall TCustomDialog::CreateLabel(UnicodeString Label)\r\n{\r\n TLabel * Result = new TLabel(this);\r\n Result->Caption = Label;\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddEditLikeControl(TWinControl * Edit, TLabel * Label, bool OneLine)\r\n{\r\n Edit->Parent = GetDefaultParent();\r\n // this updates Height property to real value\r\n Edit->HandleNeeded();\r\n\r\n if (Label != NULL)\r\n {\r\n Label->Parent = GetDefaultParent();\r\n Label->Left = FIndent;\r\n\r\n if (OneLine)\r\n {\r\n DebugAssert(Edit->Height > Label->Height);\r\n Label->Top = FPos + ((Edit->Height - Label->Height) / 2);\r\n }\r\n else\r\n {\r\n Label->Top = FPos;\r\n\r\n FPos += Label->Height + ScaleByTextHeight(this, 4);\r\n }\r\n }\r\n\r\n Edit->Top = FPos;\r\n if (OneLine)\r\n {\r\n Edit->Left = GetDefaultParent()->ClientWidth - FHorizontalMargin - Edit->Width;\r\n }\r\n else\r\n {\r\n Edit->Left = FIndent;\r\n Edit->Width = GetMaxControlWidth(Edit);\r\n }\r\n\r\n AdjustHeight(Edit);\r\n\r\n if (Label != NULL)\r\n {\r\n if (Label->FocusControl == NULL)\r\n {\r\n Label->FocusControl = Edit;\r\n }\r\n else\r\n {\r\n DebugAssert(Label->FocusControl == Edit);\r\n }\r\n }\r\n\r\n AddWinControl(Edit);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddEdit(TCustomEdit * Edit, TLabel * Label, bool OneLine)\r\n{\r\n AddEditLikeControl(Edit, Label, OneLine);\r\n\r\n TEdit * PublicEdit = reinterpret_cast<TEdit *>(Edit);\r\n if (PublicEdit->OnChange == NULL)\r\n {\r\n PublicEdit->OnChange = Change;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::SetUpComboBox(TCustomCombo * Combo, TStrings * Items, bool OneLine)\r\n{\r\n if (Items != NULL)\r\n {\r\n Combo->Items = Items;\r\n }\r\n\r\n if (OneLine)\r\n {\r\n int Width = 0;\r\n for (int Index = 0; Index < Combo->Items->Count; Index++)\r\n {\r\n Width = Max(Width, Combo->Canvas->TextWidth(Combo->Items->Strings[Index]));\r\n }\r\n\r\n Width += ScaleByTextHeight(Combo, 4 + 16 + 14);\r\n Width = Max(Width, HelpButton->Width);\r\n\r\n Combo->Width = Width;\r\n Combo->Left = GetDefaultParent()->ClientWidth - FHorizontalMargin - Width;\r\n }\r\n\r\n TComboBox * PublicCombo = reinterpret_cast<TComboBox *>(Combo);\r\n if (PublicCombo->OnChange == NULL)\r\n {\r\n PublicCombo->OnChange = Change;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddComboBox(TCustomCombo * Combo, TLabel * Label, TStrings * Items, bool OneLine)\r\n{\r\n AddEditLikeControl(Combo, Label, OneLine);\r\n\r\n SetUpComboBox(Combo, Items, OneLine);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddShortCutComboBox(TComboBox * Combo, TLabel * Label, const TShortCuts & ShortCuts)\r\n{\r\n AddEditLikeControl(Combo, Label, true);\r\n InitializeShortCutCombo(Combo, ShortCuts);\r\n SetUpComboBox(Combo, NULL, true);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::ScaleButtonControl(TButtonControl * Control)\r\n{\r\n // this updates Height property to real value\r\n Control->HandleNeeded();\r\n // buttons do not scale with text on their own\r\n Control->Height = ScaleByTextHeight(Control, Control->Height);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddButtonControl(TButtonControl * Control)\r\n{\r\n Control->Parent = GetDefaultParent();\r\n Control->Left = FIndent + ScaleByTextHeight(this, 6);\r\n Control->Top = FPos;\r\n Control->Width = GetMaxControlWidth(Control);\r\n ScaleButtonControl(Control);\r\n\r\n AdjustHeight(Control);\r\n\r\n AddWinControl(Control);\r\n\r\n TCheckBox * PublicControl = reinterpret_cast<TCheckBox *>(Control);\r\n if (PublicControl->OnClick == NULL)\r\n {\r\n PublicControl->OnClick = Change;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddText(TLabel * Label)\r\n{\r\n Label->Parent = GetDefaultParent();\r\n\r\n Label->WordWrap = true;\r\n Label->Left = FIndent;\r\n Label->Width = GetMaxControlWidth(Label);\r\n Label->Top = FPos;\r\n Label->ShowAccelChar = false;\r\n\r\n TRect TextRect;\r\n SetRect(&TextRect, 0, 0, Label->Width, 0);\r\n DrawText(Label->Canvas->Handle, Label->Caption.c_str(), Label->Caption.Length() + 1, &TextRect,\r\n DT_EXPANDTABS | DT_CALCRECT | DT_WORDBREAK | DT_NOPREFIX |\r\n Label->DrawTextBiDiModeFlagsReadingOnly());\r\n Label->Height = TextRect.Height();\r\n\r\n AdjustHeight(Label);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddText(TStaticText * Label)\r\n{\r\n Label->Parent = GetDefaultParent();\r\n\r\n Label->Left = FIndent;\r\n Label->Width = GetMaxControlWidth(Label);\r\n Label->Top = FPos;\r\n Label->ShowAccelChar = false;\r\n\r\n AdjustHeight(Label);\r\n AddWinControl(Label);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddSeparator()\r\n{\r\n TBevel * Bevel = new TBevel(this);\r\n Bevel->Parent = GetDefaultParent();\r\n\r\n Bevel->Left = FIndent;\r\n Bevel->Top = FPos;\r\n Bevel->Height = 2;\r\n Bevel->Width = GetMaxControlWidth(Bevel);\r\n\r\n AdjustHeight(Bevel);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::StartGroup(const UnicodeString & Caption)\r\n{\r\n if (FGroupBox != NULL)\r\n {\r\n FIndent = FGroupBox->Left;\r\n FPos = FGroupBox->Top + FGroupBox->Height + FControlPadding;\r\n FPrePos = FPos;\r\n FGroupBox = NULL;\r\n }\r\n\r\n TGroupBox * GroupBox = new TGroupBox(this);\r\n GroupBox->Parent = this;\r\n GroupBox->Caption = Caption;\r\n\r\n GroupBox->Left = FIndent;\r\n GroupBox->Top = FPos;\r\n GroupBox->Height = ScaleByTextHeight(GroupBox, 20);\r\n GroupBox->Width = GetMaxControlWidth(GroupBox);\r\n\r\n AdjustHeight(GroupBox);\r\n\r\n AddWinControl(GroupBox);\r\n\r\n FPos = ScaleByTextHeight(this, 16);\r\n FPrePos = FPos;\r\n FIndent = FHorizontalMargin;\r\n\r\n FGroupBox = GroupBox;\r\n}\r\n//---------------------------------------------------------------------------\r\n//---------------------------------------------------------------------------\r\nclass TSaveSessionDialog : public TCustomDialog\r\n{\r\npublic:\r\n __fastcall TSaveSessionDialog(TComponent* AOwner);\r\n void __fastcall Init(bool CanSavePassword, bool NotRecommendedSavingPassword,\r\n TStrings * AdditionalFolders);\r\n\r\n bool __fastcall Execute(UnicodeString & SessionName, bool & SavePassword,\r\n bool & CreateShortcut, const UnicodeString & OriginalSessionName);\r\n\r\nprotected:\r\n virtual void __fastcall DoValidate();\r\n virtual void __fastcall DoChange(bool & CanSubmit);\r\n\r\nprivate:\r\n UnicodeString FOriginalSessionName;\r\n TEdit * SessionNameEdit;\r\n TComboBox * FolderCombo;\r\n TCheckBox * SavePasswordCheck;\r\n TCheckBox * CreateShortcutCheck;\r\n UnicodeString FRootFolder;\r\n\r\n UnicodeString __fastcall GetSessionName();\r\n};\r\n//---------------------------------------------------------------------------\r\n// Need to have an Owner argument for SafeFormCreate\r\n__fastcall TSaveSessionDialog::TSaveSessionDialog(TComponent* /*AOwner*/) :\r\n TCustomDialog(HELP_SESSION_SAVE)\r\n{\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSaveSessionDialog::Init(bool CanSavePassword,\r\n bool NotRecommendedSavingPassword, TStrings * AdditionalFolders)\r\n{\r\n Caption = LoadStr(SAVE_SESSION_CAPTION);\r\n\r\n SessionNameEdit = new TEdit(this);\r\n AddEdit(SessionNameEdit, CreateLabel(LoadStr(SAVE_SESSION_PROMPT)));\r\n\r\n FRootFolder = LoadStr(SAVE_SESSION_ROOT_FOLDER2);\r\n std::unique_ptr<TStringList> Folders(new TStringList());\r\n\r\n if (AdditionalFolders != NULL)\r\n {\r\n Folders->AddStrings(AdditionalFolders);\r\n }\r\n\r\n for (int Index = 0; Index < StoredSessions->Count; Index++)\r\n {\r\n TSessionData * Data = StoredSessions->Sessions[Index];\r\n if (!Data->Special && !Data->IsWorkspace)\r\n {\r\n UnicodeString Folder = Data->FolderName;\r\n if (!Folder.IsEmpty() && Folders->IndexOf(Folder) < 0)\r\n {\r\n Folders->Add(Folder);\r\n }\r\n }\r\n }\r\n\r\n DebugAssert(!Folders->CaseSensitive);\r\n Folders->Sort();\r\n\r\n FolderCombo = new TComboBox(this);\r\n AddComboBox(FolderCombo, CreateLabel(LoadStr(SAVE_SESSION_FOLDER)));\r\n FolderCombo->DropDownCount = Max(FolderCombo->DropDownCount, 16);\r\n FolderCombo->Items->Add(FRootFolder);\r\n FolderCombo->Items->AddStrings(Folders.get());\r\n\r\n SavePasswordCheck = CreateAndAddCheckBox(\r\n LoadStr(NotRecommendedSavingPassword ? SAVE_SESSION_PASSWORD :\r\n (CustomWinConfiguration->UseMasterPassword ? SAVE_SESSION_PASSWORD_MASTER : SAVE_SESSION_PASSWORD_RECOMMENDED)));\r\n\r\n CreateShortcutCheck = CreateAndAddCheckBox(LoadStr(SAVE_SITE_WORKSPACE_SHORTCUT));\r\n\r\n EnableControl(SavePasswordCheck, CanSavePassword);\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TSaveSessionDialog::Execute(\r\n UnicodeString & SessionName, bool & SavePassword, bool & CreateShortcut,\r\n const UnicodeString & OriginalSessionName)\r\n{\r\n FOriginalSessionName = OriginalSessionName;\r\n SessionNameEdit->Text = TSessionData::ExtractLocalName(SessionName);\r\n UnicodeString Folder = TSessionData::ExtractFolderName(SessionName);\r\n if (Folder.IsEmpty())\r\n {\r\n FolderCombo->Text = FRootFolder;\r\n }\r\n else\r\n {\r\n FolderCombo->Text = Folder;\r\n }\r\n SavePasswordCheck->Checked = SavePassword;\r\n CreateShortcutCheck->Checked = CreateShortcut;\r\n bool Result = TCustomDialog::Execute();\r\n if (Result)\r\n {\r\n SessionName = GetSessionName();\r\n SavePassword = SavePasswordCheck->Checked;\r\n CreateShortcut = CreateShortcutCheck->Checked;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TSaveSessionDialog::GetSessionName()\r\n{\r\n UnicodeString Folder;\r\n if (FolderCombo->Text != FRootFolder)\r\n {\r\n Folder = FolderCombo->Text;\r\n }\r\n return TSessionData::ComposePath(Folder, SessionNameEdit->Text);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSaveSessionDialog::DoValidate()\r\n{\r\n TSessionData::ValidateName(SessionNameEdit->Text);\r\n SessionNameValidate(GetSessionName(), FOriginalSessionName);\r\n\r\n UnicodeString Folder = TSessionData::ExtractFolderName(GetSessionName());\r\n if (!Folder.IsEmpty() && StoredSessions->IsWorkspace(Folder))\r\n {\r\n throw Exception(FMTLOAD(WORKSPACE_NOT_FOLDER, (Folder)));\r\n }\r\n\r\n if (SavePasswordCheck->Enabled && SavePasswordCheck->Checked &&\r\n CustomWinConfiguration->UseMasterPassword)\r\n {\r\n CustomWinConfiguration->AskForMasterPasswordIfNotSet();\r\n }\r\n\r\n TCustomDialog::DoValidate();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSaveSessionDialog::DoChange(bool & CanSubmit)\r\n{\r\n CanSubmit = !SessionNameEdit->Text.IsEmpty();\r\n TCustomDialog::DoChange(CanSubmit);\r\n}\r\n//---------------------------------------------------------------------------\r\nTSessionData * __fastcall DoSaveSession(TSessionData * SessionData,\r\n TSessionData * OriginalSession, bool ForceDialog,\r\n TStrings * AdditionalFolders)\r\n{\r\n bool SavePassword = false;\r\n bool * PSavePassword;\r\n bool NotRecommendedSavingPassword =\r\n !CustomWinConfiguration->UseMasterPassword &&\r\n !SameText(SessionData->UserName, AnonymousUserName);\r\n\r\n if (Configuration->DisablePasswordStoring ||\r\n !SessionData->HasAnySessionPassword())\r\n {\r\n PSavePassword = NULL;\r\n }\r\n else\r\n {\r\n PSavePassword = &SavePassword;\r\n SavePassword =\r\n ((OriginalSession != NULL) && OriginalSession->HasAnySessionPassword()) ||\r\n !NotRecommendedSavingPassword;\r\n }\r\n\r\n UnicodeString SessionName = SessionData->SessionName;\r\n\r\n bool Result;\r\n bool CreateShortcut = false;\r\n if (!ForceDialog && ((PSavePassword == NULL) || SavePassword))\r\n {\r\n // This is probably here to ask before session is started saving.\r\n // Otherwise we would ask implicitly, when saving passwords, but at that moment,\r\n // part of the site is already saved and when the user cancel the prompt it's too late.\r\n CustomWinConfiguration->AskForMasterPasswordIfNotSetAndNeededToPersistSessionData(SessionData);\r\n Result = true;\r\n }\r\n else\r\n {\r\n // This can be a standalone dialog when used with save URL (from GetLoginData)\r\n TSaveSessionDialog * Dialog = SafeFormCreate<TSaveSessionDialog>();\r\n try\r\n {\r\n Dialog->Init((PSavePassword != NULL), NotRecommendedSavingPassword, AdditionalFolders);\r\n Result = Dialog->Execute(SessionName, SavePassword, CreateShortcut, SessionData->Name);\r\n }\r\n __finally\r\n {\r\n delete Dialog;\r\n }\r\n }\r\n\r\n TSessionData * NewSession = NULL;\r\n if (Result)\r\n {\r\n if ((PSavePassword != NULL) && !SavePassword)\r\n {\r\n SessionData->ClearSessionPasswords();\r\n }\r\n\r\n NewSession =\r\n StoredSessions->NewSession(SessionName, SessionData);\r\n // modified only, explicit\r\n StoredSessions->Save(false, true);\r\n if (!SessionData->HostKey.IsEmpty())\r\n {\r\n SessionData->CacheHostKeyIfNotCached();\r\n }\r\n\r\n if (CreateShortcut)\r\n {\r\n TOperationVisualizer Visualizer;\r\n UnicodeString AdditionalParams =\r\n TProgramParams::FormatSwitch(DESKTOP_SWITCH) + L\" \" +\r\n TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH);\r\n CreateDesktopSessionShortCut(SessionName, L\"\", AdditionalParams, -1, SITE_ICON);\r\n }\r\n }\r\n\r\n return NewSession;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall SessionNameValidate(const UnicodeString & Text,\r\n const UnicodeString & OriginalName)\r\n{\r\n TSessionData::ValidatePath(Text);\r\n\r\n DebugAssert(StoredSessions);\r\n TSessionData * Data = (TSessionData *)StoredSessions->FindByName(Text);\r\n if (Data && Data->Special)\r\n {\r\n MessageDialog(FMTLOAD(CANNOT_OVERWRITE_SPECIAL_SESSION, (Text)),\r\n qtError, qaOK, HELP_NONE);\r\n Abort();\r\n }\r\n else if ((Data != NULL) && !Data->IsSameName(OriginalName) &&\r\n MessageDialog(MainInstructions(FMTLOAD(CONFIRM_OVERWRITE_SESSION, (Text))),\r\n qtConfirmation, qaYes | qaNo, HELP_SESSION_SAVE_OVERWRITE) != qaYes)\r\n {\r\n Abort();\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\n//---------------------------------------------------------------------------\r\nclass TSaveWorkspaceDialog : public TCustomDialog\r\n{\r\npublic:\r\n __fastcall TSaveWorkspaceDialog(bool CanSavePasswords,\r\n bool NotRecommendedSavingPasswords);\r\n\r\n bool __fastcall Execute(\r\n UnicodeString & WorkspaceName, bool & SavePasswords, bool & CreateShortcut,\r\n bool & EnableAutoSave);\r\n\r\nprotected:\r\n virtual void __fastcall DoValidate();\r\n virtual void __fastcall DoChange(bool & CanSubmit);\r\n\r\nprivate:\r\n TComboBox * WorkspaceNameCombo;\r\n TCheckBox * SavePasswordsCheck;\r\n TCheckBox * CreateShortcutCheck;\r\n TCheckBox * EnableAutoSaveCheck;\r\n};\r\n//---------------------------------------------------------------------------\r\n__fastcall TSaveWorkspaceDialog::TSaveWorkspaceDialog(\r\n bool CanSavePasswords, bool NotRecommendedSavingPasswords) :\r\n TCustomDialog(HELP_WORKSPACE_SAVE)\r\n{\r\n Caption = LoadStr(SAVE_WORKSPACE_CAPTION);\r\n\r\n WorkspaceNameCombo = new TComboBox(this);\r\n WorkspaceNameCombo->AutoComplete = false;\r\n AddComboBox(WorkspaceNameCombo, CreateLabel(LoadStr(SAVE_WORKSPACE_PROMPT)));\r\n WorkspaceNameCombo->DropDownCount = Max(WorkspaceNameCombo->DropDownCount, 16);\r\n\r\n std::unique_ptr<TStrings> Workspaces(StoredSessions->GetWorkspaces());\r\n WorkspaceNameCombo->Items->AddStrings(Workspaces.get());\r\n\r\n SavePasswordsCheck = CreateAndAddCheckBox(\r\n LoadStr(NotRecommendedSavingPasswords ? SAVE_WORKSPACE_PASSWORDS :\r\n (CustomWinConfiguration->UseMasterPassword ?\r\n SAVE_WORKSPACE_PASSWORDS_MASTER : SAVE_WORKSPACE_PASSWORDS_RECOMMENDED)));\r\n\r\n EnableControl(SavePasswordsCheck, CanSavePasswords);\r\n\r\n CreateShortcutCheck = CreateAndAddCheckBox(LoadStr(SAVE_SITE_WORKSPACE_SHORTCUT));\r\n\r\n EnableAutoSaveCheck = CreateAndAddCheckBox(LoadStr(SAVE_WORKSPACE_AUTO));\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TSaveWorkspaceDialog::Execute(\r\n UnicodeString & WorkspaceName, bool & SavePasswords, bool & CreateShortcut,\r\n bool & EnableAutoSave)\r\n{\r\n WorkspaceNameCombo->Text = WorkspaceName;\r\n SavePasswordsCheck->Checked = SavePasswords;\r\n CreateShortcutCheck->Checked = CreateShortcut;\r\n EnableAutoSaveCheck->Checked = EnableAutoSave;\r\n bool Result = TCustomDialog::Execute();\r\n if (Result)\r\n {\r\n WorkspaceName = WorkspaceNameCombo->Text;\r\n SavePasswords = SavePasswordsCheck->Checked;\r\n CreateShortcut = CreateShortcutCheck->Checked;\r\n EnableAutoSave = EnableAutoSaveCheck->Checked;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSaveWorkspaceDialog::DoValidate()\r\n{\r\n TSessionData::ValidateName(WorkspaceNameCombo->Text);\r\n\r\n if (StoredSessions->IsFolder(WorkspaceNameCombo->Text))\r\n {\r\n throw Exception(FMTLOAD(FOLDER_NOT_WORKSPACE, (WorkspaceNameCombo->Text)));\r\n }\r\n\r\n if (SavePasswordsCheck->Enabled && SavePasswordsCheck->Checked &&\r\n CustomWinConfiguration->UseMasterPassword)\r\n {\r\n CustomWinConfiguration->AskForMasterPasswordIfNotSet();\r\n }\r\n\r\n TCustomDialog::DoValidate();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSaveWorkspaceDialog::DoChange(bool & CanSubmit)\r\n{\r\n CanSubmit = !WorkspaceNameCombo->Text.IsEmpty();\r\n\r\n TCustomDialog::DoChange(CanSubmit);\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall DoSaveWorkspaceDialog(UnicodeString & WorkspaceName,\r\n bool * SavePasswords, bool NotRecommendedSavingPasswords,\r\n bool & CreateShortcut, bool & EnableAutoSave)\r\n{\r\n std::unique_ptr<TSaveWorkspaceDialog> Dialog(\r\n new TSaveWorkspaceDialog((SavePasswords != NULL), NotRecommendedSavingPasswords));\r\n\r\n bool Dummy = false;\r\n if (SavePasswords == NULL)\r\n {\r\n SavePasswords = &Dummy;\r\n }\r\n return\r\n Dialog->Execute(\r\n WorkspaceName, *SavePasswords, CreateShortcut, EnableAutoSave);\r\n}\r\n//---------------------------------------------------------------------------\r\n//---------------------------------------------------------------------------\r\nclass TShortCutDialog : public TCustomDialog\r\n{\r\npublic:\r\n __fastcall TShortCutDialog(const TShortCuts & ShortCuts, UnicodeString HelpKeyword);\r\n\r\n bool __fastcall Execute(TShortCut & ShortCut);\r\n\r\nprivate:\r\n TComboBox * ShortCutCombo;\r\n};\r\n//---------------------------------------------------------------------------\r\n__fastcall TShortCutDialog::TShortCutDialog(const TShortCuts & ShortCuts, UnicodeString HelpKeyword) :\r\n TCustomDialog(HelpKeyword)\r\n{\r\n Caption = LoadStr(SHORTCUT_CAPTION);\r\n\r\n ShortCutCombo = new TComboBox(this);\r\n AddShortCutComboBox(ShortCutCombo, CreateLabel(LoadStr(SHORTCUT_LABEL)), ShortCuts);\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TShortCutDialog::Execute(TShortCut & ShortCut)\r\n{\r\n SetShortCutCombo(ShortCutCombo, ShortCut);\r\n bool Result = TCustomDialog::Execute();\r\n if (Result)\r\n {\r\n ShortCut = GetShortCutCombo(ShortCutCombo);\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall DoShortCutDialog(TShortCut & ShortCut,\r\n const TShortCuts & ShortCuts, UnicodeString HelpKeyword)\r\n{\r\n bool Result;\r\n TShortCutDialog * Dialog = new TShortCutDialog(ShortCuts, HelpKeyword);\r\n try\r\n {\r\n Result = Dialog->Execute(ShortCut);\r\n }\r\n __finally\r\n {\r\n delete Dialog;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\n//---------------------------------------------------------------------------\r\nclass TRemoteMoveDialog : public TCustomDialog\r\n{\r\npublic:\r\n __fastcall TRemoteMoveDialog(bool Multi);\r\n\r\n bool __fastcall Execute(UnicodeString & Target, UnicodeString & FileMask);\r\n\r\nprotected:\r\n DYNAMIC void __fastcall DoShow();\r\n virtual void __fastcall DoValidate();\r\n UnicodeString __fastcall GetFileMask();\r\n\r\nprivate:\r\n THistoryComboBox * Combo;\r\n bool FMulti;\r\n};\r\n//---------------------------------------------------------------------------\r\n__fastcall TRemoteMoveDialog::TRemoteMoveDialog(bool Multi) :\r\n TCustomDialog(HELP_REMOTE_MOVE)\r\n{\r\n Caption = LoadStr(REMOTE_MOVE_TITLE);\r\n // The same as TRemoteTransferDialog\r\n ClientWidth = ScaleByTextHeight(this, 420);\r\n\r\n FMulti = Multi;\r\n\r\n AddImage(L\"Move To\");\r\n\r\n Combo = new THistoryComboBox(this);\r\n Combo->AutoComplete = false;\r\n AddComboBox(Combo, CreateLabel(LoadStr(REMOTE_TRANSFER_PROMPT2)));\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TRemoteMoveDialog::Execute(UnicodeString & Target, UnicodeString & FileMask)\r\n{\r\n Combo->Items = CustomWinConfiguration->History[L\"RemoteTarget\"];\r\n Combo->Text = UnixIncludeTrailingBackslash(Target) + FileMask;\r\n bool Result = TCustomDialog::Execute();\r\n if (Result)\r\n {\r\n Target = UnixExtractFilePath(Combo->Text);\r\n FileMask = GetFileMask();\r\n Combo->SaveToHistory();\r\n CustomWinConfiguration->History[L\"RemoteTarget\"] = Combo->Items;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TRemoteMoveDialog::GetFileMask()\r\n{\r\n return UnixExtractFileName(Combo->Text);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TRemoteMoveDialog::DoShow()\r\n{\r\n TCustomDialog::DoShow();\r\n InstallPathWordBreakProc(Combo);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TRemoteMoveDialog::DoValidate()\r\n{\r\n if (!IsFileNameMask(GetFileMask()) && FMulti)\r\n {\r\n UnicodeString Message =\r\n FormatMultiFilesToOneConfirmation(Combo->Text, true);\r\n if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_NONE) == qaCancel)\r\n {\r\n Abort();\r\n }\r\n }\r\n\r\n TCustomDialog::DoValidate();\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall DoRemoteMoveDialog(bool Multi, UnicodeString & Target, UnicodeString & FileMask)\r\n{\r\n std::unique_ptr<TRemoteMoveDialog> Dialog(new TRemoteMoveDialog(Multi));\r\n return Dialog->Execute(Target, FileMask);\r\n}\r\n//---------------------------------------------------------------------------\r\n//---------------------------------------------------------------------------\r\nclass TCustomCommandOptionsDialog : public TCustomDialog\r\n{\r\npublic:\r\n __fastcall TCustomCommandOptionsDialog(\r\n const TCustomCommandType * Command, TStrings * CustomCommandOptions, unsigned int Flags,\r\n TCustomCommand * CustomCommandForOptions, const UnicodeString & Site, const TShortCuts * ShortCuts);\r\n\r\n bool __fastcall Execute(TShortCut * ShortCut);\r\n\r\nprotected:\r\n virtual void __fastcall DoHelp();\r\n DYNAMIC void __fastcall DoShow();\r\n\r\nprivate:\r\n const TCustomCommandType * FCommand;\r\n TStrings * FCustomCommandOptions;\r\n std::vector<TControl *> FControls;\r\n std::vector<std::vector<UnicodeString> > FValues;\r\n unsigned int FFlags;\r\n UnicodeString FSite;\r\n TComboBox * FShortCutCombo;\r\n\r\n UnicodeString __fastcall HistoryKey(const TCustomCommandType::TOption & Option);\r\n THistoryComboBox * __fastcall CreateHistoryComboBox(const TCustomCommandType::TOption & Option, const UnicodeString & Value);\r\n void __fastcall BrowseButtonClick(TObject * Sender);\r\n void __fastcall LinkLabelClick(TObject * Sender);\r\n UnicodeString __fastcall SaveHistoryComboBoxValue(TControl * Control, const TCustomCommandType::TOption & Option);\r\n void __fastcall AddOptionComboBox(\r\n TComboBox * ComboBox, const UnicodeString & Value, const TCustomCommandType::TOption & Option,\r\n std::vector<UnicodeString> & Values);\r\n UnicodeString __fastcall GetComboBoxValue(TControl * Control, const UnicodeString & Default);\r\n int __fastcall GetOptionIndex(TControl * Control);\r\n int __fastcall GetControlIndex(TControl * Control);\r\n};\r\n//---------------------------------------------------------------------------\r\n__fastcall TCustomCommandOptionsDialog::TCustomCommandOptionsDialog(\r\n const TCustomCommandType * Command, TStrings * CustomCommandOptions,\r\n unsigned int Flags, TCustomCommand * CustomCommandForOptions,\r\n const UnicodeString & Site, const TShortCuts * ShortCuts) :\r\n TCustomDialog(HELP_EXTENSION_OPTIONS)\r\n{\r\n FCommand = Command;\r\n FFlags = Flags;\r\n FCustomCommandOptions = CustomCommandOptions;\r\n FSite = Site;\r\n Caption = StripEllipsis(StripHotkey(FCommand->Name));\r\n Width = ScaleByTextHeight(this, 400);\r\n\r\n bool HasGroups = false;\r\n int ControlIndex = 0;\r\n for (int OptionIndex = 0; OptionIndex < FCommand->OptionsCount; OptionIndex++)\r\n {\r\n const TCustomCommandType::TOption & Option = FCommand->GetOption(OptionIndex);\r\n\r\n if ((Option.Flags & FFlags) != 0)\r\n {\r\n UnicodeString OptionKey = FCommand->GetOptionKey(Option, FSite);\r\n UnicodeString Value;\r\n if ((CustomCommandForOptions != NULL) &&\r\n Option.HasPatterns(CustomCommandForOptions))\r\n {\r\n Value = CustomCommandForOptions->Complete(Option.Default, true);\r\n }\r\n else\r\n {\r\n if (FCustomCommandOptions->IndexOfName(OptionKey) >= 0)\r\n {\r\n Value = FCustomCommandOptions->Values[OptionKey];\r\n }\r\n else\r\n {\r\n Value = Option.Default;\r\n }\r\n }\r\n\r\n int Tag = (OptionIndex << 16) + ControlIndex;\r\n TControl * Control = NULL;\r\n std::vector<UnicodeString> Values;\r\n if (Option.Kind == TCustomCommandType::okUnknown)\r\n {\r\n Control = NULL;\r\n }\r\n else if (Option.Kind == TCustomCommandType::okLabel)\r\n {\r\n TLabel * Label = CreateLabel(Option.Caption);\r\n AddText(Label);\r\n Control = Label;\r\n }\r\n else if (Option.Kind == TCustomCommandType::okLink)\r\n {\r\n TStaticText * Label = new TStaticText(this);\r\n Label->Caption = Option.Caption;\r\n if (IsHttpOrHttpsUrl(Label->Caption))\r\n {\r\n Label->Caption = SecureUrl(Label->Caption);\r\n LinkLabel(Label);\r\n Label->TabStop = true;\r\n }\r\n else if (!Option.Default.IsEmpty() && IsHttpOrHttpsUrl(Option.Default))\r\n {\r\n Label->OnClick = LinkLabelClick;\r\n LinkLabel(Label);\r\n Label->TabStop = true;\r\n }\r\n else\r\n {\r\n // keep it plain text, as we have no URL\r\n }\r\n AddText(Label);\r\n Control = Label;\r\n }\r\n else if (Option.Kind == TCustomCommandType::okGroup)\r\n {\r\n StartGroup(Option.Caption);\r\n HasGroups = true;\r\n }\r\n else if (Option.Kind == TCustomCommandType::okSeparator)\r\n {\r\n AddSeparator();\r\n }\r\n else if (Option.Kind == TCustomCommandType::okTextBox)\r\n {\r\n Control = CreateHistoryComboBox(Option, Value);\r\n }\r\n else if (Option.Kind == TCustomCommandType::okFile)\r\n {\r\n THistoryComboBox * ComboBox = CreateHistoryComboBox(Option, Value);\r\n TButton * Button = new TButton(this);\r\n Button->Parent = GetDefaultParent();\r\n Button->Width = HelpButton->Width;\r\n Button->Left = GetDefaultParent()->ClientWidth - Button->Width - HorizontalMargin;\r\n ComboBox->Width = Button->Left - ComboBox->Left - ScaleByTextHeight(this, 6);\r\n Button->Top = ComboBox->Top - ScaleByTextHeight(this, 2);\r\n Button->Tag = Tag;\r\n Button->Caption = LoadStr(EXTENSION_OPTIONS_BROWSE);\r\n Button->OnClick = BrowseButtonClick;\r\n ScaleButtonControl(Button);\r\n AddWinControl(Button);\r\n Control = ComboBox;\r\n }\r\n else if (Option.Kind == TCustomCommandType::okDropDownList)\r\n {\r\n TComboBox * ComboBox = new TComboBox(this);\r\n ComboBox->Style = csDropDownList;\r\n\r\n AddOptionComboBox(ComboBox, Value, Option, Values);\r\n\r\n Control = ComboBox;\r\n }\r\n else if (Option.Kind == TCustomCommandType::okComboBox)\r\n {\r\n TComboBox * ComboBox = new TComboBox(this);\r\n ComboBox->Style = csDropDown;\r\n\r\n AddOptionComboBox(ComboBox, Value, Option, Values);\r\n if (ComboBox->ItemIndex < 0)\r\n {\r\n ComboBox->Text = Value;\r\n }\r\n\r\n Control = ComboBox;\r\n }\r\n else if (Option.Kind == TCustomCommandType::okCheckBox)\r\n {\r\n TCheckBox * CheckBox = CreateAndAddCheckBox(Option.Caption);\r\n\r\n CheckBox->Checked =\r\n (Option.Params.size() >= 1) &&\r\n (Value == Option.Params[0]);\r\n\r\n Control = CheckBox;\r\n }\r\n else\r\n {\r\n DebugFail();\r\n }\r\n\r\n if (Control != NULL)\r\n {\r\n Control->Tag = Tag;\r\n }\r\n FControls.push_back(Control);\r\n FValues.push_back(Values);\r\n ControlIndex++;\r\n DebugAssert(static_cast<int>(FControls.size()) == ControlIndex);\r\n }\r\n }\r\n\r\n if (ShortCuts != NULL)\r\n {\r\n if (HasGroups)\r\n {\r\n StartGroup(LoadStr(EXTENSION_GENERAL_GROUP));\r\n }\r\n else if (ControlIndex > 0)\r\n {\r\n AddSeparator();\r\n }\r\n FShortCutCombo = new TComboBox(this);\r\n AddShortCutComboBox(FShortCutCombo, CreateLabel(LoadStr(EXTENSION_SHORTCUT)), *ShortCuts);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomCommandOptionsDialog::AddOptionComboBox(\r\n TComboBox * ComboBox, const UnicodeString & Value, const TCustomCommandType::TOption & Option, std::vector<UnicodeString> & Values)\r\n{\r\n std::unique_ptr<TStringList> Items(new TStringList());\r\n int ItemIndex = -1;\r\n\r\n TCustomCommandType::TOption::TParams::const_iterator ParamI = Option.Params.begin();\r\n while (ParamI != Option.Params.end())\r\n {\r\n UnicodeString Item = (*ParamI);\r\n int P = Item.Pos(L\"=\");\r\n UnicodeString ParamValue;\r\n if (P > 0)\r\n {\r\n ParamValue = Item.SubString(1, P - 1);\r\n Item.Delete(1, P);\r\n }\r\n else\r\n {\r\n ParamValue = Item;\r\n }\r\n Item = WinConfiguration->ExtensionStringTranslation(FCommand->Id, Item);\r\n Items->Add(Item);\r\n if (Value == ParamValue)\r\n {\r\n ItemIndex = Items->Count - 1;\r\n }\r\n Values.push_back(ParamValue);\r\n ParamI++;\r\n }\r\n\r\n AddComboBox(ComboBox, CreateLabel(Option.Caption), Items.get(), true);\r\n\r\n ComboBox->ItemIndex = ItemIndex;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall TCustomCommandOptionsDialog::GetOptionIndex(TControl * Control)\r\n{\r\n return (Control->Tag >> 16);\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall TCustomCommandOptionsDialog::GetControlIndex(TControl * Control)\r\n{\r\n return (Control->Tag & 0xFFFF);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomCommandOptionsDialog::LinkLabelClick(TObject * Sender)\r\n{\r\n TStaticText * Label = DebugNotNull(dynamic_cast<TStaticText *>(Sender));\r\n const TCustomCommandType::TOption & Option = FCommand->GetOption(GetOptionIndex(Label));\r\n OpenBrowser(SecureUrl(Option.Default));\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomCommandOptionsDialog::BrowseButtonClick(TObject * Sender)\r\n{\r\n TButton * Button = DebugNotNull(dynamic_cast<TButton *>(Sender));\r\n int OptionIndex = GetOptionIndex(Button);\r\n const TCustomCommandType::TOption & Option = FCommand->GetOption(OptionIndex);\r\n int ControlIndex = GetControlIndex(Button);\r\n THistoryComboBox * ComboBox = dynamic_cast<THistoryComboBox *>(FControls[ControlIndex]);\r\n\r\n std::unique_ptr<TOpenDialog> OpenDialog(new TOpenDialog(Application));\r\n\r\n UnicodeString Title;\r\n if (!Option.FileCaption.IsEmpty())\r\n {\r\n Title = Option.FileCaption;\r\n }\r\n else\r\n {\r\n UnicodeString Caption = Option.Caption;\r\n Caption = StripHotkey(Caption);\r\n if (!Caption.IsEmpty() && (Caption[Caption.Length()] == L':'))\r\n {\r\n Caption.SetLength(Caption.Length() - 1);\r\n }\r\n Title = FMTLOAD(EXTENSION_OPTIONS_BROWSE_TITLE, (Caption));\r\n }\r\n OpenDialog->Title = Title;\r\n\r\n UnicodeString Value;\r\n if (ComboBox->Text.IsEmpty())\r\n {\r\n Value = Option.FileInitial;\r\n }\r\n else\r\n {\r\n Value = ComboBox->Text;\r\n }\r\n UnicodeString ExpandedValue = ExpandEnvironmentVariables(Value);\r\n OpenDialog->FileName = ExpandedValue;\r\n UnicodeString InitialDir = ExtractFilePath(ExpandedValue);\r\n if (!InitialDir.IsEmpty())\r\n {\r\n OpenDialog->InitialDir = InitialDir;\r\n }\r\n OpenDialog->Filter = Option.FileFilter;\r\n OpenDialog->DefaultExt = Option.FileExt;\r\n\r\n if (OpenDialog->Execute())\r\n {\r\n if (OpenDialog->FileName != ExpandedValue)\r\n {\r\n ComboBox->Text = OpenDialog->FileName;\r\n }\r\n // If user just confirms the initial value, persist it\r\n else if (ComboBox->Text.IsEmpty())\r\n {\r\n DebugAssert(Option.FileInitial == Value);\r\n ComboBox->Text = Value;\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nTHistoryComboBox * __fastcall TCustomCommandOptionsDialog::CreateHistoryComboBox(\r\n const TCustomCommandType::TOption & Option, const UnicodeString & Value)\r\n{\r\n THistoryComboBox * ComboBox = new THistoryComboBox(this);\r\n ComboBox->AutoComplete = false;\r\n AddComboBox(ComboBox, CreateLabel(Option.Caption));\r\n ComboBox->Items = CustomWinConfiguration->History[HistoryKey(Option)];\r\n ComboBox->Text = Value;\r\n return ComboBox;\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TCustomCommandOptionsDialog::HistoryKey(const TCustomCommandType::TOption & Option)\r\n{\r\n UnicodeString Result = FCommand->GetOptionKey(Option, FSite);\r\n Result = CustomWinConfiguration->GetValidHistoryKey(Result);\r\n return L\"CustomCommandOption_\" + Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TCustomCommandOptionsDialog::Execute(TShortCut * ShortCut)\r\n{\r\n if (ShortCut != NULL)\r\n {\r\n SetShortCutCombo(FShortCutCombo, *ShortCut);\r\n }\r\n\r\n bool Result = TCustomDialog::Execute();\r\n\r\n if (Result)\r\n {\r\n int ControlIndex = 0;\r\n for (int OptionIndex = 0; OptionIndex < FCommand->OptionsCount; OptionIndex++)\r\n {\r\n const TCustomCommandType::TOption & Option = FCommand->GetOption(OptionIndex);\r\n if ((Option.Flags & FFlags) != 0)\r\n {\r\n if ((Option.Kind != TCustomCommandType::okUnknown) &&\r\n Option.IsControl)\r\n {\r\n UnicodeString OptionKey = FCommand->GetOptionKey(Option, FSite);\r\n\r\n TControl * Control = FControls[ControlIndex];\r\n\r\n UnicodeString Value;\r\n if (Option.Kind == TCustomCommandType::okTextBox)\r\n {\r\n Value = SaveHistoryComboBoxValue(Control, Option);\r\n }\r\n else if (Option.Kind == TCustomCommandType::okFile)\r\n {\r\n Value = SaveHistoryComboBoxValue(Control, Option);\r\n }\r\n else if (Option.Kind == TCustomCommandType::okDropDownList)\r\n {\r\n Value = GetComboBoxValue(Control, Option.Default);\r\n }\r\n else if (Option.Kind == TCustomCommandType::okComboBox)\r\n {\r\n TComboBox * ComboBox = DebugNotNull(dynamic_cast<TComboBox *>(Control));\r\n Value = GetComboBoxValue(Control, ComboBox->Text);\r\n }\r\n else if (Option.Kind == TCustomCommandType::okCheckBox)\r\n {\r\n TCheckBox * CheckBox = DebugNotNull(dynamic_cast<TCheckBox *>(Control));\r\n int Index = (CheckBox->Checked ? 0 : 1);\r\n Value = (Index < static_cast<int>(Option.Params.size())) ? Option.Params[Index] : UnicodeString();\r\n }\r\n else\r\n {\r\n DebugFail();\r\n }\r\n\r\n // The default value setter deletes the \"name\" when the value is empty.\r\n // It would cause us to fall back to the default value, but we want to remember the empty value.\r\n SetStringValueEvenIfEmpty(FCustomCommandOptions, OptionKey, Value);\r\n }\r\n\r\n ControlIndex++;\r\n }\r\n }\r\n\r\n if (ShortCut != NULL)\r\n {\r\n *ShortCut = GetShortCutCombo(FShortCutCombo);\r\n }\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TCustomCommandOptionsDialog::GetComboBoxValue(\r\n TControl * Control, const UnicodeString & Default)\r\n{\r\n TComboBox * ComboBox = DebugNotNull(dynamic_cast<TComboBox *>(Control));\r\n UnicodeString Result;\r\n if (ComboBox->ItemIndex < 0)\r\n {\r\n Result = Default;\r\n }\r\n else\r\n {\r\n Result = FValues[GetControlIndex(Control)][ComboBox->ItemIndex];\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TCustomCommandOptionsDialog::SaveHistoryComboBoxValue(\r\n TControl * Control, const TCustomCommandType::TOption & Option)\r\n{\r\n THistoryComboBox * ComboBox = DebugNotNull(dynamic_cast<THistoryComboBox *>(Control));\r\n ComboBox->SaveToHistory();\r\n CustomWinConfiguration->History[HistoryKey(Option)] = ComboBox->Items;\r\n return ComboBox->Text;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomCommandOptionsDialog::DoHelp()\r\n{\r\n UnicodeString HelpPage;\r\n if (!FCommand->OptionsPage.IsEmpty())\r\n {\r\n HelpPage = FCommand->OptionsPage;\r\n }\r\n else\r\n {\r\n HelpPage = FCommand->HomePage;\r\n }\r\n\r\n if (!HelpPage.IsEmpty())\r\n {\r\n OpenBrowser(HelpPage);\r\n }\r\n else\r\n {\r\n TCustomDialog::DoHelp();\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomCommandOptionsDialog::DoShow()\r\n{\r\n TCustomDialog::DoShow();\r\n\r\n int ControlIndex = 0;\r\n for (int OptionIndex = 0; OptionIndex < FCommand->OptionsCount; OptionIndex++)\r\n {\r\n const TCustomCommandType::TOption & Option = FCommand->GetOption(OptionIndex);\r\n\r\n if ((Option.Flags & FFlags) != 0)\r\n {\r\n if (Option.Kind == TCustomCommandType::okFile)\r\n {\r\n TControl * Control = FControls[ControlIndex];\r\n InstallPathWordBreakProc(DebugNotNull(dynamic_cast<TWinControl *>(Control)));\r\n }\r\n ControlIndex++;\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall DoCustomCommandOptionsDialog(\r\n const TCustomCommandType * Command, TStrings * CustomCommandOptions, TShortCut * ShortCut,\r\n unsigned int Flags, TCustomCommand * CustomCommandForOptions,\r\n const UnicodeString & Site, const TShortCuts * ShortCuts)\r\n{\r\n std::unique_ptr<TCustomCommandOptionsDialog> Dialog(\r\n new TCustomCommandOptionsDialog(Command, CustomCommandOptions, Flags, CustomCommandForOptions, Site, ShortCuts));\r\n return Dialog->Execute(ShortCut);\r\n}\r\n//---------------------------------------------------------------------------\r\n//---------------------------------------------------------------------------\r\nclass TUsageStatisticsDialog : public TCustomDialog\r\n{\r\npublic:\r\n __fastcall TUsageStatisticsDialog();\r\n\r\nprotected:\r\n virtual void __fastcall DoChange(bool & CanSubmit);\r\n\r\nprivate:\r\n TEdit * FilterEdit;\r\n TMemo * UsageMemo;\r\n TButton * ClipboardButton;\r\n\r\n void __fastcall ClipboardButtonClick(TObject * Sender);\r\n};\r\n//---------------------------------------------------------------------------\r\n__fastcall TUsageStatisticsDialog::TUsageStatisticsDialog() :\r\n TCustomDialog(HELP_USAGE)\r\n{\r\n Caption = LoadStr(USAGE_CAPTION);\r\n Width = ScaleByTextHeight(this, 400);\r\n\r\n TLabel * Label = new TLabel(this);\r\n // UnformatMessage is called, because previously, ** markup was used and translations may still contain that\r\n Label->Caption = UnformatMessage(LoadStr(USAGE_DATA2));\r\n AddText(Label);\r\n\r\n FilterEdit = new TEdit(this);\r\n FilterEdit->Width = ScaleByTextHeight(this, 250);\r\n TLabel * FilterLabel = new TLabel(this);\r\n FilterLabel->Caption = LoadStr(USAGE_FILTER);\r\n AddEdit(FilterEdit, FilterLabel, true);\r\n\r\n UsageMemo = new TMemo(this);\r\n UsageMemo->Height = ScaleByTextHeight(this, 300);\r\n UsageMemo->ScrollBars = ssVertical;\r\n AddEdit(UsageMemo, NULL);\r\n ReadOnlyControl(UsageMemo);\r\n\r\n ClipboardButton = new TButton(this);\r\n ClipboardButton->Caption = LoadStr(USAGE_COPY);\r\n ClipboardButton->Width = ScaleByTextHeight(this, 121);\r\n ClipboardButton->OnClick = ClipboardButtonClick;\r\n AddDialogButton(ClipboardButton);\r\n\r\n RemoveCancelButton();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TUsageStatisticsDialog::ClipboardButtonClick(TObject * /*Sender*/)\r\n{\r\n TInstantOperationVisualizer Visualizer;\r\n CopyToClipboard(UsageMemo->Lines);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TUsageStatisticsDialog::DoChange(bool & CanSubmit)\r\n{\r\n TCustomDialog::DoChange(CanSubmit);\r\n UnicodeString Text = Configuration->Usage->Serialize(L\"\\n\", FilterEdit->Text);\r\n bool NoUsage = Text.IsEmpty();\r\n ClipboardButton->Enabled = !NoUsage;\r\n if (NoUsage)\r\n {\r\n Text = LoadStr(USAGE_DATA_NONE2);\r\n }\r\n UsageMemo->Lines->Text = Text;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall DoUsageStatisticsDialog()\r\n{\r\n std::unique_ptr<TUsageStatisticsDialog> Dialog(new TUsageStatisticsDialog());\r\n Dialog->Execute();\r\n}\r\n//---------------------------------------------------------------------------\r\n//---------------------------------------------------------------------------\r\nclass TSiteRawDialog : public TCustomDialog\r\n{\r\npublic:\r\n __fastcall TSiteRawDialog();\r\n\r\n bool __fastcall Execute(TSessionData * Data);\r\n\r\nprotected:\r\n DYNAMIC void __fastcall DoShow();\r\n\r\nprivate:\r\n TMemo * SettingsMemo;\r\n\r\n void __fastcall AddButtonClick(TObject * Sender);\r\n void __fastcall SettingsMemoKeyDown(TObject * Sender, WORD & Key, TShiftState Shift);\r\n\r\n void DeleteNames(TStrings * Names, TStrings * Options);\r\n};\r\n//---------------------------------------------------------------------------\r\n__fastcall TSiteRawDialog::TSiteRawDialog() :\r\n TCustomDialog(HELP_SITE_RAW)\r\n{\r\n Caption = LoadStr(SITE_RAW_CAPTION);\r\n Width = ScaleByTextHeight(this, 400);\r\n\r\n SettingsMemo = new TMemo(this);\r\n SettingsMemo->Height = ScaleByTextHeight(this, 300);\r\n SettingsMemo->OnKeyDown = SettingsMemoKeyDown;\r\n AddEdit(SettingsMemo, NULL);\r\n\r\n TButton * AddButton = new TButton(this);\r\n AddButton->Caption = LoadStr(SITE_RAW_ADD);\r\n AddButton->Width = OKButton->Width;\r\n AddButton->OnClick = AddButtonClick;\r\n AddDialogButton(AddButton);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSiteRawDialog::DoShow()\r\n{\r\n TCustomDialog::DoShow();\r\n InstallPathWordBreakProc(SettingsMemo);\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TSiteRawDialog::Execute(TSessionData * Data)\r\n{\r\n std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L\"\"));\r\n std::unique_ptr<TSessionData> RawData(new TSessionData(L\"\"));\r\n RawData->Assign(Data);\r\n // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that\r\n if (RawData->FSProtocol != fsSFTPonly)\r\n {\r\n RawData->FSProtocol = FactoryDefaults->FSProtocol;\r\n }\r\n RawData->HostName = FactoryDefaults->HostName;\r\n RawData->PortNumber = FactoryDefaults->PortNumber;\r\n RawData->UserName = FactoryDefaults->UserName;\r\n RawData->Password = FactoryDefaults->Password;\r\n RawData->Ftps = FactoryDefaults->Ftps;\r\n\r\n std::unique_ptr<TStrings> Options(RawData->SaveToOptions(FactoryDefaults.get(), false, false));\r\n\r\n SettingsMemo->Lines = Options.get();\r\n\r\n bool Result = TCustomDialog::Execute();\r\n if (Result)\r\n {\r\n std::unique_ptr<TSessionData> BackupData(new TSessionData(L\"\"));\r\n BackupData->Assign(Data);\r\n Data->DefaultSettings();\r\n\r\n Data->FSProtocol = BackupData->FSProtocol;\r\n Data->HostName = BackupData->HostName;\r\n Data->PortNumber = BackupData->PortNumber;\r\n Data->UserName = BackupData->UserName;\r\n Data->Password = BackupData->Password;\r\n Data->Ftps = BackupData->Ftps;\r\n\r", " Data->ApplyRawSettings(SettingsMemo->Lines);\r", " }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSiteRawDialog::SettingsMemoKeyDown(TObject * Sender, WORD & Key, TShiftState Shift)\r\n{\r\n MemoKeyDown(Sender, Key, Shift);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSiteRawDialog::AddButtonClick(TObject *)\r\n{\r\n std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L\"\"));\r\n std::unique_ptr<TSessionData> BasicData(new TSessionData(L\"\"));\r\n BasicData->FSProtocol = TFSProtocol(FactoryDefaults->FSProtocol + 1);\r\n UnicodeString RandomAppendix(L\"_\");\r\n BasicData->HostName = FactoryDefaults->HostName + RandomAppendix;\r\n BasicData->Ftps = TFtps(FactoryDefaults->Ftps + 1);\r\n BasicData->PortNumber = DefaultPort(BasicData->FSProtocol, BasicData->Ftps) + 1;\r\n BasicData->UserName = FactoryDefaults->UserName + RandomAppendix;\r\n BasicData->Password = FactoryDefaults->Password + RandomAppendix;\r\n\r\n std::unique_ptr<TStrings> BasicOptions(BasicData->SaveToOptions(FactoryDefaults.get(), false, false));\r\n\r\n std::unique_ptr<TStrings> AllOptions(TSessionData::GetAllOptionNames(false));\r\n\r\n std::unique_ptr<TStrings> Names(CreateSortedStringList());\r\n for (int Index = 0; Index < AllOptions->Count; Index++)\r\n {\r\n Names->Add(AllOptions->Names[Index]);\r\n }\r\n DeleteNames(Names.get(), BasicOptions.get());\r\n DeleteNames(Names.get(), SettingsMemo->Lines);\r\n\r\n std::unique_ptr<TCustomDialog> AddDialog(new TCustomDialog(HelpKeyword));\r\n AddDialog->Caption = LoadStr(SITE_RAW_ADD_CAPTION);\r\n TComboBox * AddComboBox = new TComboBox(AddDialog.get());\r\n AddComboBox->Style = csDropDownList;\r\n AddComboBox->DropDownCount = Max(AddComboBox->DropDownCount, 16);\r\n AddDialog->AddComboBox(AddComboBox, CreateLabel(LoadStr(SITE_RAW_ADD_LABEL)), Names.get(), true);\r\n AddComboBox->ItemIndex = 0;\r\n if (AddDialog->Execute())\r\n {\r\n UnicodeString Name = AddComboBox->Items->Strings[AddComboBox->ItemIndex];\r\n UnicodeString Value = AllOptions->Values[Name];\r\n UnicodeString NameAndSeparator = Name + SettingsMemo->Lines->NameValueSeparator;\r\n int Start = (SettingsMemo->Lines->Text + NameAndSeparator).Length();\r\n SettingsMemo->Lines->Add(NameAndSeparator + Value);\r\n SettingsMemo->SetFocus();\r\n SettingsMemo->SelStart = Start;\r\n SettingsMemo->SelLength = Value.Length();\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid TSiteRawDialog::DeleteNames(TStrings * Names, TStrings * Options)\r\n{\r\n for (int Index = 0; Index < Options->Count; Index++)\r\n {\r\n UnicodeString Name = Options->Names[Index];\r\n if (!Name.IsEmpty())\r\n {\r\n int I = Names->IndexOf(Name);\r\n if (I >= 0)\r\n {\r\n Names->Delete(I);\r\n }\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall DoSiteRawDialog(TSessionData * Data)\r\n{\r\n std::unique_ptr<TSiteRawDialog> Dialog(new TSiteRawDialog());\r\n Dialog->Execute(Data);\r\n}" ]
[ 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 53, 80, 2275, 473, 1511, 2372, 1100], "buggy_code_start_loc": [46, 52, 79, 599, 57, 1510, 2371, 1099], "filenames": ["source/Console.cbproj", "source/DragExt.cbproj", "source/WinSCP.cbproj", "source/core/SessionData.cpp", "source/core/SessionData.h", "source/forms/Custom.cpp", "source/windows/ConsoleRunner.cpp", "source/windows/WinMain.cpp"], "fixing_code_end_loc": [47, 53, 80, 2294, 474, 1511, 2372, 1103], "fixing_code_start_loc": [46, 52, 79, 599, 58, 1510, 2371, 1099], "message": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:winscp:winscp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C081564B-8EF8-4C8A-9EB0-1C50D5A8F18B", "versionEndExcluding": "5.17.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)"}, {"lang": "es", "value": "WinSCP anterior a la versi\u00f3n 5.17.10 permite a los atacantes remotos ejecutar programas arbitrarios cuando el manejador de URLs encuentra una URL manipulada que carga la configuraci\u00f3n de la sesi\u00f3n. (Por ejemplo, esto es explotable en una instalaci\u00f3n por defecto en la que WinSCP es el manejador de URLs sftp://)"}], "evaluatorComment": null, "id": "CVE-2021-3331", "lastModified": "2021-02-04T15:59:24.960", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-01-27T21:15:16.840", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://winscp.net/eng/docs/history#5.17.10"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://winscp.net/eng/docs/rawsettings"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://winscp.net/tracker/1943"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, "type": "NVD-CWE-Other"}
177
Determine whether the {function_name} code is vulnerable or not.
[ "//---------------------------------------------------------------------\r\n#include <vcl.h>\r\n#pragma hdrstop\r\n\r\n#include <Dialogs.hpp>\r\n//---------------------------------------------------------------------\r\n#include <Common.h>\r\n#include <CustomWinConfiguration.h>\r\n#include <WinInterface.h>\r\n#include <VCLCommon.h>\r\n#include <TextsWin.h>\r\n#include <HelpWin.h>\r\n#include <CoreMain.h>\r\n#include <PasTools.hpp>\r\n#include <ProgParams.h>\r\n#include <Tools.h>\r\n#include <GUITools.h>\r\n#include <HistoryComboBox.hpp>\r\n#include <Math.hpp>\r\n\r\n#include \"Custom.h\"\r\n//---------------------------------------------------------------------\r\n#pragma link \"PasswordEdit\"\r\n#pragma resource \"*.dfm\"\r\n//---------------------------------------------------------------------\r\n__fastcall TCustomDialog::TCustomDialog(UnicodeString AHelpKeyword)\r\n : TForm(GetFormOwner())\r\n{\r\n UseSystemSettings(this);\r\n\r\n FControlPadding = ScaleByTextHeight(this, 8);\r\n FPos = ScaleByTextHeight(this, 8);\r\n FPrePos = FPos;\r\n FHorizontalMargin = ScaleByTextHeight(this, 8);\r\n FIndent = FHorizontalMargin;\r\n FGroupBox = NULL;\r\n\r\n HelpKeyword = AHelpKeyword;\r\n\r\n TBorderIcons BI = BorderIcons;\r\n if (HelpKeyword.IsEmpty())\r\n {\r\n BI >> biHelp;\r\n\r\n OKButton->Left = CancelButton->Left;\r\n CancelButton->Left = HelpButton->Left;\r\n HelpButton->Visible = false;\r\n }\r\n else\r\n {\r\n BI << biHelp;\r\n }\r\n BorderIcons = BI;\r\n}\r\n//---------------------------------------------------------------------\r\nbool __fastcall TCustomDialog::Execute()\r\n{\r\n Changed();\r\n return (ShowModal() == DefaultResult(this));\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::DoChange(bool & /*CanSubmit*/)\r\n{\r\n // noop\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::Changed()\r\n{\r\n bool CanSubmit = true;\r\n DoChange(CanSubmit);\r\n EnableControl(OKButton, CanSubmit);\r\n}\r\n//---------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::Change(TObject * /*Sender*/)\r\n{\r\n Changed();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::DoHelp()\r\n{\r\n FormHelp(this);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::HelpButtonClick(TObject * /*Sender*/)\r\n{\r\n DoHelp();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::DoShow()\r\n{\r\n OKButton->TabOrder = FCount;\r\n CancelButton->TabOrder = static_cast<short>(FCount + 1);\r\n HelpButton->TabOrder = static_cast<short>(FCount + 2);\r\n Changed();\r\n TForm::DoShow();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::DoValidate()\r\n{\r\n // noop\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TCustomDialog::CloseQuery()\r\n{\r\n if (ModalResult == DefaultResult(this))\r\n {\r\n DoValidate();\r\n }\r\n return TForm::CloseQuery();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::RemoveCancelButton()\r\n{\r\n CancelButton->Visible = false;\r\n OKButton->Left = CancelButton->Left;\r\n OKButton->Cancel = true;\r\n DebugAssert(OKButton->Width == CancelButton->Width);\r\n DebugAssert(OKButton->Top == CancelButton->Top);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddDialogButton(TButton * Button)\r\n{\r\n Button->Parent = this;\r\n Button->Top = OKButton->Top;\r\n Button->Left = FHorizontalMargin;\r\n Button->Height = OKButton->Height;\r\n AddWinControl(Button);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddImage(const UnicodeString & ImageName)\r\n{\r\n TImage * Image = new TImage(this);\r\n Image->Name = L\"Image\";\r\n Image->Parent = GetDefaultParent();\r\n LoadDialogImage(Image, ImageName);\r\n Image->SetBounds(FIndent, FPos + ScaleByTextHeight(this, 3), Image->Picture->Width, Image->Picture->Height);\r\n FIndent += Image->Width + ScaleByTextHeight(this, 12);\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall TCustomDialog::GetMaxControlWidth(TControl * Control)\r\n{\r\n return GetDefaultParent()->ClientWidth - Control->Left - FHorizontalMargin;\r\n}\r\n//---------------------------------------------------------------------------\r\nTWinControl * __fastcall TCustomDialog::GetDefaultParent()\r\n{\r\n return (FGroupBox != NULL) ? FGroupBox : static_cast<TWinControl *>(this);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AdjustHeight(TControl * Control)\r\n{\r\n FPos = Control->Top + Control->Height + FControlPadding;\r\n int Delta = (FPos - FPrePos);\r\n ClientHeight = ClientHeight + Delta;\r\n if (FGroupBox != NULL)\r\n {\r\n FGroupBox->Height = FGroupBox->Height + Delta;\r\n }\r\n FPrePos = FPos;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddWinControl(TWinControl * Control)\r\n{\r\n Control->TabOrder = FCount;\r\n FCount++;\r\n}\r\n//---------------------------------------------------------------------------\r\nTCheckBox * __fastcall TCustomDialog::CreateAndAddCheckBox(const UnicodeString & Caption)\r\n{\r\n TCheckBox * CheckBox = new TCheckBox(this);\r\n CheckBox->Caption = Caption;\r\n AddButtonControl(CheckBox);\r\n return CheckBox;\r\n}\r\n//---------------------------------------------------------------------------\r\nTLabel * __fastcall TCustomDialog::CreateLabel(UnicodeString Label)\r\n{\r\n TLabel * Result = new TLabel(this);\r\n Result->Caption = Label;\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddEditLikeControl(TWinControl * Edit, TLabel * Label, bool OneLine)\r\n{\r\n Edit->Parent = GetDefaultParent();\r\n // this updates Height property to real value\r\n Edit->HandleNeeded();\r\n\r\n if (Label != NULL)\r\n {\r\n Label->Parent = GetDefaultParent();\r\n Label->Left = FIndent;\r\n\r\n if (OneLine)\r\n {\r\n DebugAssert(Edit->Height > Label->Height);\r\n Label->Top = FPos + ((Edit->Height - Label->Height) / 2);\r\n }\r\n else\r\n {\r\n Label->Top = FPos;\r\n\r\n FPos += Label->Height + ScaleByTextHeight(this, 4);\r\n }\r\n }\r\n\r\n Edit->Top = FPos;\r\n if (OneLine)\r\n {\r\n Edit->Left = GetDefaultParent()->ClientWidth - FHorizontalMargin - Edit->Width;\r\n }\r\n else\r\n {\r\n Edit->Left = FIndent;\r\n Edit->Width = GetMaxControlWidth(Edit);\r\n }\r\n\r\n AdjustHeight(Edit);\r\n\r\n if (Label != NULL)\r\n {\r\n if (Label->FocusControl == NULL)\r\n {\r\n Label->FocusControl = Edit;\r\n }\r\n else\r\n {\r\n DebugAssert(Label->FocusControl == Edit);\r\n }\r\n }\r\n\r\n AddWinControl(Edit);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddEdit(TCustomEdit * Edit, TLabel * Label, bool OneLine)\r\n{\r\n AddEditLikeControl(Edit, Label, OneLine);\r\n\r\n TEdit * PublicEdit = reinterpret_cast<TEdit *>(Edit);\r\n if (PublicEdit->OnChange == NULL)\r\n {\r\n PublicEdit->OnChange = Change;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::SetUpComboBox(TCustomCombo * Combo, TStrings * Items, bool OneLine)\r\n{\r\n if (Items != NULL)\r\n {\r\n Combo->Items = Items;\r\n }\r\n\r\n if (OneLine)\r\n {\r\n int Width = 0;\r\n for (int Index = 0; Index < Combo->Items->Count; Index++)\r\n {\r\n Width = Max(Width, Combo->Canvas->TextWidth(Combo->Items->Strings[Index]));\r\n }\r\n\r\n Width += ScaleByTextHeight(Combo, 4 + 16 + 14);\r\n Width = Max(Width, HelpButton->Width);\r\n\r\n Combo->Width = Width;\r\n Combo->Left = GetDefaultParent()->ClientWidth - FHorizontalMargin - Width;\r\n }\r\n\r\n TComboBox * PublicCombo = reinterpret_cast<TComboBox *>(Combo);\r\n if (PublicCombo->OnChange == NULL)\r\n {\r\n PublicCombo->OnChange = Change;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddComboBox(TCustomCombo * Combo, TLabel * Label, TStrings * Items, bool OneLine)\r\n{\r\n AddEditLikeControl(Combo, Label, OneLine);\r\n\r\n SetUpComboBox(Combo, Items, OneLine);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddShortCutComboBox(TComboBox * Combo, TLabel * Label, const TShortCuts & ShortCuts)\r\n{\r\n AddEditLikeControl(Combo, Label, true);\r\n InitializeShortCutCombo(Combo, ShortCuts);\r\n SetUpComboBox(Combo, NULL, true);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::ScaleButtonControl(TButtonControl * Control)\r\n{\r\n // this updates Height property to real value\r\n Control->HandleNeeded();\r\n // buttons do not scale with text on their own\r\n Control->Height = ScaleByTextHeight(Control, Control->Height);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddButtonControl(TButtonControl * Control)\r\n{\r\n Control->Parent = GetDefaultParent();\r\n Control->Left = FIndent + ScaleByTextHeight(this, 6);\r\n Control->Top = FPos;\r\n Control->Width = GetMaxControlWidth(Control);\r\n ScaleButtonControl(Control);\r\n\r\n AdjustHeight(Control);\r\n\r\n AddWinControl(Control);\r\n\r\n TCheckBox * PublicControl = reinterpret_cast<TCheckBox *>(Control);\r\n if (PublicControl->OnClick == NULL)\r\n {\r\n PublicControl->OnClick = Change;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddText(TLabel * Label)\r\n{\r\n Label->Parent = GetDefaultParent();\r\n\r\n Label->WordWrap = true;\r\n Label->Left = FIndent;\r\n Label->Width = GetMaxControlWidth(Label);\r\n Label->Top = FPos;\r\n Label->ShowAccelChar = false;\r\n\r\n TRect TextRect;\r\n SetRect(&TextRect, 0, 0, Label->Width, 0);\r\n DrawText(Label->Canvas->Handle, Label->Caption.c_str(), Label->Caption.Length() + 1, &TextRect,\r\n DT_EXPANDTABS | DT_CALCRECT | DT_WORDBREAK | DT_NOPREFIX |\r\n Label->DrawTextBiDiModeFlagsReadingOnly());\r\n Label->Height = TextRect.Height();\r\n\r\n AdjustHeight(Label);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddText(TStaticText * Label)\r\n{\r\n Label->Parent = GetDefaultParent();\r\n\r\n Label->Left = FIndent;\r\n Label->Width = GetMaxControlWidth(Label);\r\n Label->Top = FPos;\r\n Label->ShowAccelChar = false;\r\n\r\n AdjustHeight(Label);\r\n AddWinControl(Label);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::AddSeparator()\r\n{\r\n TBevel * Bevel = new TBevel(this);\r\n Bevel->Parent = GetDefaultParent();\r\n\r\n Bevel->Left = FIndent;\r\n Bevel->Top = FPos;\r\n Bevel->Height = 2;\r\n Bevel->Width = GetMaxControlWidth(Bevel);\r\n\r\n AdjustHeight(Bevel);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomDialog::StartGroup(const UnicodeString & Caption)\r\n{\r\n if (FGroupBox != NULL)\r\n {\r\n FIndent = FGroupBox->Left;\r\n FPos = FGroupBox->Top + FGroupBox->Height + FControlPadding;\r\n FPrePos = FPos;\r\n FGroupBox = NULL;\r\n }\r\n\r\n TGroupBox * GroupBox = new TGroupBox(this);\r\n GroupBox->Parent = this;\r\n GroupBox->Caption = Caption;\r\n\r\n GroupBox->Left = FIndent;\r\n GroupBox->Top = FPos;\r\n GroupBox->Height = ScaleByTextHeight(GroupBox, 20);\r\n GroupBox->Width = GetMaxControlWidth(GroupBox);\r\n\r\n AdjustHeight(GroupBox);\r\n\r\n AddWinControl(GroupBox);\r\n\r\n FPos = ScaleByTextHeight(this, 16);\r\n FPrePos = FPos;\r\n FIndent = FHorizontalMargin;\r\n\r\n FGroupBox = GroupBox;\r\n}\r\n//---------------------------------------------------------------------------\r\n//---------------------------------------------------------------------------\r\nclass TSaveSessionDialog : public TCustomDialog\r\n{\r\npublic:\r\n __fastcall TSaveSessionDialog(TComponent* AOwner);\r\n void __fastcall Init(bool CanSavePassword, bool NotRecommendedSavingPassword,\r\n TStrings * AdditionalFolders);\r\n\r\n bool __fastcall Execute(UnicodeString & SessionName, bool & SavePassword,\r\n bool & CreateShortcut, const UnicodeString & OriginalSessionName);\r\n\r\nprotected:\r\n virtual void __fastcall DoValidate();\r\n virtual void __fastcall DoChange(bool & CanSubmit);\r\n\r\nprivate:\r\n UnicodeString FOriginalSessionName;\r\n TEdit * SessionNameEdit;\r\n TComboBox * FolderCombo;\r\n TCheckBox * SavePasswordCheck;\r\n TCheckBox * CreateShortcutCheck;\r\n UnicodeString FRootFolder;\r\n\r\n UnicodeString __fastcall GetSessionName();\r\n};\r\n//---------------------------------------------------------------------------\r\n// Need to have an Owner argument for SafeFormCreate\r\n__fastcall TSaveSessionDialog::TSaveSessionDialog(TComponent* /*AOwner*/) :\r\n TCustomDialog(HELP_SESSION_SAVE)\r\n{\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSaveSessionDialog::Init(bool CanSavePassword,\r\n bool NotRecommendedSavingPassword, TStrings * AdditionalFolders)\r\n{\r\n Caption = LoadStr(SAVE_SESSION_CAPTION);\r\n\r\n SessionNameEdit = new TEdit(this);\r\n AddEdit(SessionNameEdit, CreateLabel(LoadStr(SAVE_SESSION_PROMPT)));\r\n\r\n FRootFolder = LoadStr(SAVE_SESSION_ROOT_FOLDER2);\r\n std::unique_ptr<TStringList> Folders(new TStringList());\r\n\r\n if (AdditionalFolders != NULL)\r\n {\r\n Folders->AddStrings(AdditionalFolders);\r\n }\r\n\r\n for (int Index = 0; Index < StoredSessions->Count; Index++)\r\n {\r\n TSessionData * Data = StoredSessions->Sessions[Index];\r\n if (!Data->Special && !Data->IsWorkspace)\r\n {\r\n UnicodeString Folder = Data->FolderName;\r\n if (!Folder.IsEmpty() && Folders->IndexOf(Folder) < 0)\r\n {\r\n Folders->Add(Folder);\r\n }\r\n }\r\n }\r\n\r\n DebugAssert(!Folders->CaseSensitive);\r\n Folders->Sort();\r\n\r\n FolderCombo = new TComboBox(this);\r\n AddComboBox(FolderCombo, CreateLabel(LoadStr(SAVE_SESSION_FOLDER)));\r\n FolderCombo->DropDownCount = Max(FolderCombo->DropDownCount, 16);\r\n FolderCombo->Items->Add(FRootFolder);\r\n FolderCombo->Items->AddStrings(Folders.get());\r\n\r\n SavePasswordCheck = CreateAndAddCheckBox(\r\n LoadStr(NotRecommendedSavingPassword ? SAVE_SESSION_PASSWORD :\r\n (CustomWinConfiguration->UseMasterPassword ? SAVE_SESSION_PASSWORD_MASTER : SAVE_SESSION_PASSWORD_RECOMMENDED)));\r\n\r\n CreateShortcutCheck = CreateAndAddCheckBox(LoadStr(SAVE_SITE_WORKSPACE_SHORTCUT));\r\n\r\n EnableControl(SavePasswordCheck, CanSavePassword);\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TSaveSessionDialog::Execute(\r\n UnicodeString & SessionName, bool & SavePassword, bool & CreateShortcut,\r\n const UnicodeString & OriginalSessionName)\r\n{\r\n FOriginalSessionName = OriginalSessionName;\r\n SessionNameEdit->Text = TSessionData::ExtractLocalName(SessionName);\r\n UnicodeString Folder = TSessionData::ExtractFolderName(SessionName);\r\n if (Folder.IsEmpty())\r\n {\r\n FolderCombo->Text = FRootFolder;\r\n }\r\n else\r\n {\r\n FolderCombo->Text = Folder;\r\n }\r\n SavePasswordCheck->Checked = SavePassword;\r\n CreateShortcutCheck->Checked = CreateShortcut;\r\n bool Result = TCustomDialog::Execute();\r\n if (Result)\r\n {\r\n SessionName = GetSessionName();\r\n SavePassword = SavePasswordCheck->Checked;\r\n CreateShortcut = CreateShortcutCheck->Checked;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TSaveSessionDialog::GetSessionName()\r\n{\r\n UnicodeString Folder;\r\n if (FolderCombo->Text != FRootFolder)\r\n {\r\n Folder = FolderCombo->Text;\r\n }\r\n return TSessionData::ComposePath(Folder, SessionNameEdit->Text);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSaveSessionDialog::DoValidate()\r\n{\r\n TSessionData::ValidateName(SessionNameEdit->Text);\r\n SessionNameValidate(GetSessionName(), FOriginalSessionName);\r\n\r\n UnicodeString Folder = TSessionData::ExtractFolderName(GetSessionName());\r\n if (!Folder.IsEmpty() && StoredSessions->IsWorkspace(Folder))\r\n {\r\n throw Exception(FMTLOAD(WORKSPACE_NOT_FOLDER, (Folder)));\r\n }\r\n\r\n if (SavePasswordCheck->Enabled && SavePasswordCheck->Checked &&\r\n CustomWinConfiguration->UseMasterPassword)\r\n {\r\n CustomWinConfiguration->AskForMasterPasswordIfNotSet();\r\n }\r\n\r\n TCustomDialog::DoValidate();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSaveSessionDialog::DoChange(bool & CanSubmit)\r\n{\r\n CanSubmit = !SessionNameEdit->Text.IsEmpty();\r\n TCustomDialog::DoChange(CanSubmit);\r\n}\r\n//---------------------------------------------------------------------------\r\nTSessionData * __fastcall DoSaveSession(TSessionData * SessionData,\r\n TSessionData * OriginalSession, bool ForceDialog,\r\n TStrings * AdditionalFolders)\r\n{\r\n bool SavePassword = false;\r\n bool * PSavePassword;\r\n bool NotRecommendedSavingPassword =\r\n !CustomWinConfiguration->UseMasterPassword &&\r\n !SameText(SessionData->UserName, AnonymousUserName);\r\n\r\n if (Configuration->DisablePasswordStoring ||\r\n !SessionData->HasAnySessionPassword())\r\n {\r\n PSavePassword = NULL;\r\n }\r\n else\r\n {\r\n PSavePassword = &SavePassword;\r\n SavePassword =\r\n ((OriginalSession != NULL) && OriginalSession->HasAnySessionPassword()) ||\r\n !NotRecommendedSavingPassword;\r\n }\r\n\r\n UnicodeString SessionName = SessionData->SessionName;\r\n\r\n bool Result;\r\n bool CreateShortcut = false;\r\n if (!ForceDialog && ((PSavePassword == NULL) || SavePassword))\r\n {\r\n // This is probably here to ask before session is started saving.\r\n // Otherwise we would ask implicitly, when saving passwords, but at that moment,\r\n // part of the site is already saved and when the user cancel the prompt it's too late.\r\n CustomWinConfiguration->AskForMasterPasswordIfNotSetAndNeededToPersistSessionData(SessionData);\r\n Result = true;\r\n }\r\n else\r\n {\r\n // This can be a standalone dialog when used with save URL (from GetLoginData)\r\n TSaveSessionDialog * Dialog = SafeFormCreate<TSaveSessionDialog>();\r\n try\r\n {\r\n Dialog->Init((PSavePassword != NULL), NotRecommendedSavingPassword, AdditionalFolders);\r\n Result = Dialog->Execute(SessionName, SavePassword, CreateShortcut, SessionData->Name);\r\n }\r\n __finally\r\n {\r\n delete Dialog;\r\n }\r\n }\r\n\r\n TSessionData * NewSession = NULL;\r\n if (Result)\r\n {\r\n if ((PSavePassword != NULL) && !SavePassword)\r\n {\r\n SessionData->ClearSessionPasswords();\r\n }\r\n\r\n NewSession =\r\n StoredSessions->NewSession(SessionName, SessionData);\r\n // modified only, explicit\r\n StoredSessions->Save(false, true);\r\n if (!SessionData->HostKey.IsEmpty())\r\n {\r\n SessionData->CacheHostKeyIfNotCached();\r\n }\r\n\r\n if (CreateShortcut)\r\n {\r\n TOperationVisualizer Visualizer;\r\n UnicodeString AdditionalParams =\r\n TProgramParams::FormatSwitch(DESKTOP_SWITCH) + L\" \" +\r\n TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH);\r\n CreateDesktopSessionShortCut(SessionName, L\"\", AdditionalParams, -1, SITE_ICON);\r\n }\r\n }\r\n\r\n return NewSession;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall SessionNameValidate(const UnicodeString & Text,\r\n const UnicodeString & OriginalName)\r\n{\r\n TSessionData::ValidatePath(Text);\r\n\r\n DebugAssert(StoredSessions);\r\n TSessionData * Data = (TSessionData *)StoredSessions->FindByName(Text);\r\n if (Data && Data->Special)\r\n {\r\n MessageDialog(FMTLOAD(CANNOT_OVERWRITE_SPECIAL_SESSION, (Text)),\r\n qtError, qaOK, HELP_NONE);\r\n Abort();\r\n }\r\n else if ((Data != NULL) && !Data->IsSameName(OriginalName) &&\r\n MessageDialog(MainInstructions(FMTLOAD(CONFIRM_OVERWRITE_SESSION, (Text))),\r\n qtConfirmation, qaYes | qaNo, HELP_SESSION_SAVE_OVERWRITE) != qaYes)\r\n {\r\n Abort();\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\n//---------------------------------------------------------------------------\r\nclass TSaveWorkspaceDialog : public TCustomDialog\r\n{\r\npublic:\r\n __fastcall TSaveWorkspaceDialog(bool CanSavePasswords,\r\n bool NotRecommendedSavingPasswords);\r\n\r\n bool __fastcall Execute(\r\n UnicodeString & WorkspaceName, bool & SavePasswords, bool & CreateShortcut,\r\n bool & EnableAutoSave);\r\n\r\nprotected:\r\n virtual void __fastcall DoValidate();\r\n virtual void __fastcall DoChange(bool & CanSubmit);\r\n\r\nprivate:\r\n TComboBox * WorkspaceNameCombo;\r\n TCheckBox * SavePasswordsCheck;\r\n TCheckBox * CreateShortcutCheck;\r\n TCheckBox * EnableAutoSaveCheck;\r\n};\r\n//---------------------------------------------------------------------------\r\n__fastcall TSaveWorkspaceDialog::TSaveWorkspaceDialog(\r\n bool CanSavePasswords, bool NotRecommendedSavingPasswords) :\r\n TCustomDialog(HELP_WORKSPACE_SAVE)\r\n{\r\n Caption = LoadStr(SAVE_WORKSPACE_CAPTION);\r\n\r\n WorkspaceNameCombo = new TComboBox(this);\r\n WorkspaceNameCombo->AutoComplete = false;\r\n AddComboBox(WorkspaceNameCombo, CreateLabel(LoadStr(SAVE_WORKSPACE_PROMPT)));\r\n WorkspaceNameCombo->DropDownCount = Max(WorkspaceNameCombo->DropDownCount, 16);\r\n\r\n std::unique_ptr<TStrings> Workspaces(StoredSessions->GetWorkspaces());\r\n WorkspaceNameCombo->Items->AddStrings(Workspaces.get());\r\n\r\n SavePasswordsCheck = CreateAndAddCheckBox(\r\n LoadStr(NotRecommendedSavingPasswords ? SAVE_WORKSPACE_PASSWORDS :\r\n (CustomWinConfiguration->UseMasterPassword ?\r\n SAVE_WORKSPACE_PASSWORDS_MASTER : SAVE_WORKSPACE_PASSWORDS_RECOMMENDED)));\r\n\r\n EnableControl(SavePasswordsCheck, CanSavePasswords);\r\n\r\n CreateShortcutCheck = CreateAndAddCheckBox(LoadStr(SAVE_SITE_WORKSPACE_SHORTCUT));\r\n\r\n EnableAutoSaveCheck = CreateAndAddCheckBox(LoadStr(SAVE_WORKSPACE_AUTO));\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TSaveWorkspaceDialog::Execute(\r\n UnicodeString & WorkspaceName, bool & SavePasswords, bool & CreateShortcut,\r\n bool & EnableAutoSave)\r\n{\r\n WorkspaceNameCombo->Text = WorkspaceName;\r\n SavePasswordsCheck->Checked = SavePasswords;\r\n CreateShortcutCheck->Checked = CreateShortcut;\r\n EnableAutoSaveCheck->Checked = EnableAutoSave;\r\n bool Result = TCustomDialog::Execute();\r\n if (Result)\r\n {\r\n WorkspaceName = WorkspaceNameCombo->Text;\r\n SavePasswords = SavePasswordsCheck->Checked;\r\n CreateShortcut = CreateShortcutCheck->Checked;\r\n EnableAutoSave = EnableAutoSaveCheck->Checked;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSaveWorkspaceDialog::DoValidate()\r\n{\r\n TSessionData::ValidateName(WorkspaceNameCombo->Text);\r\n\r\n if (StoredSessions->IsFolder(WorkspaceNameCombo->Text))\r\n {\r\n throw Exception(FMTLOAD(FOLDER_NOT_WORKSPACE, (WorkspaceNameCombo->Text)));\r\n }\r\n\r\n if (SavePasswordsCheck->Enabled && SavePasswordsCheck->Checked &&\r\n CustomWinConfiguration->UseMasterPassword)\r\n {\r\n CustomWinConfiguration->AskForMasterPasswordIfNotSet();\r\n }\r\n\r\n TCustomDialog::DoValidate();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSaveWorkspaceDialog::DoChange(bool & CanSubmit)\r\n{\r\n CanSubmit = !WorkspaceNameCombo->Text.IsEmpty();\r\n\r\n TCustomDialog::DoChange(CanSubmit);\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall DoSaveWorkspaceDialog(UnicodeString & WorkspaceName,\r\n bool * SavePasswords, bool NotRecommendedSavingPasswords,\r\n bool & CreateShortcut, bool & EnableAutoSave)\r\n{\r\n std::unique_ptr<TSaveWorkspaceDialog> Dialog(\r\n new TSaveWorkspaceDialog((SavePasswords != NULL), NotRecommendedSavingPasswords));\r\n\r\n bool Dummy = false;\r\n if (SavePasswords == NULL)\r\n {\r\n SavePasswords = &Dummy;\r\n }\r\n return\r\n Dialog->Execute(\r\n WorkspaceName, *SavePasswords, CreateShortcut, EnableAutoSave);\r\n}\r\n//---------------------------------------------------------------------------\r\n//---------------------------------------------------------------------------\r\nclass TShortCutDialog : public TCustomDialog\r\n{\r\npublic:\r\n __fastcall TShortCutDialog(const TShortCuts & ShortCuts, UnicodeString HelpKeyword);\r\n\r\n bool __fastcall Execute(TShortCut & ShortCut);\r\n\r\nprivate:\r\n TComboBox * ShortCutCombo;\r\n};\r\n//---------------------------------------------------------------------------\r\n__fastcall TShortCutDialog::TShortCutDialog(const TShortCuts & ShortCuts, UnicodeString HelpKeyword) :\r\n TCustomDialog(HelpKeyword)\r\n{\r\n Caption = LoadStr(SHORTCUT_CAPTION);\r\n\r\n ShortCutCombo = new TComboBox(this);\r\n AddShortCutComboBox(ShortCutCombo, CreateLabel(LoadStr(SHORTCUT_LABEL)), ShortCuts);\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TShortCutDialog::Execute(TShortCut & ShortCut)\r\n{\r\n SetShortCutCombo(ShortCutCombo, ShortCut);\r\n bool Result = TCustomDialog::Execute();\r\n if (Result)\r\n {\r\n ShortCut = GetShortCutCombo(ShortCutCombo);\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall DoShortCutDialog(TShortCut & ShortCut,\r\n const TShortCuts & ShortCuts, UnicodeString HelpKeyword)\r\n{\r\n bool Result;\r\n TShortCutDialog * Dialog = new TShortCutDialog(ShortCuts, HelpKeyword);\r\n try\r\n {\r\n Result = Dialog->Execute(ShortCut);\r\n }\r\n __finally\r\n {\r\n delete Dialog;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\n//---------------------------------------------------------------------------\r\nclass TRemoteMoveDialog : public TCustomDialog\r\n{\r\npublic:\r\n __fastcall TRemoteMoveDialog(bool Multi);\r\n\r\n bool __fastcall Execute(UnicodeString & Target, UnicodeString & FileMask);\r\n\r\nprotected:\r\n DYNAMIC void __fastcall DoShow();\r\n virtual void __fastcall DoValidate();\r\n UnicodeString __fastcall GetFileMask();\r\n\r\nprivate:\r\n THistoryComboBox * Combo;\r\n bool FMulti;\r\n};\r\n//---------------------------------------------------------------------------\r\n__fastcall TRemoteMoveDialog::TRemoteMoveDialog(bool Multi) :\r\n TCustomDialog(HELP_REMOTE_MOVE)\r\n{\r\n Caption = LoadStr(REMOTE_MOVE_TITLE);\r\n // The same as TRemoteTransferDialog\r\n ClientWidth = ScaleByTextHeight(this, 420);\r\n\r\n FMulti = Multi;\r\n\r\n AddImage(L\"Move To\");\r\n\r\n Combo = new THistoryComboBox(this);\r\n Combo->AutoComplete = false;\r\n AddComboBox(Combo, CreateLabel(LoadStr(REMOTE_TRANSFER_PROMPT2)));\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TRemoteMoveDialog::Execute(UnicodeString & Target, UnicodeString & FileMask)\r\n{\r\n Combo->Items = CustomWinConfiguration->History[L\"RemoteTarget\"];\r\n Combo->Text = UnixIncludeTrailingBackslash(Target) + FileMask;\r\n bool Result = TCustomDialog::Execute();\r\n if (Result)\r\n {\r\n Target = UnixExtractFilePath(Combo->Text);\r\n FileMask = GetFileMask();\r\n Combo->SaveToHistory();\r\n CustomWinConfiguration->History[L\"RemoteTarget\"] = Combo->Items;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TRemoteMoveDialog::GetFileMask()\r\n{\r\n return UnixExtractFileName(Combo->Text);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TRemoteMoveDialog::DoShow()\r\n{\r\n TCustomDialog::DoShow();\r\n InstallPathWordBreakProc(Combo);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TRemoteMoveDialog::DoValidate()\r\n{\r\n if (!IsFileNameMask(GetFileMask()) && FMulti)\r\n {\r\n UnicodeString Message =\r\n FormatMultiFilesToOneConfirmation(Combo->Text, true);\r\n if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_NONE) == qaCancel)\r\n {\r\n Abort();\r\n }\r\n }\r\n\r\n TCustomDialog::DoValidate();\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall DoRemoteMoveDialog(bool Multi, UnicodeString & Target, UnicodeString & FileMask)\r\n{\r\n std::unique_ptr<TRemoteMoveDialog> Dialog(new TRemoteMoveDialog(Multi));\r\n return Dialog->Execute(Target, FileMask);\r\n}\r\n//---------------------------------------------------------------------------\r\n//---------------------------------------------------------------------------\r\nclass TCustomCommandOptionsDialog : public TCustomDialog\r\n{\r\npublic:\r\n __fastcall TCustomCommandOptionsDialog(\r\n const TCustomCommandType * Command, TStrings * CustomCommandOptions, unsigned int Flags,\r\n TCustomCommand * CustomCommandForOptions, const UnicodeString & Site, const TShortCuts * ShortCuts);\r\n\r\n bool __fastcall Execute(TShortCut * ShortCut);\r\n\r\nprotected:\r\n virtual void __fastcall DoHelp();\r\n DYNAMIC void __fastcall DoShow();\r\n\r\nprivate:\r\n const TCustomCommandType * FCommand;\r\n TStrings * FCustomCommandOptions;\r\n std::vector<TControl *> FControls;\r\n std::vector<std::vector<UnicodeString> > FValues;\r\n unsigned int FFlags;\r\n UnicodeString FSite;\r\n TComboBox * FShortCutCombo;\r\n\r\n UnicodeString __fastcall HistoryKey(const TCustomCommandType::TOption & Option);\r\n THistoryComboBox * __fastcall CreateHistoryComboBox(const TCustomCommandType::TOption & Option, const UnicodeString & Value);\r\n void __fastcall BrowseButtonClick(TObject * Sender);\r\n void __fastcall LinkLabelClick(TObject * Sender);\r\n UnicodeString __fastcall SaveHistoryComboBoxValue(TControl * Control, const TCustomCommandType::TOption & Option);\r\n void __fastcall AddOptionComboBox(\r\n TComboBox * ComboBox, const UnicodeString & Value, const TCustomCommandType::TOption & Option,\r\n std::vector<UnicodeString> & Values);\r\n UnicodeString __fastcall GetComboBoxValue(TControl * Control, const UnicodeString & Default);\r\n int __fastcall GetOptionIndex(TControl * Control);\r\n int __fastcall GetControlIndex(TControl * Control);\r\n};\r\n//---------------------------------------------------------------------------\r\n__fastcall TCustomCommandOptionsDialog::TCustomCommandOptionsDialog(\r\n const TCustomCommandType * Command, TStrings * CustomCommandOptions,\r\n unsigned int Flags, TCustomCommand * CustomCommandForOptions,\r\n const UnicodeString & Site, const TShortCuts * ShortCuts) :\r\n TCustomDialog(HELP_EXTENSION_OPTIONS)\r\n{\r\n FCommand = Command;\r\n FFlags = Flags;\r\n FCustomCommandOptions = CustomCommandOptions;\r\n FSite = Site;\r\n Caption = StripEllipsis(StripHotkey(FCommand->Name));\r\n Width = ScaleByTextHeight(this, 400);\r\n\r\n bool HasGroups = false;\r\n int ControlIndex = 0;\r\n for (int OptionIndex = 0; OptionIndex < FCommand->OptionsCount; OptionIndex++)\r\n {\r\n const TCustomCommandType::TOption & Option = FCommand->GetOption(OptionIndex);\r\n\r\n if ((Option.Flags & FFlags) != 0)\r\n {\r\n UnicodeString OptionKey = FCommand->GetOptionKey(Option, FSite);\r\n UnicodeString Value;\r\n if ((CustomCommandForOptions != NULL) &&\r\n Option.HasPatterns(CustomCommandForOptions))\r\n {\r\n Value = CustomCommandForOptions->Complete(Option.Default, true);\r\n }\r\n else\r\n {\r\n if (FCustomCommandOptions->IndexOfName(OptionKey) >= 0)\r\n {\r\n Value = FCustomCommandOptions->Values[OptionKey];\r\n }\r\n else\r\n {\r\n Value = Option.Default;\r\n }\r\n }\r\n\r\n int Tag = (OptionIndex << 16) + ControlIndex;\r\n TControl * Control = NULL;\r\n std::vector<UnicodeString> Values;\r\n if (Option.Kind == TCustomCommandType::okUnknown)\r\n {\r\n Control = NULL;\r\n }\r\n else if (Option.Kind == TCustomCommandType::okLabel)\r\n {\r\n TLabel * Label = CreateLabel(Option.Caption);\r\n AddText(Label);\r\n Control = Label;\r\n }\r\n else if (Option.Kind == TCustomCommandType::okLink)\r\n {\r\n TStaticText * Label = new TStaticText(this);\r\n Label->Caption = Option.Caption;\r\n if (IsHttpOrHttpsUrl(Label->Caption))\r\n {\r\n Label->Caption = SecureUrl(Label->Caption);\r\n LinkLabel(Label);\r\n Label->TabStop = true;\r\n }\r\n else if (!Option.Default.IsEmpty() && IsHttpOrHttpsUrl(Option.Default))\r\n {\r\n Label->OnClick = LinkLabelClick;\r\n LinkLabel(Label);\r\n Label->TabStop = true;\r\n }\r\n else\r\n {\r\n // keep it plain text, as we have no URL\r\n }\r\n AddText(Label);\r\n Control = Label;\r\n }\r\n else if (Option.Kind == TCustomCommandType::okGroup)\r\n {\r\n StartGroup(Option.Caption);\r\n HasGroups = true;\r\n }\r\n else if (Option.Kind == TCustomCommandType::okSeparator)\r\n {\r\n AddSeparator();\r\n }\r\n else if (Option.Kind == TCustomCommandType::okTextBox)\r\n {\r\n Control = CreateHistoryComboBox(Option, Value);\r\n }\r\n else if (Option.Kind == TCustomCommandType::okFile)\r\n {\r\n THistoryComboBox * ComboBox = CreateHistoryComboBox(Option, Value);\r\n TButton * Button = new TButton(this);\r\n Button->Parent = GetDefaultParent();\r\n Button->Width = HelpButton->Width;\r\n Button->Left = GetDefaultParent()->ClientWidth - Button->Width - HorizontalMargin;\r\n ComboBox->Width = Button->Left - ComboBox->Left - ScaleByTextHeight(this, 6);\r\n Button->Top = ComboBox->Top - ScaleByTextHeight(this, 2);\r\n Button->Tag = Tag;\r\n Button->Caption = LoadStr(EXTENSION_OPTIONS_BROWSE);\r\n Button->OnClick = BrowseButtonClick;\r\n ScaleButtonControl(Button);\r\n AddWinControl(Button);\r\n Control = ComboBox;\r\n }\r\n else if (Option.Kind == TCustomCommandType::okDropDownList)\r\n {\r\n TComboBox * ComboBox = new TComboBox(this);\r\n ComboBox->Style = csDropDownList;\r\n\r\n AddOptionComboBox(ComboBox, Value, Option, Values);\r\n\r\n Control = ComboBox;\r\n }\r\n else if (Option.Kind == TCustomCommandType::okComboBox)\r\n {\r\n TComboBox * ComboBox = new TComboBox(this);\r\n ComboBox->Style = csDropDown;\r\n\r\n AddOptionComboBox(ComboBox, Value, Option, Values);\r\n if (ComboBox->ItemIndex < 0)\r\n {\r\n ComboBox->Text = Value;\r\n }\r\n\r\n Control = ComboBox;\r\n }\r\n else if (Option.Kind == TCustomCommandType::okCheckBox)\r\n {\r\n TCheckBox * CheckBox = CreateAndAddCheckBox(Option.Caption);\r\n\r\n CheckBox->Checked =\r\n (Option.Params.size() >= 1) &&\r\n (Value == Option.Params[0]);\r\n\r\n Control = CheckBox;\r\n }\r\n else\r\n {\r\n DebugFail();\r\n }\r\n\r\n if (Control != NULL)\r\n {\r\n Control->Tag = Tag;\r\n }\r\n FControls.push_back(Control);\r\n FValues.push_back(Values);\r\n ControlIndex++;\r\n DebugAssert(static_cast<int>(FControls.size()) == ControlIndex);\r\n }\r\n }\r\n\r\n if (ShortCuts != NULL)\r\n {\r\n if (HasGroups)\r\n {\r\n StartGroup(LoadStr(EXTENSION_GENERAL_GROUP));\r\n }\r\n else if (ControlIndex > 0)\r\n {\r\n AddSeparator();\r\n }\r\n FShortCutCombo = new TComboBox(this);\r\n AddShortCutComboBox(FShortCutCombo, CreateLabel(LoadStr(EXTENSION_SHORTCUT)), *ShortCuts);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomCommandOptionsDialog::AddOptionComboBox(\r\n TComboBox * ComboBox, const UnicodeString & Value, const TCustomCommandType::TOption & Option, std::vector<UnicodeString> & Values)\r\n{\r\n std::unique_ptr<TStringList> Items(new TStringList());\r\n int ItemIndex = -1;\r\n\r\n TCustomCommandType::TOption::TParams::const_iterator ParamI = Option.Params.begin();\r\n while (ParamI != Option.Params.end())\r\n {\r\n UnicodeString Item = (*ParamI);\r\n int P = Item.Pos(L\"=\");\r\n UnicodeString ParamValue;\r\n if (P > 0)\r\n {\r\n ParamValue = Item.SubString(1, P - 1);\r\n Item.Delete(1, P);\r\n }\r\n else\r\n {\r\n ParamValue = Item;\r\n }\r\n Item = WinConfiguration->ExtensionStringTranslation(FCommand->Id, Item);\r\n Items->Add(Item);\r\n if (Value == ParamValue)\r\n {\r\n ItemIndex = Items->Count - 1;\r\n }\r\n Values.push_back(ParamValue);\r\n ParamI++;\r\n }\r\n\r\n AddComboBox(ComboBox, CreateLabel(Option.Caption), Items.get(), true);\r\n\r\n ComboBox->ItemIndex = ItemIndex;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall TCustomCommandOptionsDialog::GetOptionIndex(TControl * Control)\r\n{\r\n return (Control->Tag >> 16);\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall TCustomCommandOptionsDialog::GetControlIndex(TControl * Control)\r\n{\r\n return (Control->Tag & 0xFFFF);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomCommandOptionsDialog::LinkLabelClick(TObject * Sender)\r\n{\r\n TStaticText * Label = DebugNotNull(dynamic_cast<TStaticText *>(Sender));\r\n const TCustomCommandType::TOption & Option = FCommand->GetOption(GetOptionIndex(Label));\r\n OpenBrowser(SecureUrl(Option.Default));\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomCommandOptionsDialog::BrowseButtonClick(TObject * Sender)\r\n{\r\n TButton * Button = DebugNotNull(dynamic_cast<TButton *>(Sender));\r\n int OptionIndex = GetOptionIndex(Button);\r\n const TCustomCommandType::TOption & Option = FCommand->GetOption(OptionIndex);\r\n int ControlIndex = GetControlIndex(Button);\r\n THistoryComboBox * ComboBox = dynamic_cast<THistoryComboBox *>(FControls[ControlIndex]);\r\n\r\n std::unique_ptr<TOpenDialog> OpenDialog(new TOpenDialog(Application));\r\n\r\n UnicodeString Title;\r\n if (!Option.FileCaption.IsEmpty())\r\n {\r\n Title = Option.FileCaption;\r\n }\r\n else\r\n {\r\n UnicodeString Caption = Option.Caption;\r\n Caption = StripHotkey(Caption);\r\n if (!Caption.IsEmpty() && (Caption[Caption.Length()] == L':'))\r\n {\r\n Caption.SetLength(Caption.Length() - 1);\r\n }\r\n Title = FMTLOAD(EXTENSION_OPTIONS_BROWSE_TITLE, (Caption));\r\n }\r\n OpenDialog->Title = Title;\r\n\r\n UnicodeString Value;\r\n if (ComboBox->Text.IsEmpty())\r\n {\r\n Value = Option.FileInitial;\r\n }\r\n else\r\n {\r\n Value = ComboBox->Text;\r\n }\r\n UnicodeString ExpandedValue = ExpandEnvironmentVariables(Value);\r\n OpenDialog->FileName = ExpandedValue;\r\n UnicodeString InitialDir = ExtractFilePath(ExpandedValue);\r\n if (!InitialDir.IsEmpty())\r\n {\r\n OpenDialog->InitialDir = InitialDir;\r\n }\r\n OpenDialog->Filter = Option.FileFilter;\r\n OpenDialog->DefaultExt = Option.FileExt;\r\n\r\n if (OpenDialog->Execute())\r\n {\r\n if (OpenDialog->FileName != ExpandedValue)\r\n {\r\n ComboBox->Text = OpenDialog->FileName;\r\n }\r\n // If user just confirms the initial value, persist it\r\n else if (ComboBox->Text.IsEmpty())\r\n {\r\n DebugAssert(Option.FileInitial == Value);\r\n ComboBox->Text = Value;\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nTHistoryComboBox * __fastcall TCustomCommandOptionsDialog::CreateHistoryComboBox(\r\n const TCustomCommandType::TOption & Option, const UnicodeString & Value)\r\n{\r\n THistoryComboBox * ComboBox = new THistoryComboBox(this);\r\n ComboBox->AutoComplete = false;\r\n AddComboBox(ComboBox, CreateLabel(Option.Caption));\r\n ComboBox->Items = CustomWinConfiguration->History[HistoryKey(Option)];\r\n ComboBox->Text = Value;\r\n return ComboBox;\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TCustomCommandOptionsDialog::HistoryKey(const TCustomCommandType::TOption & Option)\r\n{\r\n UnicodeString Result = FCommand->GetOptionKey(Option, FSite);\r\n Result = CustomWinConfiguration->GetValidHistoryKey(Result);\r\n return L\"CustomCommandOption_\" + Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TCustomCommandOptionsDialog::Execute(TShortCut * ShortCut)\r\n{\r\n if (ShortCut != NULL)\r\n {\r\n SetShortCutCombo(FShortCutCombo, *ShortCut);\r\n }\r\n\r\n bool Result = TCustomDialog::Execute();\r\n\r\n if (Result)\r\n {\r\n int ControlIndex = 0;\r\n for (int OptionIndex = 0; OptionIndex < FCommand->OptionsCount; OptionIndex++)\r\n {\r\n const TCustomCommandType::TOption & Option = FCommand->GetOption(OptionIndex);\r\n if ((Option.Flags & FFlags) != 0)\r\n {\r\n if ((Option.Kind != TCustomCommandType::okUnknown) &&\r\n Option.IsControl)\r\n {\r\n UnicodeString OptionKey = FCommand->GetOptionKey(Option, FSite);\r\n\r\n TControl * Control = FControls[ControlIndex];\r\n\r\n UnicodeString Value;\r\n if (Option.Kind == TCustomCommandType::okTextBox)\r\n {\r\n Value = SaveHistoryComboBoxValue(Control, Option);\r\n }\r\n else if (Option.Kind == TCustomCommandType::okFile)\r\n {\r\n Value = SaveHistoryComboBoxValue(Control, Option);\r\n }\r\n else if (Option.Kind == TCustomCommandType::okDropDownList)\r\n {\r\n Value = GetComboBoxValue(Control, Option.Default);\r\n }\r\n else if (Option.Kind == TCustomCommandType::okComboBox)\r\n {\r\n TComboBox * ComboBox = DebugNotNull(dynamic_cast<TComboBox *>(Control));\r\n Value = GetComboBoxValue(Control, ComboBox->Text);\r\n }\r\n else if (Option.Kind == TCustomCommandType::okCheckBox)\r\n {\r\n TCheckBox * CheckBox = DebugNotNull(dynamic_cast<TCheckBox *>(Control));\r\n int Index = (CheckBox->Checked ? 0 : 1);\r\n Value = (Index < static_cast<int>(Option.Params.size())) ? Option.Params[Index] : UnicodeString();\r\n }\r\n else\r\n {\r\n DebugFail();\r\n }\r\n\r\n // The default value setter deletes the \"name\" when the value is empty.\r\n // It would cause us to fall back to the default value, but we want to remember the empty value.\r\n SetStringValueEvenIfEmpty(FCustomCommandOptions, OptionKey, Value);\r\n }\r\n\r\n ControlIndex++;\r\n }\r\n }\r\n\r\n if (ShortCut != NULL)\r\n {\r\n *ShortCut = GetShortCutCombo(FShortCutCombo);\r\n }\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TCustomCommandOptionsDialog::GetComboBoxValue(\r\n TControl * Control, const UnicodeString & Default)\r\n{\r\n TComboBox * ComboBox = DebugNotNull(dynamic_cast<TComboBox *>(Control));\r\n UnicodeString Result;\r\n if (ComboBox->ItemIndex < 0)\r\n {\r\n Result = Default;\r\n }\r\n else\r\n {\r\n Result = FValues[GetControlIndex(Control)][ComboBox->ItemIndex];\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TCustomCommandOptionsDialog::SaveHistoryComboBoxValue(\r\n TControl * Control, const TCustomCommandType::TOption & Option)\r\n{\r\n THistoryComboBox * ComboBox = DebugNotNull(dynamic_cast<THistoryComboBox *>(Control));\r\n ComboBox->SaveToHistory();\r\n CustomWinConfiguration->History[HistoryKey(Option)] = ComboBox->Items;\r\n return ComboBox->Text;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomCommandOptionsDialog::DoHelp()\r\n{\r\n UnicodeString HelpPage;\r\n if (!FCommand->OptionsPage.IsEmpty())\r\n {\r\n HelpPage = FCommand->OptionsPage;\r\n }\r\n else\r\n {\r\n HelpPage = FCommand->HomePage;\r\n }\r\n\r\n if (!HelpPage.IsEmpty())\r\n {\r\n OpenBrowser(HelpPage);\r\n }\r\n else\r\n {\r\n TCustomDialog::DoHelp();\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TCustomCommandOptionsDialog::DoShow()\r\n{\r\n TCustomDialog::DoShow();\r\n\r\n int ControlIndex = 0;\r\n for (int OptionIndex = 0; OptionIndex < FCommand->OptionsCount; OptionIndex++)\r\n {\r\n const TCustomCommandType::TOption & Option = FCommand->GetOption(OptionIndex);\r\n\r\n if ((Option.Flags & FFlags) != 0)\r\n {\r\n if (Option.Kind == TCustomCommandType::okFile)\r\n {\r\n TControl * Control = FControls[ControlIndex];\r\n InstallPathWordBreakProc(DebugNotNull(dynamic_cast<TWinControl *>(Control)));\r\n }\r\n ControlIndex++;\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall DoCustomCommandOptionsDialog(\r\n const TCustomCommandType * Command, TStrings * CustomCommandOptions, TShortCut * ShortCut,\r\n unsigned int Flags, TCustomCommand * CustomCommandForOptions,\r\n const UnicodeString & Site, const TShortCuts * ShortCuts)\r\n{\r\n std::unique_ptr<TCustomCommandOptionsDialog> Dialog(\r\n new TCustomCommandOptionsDialog(Command, CustomCommandOptions, Flags, CustomCommandForOptions, Site, ShortCuts));\r\n return Dialog->Execute(ShortCut);\r\n}\r\n//---------------------------------------------------------------------------\r\n//---------------------------------------------------------------------------\r\nclass TUsageStatisticsDialog : public TCustomDialog\r\n{\r\npublic:\r\n __fastcall TUsageStatisticsDialog();\r\n\r\nprotected:\r\n virtual void __fastcall DoChange(bool & CanSubmit);\r\n\r\nprivate:\r\n TEdit * FilterEdit;\r\n TMemo * UsageMemo;\r\n TButton * ClipboardButton;\r\n\r\n void __fastcall ClipboardButtonClick(TObject * Sender);\r\n};\r\n//---------------------------------------------------------------------------\r\n__fastcall TUsageStatisticsDialog::TUsageStatisticsDialog() :\r\n TCustomDialog(HELP_USAGE)\r\n{\r\n Caption = LoadStr(USAGE_CAPTION);\r\n Width = ScaleByTextHeight(this, 400);\r\n\r\n TLabel * Label = new TLabel(this);\r\n // UnformatMessage is called, because previously, ** markup was used and translations may still contain that\r\n Label->Caption = UnformatMessage(LoadStr(USAGE_DATA2));\r\n AddText(Label);\r\n\r\n FilterEdit = new TEdit(this);\r\n FilterEdit->Width = ScaleByTextHeight(this, 250);\r\n TLabel * FilterLabel = new TLabel(this);\r\n FilterLabel->Caption = LoadStr(USAGE_FILTER);\r\n AddEdit(FilterEdit, FilterLabel, true);\r\n\r\n UsageMemo = new TMemo(this);\r\n UsageMemo->Height = ScaleByTextHeight(this, 300);\r\n UsageMemo->ScrollBars = ssVertical;\r\n AddEdit(UsageMemo, NULL);\r\n ReadOnlyControl(UsageMemo);\r\n\r\n ClipboardButton = new TButton(this);\r\n ClipboardButton->Caption = LoadStr(USAGE_COPY);\r\n ClipboardButton->Width = ScaleByTextHeight(this, 121);\r\n ClipboardButton->OnClick = ClipboardButtonClick;\r\n AddDialogButton(ClipboardButton);\r\n\r\n RemoveCancelButton();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TUsageStatisticsDialog::ClipboardButtonClick(TObject * /*Sender*/)\r\n{\r\n TInstantOperationVisualizer Visualizer;\r\n CopyToClipboard(UsageMemo->Lines);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TUsageStatisticsDialog::DoChange(bool & CanSubmit)\r\n{\r\n TCustomDialog::DoChange(CanSubmit);\r\n UnicodeString Text = Configuration->Usage->Serialize(L\"\\n\", FilterEdit->Text);\r\n bool NoUsage = Text.IsEmpty();\r\n ClipboardButton->Enabled = !NoUsage;\r\n if (NoUsage)\r\n {\r\n Text = LoadStr(USAGE_DATA_NONE2);\r\n }\r\n UsageMemo->Lines->Text = Text;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall DoUsageStatisticsDialog()\r\n{\r\n std::unique_ptr<TUsageStatisticsDialog> Dialog(new TUsageStatisticsDialog());\r\n Dialog->Execute();\r\n}\r\n//---------------------------------------------------------------------------\r\n//---------------------------------------------------------------------------\r\nclass TSiteRawDialog : public TCustomDialog\r\n{\r\npublic:\r\n __fastcall TSiteRawDialog();\r\n\r\n bool __fastcall Execute(TSessionData * Data);\r\n\r\nprotected:\r\n DYNAMIC void __fastcall DoShow();\r\n\r\nprivate:\r\n TMemo * SettingsMemo;\r\n\r\n void __fastcall AddButtonClick(TObject * Sender);\r\n void __fastcall SettingsMemoKeyDown(TObject * Sender, WORD & Key, TShiftState Shift);\r\n\r\n void DeleteNames(TStrings * Names, TStrings * Options);\r\n};\r\n//---------------------------------------------------------------------------\r\n__fastcall TSiteRawDialog::TSiteRawDialog() :\r\n TCustomDialog(HELP_SITE_RAW)\r\n{\r\n Caption = LoadStr(SITE_RAW_CAPTION);\r\n Width = ScaleByTextHeight(this, 400);\r\n\r\n SettingsMemo = new TMemo(this);\r\n SettingsMemo->Height = ScaleByTextHeight(this, 300);\r\n SettingsMemo->OnKeyDown = SettingsMemoKeyDown;\r\n AddEdit(SettingsMemo, NULL);\r\n\r\n TButton * AddButton = new TButton(this);\r\n AddButton->Caption = LoadStr(SITE_RAW_ADD);\r\n AddButton->Width = OKButton->Width;\r\n AddButton->OnClick = AddButtonClick;\r\n AddDialogButton(AddButton);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSiteRawDialog::DoShow()\r\n{\r\n TCustomDialog::DoShow();\r\n InstallPathWordBreakProc(SettingsMemo);\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TSiteRawDialog::Execute(TSessionData * Data)\r\n{\r\n std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L\"\"));\r\n std::unique_ptr<TSessionData> RawData(new TSessionData(L\"\"));\r\n RawData->Assign(Data);\r\n // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that\r\n if (RawData->FSProtocol != fsSFTPonly)\r\n {\r\n RawData->FSProtocol = FactoryDefaults->FSProtocol;\r\n }\r\n RawData->HostName = FactoryDefaults->HostName;\r\n RawData->PortNumber = FactoryDefaults->PortNumber;\r\n RawData->UserName = FactoryDefaults->UserName;\r\n RawData->Password = FactoryDefaults->Password;\r\n RawData->Ftps = FactoryDefaults->Ftps;\r\n\r\n std::unique_ptr<TStrings> Options(RawData->SaveToOptions(FactoryDefaults.get(), false, false));\r\n\r\n SettingsMemo->Lines = Options.get();\r\n\r\n bool Result = TCustomDialog::Execute();\r\n if (Result)\r\n {\r\n std::unique_ptr<TSessionData> BackupData(new TSessionData(L\"\"));\r\n BackupData->Assign(Data);\r\n Data->DefaultSettings();\r\n\r\n Data->FSProtocol = BackupData->FSProtocol;\r\n Data->HostName = BackupData->HostName;\r\n Data->PortNumber = BackupData->PortNumber;\r\n Data->UserName = BackupData->UserName;\r\n Data->Password = BackupData->Password;\r\n Data->Ftps = BackupData->Ftps;\r\n\r", " Data->ApplyRawSettings(SettingsMemo->Lines, false);\r", " }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSiteRawDialog::SettingsMemoKeyDown(TObject * Sender, WORD & Key, TShiftState Shift)\r\n{\r\n MemoKeyDown(Sender, Key, Shift);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TSiteRawDialog::AddButtonClick(TObject *)\r\n{\r\n std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L\"\"));\r\n std::unique_ptr<TSessionData> BasicData(new TSessionData(L\"\"));\r\n BasicData->FSProtocol = TFSProtocol(FactoryDefaults->FSProtocol + 1);\r\n UnicodeString RandomAppendix(L\"_\");\r\n BasicData->HostName = FactoryDefaults->HostName + RandomAppendix;\r\n BasicData->Ftps = TFtps(FactoryDefaults->Ftps + 1);\r\n BasicData->PortNumber = DefaultPort(BasicData->FSProtocol, BasicData->Ftps) + 1;\r\n BasicData->UserName = FactoryDefaults->UserName + RandomAppendix;\r\n BasicData->Password = FactoryDefaults->Password + RandomAppendix;\r\n\r\n std::unique_ptr<TStrings> BasicOptions(BasicData->SaveToOptions(FactoryDefaults.get(), false, false));\r\n\r\n std::unique_ptr<TStrings> AllOptions(TSessionData::GetAllOptionNames(false));\r\n\r\n std::unique_ptr<TStrings> Names(CreateSortedStringList());\r\n for (int Index = 0; Index < AllOptions->Count; Index++)\r\n {\r\n Names->Add(AllOptions->Names[Index]);\r\n }\r\n DeleteNames(Names.get(), BasicOptions.get());\r\n DeleteNames(Names.get(), SettingsMemo->Lines);\r\n\r\n std::unique_ptr<TCustomDialog> AddDialog(new TCustomDialog(HelpKeyword));\r\n AddDialog->Caption = LoadStr(SITE_RAW_ADD_CAPTION);\r\n TComboBox * AddComboBox = new TComboBox(AddDialog.get());\r\n AddComboBox->Style = csDropDownList;\r\n AddComboBox->DropDownCount = Max(AddComboBox->DropDownCount, 16);\r\n AddDialog->AddComboBox(AddComboBox, CreateLabel(LoadStr(SITE_RAW_ADD_LABEL)), Names.get(), true);\r\n AddComboBox->ItemIndex = 0;\r\n if (AddDialog->Execute())\r\n {\r\n UnicodeString Name = AddComboBox->Items->Strings[AddComboBox->ItemIndex];\r\n UnicodeString Value = AllOptions->Values[Name];\r\n UnicodeString NameAndSeparator = Name + SettingsMemo->Lines->NameValueSeparator;\r\n int Start = (SettingsMemo->Lines->Text + NameAndSeparator).Length();\r\n SettingsMemo->Lines->Add(NameAndSeparator + Value);\r\n SettingsMemo->SetFocus();\r\n SettingsMemo->SelStart = Start;\r\n SettingsMemo->SelLength = Value.Length();\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid TSiteRawDialog::DeleteNames(TStrings * Names, TStrings * Options)\r\n{\r\n for (int Index = 0; Index < Options->Count; Index++)\r\n {\r\n UnicodeString Name = Options->Names[Index];\r\n if (!Name.IsEmpty())\r\n {\r\n int I = Names->IndexOf(Name);\r\n if (I >= 0)\r\n {\r\n Names->Delete(I);\r\n }\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall DoSiteRawDialog(TSessionData * Data)\r\n{\r\n std::unique_ptr<TSiteRawDialog> Dialog(new TSiteRawDialog());\r\n Dialog->Execute(Data);\r\n}" ]
[ 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 53, 80, 2275, 473, 1511, 2372, 1100], "buggy_code_start_loc": [46, 52, 79, 599, 57, 1510, 2371, 1099], "filenames": ["source/Console.cbproj", "source/DragExt.cbproj", "source/WinSCP.cbproj", "source/core/SessionData.cpp", "source/core/SessionData.h", "source/forms/Custom.cpp", "source/windows/ConsoleRunner.cpp", "source/windows/WinMain.cpp"], "fixing_code_end_loc": [47, 53, 80, 2294, 474, 1511, 2372, 1103], "fixing_code_start_loc": [46, 52, 79, 599, 58, 1510, 2371, 1099], "message": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:winscp:winscp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C081564B-8EF8-4C8A-9EB0-1C50D5A8F18B", "versionEndExcluding": "5.17.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)"}, {"lang": "es", "value": "WinSCP anterior a la versi\u00f3n 5.17.10 permite a los atacantes remotos ejecutar programas arbitrarios cuando el manejador de URLs encuentra una URL manipulada que carga la configuraci\u00f3n de la sesi\u00f3n. (Por ejemplo, esto es explotable en una instalaci\u00f3n por defecto en la que WinSCP es el manejador de URLs sftp://)"}], "evaluatorComment": null, "id": "CVE-2021-3331", "lastModified": "2021-02-04T15:59:24.960", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-01-27T21:15:16.840", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://winscp.net/eng/docs/history#5.17.10"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://winscp.net/eng/docs/rawsettings"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://winscp.net/tracker/1943"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, "type": "NVD-CWE-Other"}
177
Determine whether the {function_name} code is vulnerable or not.
[ "//---------------------------------------------------------------------------\r\n#include <vcl.h>\r\n#pragma hdrstop\r\n\r\n#include <Common.h>\r\n#include <Exceptions.h>\r\n#include <Script.h>\r\n#include <CoreMain.h>\r\n#include <Terminal.h>\r\n#include <PuttyTools.h>\r\n#include <Queue.h>\r\n#include <HierarchicalStorage.h>\r\n#include <Tools.h>\r\n\r\n#include <Consts.hpp>\r\n#include <StrUtils.hpp>\r\n\r\n#include \"Console.h\"\r\n#include \"WinInterface.h\"\r\n#include \"ProgParams.h\"\r\n#include \"TextsWin.h\"\r\n#include \"TextsCore.h\"\r\n#include \"WinConfiguration.h\"\r\n#include \"SynchronizeController.h\"\r\n#include \"GUITools.h\"\r\n#include \"VCLCommon.h\"\r\n#include \"Setup.h\"\r\n//---------------------------------------------------------------------------\r\n#define WM_INTERUPT_IDLE (WM_WINSCP_USER + 3)\r\n#define BATCH_INPUT_TIMEOUT 10000\r\n//---------------------------------------------------------------------------\r\n#pragma package(smart_init)\r\n//---------------------------------------------------------------------------\r\nvoid TrimNewLine(UnicodeString & Str)\r\n{\r\n while (!Str.IsEmpty() &&\r\n ((Str[Str.Length()] == L'\\n') || (Str[Str.Length()] == L'\\r')))\r\n {\r\n Str.SetLength(Str.Length() - 1);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsole::PrintLine(const UnicodeString & Str, bool Error)\r\n{\r\n Print(Str + L\"\\n\", false, Error);\r\n};\r\n//---------------------------------------------------------------------------\r\nclass TOwnConsole : public TConsole\r\n{\r\npublic:\r\n static TOwnConsole * __fastcall Instance();\r\n\r\n virtual void __fastcall Print(UnicodeString Str, bool FromBeginning = false, bool Error = false);\r\n virtual bool __fastcall Input(UnicodeString & Str, bool Echo, unsigned int Timer);\r\n virtual int __fastcall Choice(\r\n UnicodeString Options, int Cancel, int Break, int Continue, int Timeouted, bool Timeouting, unsigned int Timer,\r\n UnicodeString Message);\r\n virtual bool __fastcall PendingAbort();\r\n virtual void __fastcall SetTitle(UnicodeString Title);\r\n virtual bool __fastcall LimitedOutput();\r\n virtual bool __fastcall LiveOutput();\r\n virtual bool __fastcall NoInteractiveInput();\r\n virtual bool __fastcall Interactive();\r\n virtual void __fastcall WaitBeforeExit();\r\n virtual bool __fastcall CommandLineOnly();\r\n virtual bool __fastcall WantsProgress();\r\n virtual void __fastcall Progress(TScriptProgress & Progress);\r\n virtual UnicodeString __fastcall FinalLogMessage();\r\n\r\nprotected:\r\n static TOwnConsole * FInstance;\r\n friend class TConsoleInputThread;\r\n\r\n __fastcall TOwnConsole();\r\n virtual __fastcall ~TOwnConsole();\r\n\r\n void __fastcall BreakInput();\r\n void __fastcall CancelInput();\r\n static BOOL WINAPI HandlerRoutine(DWORD CtrlType);\r\n void __fastcall WindowStateTimer(TObject * Sender);\r\n void __fastcall ProcessMessages();\r\n void __fastcall TrayIconClick(TObject * Sender);\r\n\r\nprivate:\r\n HANDLE FInput;\r\n HANDLE FOutput;\r\n HWND FConsoleWindow;\r\n TTimer * FWindowStateTimer;\r\n bool FMinimized;\r\n ::TTrayIcon * FTrayIcon;\r\n static std::unique_ptr<TCriticalSection> FSection;\r\n\r\n bool FPendingAbort;\r\n};\r\n//---------------------------------------------------------------------------\r\nTOwnConsole * TOwnConsole::FInstance = NULL;\r\nstd::unique_ptr<TCriticalSection> TOwnConsole::FSection(TraceInitPtr(new TCriticalSection()));\r\n//---------------------------------------------------------------------------\r\n__fastcall TOwnConsole::TOwnConsole()\r\n{\r\n DebugAssert(FInstance == NULL);\r\n FInstance = this;\r\n\r\n AllocConsole();\r\n SetConsoleCtrlHandler(HandlerRoutine, true);\r\n\r\n FInput = GetStdHandle(STD_INPUT_HANDLE);\r\n FOutput = GetStdHandle(STD_OUTPUT_HANDLE);\r\n FPendingAbort = false;\r\n FConsoleWindow = NULL;\r\n FWindowStateTimer = NULL;\r\n FMinimized = false;\r\n FTrayIcon = new ::TTrayIcon(0);\r\n FTrayIcon->OnClick = TrayIconClick;\r\n\r\n if (WinConfiguration->MinimizeToTray)\r\n {\r\n FConsoleWindow = GetConsoleWindow();\r\n if (DebugAlwaysTrue(FConsoleWindow != NULL))\r\n {\r\n FWindowStateTimer = new TTimer(Application);\r\n FWindowStateTimer->OnTimer = WindowStateTimer;\r\n FWindowStateTimer->Interval = 250;\r\n FWindowStateTimer->Enabled = true;\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\n__fastcall TOwnConsole::~TOwnConsole()\r\n{\r\n TGuard Guard(FSection.get());\r\n\r\n delete FTrayIcon;\r\n delete FWindowStateTimer;\r\n\r\n // deliberately do not remove ConsoleCtrlHandler as it causes\r\n // failures while exiting\r\n\r\n FreeConsole();\r\n\r\n DebugAssert(FInstance == this);\r\n FInstance = NULL;\r\n}\r\n//---------------------------------------------------------------------------\r\nTOwnConsole * __fastcall TOwnConsole::Instance()\r\n{\r\n return new TOwnConsole();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::WindowStateTimer(TObject * /*Sender*/)\r\n{\r\n DebugAssert(FConsoleWindow != NULL);\r\n WINDOWPLACEMENT Placement;\r\n memset(&Placement, 0, sizeof(Placement));\r\n Placement.length = sizeof(Placement);\r\n if (GetWindowPlacement(FConsoleWindow, &Placement))\r\n {\r\n bool Minimized = (Placement.showCmd == SW_SHOWMINIMIZED);\r\n if (FMinimized != Minimized)\r\n {\r\n FMinimized = Minimized;\r\n\r\n if (FMinimized && WinConfiguration->MinimizeToTray)\r\n {\r\n FTrayIcon->Visible = true;\r\n ShowWindow(FConsoleWindow, SW_HIDE);\r\n }\r\n else\r\n {\r\n FTrayIcon->Visible = false;\r\n ShowWindow(FConsoleWindow, SW_SHOW);\r\n }\r\n }\r\n }\r\n else\r\n {\r\n DebugFail();\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::ProcessMessages()\r\n{\r\n // as of now, there's no point doing this unless we have icon tray\r\n // (i.e. we need to monitor window state and eventually process tray icon messages)\r\n if (FWindowStateTimer != NULL)\r\n {\r\n DebugAssert(WinConfiguration->MinimizeToTray);\r\n\r\n Application->ProcessMessages();\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::TrayIconClick(TObject * /*Sender*/)\r\n{\r\n DebugAssert(FConsoleWindow != NULL);\r\n SetForegroundWindow(FConsoleWindow);\r\n ShowWindow(FConsoleWindow, SW_RESTORE);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::BreakInput()\r\n{\r\n FlushConsoleInputBuffer(FInput);\r\n INPUT_RECORD InputRecord;\r\n memset(&InputRecord, 0, sizeof(InputRecord));\r\n InputRecord.EventType = KEY_EVENT;\r\n InputRecord.Event.KeyEvent.bKeyDown = true;\r\n InputRecord.Event.KeyEvent.wRepeatCount = 1;\r\n InputRecord.Event.KeyEvent.uChar.UnicodeChar = L'\\r';\r\n\r\n unsigned long Written;\r\n // this assertion occasionally fails (when console is being exited)\r\n DebugCheck(WriteConsoleInput(FInput, &InputRecord, 1, &Written));\r\n DebugAssert(Written == 1);\r\n\r\n CancelInput();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::CancelInput()\r\n{\r\n FPendingAbort = true;\r\n\r\n PostMessage(Application->Handle, WM_INTERUPT_IDLE, 0, 0);\r\n}\r\n//---------------------------------------------------------------------------\r\nBOOL WINAPI TOwnConsole::HandlerRoutine(DWORD CtrlType)\r\n{\r\n if ((CtrlType == CTRL_C_EVENT) || (CtrlType == CTRL_BREAK_EVENT))\r\n {\r\n {\r\n TGuard Guard(FSection.get());\r\n\r\n // just to be real thread-safe\r\n if (FInstance != NULL)\r\n {\r\n FInstance->CancelInput();\r\n }\r\n }\r\n\r\n return true;\r\n }\r\n else\r\n {\r\n return false;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TOwnConsole::PendingAbort()\r\n{\r\n if (FPendingAbort)\r\n {\r\n FPendingAbort = false;\r\n return true;\r\n }\r\n else\r\n {\r\n return FPendingAbort;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::Print(UnicodeString Str, bool FromBeginning, bool /*Error*/)\r\n{\r\n if (FromBeginning)\r\n {\r\n CONSOLE_SCREEN_BUFFER_INFO BufferInfo;\r\n GetConsoleScreenBufferInfo(FOutput, &BufferInfo);\r\n BufferInfo.dwCursorPosition.X = 0;\r\n SetConsoleCursorPosition(FOutput, BufferInfo.dwCursorPosition);\r\n }\r\n unsigned long Written;\r\n bool Result = WriteConsole(FOutput, Str.c_str(), Str.Length(), &Written, NULL);\r\n DebugAssert(Result);\r\n DebugUsedParam(Result);\r\n DebugAssert(Str.Length() == static_cast<long>(Written));\r\n ProcessMessages();\r\n}\r\n//---------------------------------------------------------------------------\r\nclass TConsoleInputThread : public TSimpleThread\r\n{\r\npublic:\r\n __fastcall TConsoleInputThread(HANDLE Input, UnicodeString & Str, bool & Result) :\r\n FInput(Input),\r\n FStr(Str),\r\n FResult(Result)\r\n {\r\n }\r\n\r\n virtual __fastcall ~TConsoleInputThread()\r\n {\r\n Close();\r\n }\r\n\r\nprotected:\r\n virtual void __fastcall Execute()\r\n {\r\n unsigned long Read;\r\n FStr.SetLength(10240);\r\n FResult = ReadConsole(FInput, FStr.c_str(), FStr.Length(), &Read, NULL);\r\n DebugAssert(FResult);\r\n FStr.SetLength(Read);\r\n TrimNewLine(FStr);\r\n }\r\n\r\n virtual void __fastcall Terminate()\r\n {\r\n TOwnConsole::FInstance->BreakInput();\r\n }\r\n\r\nprivate:\r\n HANDLE FInput;\r\n UnicodeString & FStr;\r\n bool & FResult;\r\n};\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TOwnConsole::Input(UnicodeString & Str, bool Echo, unsigned int Timer)\r\n{\r\n unsigned long PrevMode, NewMode;\r\n GetConsoleMode(FInput, &PrevMode);\r\n NewMode = PrevMode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;\r\n if (Echo)\r\n {\r\n NewMode |= ENABLE_ECHO_INPUT;\r\n }\r\n else\r\n {\r\n NewMode &= ~ENABLE_ECHO_INPUT;\r\n }\r\n SetConsoleMode(FInput, NewMode);\r\n\r\n bool Result = false;\r\n\r\n try\r\n {\r\n {\r\n const int FirstKey = VK_LBUTTON; // 0x01\r\n const int LastKey = VK_OEM_CLEAR; // 0xFE\r\n\r\n // reset key state\r\n for (int Key = FirstKey; Key <= LastKey; Key++)\r\n {\r\n GetAsyncKeyState(Key);\r\n }\r\n\r\n TConsoleInputThread InputThread(FInput, Str, Result);\r\n\r\n InputThread.Start();\r\n\r\n double TimerD = double(Timer)/MSecsPerDay;\r\n double End = Now() + TimerD;\r\n while (!InputThread.IsFinished() &&\r\n ((Timer == 0) || (double(Now()) < End)))\r\n {\r\n ProcessMessages();\r\n InputThread.WaitFor(50);\r\n\r\n for (int Key = FirstKey; Key <= LastKey; Key++)\r\n {\r\n if ((GetAsyncKeyState(Key) & 0x01) != 0)\r\n {\r\n End = Now() + TimerD;\r\n // Finishing the loop nevertheless to reset state of all keys\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (FPendingAbort || !Echo)\r\n {\r\n Print(L\"\\n\");\r\n }\r\n\r\n if (FPendingAbort || (Str.Length() == 0))\r\n {\r\n Result = false;\r\n FPendingAbort = false;\r\n }\r\n }\r\n __finally\r\n {\r\n SetConsoleMode(FInput, PrevMode);\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall TOwnConsole::Choice(\r\n UnicodeString Options, int Cancel, int Break, int /*Continue*/, int Timeouted, bool /*Timeouting*/, unsigned int Timer,\r\n UnicodeString Message)\r\n{\r\n unsigned int ATimer = Timer;\r\n int Result = 0;\r\n unsigned long PrevMode, NewMode;\r\n GetConsoleMode(FInput, &PrevMode);\r\n NewMode = (PrevMode | ENABLE_PROCESSED_INPUT) & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);\r\n SetConsoleMode(FInput, NewMode);\r\n\r\n try\r\n {\r\n do\r\n {\r\n unsigned long Read;\r\n INPUT_RECORD Record;\r\n if ((PeekConsoleInput(FInput, &Record, 1, &Read) != 0) &&\r\n (Read == 1))\r\n {\r\n if ((ReadConsoleInput(FInput, &Record, 1, &Read) != 0) &&\r\n (Read == 1))\r\n {\r\n if (PendingAbort())\r\n {\r\n Result = Break;\r\n }\r\n else if ((Record.EventType == KEY_EVENT) &&\r\n Record.Event.KeyEvent.bKeyDown)\r\n {\r\n wchar_t C = AnsiUpperCase(Record.Event.KeyEvent.uChar.UnicodeChar)[1];\r\n if (C == 27)\r\n {\r\n Result = Cancel;\r\n }\r\n else if ((Options.Pos(C) > 0) &&\r\n FLAGCLEAR(Record.Event.KeyEvent.dwControlKeyState,\r\n LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED | LEFT_ALT_PRESSED |\r\n RIGHT_ALT_PRESSED))\r\n\r\n {\r\n Result = Options.Pos(C);\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (Result == 0)\r\n {\r\n unsigned int TimerSlice = 50;\r\n Sleep(TimerSlice);\r\n if (Timer > 0)\r\n {\r\n if (ATimer > TimerSlice)\r\n {\r\n ATimer -= TimerSlice;\r\n }\r\n else\r\n {\r\n Result = Timeouted;\r\n }\r\n }\r\n }\r\n\r\n ProcessMessages();\r\n }\r\n while (Result == 0);\r\n }\r\n __finally\r\n {\r\n SetConsoleMode(FInput, PrevMode);\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::SetTitle(UnicodeString Title)\r\n{\r\n FTrayIcon->Hint = Title;\r\n SetConsoleTitle(Title.c_str());\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TOwnConsole::LimitedOutput()\r\n{\r\n return true;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TOwnConsole::LiveOutput()\r\n{\r\n return true;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TOwnConsole::NoInteractiveInput()\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TOwnConsole::Interactive()\r\n{\r\n return true;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::WaitBeforeExit()\r\n{\r\n unsigned long Read;\r\n INPUT_RECORD Record;\r\n while (true)\r\n {\r\n if (PeekConsoleInput(FInput, &Record, 1, &Read) && (Read == 1) &&\r\n ReadConsoleInput(FInput, &Record, 1, &Read) &&\r\n (Read == 1) && (Record.EventType == KEY_EVENT) &&\r\n (Record.Event.KeyEvent.uChar.UnicodeChar != 0) &&\r\n Record.Event.KeyEvent.bKeyDown)\r\n {\r\n break;\r\n }\r\n Sleep(50);\r\n ProcessMessages();\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TOwnConsole::CommandLineOnly()\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TOwnConsole::WantsProgress()\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::Progress(TScriptProgress & /*Progress*/)\r\n{\r\n DebugFail();\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TOwnConsole::FinalLogMessage()\r\n{\r\n return UnicodeString();\r\n}\r\n//---------------------------------------------------------------------------\r\nclass TExternalConsole : public TConsole\r\n{\r\npublic:\r\n __fastcall TExternalConsole(const UnicodeString Instance, bool NoInteractiveInput);\r\n virtual __fastcall ~TExternalConsole();\r\n\r\n virtual void __fastcall Print(UnicodeString Str, bool FromBeginning = false, bool Error = false);\r\n virtual bool __fastcall Input(UnicodeString & Str, bool Echo, unsigned int Timer);\r\n virtual int __fastcall Choice(\r\n UnicodeString Options, int Cancel, int Break, int Continue, int Timeouted, bool Timeouting, unsigned int Timer,\r\n UnicodeString Message);\r\n virtual bool __fastcall PendingAbort();\r\n virtual void __fastcall SetTitle(UnicodeString Title);\r\n virtual bool __fastcall LimitedOutput();\r\n virtual bool __fastcall LiveOutput();\r\n virtual bool __fastcall NoInteractiveInput();\r\n virtual void __fastcall WaitBeforeExit();\r\n virtual bool __fastcall Interactive();\r\n virtual bool __fastcall CommandLineOnly();\r\n virtual bool __fastcall WantsProgress();\r\n virtual void __fastcall Progress(TScriptProgress & Progress);\r\n virtual UnicodeString __fastcall FinalLogMessage();\r\n\r\nprivate:\r\n bool FPendingAbort;\r\n HANDLE FRequestEvent;\r\n HANDLE FResponseEvent;\r\n HANDLE FCancelEvent;\r\n HANDLE FFileMapping;\r\n bool FLimitedOutput;\r\n bool FLiveOutput;\r\n bool FPipeOutput;\r\n bool FNoInteractiveInput;\r\n bool FWantsProgress;\r\n bool FInteractive;\r\n unsigned int FMaxSend;\r\n\r\n inline TConsoleCommStruct * __fastcall GetCommStruct();\r\n inline void __fastcall FreeCommStruct(TConsoleCommStruct * CommStruct);\r\n inline void __fastcall SendEvent(int Timeout);\r\n void __fastcall Init();\r\n void __fastcall CheckHandle(HANDLE Handle, const UnicodeString & Desc);\r\n};\r\n//---------------------------------------------------------------------------\r\n__fastcall TExternalConsole::TExternalConsole(\r\n const UnicodeString Instance, bool NoInteractiveInput)\r\n{\r\n UnicodeString Name;\r\n Name = FORMAT(L\"%s%s\", (CONSOLE_EVENT_REQUEST, (Instance)));\r\n CheckHandle(FRequestEvent = OpenEvent(EVENT_ALL_ACCESS, false, Name.c_str()), L\"Request event\");\r\n Name = FORMAT(L\"%s%s\", (CONSOLE_EVENT_RESPONSE, (Instance)));\r\n CheckHandle(FResponseEvent = OpenEvent(EVENT_ALL_ACCESS, false, Name.c_str()), L\"Response event\");\r\n Name = FORMAT(L\"%s%s\", (CONSOLE_EVENT_CANCEL, (Instance)));\r\n CheckHandle(FCancelEvent = OpenEvent(EVENT_ALL_ACCESS, false, Name.c_str()), L\"Cancel event\");\r\n Name = FORMAT(L\"%s%s\", (CONSOLE_MAPPING, (Instance)));\r\n CheckHandle(FFileMapping = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, Name.c_str()), L\"File mapping\");\r\n\r\n HANDLE Job = OpenJobObject(JOB_OBJECT_ASSIGN_PROCESS, FALSE,\r\n FORMAT(L\"%s%s\", (CONSOLE_JOB, Instance)).c_str());\r\n if (DebugAlwaysTrue(Job != NULL))\r\n {\r\n AssignProcessToJobObject(Job, GetCurrentProcess());\r\n // winscp.com/winscp.dll keeps the only reference to the job.\r\n // once it gets closed (because winscp.com if forcefully terminated),\r\n // we get terminated as well\r\n CloseHandle(Job);\r\n }\r\n\r\n TConsoleCommStruct * CommStruct = GetCommStruct();\r\n try\r\n {\r\n if (CommStruct->Version != TConsoleCommStruct::CurrentVersion)\r\n {\r\n throw Exception(FMTLOAD(EXTERNAL_CONSOLE_INCOMPATIBLE, (CommStruct->Version)));\r\n }\r\n\r\n CommStruct->Version = TConsoleCommStruct::CurrentVersionConfirmed;\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n\r\n // to break application event loop regularly during \"watching for changes\"\r\n // to allow user to abort it\r\n SetTimer(Application->Handle, 1, 500, NULL);\r\n\r\n FNoInteractiveInput = NoInteractiveInput;\r\n FMaxSend = 0;\r\n\r\n Init();\r\n}\r\n//---------------------------------------------------------------------------\r\n__fastcall TExternalConsole::~TExternalConsole()\r\n{\r\n CloseHandle(FRequestEvent);\r\n CloseHandle(FResponseEvent);\r\n CloseHandle(FCancelEvent);\r\n CloseHandle(FFileMapping);\r\n KillTimer(Application->Handle, 1);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TExternalConsole::CheckHandle(HANDLE Handle, const UnicodeString & Desc)\r\n{\r\n if (Handle == NULL)\r\n {\r\n throw ExtException(LoadStr(EXTERNAL_CONSOLE_INIT_ERROR), FORMAT(L\"%s\\n%s\", (Desc, LastSysErrorMessage())));\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nTConsoleCommStruct * __fastcall TExternalConsole::GetCommStruct()\r\n{\r\n TConsoleCommStruct * Result;\r\n Result = static_cast<TConsoleCommStruct*>(MapViewOfFile(FFileMapping,\r\n FILE_MAP_ALL_ACCESS, 0, 0, 0));\r\n if (Result == NULL)\r\n {\r\n throw Exception(LoadStr(CONSOLE_COMM_ERROR));\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TExternalConsole::FreeCommStruct(TConsoleCommStruct * CommStruct)\r\n{\r\n UnmapViewOfFile(CommStruct);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TExternalConsole::SendEvent(int Timeout)\r\n{\r\n SetEvent(FRequestEvent);\r\n unsigned int Start = 0; // shut up\r\n if (Configuration->LogProtocol >= 1)\r\n {\r\n Start = GetTickCount();\r\n }\r\n unsigned int Result = WaitForSingleObject(FResponseEvent, Timeout);\r\n if (Configuration->LogProtocol >= 1)\r\n {\r\n unsigned int End = GetTickCount();\r\n unsigned int Duration = End - Start;\r\n FMaxSend = std::max(Duration, FMaxSend);\r\n }\r\n if (Result != WAIT_OBJECT_0)\r\n {\r\n UnicodeString Message = LoadStr(CONSOLE_SEND_TIMEOUT);\r\n if (FPipeOutput)\r\n {\r\n Message = FORMAT(\"%s %s\", (Message, LoadStr(CONSOLE_SEND_PIPE)));\r\n }\r\n throw Exception(Message);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TExternalConsole::FinalLogMessage()\r\n{\r\n return FORMAT(L\"Max roundtrip: %d\", (static_cast<int>(FMaxSend)));\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TExternalConsole::Print(UnicodeString Str, bool FromBeginning, bool Error)\r\n{\r\n // need to do at least one iteration, even when Str is empty (new line)\r\n do\r\n {\r\n TConsoleCommStruct * CommStruct = GetCommStruct();\r\n try\r\n {\r\n size_t MaxLen = LENOF(CommStruct->PrintEvent.Message) - 1;\r\n UnicodeString Piece = Str.SubString(1, MaxLen);\r\n Str.Delete(1, MaxLen);\r\n\r\n CommStruct->Event = TConsoleCommStruct::PRINT;\r\n wcscpy(CommStruct->PrintEvent.Message, Piece.c_str());\r\n CommStruct->PrintEvent.FromBeginning = FromBeginning;\r\n CommStruct->PrintEvent.Error = Error;\r\n\r\n // In the next iteration we need to append never overwrite.\r\n // Note that this won't work properly for disk/pipe outputs,\r\n // when the next line is also FromBeginning,\r\n // as !FromBeginning print effectively commits previous FromBeginning print.\r\n // On the other hand, FromBeginning print is always initiated by us,\r\n // and it's not likely we ever issue print over 10 KB.\r\n FromBeginning = false;\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n\r\n SendEvent(INFINITE);\r\n }\r\n while (!Str.IsEmpty());\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TExternalConsole::Input(UnicodeString & Str, bool Echo, unsigned int Timer)\r\n{\r\n TConsoleCommStruct * CommStruct = GetCommStruct();\r\n try\r\n {\r\n CommStruct->Event = TConsoleCommStruct::INPUT;\r\n CommStruct->InputEvent.Echo = Echo;\r\n CommStruct->InputEvent.Result = false;\r\n CommStruct->InputEvent.Str[0] = L'\\0';\r\n CommStruct->InputEvent.Timer = Timer;\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n\r\n SendEvent(INFINITE);\r\n\r\n bool Result;\r\n CommStruct = GetCommStruct();\r\n try\r\n {\r\n Result = CommStruct->InputEvent.Result;\r\n Str = CommStruct->InputEvent.Str;\r\n TrimNewLine(Str);\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall TExternalConsole::Choice(\r\n UnicodeString Options, int Cancel, int Break, int Continue, int Timeouted, bool Timeouting, unsigned int Timer,\r\n UnicodeString Message)\r\n{\r\n TConsoleCommStruct * CommStruct = GetCommStruct();\r\n try\r\n {\r\n CommStruct->Event = TConsoleCommStruct::CHOICE;\r\n\r\n DebugAssert(Options.Length() < static_cast<int>(LENOF(CommStruct->ChoiceEvent.Options)));\r\n wcscpy(CommStruct->ChoiceEvent.Options, Options.c_str());\r\n CommStruct->ChoiceEvent.Cancel = Cancel;\r\n CommStruct->ChoiceEvent.Break = Break;\r\n CommStruct->ChoiceEvent.Result = Break;\r\n CommStruct->ChoiceEvent.Continue = Continue;\r\n CommStruct->ChoiceEvent.Timeouted = Timeouted;\r\n CommStruct->ChoiceEvent.Timer = Timer;\r\n CommStruct->ChoiceEvent.Timeouting = Timeouting;\r\n size_t MaxLen = LENOF(CommStruct->ChoiceEvent.Message) - 1;\r\n Message = Message.SubString(1, MaxLen);\r\n wcscpy(CommStruct->ChoiceEvent.Message, Message.c_str());\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n\r\n SendEvent(INFINITE);\r\n\r\n int Result;\r\n CommStruct = GetCommStruct();\r\n try\r\n {\r\n Result = CommStruct->ChoiceEvent.Result;\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TExternalConsole::PendingAbort()\r\n{\r\n return (WaitForSingleObject(FCancelEvent, 0) == WAIT_OBJECT_0);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TExternalConsole::SetTitle(UnicodeString Title)\r\n{\r\n TConsoleCommStruct * CommStruct = GetCommStruct();\r\n try\r\n {\r\n // Truncate to maximum allowed. Title over 10 KB won't fit to screen anyway\r\n Title = Title.SubString(1, LENOF(CommStruct->TitleEvent.Title) - 1);\r\n\r\n CommStruct->Event = TConsoleCommStruct::TITLE;\r\n wcscpy(CommStruct->TitleEvent.Title, Title.c_str());\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n\r\n SendEvent(INFINITE);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TExternalConsole::Init()\r\n{\r\n TConsoleCommStruct * CommStruct = GetCommStruct();\r\n try\r\n {\r\n CommStruct->Event = TConsoleCommStruct::INIT;\r\n CommStruct->InitEvent.WantsProgress = false;\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n SendEvent(INFINITE);\r\n\r\n CommStruct = GetCommStruct();\r\n try\r\n {\r\n FLimitedOutput = (CommStruct->InitEvent.OutputType == FILE_TYPE_CHAR);\r\n FLiveOutput =\r\n (CommStruct->InitEvent.OutputType != FILE_TYPE_DISK) &&\r\n (CommStruct->InitEvent.OutputType != FILE_TYPE_PIPE);\r\n FPipeOutput = (CommStruct->InitEvent.OutputType != FILE_TYPE_PIPE);\r\n FInteractive =\r\n (CommStruct->InitEvent.InputType != FILE_TYPE_DISK) &&\r\n (CommStruct->InitEvent.InputType != FILE_TYPE_PIPE);\r\n FWantsProgress = CommStruct->InitEvent.WantsProgress;\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TExternalConsole::LimitedOutput()\r\n{\r\n return FLimitedOutput;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TExternalConsole::LiveOutput()\r\n{\r\n return FLiveOutput;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TExternalConsole::NoInteractiveInput()\r\n{\r\n return FNoInteractiveInput;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TExternalConsole::Interactive()\r\n{\r\n return FInteractive;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TExternalConsole::WaitBeforeExit()\r\n{\r\n // noop\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TExternalConsole::CommandLineOnly()\r\n{\r\n return true;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TExternalConsole::WantsProgress()\r\n{\r\n return FWantsProgress;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TExternalConsole::Progress(TScriptProgress & Progress)\r\n{\r\n TConsoleCommStruct * CommStruct = GetCommStruct();\r\n\r\n typedef TConsoleCommStruct::TProgressEvent TProgressEvent;\r\n\r\n try\r\n {\r\n TProgressEvent & ProgressEvent = CommStruct->ProgressEvent;\r\n\r\n CommStruct->Event = TConsoleCommStruct::PROGRESS;\r\n\r\n switch (Progress.Operation)\r\n {\r\n case foCopy:\r\n case foMove:\r\n ProgressEvent.Operation = TProgressEvent::COPY;\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n }\r\n\r\n switch (Progress.Side)\r\n {\r\n case osLocal:\r\n ProgressEvent.Side = TProgressEvent::LOCAL;\r\n break;\r\n\r\n case osRemote:\r\n ProgressEvent.Side = TProgressEvent::REMOTE;\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n }\r\n\r\n wcsncpy(ProgressEvent.FileName, Progress.FileName.c_str(), LENOF(ProgressEvent.FileName));\r\n NULL_TERMINATE(ProgressEvent.FileName);\r\n\r\n wcsncpy(ProgressEvent.Directory, Progress.Directory.c_str(), LENOF(ProgressEvent.Directory));\r\n NULL_TERMINATE(ProgressEvent.Directory);\r\n\r\n ProgressEvent.OverallProgress = Progress.OverallProgress;\r\n ProgressEvent.FileProgress = Progress.FileProgress;\r\n ProgressEvent.CPS = Progress.CPS;\r\n ProgressEvent.Cancel = Progress.Cancel;\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n SendEvent(INFINITE);\r\n\r\n CommStruct = GetCommStruct();\r\n try\r\n {\r\n TProgressEvent & ProgressEvent = CommStruct->ProgressEvent;\r\n Progress.Cancel = ProgressEvent.Cancel;\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nclass TNullConsole : public TConsole\r\n{\r\npublic:\r\n __fastcall TNullConsole();\r\n\r\n virtual void __fastcall Print(UnicodeString Str, bool FromBeginning = false, bool Error = false);\r\n virtual bool __fastcall Input(UnicodeString & Str, bool Echo, unsigned int Timer);\r\n virtual int __fastcall Choice(\r\n UnicodeString Options, int Cancel, int Break, int Continue, int Timeouted, bool Timeouting, unsigned int Timer,\r\n UnicodeString Message);\r\n virtual bool __fastcall PendingAbort();\r\n virtual void __fastcall SetTitle(UnicodeString Title);\r\n virtual bool __fastcall LimitedOutput();\r\n virtual bool __fastcall LiveOutput();\r\n virtual bool __fastcall NoInteractiveInput();\r\n virtual bool __fastcall Interactive();\r\n virtual void __fastcall WaitBeforeExit();\r\n virtual bool __fastcall CommandLineOnly();\r\n\r\n virtual bool __fastcall WantsProgress();\r\n virtual void __fastcall Progress(TScriptProgress & Progress);\r\n virtual UnicodeString __fastcall FinalLogMessage();\r\n};\r\n//---------------------------------------------------------------------------\r\n__fastcall TNullConsole::TNullConsole()\r\n{\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TNullConsole::Print(UnicodeString /*Str*/, bool /*FromBeginning*/, bool /*Error*/)\r\n{\r\n // noop\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TNullConsole::Input(UnicodeString & /*Str*/, bool /*Echo*/,\r\n unsigned int /*Timer*/)\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall TNullConsole::Choice(\r\n UnicodeString /*Options*/, int /*Cancel*/, int Break, int /*Continue*/, int Timeouted, bool Timeouting,\r\n unsigned int Timer, UnicodeString /*Message*/)\r\n{\r\n int Result;\r\n if (Timeouting)\r\n {\r\n Sleep(Timer);\r\n Result = Timeouted;\r\n }\r\n else\r\n {\r\n Result = Break;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TNullConsole::PendingAbort()\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TNullConsole::SetTitle(UnicodeString /*Title*/)\r\n{\r\n // noop\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TNullConsole::LimitedOutput()\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TNullConsole::LiveOutput()\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TNullConsole::NoInteractiveInput()\r\n{\r\n // do not matter, even if we return false,\r\n // it fails immediately afterwards in TNullConsole::Input\r\n return true;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TNullConsole::Interactive()\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TNullConsole::WaitBeforeExit()\r\n{\r\n DebugFail();\r\n // noop\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TNullConsole::CommandLineOnly()\r\n{\r\n DebugFail();\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TNullConsole::WantsProgress()\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TNullConsole::Progress(TScriptProgress & /*Progress*/)\r\n{\r\n DebugFail();\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TNullConsole::FinalLogMessage()\r\n{\r\n return UnicodeString();\r\n}\r\n//---------------------------------------------------------------------------\r\nstatic UnicodeString TimestampVarName(L\"TIMESTAMP\");\r\n//---------------------------------------------------------------------------\r\nclass TConsoleRunner\r\n{\r\npublic:\r\n TConsoleRunner(TConsole * Console);\r\n ~TConsoleRunner();\r\n\r\n int __fastcall Run(const UnicodeString Session, TOptions * Options,\r\n TStrings * ScriptCommands, TStrings * ScriptParameters);\r\n void __fastcall ShowException(Exception * E);\r\n inline void __fastcall PrintMessage(const UnicodeString & Str, bool Error = false);\r\n\r\nprotected:\r\n bool __fastcall DoInput(UnicodeString & Str, bool Echo, unsigned int Timer,\r\n bool Interactive);\r\n void __fastcall Input(const UnicodeString Prompt, UnicodeString & Str,\r\n bool Echo, bool Interactive);\r\n inline void __fastcall Print(const UnicodeString & Str, bool FromBeginning = false, bool Error = false);\r\n void __fastcall UpdateTitle();\r\n inline bool __fastcall NotifyAbort();\r\n inline bool __fastcall Aborted(bool AllowCompleteAbort = true);\r\n void __fastcall MasterPasswordPrompt();\r\n void __fastcall DoShowException(TTerminal * Terminal, Exception * E);\r\n\r\nprivate:\r\n TManagementScript * FScript;\r\n TConsole * FConsole;\r\n TSynchronizeController FSynchronizeController;\r\n int FLastProgressLen;\r\n bool FSynchronizeAborted;\r\n bool FCommandError;\r\n bool FBatchScript;\r\n bool FAborted;\r\n TTimer * Timer;\r\n bool FExternalTimestampVar;\r\n\r\n void __fastcall ScriptPrint(TScript * Script, const UnicodeString Str, bool Error);\r\n void __fastcall ScriptPrintProgress(TScript * Script, bool First, const UnicodeString Str);\r\n void __fastcall ScriptInput(TScript * Script, const UnicodeString Prompt, UnicodeString & Str);\r\n void __fastcall ScriptTerminalPromptUser(TTerminal * Terminal,\r\n TPromptKind Kind, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,\r\n TStrings * Results, bool & Result, void * Arg);\r\n void __fastcall ScriptShowExtendedException(TTerminal * Terminal,\r\n Exception * E, void * Arg);\r\n void __fastcall ScriptTerminalQueryUser(TObject * Sender, const UnicodeString Query,\r\n TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params, unsigned int & Answer,\r\n TQueryType QueryType, void * Arg);\r\n void __fastcall ScriptQueryCancel(TScript * Script, bool & Cancel);\r\n void __fastcall SynchronizeControllerAbort(TObject * Sender, bool Close);\r\n void __fastcall SynchronizeControllerLog(TSynchronizeController * Controller,\r\n TSynchronizeLogEntry Entry, const UnicodeString Message);\r\n void __fastcall ScriptSynchronizeStartStop(TScript * Script,\r\n const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,\r\n const TCopyParamType & CopyParam, int SynchronizeParams);\r\n void __fastcall SynchronizeControllerSynchronize(TSynchronizeController * Sender,\r\n const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,\r\n const TCopyParamType & CopyParam, const TSynchronizeParamType & Params,\r\n TSynchronizeChecklist ** Checklist, TSynchronizeOptions * Options, bool Full);\r\n void __fastcall SynchronizeControllerSynchronizeInvalid(TSynchronizeController * Sender,\r\n const UnicodeString Directory, const UnicodeString ErrorStr);\r\n void __fastcall SynchronizeControllerTooManyDirectories(TSynchronizeController * Sender,\r\n int & MaxDirectories);\r\n unsigned int InputTimeout();\r\n void __fastcall TimerTimer(TObject * Sender);\r\n UnicodeString ExpandCommand(UnicodeString Command, TStrings * ScriptParameters);\r\n void __fastcall Failed(bool & AnyError);\r\n void __fastcall ScriptProgress(TScript * Script, TScriptProgress & Progress);\r\n void __fastcall ConfigurationChange(TObject * Sender);\r\n};\r\n//---------------------------------------------------------------------------\r\nTConsoleRunner::TConsoleRunner(TConsole * Console) :\r\n FSynchronizeController(&SynchronizeControllerSynchronize,\r\n &SynchronizeControllerSynchronizeInvalid,\r\n &SynchronizeControllerTooManyDirectories)\r\n{\r\n FConsole = Console;\r\n FLastProgressLen = 0;\r\n FScript = NULL;\r\n FAborted = false;\r\n FBatchScript = false;\r\n Timer = new TTimer(Application);\r\n Timer->OnTimer = TimerTimer;\r\n Timer->Interval = MSecsPerSec;\r\n Timer->Enabled = true;\r\n DebugAssert(WinConfiguration->OnMasterPasswordPrompt == NULL);\r\n WinConfiguration->OnMasterPasswordPrompt = MasterPasswordPrompt;\r\n DebugAssert(Configuration->OnChange == NULL);\r\n FExternalTimestampVar = !GetEnvironmentVariable(TimestampVarName).IsEmpty();\r\n Configuration->OnChange = ConfigurationChange;\r\n Configuration->Scripting = true;\r\n}\r\n//---------------------------------------------------------------------------\r\nTConsoleRunner::~TConsoleRunner()\r\n{\r\n DebugAssert(WinConfiguration->OnMasterPasswordPrompt == MasterPasswordPrompt);\r\n WinConfiguration->OnMasterPasswordPrompt = NULL;\r\n DebugAssert(Configuration->OnChange == ConfigurationChange);\r\n Configuration->OnChange = NULL;\r\n delete Timer;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::TimerTimer(TObject * /*Sender*/)\r\n{\r\n // sole presence of timer causes message to be dispatched,\r\n // hence breaks the loops\r\n}\r\n//---------------------------------------------------------------------------\r\nunsigned int TConsoleRunner::InputTimeout()\r\n{\r\n return ((FScript != NULL) && (FScript->Batch != TScript::BatchOff) ? BATCH_INPUT_TIMEOUT : 0);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::Input(\r\n const UnicodeString Prompt, UnicodeString & Str, bool Echo, bool Interactive)\r\n{\r\n Print(Prompt);\r\n\r\n if (!DoInput(Str, Echo, InputTimeout(), Interactive))\r\n {\r\n Abort();\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptInput(TScript * /*Script*/,\r\n const UnicodeString Prompt, UnicodeString & Str)\r\n{\r\n Input(Prompt, Str, true, true);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::Print(const UnicodeString & Str, bool FromBeginning, bool Error)\r\n{\r\n if (FLastProgressLen > 0)\r\n {\r\n FConsole->Print(L\"\\n\" + Str, FromBeginning, Error);\r\n FLastProgressLen = 0;\r\n }\r\n else\r\n {\r\n FConsole->Print(Str, FromBeginning, Error);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::PrintMessage(const UnicodeString & Str, bool Error)\r\n{\r\n UnicodeString Line = RemoveEmptyLines(Str);\r\n\r\n if (FScript != NULL)\r\n {\r\n // this also logs the message\r\n FScript->PrintLine(Line, Error);\r\n }\r\n else\r\n {\r\n FConsole->PrintLine(Line, Error);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TConsoleRunner::NotifyAbort()\r\n{\r\n bool Result = FBatchScript;\r\n if (Result)\r\n {\r\n FAborted = true;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TConsoleRunner::Aborted(bool AllowCompleteAbort)\r\n{\r\n bool Result;\r\n if (FAborted)\r\n {\r\n Result = true;\r\n }\r\n else\r\n {\r\n Result = FConsole->PendingAbort();\r\n if (Result)\r\n {\r\n PrintMessage(LoadStr(USER_TERMINATED), true);\r\n\r\n if (AllowCompleteAbort && NotifyAbort())\r\n {\r\n if (FScript->Terminal != NULL)\r\n {\r\n std::unique_ptr<TStringList> Failure(TextToStringList(LoadStr(USER_TERMINATED)));\r\n FScript->Terminal->ActionLog->AddFailure(Failure.get());\r\n }\r\n }\r\n }\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptPrint(TScript * /*Script*/,\r\n const UnicodeString Str, bool Error)\r\n{\r\n Print(Str, false, Error);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptPrintProgress(TScript * /*Script*/,\r\n bool First, const UnicodeString Str)\r\n{\r\n UnicodeString S = Str;\r\n if (First && (FLastProgressLen > 0))\r\n {\r\n S = L\"\\n\" + S;\r\n }\r\n else if (S.Length() < FLastProgressLen)\r\n {\r\n int Padding = FLastProgressLen - S.Length();\r\n S += UnicodeString::StringOfChar(L' ', Padding) +\r\n UnicodeString::StringOfChar(L'\\b', Padding);\r\n }\r\n FConsole->Print(S, true);\r\n FLastProgressLen = Str.Length();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptTerminalPromptUser(TTerminal * /*Terminal*/,\r\n TPromptKind /*Kind*/, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,\r\n TStrings * Results, bool & Result, void * /*Arg*/)\r\n{\r\n if (!Instructions.IsEmpty())\r\n {\r\n PrintMessage(Instructions);\r\n }\r\n\r\n // if there are no prompts, success is default\r\n Result = true;\r\n\r\n for (int Index = 0; Index < Prompts->Count; Index++)\r\n {\r\n UnicodeString Prompt = Prompts->Strings[Index];\r\n if (!Prompt.IsEmpty() && (Prompt[Prompt.Length()] != L' '))\r\n {\r\n Prompt += L' ';\r\n }\r\n int P = Prompt.Pos(L'&');\r\n if (P > 0)\r\n {\r\n Prompt.Delete(P, 1);\r\n }\r\n Print(Prompt);\r\n\r\n UnicodeString AResult = Results->Strings[Index]; // useless\r\n bool Echo = FLAGSET(int(Prompts->Objects[Index]), pupEcho);\r\n Result = DoInput(AResult, Echo, InputTimeout(), true);\r\n Results->Strings[Index] = AResult;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptShowExtendedException(\r\n TTerminal * Terminal, Exception * E, void * /*Arg*/)\r\n{\r\n DoShowException(Terminal, E);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptTerminalQueryUser(TObject * /*Sender*/,\r\n const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,\r\n const TQueryParams * Params, unsigned int & Answer, TQueryType /*QueryType*/,\r\n void * /*Arg*/)\r\n{\r\n UnicodeString AQuery = Query;\r\n unsigned int Timer = 0;\r\n unsigned int Timeout = 0;\r\n unsigned int TimeoutA = 0;\r\n unsigned int NoBatchA = 0;\r\n\r\n if (Params != NULL)\r\n {\r\n if (Params->Timeout > 0)\r\n {\r\n Timeout = Params->Timeout;\r\n TimeoutA = Params->TimeoutAnswer;\r\n }\r\n\r\n if (Params->Timer > 0)\r\n {\r\n Timer = Params->Timer;\r\n if (Params->TimerAnswers > 0)\r\n {\r\n Answers = Params->TimerAnswers;\r\n }\r\n // not considering TimerQueryType as we do not use QueryType anyway\r\n if (!Params->TimerMessage.IsEmpty())\r\n {\r\n AQuery = Params->TimerMessage;\r\n }\r\n }\r\n\r\n if (FLAGSET(Params->Params, qpFatalAbort))\r\n {\r\n AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));\r\n }\r\n\r\n NoBatchA = Params->NoBatchAnswers;\r\n\r\n if (FLAGSET(Params->Params, qpWaitInBatch))\r\n {\r\n DebugAssert(Timeout == 0);\r\n Timeout = InputTimeout();\r\n if (Timeout != 0)\r\n {\r\n // See a duplicate AbortAnswer call below\r\n TimeoutA = AbortAnswer(Answers & ~NoBatchA);\r\n }\r\n }\r\n }\r\n\r\n AQuery = UnformatMessage(AQuery);\r\n AQuery = RemoveInteractiveMsgTag(AQuery);\r\n\r\n ApplyTabs(AQuery, L' ', NULL, NULL);\r\n\r\n unsigned int AAnswers = Answers;\r\n\r\n UnicodeString Message = AQuery;\r\n PrintMessage(AQuery);\r\n if ((MoreMessages != NULL) && (MoreMessages->Count > 0))\r\n {\r\n PrintMessage(MoreMessages->Text);\r\n Message += L\"\\n\" + MoreMessages->Text;\r\n }\r\n\r\n std::vector<unsigned int> Buttons;\r\n std::vector<UnicodeString> Captions;\r\n std::vector<TButtonSubmitEvent> OnSubmits;\r\n\r\n for (unsigned int Answer = qaFirst; Answer <= qaLast; Answer = Answer << 1)\r\n {\r\n if (FLAGSET(Answers, Answer))\r\n {\r\n UnicodeString Name; // unused\r\n UnicodeString Caption;\r\n AnswerNameAndCaption(Answer, Name, Caption);\r\n Captions.push_back(Caption);\r\n Buttons.push_back(Answer);\r\n OnSubmits.push_back(NULL);\r\n AAnswers -= Answer;\r\n }\r\n }\r\n\r\n DebugUsedParam(AAnswers);\r\n DebugAssert(AAnswers == 0);\r\n DebugAssert(!Buttons.empty());\r\n\r\n if ((Params != NULL) && (Params->Aliases != NULL))\r\n {\r\n for (unsigned int bi = 0; bi < Buttons.size(); bi++)\r\n {\r\n for (unsigned int ai = 0; ai < Params->AliasesCount; ai++)\r\n {\r\n if (Params->Aliases[ai].Button == Buttons[bi])\r\n {\r\n if (!Params->Aliases[ai].Alias.IsEmpty())\r\n {\r\n Captions[bi] = Params->Aliases[ai].Alias;\r\n }\r\n OnSubmits[bi] = Params->Aliases[ai].OnSubmit;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n UnicodeString Accels;\r\n for (unsigned int Index = 0; Index < Buttons.size(); Index++)\r\n {\r\n UnicodeString & Caption = Captions[Index];\r\n int P = Caption.Pos(L'&');\r\n if ((P > 0) && (P < Caption.Length()))\r\n {\r\n wchar_t Accel = AnsiUpperCase(Caption)[P + 1];\r\n if (Accels.Pos(Accel) > 0)\r\n {\r\n Caption.Delete(P, 1);\r\n Accels += L' ';\r\n }\r\n else\r\n {\r\n Accels += Accel;\r\n }\r\n }\r\n else\r\n {\r\n Accels += L' ';\r\n }\r\n }\r\n\r\n DebugAssert(Accels.Length() == static_cast<int>(Buttons.size()));\r\n int NumberAccel = 0;\r\n unsigned int CancelA = CancelAnswer(Answers);\r\n int CancelIndex;\r\n // AbortAnswer call duplicated in qpWaitInBatch branch above\r\n unsigned int AbortA = AbortAnswer(Answers & ~NoBatchA);\r\n int AbortIndex;\r\n unsigned int ContinueA = ContinueAnswer(Answers & ~NoBatchA);\r\n int ContinueIndex;\r\n int TimeoutIndex = 0;\r\n\r\n for (unsigned int Index = 0; Index < Buttons.size(); Index++)\r\n {\r\n UnicodeString & Caption = Captions[Index];\r\n\r\n if (Accels[Index + 1] == L' ')\r\n {\r\n for (int Index2 = 1; Index2 <= Caption.Length(); Index2++)\r\n {\r\n wchar_t C = AnsiUpperCase(Caption)[Index2];\r\n if (IsLetter(C) && (Accels.Pos(C) == 0))\r\n {\r\n Caption.Insert(L\"&\", Index2);\r\n Accels[Index + 1] = C;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (Accels[Index + 1] == L' ')\r\n {\r\n for (int Index2 = 1; Index2 <= Caption.Length(); Index2++)\r\n {\r\n wchar_t C = AnsiUpperCase(Caption)[Index2];\r\n if ((C != L' ') && (Accels.Pos(C) == 0))\r\n {\r\n Caption.Insert(L\"&\", Index2);\r\n Accels[Index + 1] = C;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (Accels[Index + 1] == L' ')\r\n {\r\n NumberAccel++;\r\n DebugAssert(NumberAccel <= 9);\r\n Caption = FORMAT(L\"&%d%s\", (NumberAccel, Caption));\r\n Accels[Index + 1] = Caption[2];\r\n }\r\n\r\n if (Buttons[Index] == CancelA)\r\n {\r\n CancelIndex = Index + 1;\r\n }\r\n if (Buttons[Index] == AbortA)\r\n {\r\n AbortIndex = Index + 1;\r\n }\r\n if (Buttons[Index] == ContinueA)\r\n {\r\n ContinueIndex = Index + 1;\r\n }\r\n if (Buttons[Index] == TimeoutA)\r\n {\r\n TimeoutIndex = Index + 1;\r\n }\r\n }\r\n\r\n DebugAssert(Accels.Pos(L' ') == 0);\r\n\r\n bool Timeouting = (Timeout > 0);\r\n bool FirstOutput = true;\r\n\r\n do\r\n {\r\n Answer = 0;\r\n int AnswerIndex;\r\n bool Retry;\r\n\r\n do\r\n {\r\n Retry = false;\r\n\r\n if (FirstOutput || FConsole->LiveOutput())\r\n {\r\n UnicodeString Output;\r\n for (unsigned int i = 0; i < Buttons.size(); i++)\r\n {\r\n if (i > 0)\r\n {\r\n Output += L\", \";\r\n }\r\n\r\n UnicodeString Caption = Captions[i];\r\n int P = Caption.Pos(L'&');\r\n if (DebugAlwaysTrue(P >= 0))\r\n {\r\n Caption[P] = L'(';\r\n Caption.Insert(L\")\", P + 2);\r\n }\r\n\r\n if (i + 1 == static_cast<unsigned int>(TimeoutIndex))\r\n {\r\n DebugAssert(Timeouting);\r\n Caption = FMTLOAD(TIMEOUT_BUTTON, (Caption, int(Timeout / MSecsPerSec)));\r\n }\r\n\r\n Output += Caption;\r\n }\r\n Output += L\": \";\r\n\r\n // note that length of string may decrease over time due to number of\r\n // seconds length, but supposing it decreases by one character at time\r\n // at most, we do not mind as the prompt is terminated with space\r\n\r\n // If output is not live (file or pipe), do not use 'from beginning'\r\n // as it means that the output is not actually stored until new line\r\n // is sent (and we will not [because we cannot] rewrite the output anyway)\r\n Print(Output, !FirstOutput);\r\n FirstOutput = false;\r\n }\r\n\r\n if (!Timeouting && (FScript->Batch == TScript::BatchContinue))\r\n {\r\n AnswerIndex = ContinueIndex;\r\n }\r\n else if (!Timeouting && (FScript->Batch != TScript::BatchOff))\r\n {\r\n AnswerIndex = AbortIndex;\r\n }\r\n else if (Timeouting && (Timeout < MSecsPerSec))\r\n {\r\n AnswerIndex = TimeoutIndex;\r\n }\r\n else\r\n {\r\n unsigned int ActualTimer;\r\n if (Timeouting)\r\n {\r\n if (Timer == 0)\r\n {\r\n if (FConsole->NoInteractiveInput())\r\n {\r\n ActualTimer = Timeout;\r\n }\r\n else\r\n {\r\n ActualTimer = MSecsPerSec;\r\n }\r\n }\r\n else\r\n {\r\n if (Timer < MSecsPerSec)\r\n {\r\n ActualTimer = Timer;\r\n }\r\n else\r\n {\r\n ActualTimer = MSecsPerSec;\r\n }\r\n }\r\n }\r\n else\r\n {\r\n ActualTimer = Timer;\r\n }\r\n // Not to get preliminary \"host is not responding\" messages to .NET assembly\r\n if (FConsole->NoInteractiveInput() && (Timer > 0))\r\n {\r\n Sleep(Timer);\r\n AnswerIndex = -2;\r\n }\r\n else\r\n {\r\n AnswerIndex =\r\n FConsole->Choice(Accels, CancelIndex, -1, ContinueIndex, -2, Timeouting, ActualTimer, Message);\r\n }\r\n if (AnswerIndex == -1)\r\n {\r\n NotifyAbort();\r\n AnswerIndex = AbortIndex;\r\n }\r\n else if (AnswerIndex == -2)\r\n {\r\n if (Timeouting)\r\n {\r\n DebugAssert(Timeout >= MSecsPerSec);\r\n Timeout -= ActualTimer;\r\n Retry = true;\r\n }\r\n\r\n // this does not take Timer into account,\r\n // but as of now Timer is used for TSecureShell timeout prompt only,\r\n // where Timer is less than MSecsPerSec\r\n if (Timer > 0)\r\n {\r\n DebugAssert((Params != NULL) && (Params->TimerEvent != NULL));\r\n if ((Params != NULL) && (Params->TimerEvent != NULL))\r\n {\r\n unsigned int AAnswer = 0;\r\n Params->TimerEvent(AAnswer);\r\n if (AAnswer != 0)\r\n {\r\n Answer = AAnswer;\r\n Retry = false;\r\n }\r\n else\r\n {\r\n Retry = true;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n while (Retry);\r\n\r\n if (Answer == 0)\r\n {\r\n DebugAssert((AnswerIndex >= 1) && (AnswerIndex <= Accels.Length()));\r\n UnicodeString AnswerCaption = Captions[AnswerIndex - 1];\r\n int P = AnswerCaption.Pos(L\"&\");\r\n DebugAssert(P >= 0);\r\n AnswerCaption.Delete(P, 1);\r\n FConsole->PrintLine(AnswerCaption);\r\n FirstOutput = true;\r\n\r\n if (OnSubmits[AnswerIndex - 1] != NULL)\r\n {\r\n OnSubmits[AnswerIndex - 1](NULL, Answer);\r\n }\r\n else\r\n {\r\n Answer = Buttons[AnswerIndex - 1];\r\n }\r\n }\r\n else\r\n {\r\n FConsole->PrintLine();\r\n }\r\n }\r\n while (Answer == 0);\r\n\r\n if ((Answer == AbortA) &&\r\n ((Params == NULL) || FLAGCLEAR(Params->Params, qpIgnoreAbort)))\r\n {\r\n if (FScript->Terminal != NULL)\r\n {\r\n TStrings * Messages = new TStringList();\r\n try\r\n {\r\n Messages->Add(Query);\r\n if (MoreMessages != NULL)\r\n {\r\n Messages->AddStrings(MoreMessages);\r\n }\r\n FScript->Terminal->ActionLog->AddFailure(Messages);\r\n }\r\n __finally\r\n {\r\n delete Messages;\r\n }\r\n }\r\n\r\n FCommandError = true;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptQueryCancel(TScript * /*Script*/, bool & Cancel)\r\n{\r\n if (Aborted())\r\n {\r\n Cancel = true;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptSynchronizeStartStop(TScript * /*Script*/,\r\n const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,\r\n const TCopyParamType & CopyParam, int SynchronizeParams)\r\n{\r\n TSynchronizeParamType Params;\r\n Params.LocalDirectory = LocalDirectory;\r\n Params.RemoteDirectory = RemoteDirectory;\r\n Params.Params = SynchronizeParams;\r\n Params.Options = soRecurse;\r\n\r\n FSynchronizeController.StartStop(Application, true, Params,\r\n CopyParam, NULL, SynchronizeControllerAbort, NULL,\r\n SynchronizeControllerLog);\r\n\r\n try\r\n {\r\n FSynchronizeAborted = false;\r\n\r\n while (!FSynchronizeAborted && !Aborted(false))\r\n {\r\n Application->HandleMessage();\r\n FScript->Terminal->Idle();\r\n }\r\n }\r\n __finally\r\n {\r\n FSynchronizeController.StartStop(Application, false, Params,\r\n CopyParam, NULL, SynchronizeControllerAbort, NULL,\r\n SynchronizeControllerLog);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptProgress(TScript * /*Script*/, TScriptProgress & Progress)\r\n{\r\n FConsole->Progress(Progress);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::SynchronizeControllerLog(\r\n TSynchronizeController * /*Controller*/, TSynchronizeLogEntry /*Entry*/,\r\n const UnicodeString Message)\r\n{\r\n PrintMessage(Message);\r\n LogSynchronizeEvent(FScript->Terminal, Message);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::SynchronizeControllerAbort(TObject * /*Sender*/,\r\n bool /*Close*/)\r\n{\r\n FSynchronizeAborted = true;\r\n NotifyAbort();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::SynchronizeControllerSynchronize(\r\n TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,\r\n const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,\r\n const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,\r\n TSynchronizeOptions * /*Options*/, bool Full)\r\n{\r\n if (!Full)\r\n {\r\n try\r\n {\r\n FScript->Synchronize(LocalDirectory, RemoteDirectory, CopyParam,\r\n Params.Params, Checklist);\r\n }\r\n catch (Exception & E)\r\n {\r\n if ((FScript->Batch == TScript::BatchContinue) &&\r\n FScript->Terminal->Active)\r\n {\r\n // noop\r\n }\r\n else\r\n {\r\n throw;\r\n }\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::SynchronizeControllerSynchronizeInvalid(\r\n TSynchronizeController * /*Sender*/, const UnicodeString Directory, const UnicodeString ErrorStr)\r\n{\r\n if (!Directory.IsEmpty())\r\n {\r\n PrintMessage(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), true);\r\n }\r\n else\r\n {\r\n PrintMessage(LoadStr(WATCH_ERROR_GENERAL), true);\r\n }\r\n\r\n if (!ErrorStr.IsEmpty())\r\n {\r\n PrintMessage(ErrorStr, true);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::SynchronizeControllerTooManyDirectories(\r\n TSynchronizeController * /*Sender*/, int & MaxDirectories)\r\n{\r\n if (Aborted())\r\n {\r\n Abort();\r\n }\r\n\r\n if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)\r\n {\r\n MaxDirectories = GUIConfiguration->MaxWatchDirectories;\r\n }\r\n else\r\n {\r\n MaxDirectories *= 2;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ShowException(Exception * E)\r\n{\r\n DoShowException(NULL, E);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::DoShowException(TTerminal * Terminal, Exception * E)\r\n{\r\n if ((Terminal == NULL) && (FScript != NULL))\r\n {\r\n Terminal = FScript->Terminal;\r\n }\r\n\r\n UnicodeString Message;\r\n if (ExceptionFullMessage(E, Message))\r\n {\r\n FCommandError = true;\r\n PrintMessage(Message, true);\r\n }\r\n\r\n TTerminal * LoggingTerminal = Terminal;\r\n TSecondaryTerminal * SecondaryTerminal = dynamic_cast<TSecondaryTerminal *>(LoggingTerminal);\r\n if (SecondaryTerminal != NULL)\r\n {\r\n LoggingTerminal = SecondaryTerminal->MainTerminal;\r\n }\r\n\r\n if (LoggingTerminal != NULL)\r\n {\r\n LoggingTerminal->ActionLog->AddFailure(E);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TConsoleRunner::DoInput(UnicodeString & Str, bool Echo,\r\n unsigned int Timeout, bool Interactive)\r\n{\r\n bool Result;\r\n if (Interactive && FConsole->NoInteractiveInput())\r\n {\r\n Result = false;\r\n }\r\n else\r\n {\r\n Result = FConsole->Input(Str, Echo, Timeout);\r\n }\r\n\r\n if (!Result)\r\n {\r\n NotifyAbort();\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::MasterPasswordPrompt()\r\n{\r\n bool Retry;\r\n do\r\n {\r\n UnicodeString Password;\r\n Input(LoadStr(CONSOLE_MASTER_PASSWORD_PROMPT), Password, false, true);\r\n Retry = !WinConfiguration->ValidateMasterPassword(Password);\r\n if (Retry)\r\n {\r\n FConsole->PrintLine(LoadStr(MASTER_PASSWORD_INCORRECT));\r\n }\r\n else\r\n {\r\n WinConfiguration->SetMasterPassword(Password);\r\n }\r\n }\r\n while (Retry);\r\n\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString TConsoleRunner::ExpandCommand(UnicodeString Command, TStrings * ScriptParameters)\r\n{\r\n DebugAssert(ScriptParameters != NULL);\r\n for (int Index = 0; Index < ScriptParameters->Count; Index++)\r\n {\r\n Command = ReplaceStr(Command, FORMAT(L\"%%%d%%\", (Index+1)),\r\n ScriptParameters->Strings[Index]);\r\n }\r\n\r\n TDateTime N = Now();\r\n\r\n if (!FExternalTimestampVar)\r\n {\r\n Command =\r\n ReplaceStr(Command, FORMAT(L\"%%%s%%\", (TimestampVarName)), FormatDateTime(L\"yyyymmddhhnnss\", N));\r\n }\r\n\r\n int Offset = 1;\r\n int P2;\r\n do\r\n {\r\n int P = Pos(UpperCase(L\"%\" + TimestampVarName), UpperCase(Command), Offset);\r\n if (P > 0)\r\n {\r\n Offset = P + 1 + TimestampVarName.Length();\r\n P2 = Pos(L\"%\", Command, Offset);\r\n int P3 = Pos(L\"#\", Command, Offset);\r\n if ((P2 > 0) && (P3 > 0) && (P3 < P2) &&\r\n ((P3 == Offset) || (Command[Offset] == L'+') || (Command[Offset] == L'-')))\r\n {\r\n bool Valid = true;\r\n TDateTime T = N;\r\n if (P3 > Offset)\r\n {\r\n bool Add = (Command[Offset] == L'+');\r\n Offset++;\r\n Valid = TryRelativeStrToDateTime(Command.SubString(Offset, P3 - Offset), T, Add);\r\n }\r\n\r\n Offset = P3 + 1;\r\n if (Valid)\r\n {\r\n UnicodeString TimestampFormat = Command.SubString(Offset, P2 - Offset);\r\n UnicodeString TimestampValue = FormatDateTime(TimestampFormat, T);\r\n Command = Command.SubString(1, P - 1) + TimestampValue + Command.SubString(P2 + 1, Command.Length() - P2);\r\n Offset = P + TimestampValue.Length();\r\n }\r\n }\r\n }\r\n else\r\n {\r\n P2 = 0;\r\n }\r\n }\r\n while (P2 > 0);\r\n\r\n Command = ExpandEnvironmentVariables(Command);\r\n return Command;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::Failed(bool & AnyError)\r\n{\r\n if (FScript != NULL)\r\n {\r\n FScript->Log(llMessage, L\"Failed\");\r\n }\r\n AnyError = true;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall TConsoleRunner::Run(const UnicodeString Session, TOptions * Options,\r\n TStrings * ScriptCommands, TStrings * ScriptParameters)\r\n{\r\n int ExitCode;\r\n try\r\n {\r\n bool AnyError = false;\r\n\r\n try\r\n {\r\n FScript = new TManagementScript(StoredSessions, FConsole->LimitedOutput());\r\n\r\n FScript->CopyParam = GUIConfiguration->DefaultCopyParam;\r\n FScript->SynchronizeParams = GUIConfiguration->SynchronizeParams;\r\n FScript->WantsProgress = FConsole->WantsProgress();\r\n FScript->OnPrint = ScriptPrint;\r\n FScript->OnPrintProgress = ScriptPrintProgress;\r\n FScript->OnInput = ScriptInput;\r\n FScript->OnTerminalPromptUser = ScriptTerminalPromptUser;\r\n FScript->OnShowExtendedException = ScriptShowExtendedException;\r\n FScript->OnTerminalQueryUser = ScriptTerminalQueryUser;\r\n FScript->OnQueryCancel = ScriptQueryCancel;\r\n FScript->OnSynchronizeStartStop = ScriptSynchronizeStartStop;\r\n FScript->OnProgress = ScriptProgress;\r\n FScript->Interactive = (ScriptCommands == NULL) && FConsole->Interactive();\r\n\r\n UpdateTitle();\r\n\r\n // everything until the first manually entered command is \"batch\"\r\n // (including opening session from command line and script file)\r\n FBatchScript = true;\r\n\r\n if (!Session.IsEmpty())\r\n {\r\n if (!FScript->Interactive)\r\n {\r\n PrintMessage(LoadStr(SCRIPT_CMDLINE_SESSION));\r\n }\r\n FCommandError = false;\r\n FScript->Connect(Session, Options, false);\r\n if (FCommandError)\r\n {\r\n Failed(AnyError);\r\n }\r\n }\r\n\r\n FScript->Groups = Options->SwitchValue(L\"xmlgroups\", true, false);\r\n\r\n int ScriptPos = 0;\r\n bool Result;\r\n do\r\n {\r\n UpdateTitle();\r\n\r\n UnicodeString Command;\r\n if ((ScriptCommands != NULL) && (ScriptPos < ScriptCommands->Count))\r\n {\r\n Result = true;\r\n Command = ScriptCommands->Strings[ScriptPos];\r\n ScriptPos++;\r\n }\r\n else\r\n {\r\n if (FBatchScript)\r\n {\r\n // no longer batch\r\n FBatchScript = false;\r\n FScript->StartInteractive();\r\n }\r\n Print(L\"winscp> \");\r\n Result = DoInput(Command, true, 0, false);\r\n }\r\n\r\n if (Result)\r\n {\r\n FCommandError = false;\r\n FScript->Command(ExpandCommand(Command, ScriptParameters));\r\n\r\n if (FCommandError)\r\n {\r\n Failed(AnyError);\r\n if (FScript->Batch == TScript::BatchAbort)\r\n {\r\n Result = false;\r\n }\r\n }\r\n\r\n if (FScript->Terminal != NULL)\r\n {\r\n FScript->Terminal->Idle();\r\n }\r\n }\r\n }\r\n while (Result && FScript->Continue && !Aborted());\r\n }\r\n catch(Exception & E)\r\n {\r\n Failed(AnyError);\r\n ShowException(&E);\r\n }\r\n\r\n if (FLastProgressLen > 0)\r\n {\r\n FConsole->Print(L\"\\n\");\r\n FLastProgressLen = 0;\r\n }\r\n\r\n ExitCode = (AnyError || FAborted) ? RESULT_ANY_ERROR : RESULT_SUCCESS;\r\n\r\n if (FScript != NULL)\r\n {\r\n UnicodeString ExitCodeMessage = FORMAT(L\"Exit code: %d\", (ExitCode));\r\n FScript->Log(llMessage, ExitCodeMessage);\r\n if (Configuration->LogProtocol >= 1)\r\n {\r\n FConsole->Print(ExitCodeMessage + L\"\\n\");\r\n UnicodeString LogMessage = FConsole->FinalLogMessage();\r\n if (!LogMessage.IsEmpty())\r\n {\r\n FScript->Log(llMessage, LogMessage);\r\n FConsole->Print(LogMessage + L\"\\n\");\r\n }\r\n }\r\n }\r\n }\r\n __finally\r\n {\r\n delete FScript;\r\n FScript = NULL;\r\n }\r\n\r\n return ExitCode;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::UpdateTitle()\r\n{\r\n UnicodeString NewTitle;\r\n if (FScript->Terminal != NULL)\r\n {\r\n NewTitle = FormatMainFormCaption(FScript->Terminal->SessionData->SessionName);\r\n }\r\n else\r\n {\r\n NewTitle = FormatMainFormCaption(L\"\");\r\n }\r\n FConsole->SetTitle(NewTitle);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ConfigurationChange(TObject * /*Sender*/)\r\n{\r\n if (FScript != NULL)\r\n {\r\n FScript->ReflectSettings();\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nstatic UnicodeString __fastcall GetExeBaseName()\r\n{\r\n return ExtractFileBaseName(Application->ExeName);\r\n}\r\n//---------------------------------------------------------------------------\r\nstatic void __fastcall PrintUsageSyntax(TConsole * Console, const UnicodeString & Str)\r\n{\r\n Console->PrintLine(GetExeBaseName() + L\" \" + Str);\r\n}\r\n//---------------------------------------------------------------------------\r\ntypedef std::vector<std::pair<UnicodeString, UnicodeString> > TSwitchesUsage;\r\n//---------------------------------------------------------------------------\r\nstatic void __fastcall RegisterSwitch(\r\n TSwitchesUsage & SwitchesUsage, const UnicodeString & Name, const UnicodeString & Desc)\r\n{\r\n SwitchesUsage.push_back(std::make_pair(LowerCase(Name), Desc));\r\n}\r\n//---------------------------------------------------------------------------\r\nstatic void __fastcall RegisterSwitch(\r\n TSwitchesUsage & SwitchesUsage, const UnicodeString & Name, int DescID)\r\n{\r\n UnicodeString Desc = LoadStr(DescID);\r\n Desc = ReplaceText(Desc, L\"%APP%\", GetExeBaseName());\r\n RegisterSwitch(SwitchesUsage, Name, Desc);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall Usage(TConsole * Console)\r\n{\r\n Console->PrintLine(FORMAT(L\"WinSCP, %s\", (Configuration->VersionStr)));\r\n UnicodeString Copyright =\r\n ReplaceText(LoadStr(WINSCP_COPYRIGHT), L\"©\", L\"(c)\");\r\n Console->PrintLine(Copyright);\r\n Console->PrintLine();\r\n Console->PrintLine(LoadStr(USAGE_SYNTAX_LABEL));\r\n\r\n if (!Console->CommandLineOnly())\r\n {\r\n PrintUsageSyntax(Console, L\"site|workspace|folder\");\r\n PrintUsageSyntax(Console, L\"(sftp|scp|ftp[es]|dav[s]|s3)://[user[:password]@]host[:port][/path/[file]]\");\r\n PrintUsageSyntax(Console, FORMAT(L\"[mysession] /%s=<name>\", (LowerCase(SESSIONNAME_SWICH))));\r\n PrintUsageSyntax(Console, L\"[mysession] /newinstance\");\r\n PrintUsageSyntax(Console, L\"[mysession] /edit <path>\");\r\n PrintUsageSyntax(Console, FORMAT(L\"[mysession] /%s[=<file>]\", (LowerCase(BROWSE_SWITCH))));\r\n PrintUsageSyntax(Console, FORMAT(L\"[mysession] /%s [local_dir] [remote_dir] [/%s]\", (LowerCase(SYNCHRONIZE_SWITCH), LowerCase(DEFAULTS_SWITCH))));\r\n PrintUsageSyntax(Console, FORMAT(L\"[mysession] /%s [local_dir] [remote_dir] [/%s]\", (LowerCase(KEEP_UP_TO_DATE_SWITCH), LowerCase(DEFAULTS_SWITCH))));\r\n PrintUsageSyntax(Console, FORMAT(L\"[mysession] /%s [path]\", (LowerCase(REFRESH_SWITCH))));\r\n PrintUsageSyntax(Console, FORMAT(L\"[mysession] [/privatekey=<file> [/%s=<passphrase>]]\", (PassphraseOption)));\r\n PrintUsageSyntax(Console, L\"[mysession] [/hostkey=<fingerprint>]\");\r\n PrintUsageSyntax(Console, FORMAT(L\"[mysession] [/clientcert=<file> [/%s=<passphrase>]]\", (PassphraseOption)));\r\n PrintUsageSyntax(Console, L\"[mysession] [/certificate=<fingerprint>]\");\r\n PrintUsageSyntax(Console, L\"[mysession] [/passive[=on|off]] [/implicit|explicit]\");\r\n PrintUsageSyntax(Console, L\"[mysession] [/timeout=<sec>]\");\r\n PrintUsageSyntax(Console, L\"[mysession] [/rawsettings setting1=value1 setting2=value2 ...]\");\r\n }\r\n PrintUsageSyntax(Console,\r\n UnicodeString(!Console->CommandLineOnly() ? L\"[/console] \" : L\"\") +\r\n FORMAT(L\"[/script=<file>] [/%s cmd1...] [/parameter // param1...]\", (LowerCase(COMMAND_SWITCH))));\r\n PrintUsageSyntax(Console,\r\n FORMAT(L\"[/%s=<logfile> [/loglevel=<level>]] [/%s=[<count>%s]<size>]\", (LowerCase(LOG_SWITCH), LowerCase(LOGSIZE_SWITCH), LOGSIZE_SEPARATOR)));\r\n PrintUsageSyntax(Console, L\"[/xmllog=<logfile> [/xmlgroups]]\");\r\n PrintUsageSyntax(Console,\r\n FORMAT(L\"[/%s=<inifile>]\", (LowerCase(INI_SWITCH))));\r\n PrintUsageSyntax(Console, FORMAT(L\"[/%s config1=value1 config2=value2 ...]\", (LowerCase(RAW_CONFIG_SWITCH))));\r\n PrintUsageSyntax(Console, FORMAT(L\"[/%s setting1=value1 setting2=value2 ...]\", (LowerCase(RAWTRANSFERSETTINGS_SWITCH))));\r\n PrintUsageSyntax(Console, L\"/batchsettings <site_mask> setting1=value1 setting2=value2 ...\");\r\n PrintUsageSyntax(Console, FORMAT(L\"/%s keyfile [/%s=<file>] [/%s] [/%s=<text>]\",\r\n (LowerCase(KEYGEN_SWITCH), LowerCase(KEYGEN_OUTPUT_SWITCH), LowerCase(KEYGEN_CHANGE_PASSPHRASE_SWITCH), LowerCase(KEYGEN_COMMENT_SWITCH))));\r\n if (!Console->CommandLineOnly())\r\n {\r\n PrintUsageSyntax(Console, L\"/update\");\r\n }\r\n PrintUsageSyntax(Console, TProgramParams::FormatSwitch(LowerCase(INFO_SWITCH)));\r\n PrintUsageSyntax(Console, L\"/help\");\r\n\r\n Console->PrintLine();\r\n\r\n TSwitchesUsage SwitchesUsage;\r\n if (!Console->CommandLineOnly())\r\n {\r\n RegisterSwitch(SwitchesUsage, L\"session\", USAGE_SESSION);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(SESSIONNAME_SWICH) + L\"=\", USAGE_SESSIONNAME);\r\n RegisterSwitch(SwitchesUsage, L\"/newinstance\", USAGE_NEWINSTANCE);\r\n RegisterSwitch(SwitchesUsage, L\"/edit\", USAGE_EDIT);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(BROWSE_SWITCH), USAGE_BROWSE);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH), USAGE_SYNCHRONIZE);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH), USAGE_KEEPUPTODATE);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(REFRESH_SWITCH), USAGE_REFRESH);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(DEFAULTS_SWITCH), USAGE_DEFAULTS);\r\n RegisterSwitch(SwitchesUsage, L\"/privatekey=\", USAGE_PRIVATEKEY);\r\n RegisterSwitch(SwitchesUsage, L\"/hostkey=\", USAGE_HOSTKEY);\r\n RegisterSwitch(SwitchesUsage, L\"/clientcert=\", USAGE_CLIENTCERT);\r\n RegisterSwitch(SwitchesUsage, L\"/certificate=\", USAGE_CERTIFICATE);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(PassphraseOption) + L\"=\", USAGE_PASSPHRASE);\r\n RegisterSwitch(SwitchesUsage, L\"/passive=\", USAGE_PASSIVE);\r\n RegisterSwitch(SwitchesUsage, L\"/implicit\", USAGE_IMPLICIT);\r\n RegisterSwitch(SwitchesUsage, L\"/explicit\", USAGE_EXPLICIT);\r\n RegisterSwitch(SwitchesUsage, L\"/timeout=\", USAGE_TIMEOUT);\r\n RegisterSwitch(SwitchesUsage, L\"/rawsettings\", USAGE_RAWSETTINGS);\r\n RegisterSwitch(SwitchesUsage, L\"/console\", USAGE_CONSOLE);\r\n }\r\n RegisterSwitch(SwitchesUsage, L\"/script=\", USAGE_SCRIPT);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(COMMAND_SWITCH), USAGE_COMMAND);\r\n RegisterSwitch(SwitchesUsage, L\"/parameter\", USAGE_PARAMETER);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(LOG_SWITCH) + L\"=\", USAGE_LOG);\r\n RegisterSwitch(SwitchesUsage, L\"/loglevel=\", USAGE_LOGLEVEL);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(LOGSIZE_SWITCH) + L\"=\", USAGE_LOGSIZE);\r\n RegisterSwitch(SwitchesUsage, L\"/xmllog=\", USAGE_XMLLOG);\r\n RegisterSwitch(SwitchesUsage, L\"/xmlgroups\", USAGE_XMLGROUPS);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(INI_SWITCH) + L\"=\", USAGE_INI);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(RAW_CONFIG_SWITCH), USAGE_RAWCONFIG);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), USAGE_RAWTRANSFERSETTINGS);\r\n RegisterSwitch(SwitchesUsage, L\"/batchsettings\", USAGE_BATCHSETTINGS);\r\n UnicodeString KeyGenDesc =\r\n FMTLOAD(USAGE_KEYGEN, (\r\n TProgramParams::FormatSwitch(LowerCase(KEYGEN_OUTPUT_SWITCH)) + L\"=\",\r\n TProgramParams::FormatSwitch(LowerCase(KEYGEN_CHANGE_PASSPHRASE_SWITCH)),\r\n TProgramParams::FormatSwitch(LowerCase(KEYGEN_COMMENT_SWITCH)) + L\"=\"));\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(KEYGEN_SWITCH), KeyGenDesc);\r\n if (!Console->CommandLineOnly())\r\n {\r\n RegisterSwitch(SwitchesUsage, L\"/update\", USAGE_UPDATE);\r\n }\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(INFO_SWITCH), USAGE_INFO);\r\n RegisterSwitch(SwitchesUsage, L\"/help\", USAGE_HELP);\r\n\r\n int MaxSwitchLen = 0;\r\n TSwitchesUsage::const_iterator Index = SwitchesUsage.begin();\r\n while (Index != SwitchesUsage.end())\r\n {\r\n MaxSwitchLen = std::max(Index->first.Length(), MaxSwitchLen);\r\n ++Index;\r\n }\r\n\r\n Index = SwitchesUsage.begin();\r\n while (Index != SwitchesUsage.end())\r\n {\r\n UnicodeString Label =\r\n UnicodeString(L\" \") +\r\n Index->first +\r\n UnicodeString::StringOfChar(L' ', MaxSwitchLen - Index->first.Length()) +\r\n L\" \";\r\n Console->Print(Label);\r\n\r\n const int ConsoleWidth = 80;\r\n int DescWidth = ConsoleWidth - Label.Length() - 1;\r\n\r\n bool FirstLine = true;\r\n UnicodeString Desc = Index->second;\r\n while (!Desc.IsEmpty())\r\n {\r\n UnicodeString DescLine = CutToChar(Desc, L'\\n', true);\r\n DescLine = WrapText(DescLine, L\"\\n\", TSysCharSet() << L' ', DescWidth);\r\n while (!DescLine.IsEmpty())\r\n {\r\n UnicodeString DescLineLine = CutToChar(DescLine, L'\\n', true);\r\n if (!FirstLine)\r\n {\r\n DescLineLine =\r\n UnicodeString::StringOfChar(L' ', Label.Length()) +\r\n DescLineLine;\r\n }\r\n FirstLine = false;\r\n Console->PrintLine(DescLineLine);\r\n }\r\n }\r\n ++Index;\r\n }\r\n\r\n Console->WaitBeforeExit();\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall HandleException(TConsole * Console, Exception & E)\r\n{\r\n UnicodeString Message;\r\n if (ExceptionFullMessage(&E, Message))\r\n {\r\n Console->Print(Message);\r\n }\r\n return RESULT_ANY_ERROR;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall BatchSettings(TConsole * Console, TProgramParams * Params)\r\n{\r\n int Result = RESULT_SUCCESS;\r\n try\r\n {\r\n std::unique_ptr<TStrings> Arguments(new TStringList());\r\n if (!DebugAlwaysTrue(Params->FindSwitch(L\"batchsettings\", Arguments.get())))\r\n {\r\n Abort();\r\n }\r\n else\r\n {\r\n if (Arguments->Count < 1)\r\n {\r\n throw Exception(LoadStr(BATCH_SET_NO_MASK));\r\n }\r\n else if (Arguments->Count < 2)\r\n {\r\n throw Exception(LoadStr(BATCH_SET_NO_SETTINGS));\r\n }\r\n else\r\n {\r\n TFileMasks Mask(Arguments->Strings[0]);\r\n Arguments->Delete(0);\r\n\r\n std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Arguments.get(), false));\r\n\r\n int Matches = 0;\r\n int Changes = 0;\r\n\r\n for (int Index = 0; Index < StoredSessions->Count; Index++)\r\n {\r\n TSessionData * Data = StoredSessions->Sessions[Index];\r\n if (!Data->IsWorkspace &&\r\n Mask.Matches(Data->Name, false, false))\r\n {\r\n Matches++;\r\n std::unique_ptr<TSessionData> OriginalData(new TSessionData(L\"\"));\r\n OriginalData->CopyDataNoRecrypt(Data);\r", " Data->ApplyRawSettings(OptionsStorage.get());\r", " bool Changed = !OriginalData->IsSame(Data, false);\r\n if (Changed)\r\n {\r\n Changes++;\r\n }\r\n UnicodeString StateStr = LoadStr(Changed ? BATCH_SET_CHANGED : BATCH_SET_NOT_CHANGED);\r\n Console->PrintLine(FORMAT(L\"%s - %s\", (Data->Name, StateStr)));\r\n }\r\n }\r\n\r\n StoredSessions->Save(false, true); // explicit\r\n Console->PrintLine(FMTLOAD(BATCH_SET_SUMMARY, (Matches, Changes)));\r\n }\r\n }\r\n }\r\n catch (Exception & E)\r\n {\r\n Result = HandleException(Console, E);\r\n }\r\n\r\n Console->WaitBeforeExit();\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall FindPuttygenCompatibleSwitch(\r\n TProgramParams * Params, const UnicodeString & Name, const UnicodeString & PuttygenName, UnicodeString & Value, bool & Set)\r\n{\r\n bool Result = Params->FindSwitch(Name, Value, Set);\r\n if (!Result)\r\n {\r\n std::unique_ptr<TStrings> Args(new TStringList());\r\n Result = Params->FindSwitchCaseSensitive(PuttygenName, Args.get(), 1);\r\n if (Result && (Args->Count >= 1))\r\n {\r\n Value = Args->Strings[0];\r\n Set = true;\r\n }\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall KeyGen(TConsole * Console, TProgramParams * Params)\r\n{\r\n int Result = RESULT_SUCCESS;\r\n UnicodeString Passphrase;\r\n UnicodeString NewPassphrase;\r\n try\r\n {\r\n UnicodeString InputFileName;\r\n std::unique_ptr<TStrings> Args(new TStringList());\r\n if (!Params->FindSwitch(KEYGEN_SWITCH, Args.get(), 1) ||\r\n (Args->Count < 1) ||\r\n Args->Strings[0].IsEmpty())\r\n {\r\n throw Exception(LoadStr(KEYGEN_NO_INPUT));\r\n }\r\n InputFileName = Args->Strings[0];\r\n\r\n bool ValueSet;\r\n UnicodeString OutputFileName;\r\n FindPuttygenCompatibleSwitch(Params, KEYGEN_OUTPUT_SWITCH, L\"o\", OutputFileName, ValueSet);\r\n\r\n UnicodeString NewComment;\r\n FindPuttygenCompatibleSwitch(Params, KEYGEN_COMMENT_SWITCH, L\"C\", NewComment, ValueSet);\r\n\r\n bool NewPassphraseSet;\r\n bool ChangePassphrase =\r\n FindPuttygenCompatibleSwitch(Params, KEYGEN_CHANGE_PASSPHRASE_SWITCH, L\"P\", NewPassphrase, NewPassphraseSet);\r\n\r\n TKeyType Type = KeyType(InputFileName);\r\n int Error = errno;\r\n switch (Type)\r\n {\r\n case ktSSH1:\r\n throw Exception(LoadStr(KEYGEN_SSH1));\r\n\r\n case ktSSH2:\r\n if (NewComment.IsEmpty() && !ChangePassphrase)\r\n {\r\n throw Exception(LoadStr(KEYGEN_NO_ACTION));\r\n }\r\n break;\r\n\r\n case ktOpenSSHPEM:\r\n case ktOpenSSHNew:\r\n case ktSSHCom:\r\n if (OutputFileName.IsEmpty())\r\n {\r\n throw Exception(LoadStr(KEYGEN_NO_OUTPUT));\r\n }\r\n break;\r\n\r\n case ktSSH1Public:\r\n case ktSSH2PublicRFC4716:\r\n case ktSSH2PublicOpenSSH:\r\n throw Exception(LoadStr(KEYGEN_PUBLIC));\r\n\r\n case ktUnopenable:\r\n throw EOSExtException(FMTLOAD(KEY_TYPE_UNOPENABLE, (InputFileName)), Error);\r\n\r\n case ktOpenSSHAuto:\r\n default:\r\n DebugFail();\r\n // fallthru\r\n case ktUnknown:\r\n throw Exception(FMTLOAD(KEY_TYPE_UNKNOWN2, (InputFileName)));\r\n }\r\n\r\n UnicodeString Comment;\r\n if (IsKeyEncrypted(Type, InputFileName, Comment))\r\n {\r\n Passphrase = Params->SwitchValue(PassphraseOption);\r\n if (Passphrase.IsEmpty())\r\n {\r\n Console->Print(StripHotkey(FMTLOAD(PROMPT_KEY_PASSPHRASE, (Comment))) + L\" \");\r\n if (!Console->Input(Passphrase, false, 0) ||\r\n Passphrase.IsEmpty())\r\n {\r\n Abort();\r\n }\r\n }\r\n }\r\n\r\n TPrivateKey * PrivateKey = LoadKey(Type, InputFileName, Passphrase);\r\n\r\n try\r\n {\r\n if (!NewComment.IsEmpty())\r\n {\r\n ChangeKeyComment(PrivateKey, NewComment);\r\n }\r\n\r\n if (ChangePassphrase)\r\n {\r\n if (!NewPassphraseSet)\r\n {\r\n Console->Print(LoadStr(KEYGEN_PASSPHRASE) + L\" \");\r\n if (!Console->Input(NewPassphrase, false, 0))\r\n {\r\n Abort();\r\n }\r\n\r\n Console->Print(LoadStr(KEYGEN_PASSPHRASE2) + L\" \");\r\n UnicodeString NewPassphrase2;\r\n if (!Console->Input(NewPassphrase2, false, 0))\r\n {\r\n Abort();\r\n }\r\n\r\n if (NewPassphrase != NewPassphrase2)\r\n {\r\n Shred(NewPassphrase2);\r\n throw Exception(LoadStr(KEYGEN_PASSPHRASES_MISMATCH));\r\n }\r\n }\r\n }\r\n else\r\n {\r\n NewPassphrase = Passphrase;\r\n }\r\n\r\n if (OutputFileName.IsEmpty())\r\n {\r\n OutputFileName = InputFileName;\r\n }\r\n\r\n SaveKey(ktSSH2, OutputFileName, NewPassphrase, PrivateKey);\r\n\r\n Console->PrintLine(FMTLOAD(KEYGEN_SAVED, (OutputFileName)));\r\n }\r\n __finally\r\n {\r\n FreeKey(PrivateKey);\r\n }\r\n }\r\n catch (Exception & E)\r\n {\r\n Result = HandleException(Console, E);\r\n }\r\n\r\n Shred(Passphrase);\r\n Shred(NewPassphrase);\r\n\r\n Console->WaitBeforeExit();\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall FingerprintScan(TConsole * Console, TProgramParams * Params)\r\n{\r\n int Result = RESULT_SUCCESS;\r\n try\r\n {\r\n CheckLogParam(Params);\r\n\r\n std::unique_ptr<TSessionData> SessionData;\r\n\r\n if (Params->ParamCount > 0)\r\n {\r\n UnicodeString SessionUrl = Params->Param[1];\r\n bool DefaultsOnly;\r\n SessionData.reset(StoredSessions->ParseUrl(SessionUrl, Params, DefaultsOnly));\r\n if (DefaultsOnly || !SessionData->CanLogin ||\r\n (!SessionData->UsesSsh && (SessionData->Ftps == ftpsNone)))\r\n {\r\n SessionData.reset(NULL);\r\n }\r\n }\r\n\r\n if (!SessionData)\r\n {\r\n throw Exception(LoadStr(FINGERPRINTSCAN_NEED_SECURE_SESSION));\r\n }\r\n\r\n std::unique_ptr<TTerminal> Terminal(new TTerminal(SessionData.get(), Configuration));\r\n UnicodeString SHA256;\r\n UnicodeString SHA1;\r\n UnicodeString MD5;\r\n Terminal->FingerprintScan(SHA256, SHA1, MD5);\r\n if (!SHA256.IsEmpty())\r\n {\r\n Console->PrintLine(FORMAT(L\"SHA-256: %s\", (SHA256)));\r\n }\r\n if (!SHA1.IsEmpty())\r\n {\r\n Console->PrintLine(FORMAT(L\"SHA-1: %s\", (SHA1)));\r\n }\r\n if (!MD5.IsEmpty())\r\n {\r\n Console->PrintLine(FORMAT(L\"MD5: %s\", (MD5)));\r\n }\r\n }\r\n catch (Exception & E)\r\n {\r\n Result = HandleException(Console, E);\r\n }\r\n\r\n Console->WaitBeforeExit();\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall DumpCallstack(TConsole * Console, TProgramParams * Params)\r\n{\r\n int Result = RESULT_SUCCESS;\r\n try\r\n {\r\n int ProcessId = StrToInt(Params->SwitchValue(DUMPCALLSTACK_SWITCH));\r\n UnicodeString EventName = DumpCallstackEventName(ProcessId);\r\n UnicodeString FileName = DumpCallstackFileName(ProcessId);\r\n if (FileExists(FileName))\r\n {\r\n DeleteFileChecked(FileName);\r\n }\r\n\r\n HANDLE Event = OpenEvent(EVENT_ALL_ACCESS, false, EventName.c_str());\r\n if (Event == NULL)\r\n {\r\n throw ExtException(FORMAT(L\"Error communicating with process %d.\", (ProcessId)), LastSysErrorMessage());\r\n }\r\n\r\n SetEvent(Event);\r\n CloseHandle(Event);\r\n\r\n Console->PrintLine(FORMAT(L\"Requested callstack dump for process %d...\", (ProcessId)));\r\n\r\n int Timeout = 30;\r\n while (!FileExists(FileName))\r\n {\r\n Sleep(1000);\r\n Timeout--;\r\n if (Timeout == 0)\r\n {\r\n throw Exception(L\"Timeout\");\r\n }\r\n }\r\n\r\n Console->PrintLine(FORMAT(L\"Callstack dumped to file \\\"%s\\\".\", (FileName)));\r\n }\r\n catch (Exception & E)\r\n {\r\n Result = HandleException(Console, E);\r\n }\r\n\r\n Console->WaitBeforeExit();\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid static PrintList(TConsole * Console, const UnicodeString & Caption, TStrings * List)\r\n{\r\n Console->PrintLine(Caption);\r\n for (int Index = 0; Index < List->Count; Index++)\r\n {\r\n Console->PrintLine(List->Strings[Index]);\r\n }\r\n Console->PrintLine();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid static PrintListAndFree(TConsole * Console, const UnicodeString & Caption, TStrings * List)\r\n{\r\n std::unique_ptr<TStrings> Owner(List);\r\n PrintList(Console, Caption, List);\r\n}\r\n//---------------------------------------------------------------------------\r\nint Info(TConsole * Console)\r\n{\r\n int Result = RESULT_SUCCESS;\r\n try\r\n {\r\n PrintListAndFree(Console, L\"SSH encryption ciphers:\", SshCipherList());\r\n PrintListAndFree(Console, L\"SSH key exchange algorithms:\", SshKexList());\r\n PrintListAndFree(Console, L\"SSH host key algorithms:\", SshHostKeyList());\r\n PrintListAndFree(Console, L\"SSH MAC algorithms:\", SshMacList());\r\n PrintListAndFree(Console, L\"TLS/SSL cipher suites:\", TlsCipherList());\r\n }\r\n catch (Exception & E)\r\n {\r\n Result = HandleException(Console, E);\r\n }\r\n\r\n Console->WaitBeforeExit();\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall Console(TConsoleMode Mode)\r\n{\r\n DebugAssert(Mode != cmNone);\r\n TProgramParams * Params = TProgramParams::Instance();\r\n int Result = RESULT_SUCCESS;\r\n TConsole * Console = NULL;\r\n TConsoleRunner * Runner = NULL;\r\n TStrings * ScriptCommands = new TStringList();\r\n TStrings * ScriptParameters = new TStringList();\r\n try\r\n {\r\n UnicodeString ConsoleInstance;\r\n // First check for /consoleinstance as /console is always used by winscp.com\r\n if (Params->FindSwitch(L\"consoleinstance\", ConsoleInstance))\r\n {\r\n Configuration->Usage->Inc(L\"ConsoleExternal\");\r\n Console = new TExternalConsole(ConsoleInstance, Params->FindSwitch(L\"nointeractiveinput\"));\r\n }\r\n else if (Params->FindSwitch(L\"Console\") || (Mode != cmScripting))\r\n {\r\n Configuration->Usage->Inc(L\"ConsoleOwn\");\r\n Console = TOwnConsole::Instance();\r\n }\r\n else\r\n {\r\n Configuration->Usage->Inc(L\"ConsoleNull\");\r\n Console = new TNullConsole();\r\n }\r\n\r\n SetNoGUI();\r\n\r\n if (Mode == cmHelp)\r\n {\r\n Configuration->Usage->Inc(L\"UsageShown\");\r\n Usage(Console);\r\n }\r\n else if (Mode == cmBatchSettings)\r\n {\r\n if (CheckSafe(Params))\r\n {\r\n Configuration->Usage->Inc(L\"BatchSettings\");\r\n Result = BatchSettings(Console, Params);\r\n }\r\n }\r\n else if (Mode == cmKeyGen)\r\n {\r\n if (CheckSafe(Params))\r\n {\r\n Configuration->Usage->Inc(L\"KeyGen\");\r\n Result = KeyGen(Console, Params);\r\n }\r\n }\r\n else if (Mode == cmFingerprintScan)\r\n {\r\n if (CheckSafe(Params))\r\n {\r\n Configuration->Usage->Inc(L\"FingerprintScan\");\r\n Result = FingerprintScan(Console, Params);\r\n }\r\n }\r\n else if (Mode == cmDumpCallstack)\r\n {\r\n Result = DumpCallstack(Console, Params);\r\n }\r\n else if (Mode == cmInfo)\r\n {\r\n Result = Info(Console);\r\n }\r\n else if (Mode == cmComRegistration)\r\n {\r\n if (CheckSafe(Params))\r\n {\r\n Result = ComRegistration(Console);\r\n }\r\n }\r\n else\r\n {\r\n Runner = new TConsoleRunner(Console);\r\n\r\n try\r\n {\r\n if (CheckSafe(Params))\r\n {\r\n UnicodeString Value;\r\n if (Params->FindSwitch(SCRIPT_SWITCH, Value) && !Value.IsEmpty())\r\n {\r\n Configuration->Usage->Inc(L\"ScriptFile\");\r\n LoadScriptFromFile(Value, ScriptCommands);\r\n }\r\n Params->FindSwitch(COMMAND_SWITCH, ScriptCommands);\r\n if (ScriptCommands->Count > 0)\r\n {\r\n Configuration->Usage->Inc(L\"ScriptCommands\");\r\n }\r\n Params->FindSwitch(L\"parameter\", ScriptParameters);\r\n if (ScriptParameters->Count > 0)\r\n {\r\n Configuration->Usage->Inc(L\"ScriptParameters\");\r\n }\r\n }\r\n\r\n UnicodeString Session;\r\n if (Params->ParamCount >= 1)\r\n {\r\n Session = Params->Param[1];\r\n if (Params->ParamCount > 1)\r\n {\r\n Runner->PrintMessage(LoadStr(SCRIPT_CMDLINE_PARAMETERS));\r\n }\r\n }\r\n\r\n CheckLogParam(Params);\r\n CheckXmlLogParam(Params);\r\n\r\n Result = Runner->Run(Session, Params,\r\n (ScriptCommands->Count > 0 ? ScriptCommands : NULL),\r\n ScriptParameters);\r\n }\r\n catch(Exception & E)\r\n {\r\n Runner->ShowException(&E);\r\n Result = RESULT_ANY_ERROR;\r\n }\r\n }\r\n }\r\n __finally\r\n {\r\n delete Runner;\r\n delete Console;\r\n delete ScriptCommands;\r\n delete ScriptParameters;\r\n }\r\n\r\n return Result;\r\n}" ]
[ 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 53, 80, 2275, 473, 1511, 2372, 1100], "buggy_code_start_loc": [46, 52, 79, 599, 57, 1510, 2371, 1099], "filenames": ["source/Console.cbproj", "source/DragExt.cbproj", "source/WinSCP.cbproj", "source/core/SessionData.cpp", "source/core/SessionData.h", "source/forms/Custom.cpp", "source/windows/ConsoleRunner.cpp", "source/windows/WinMain.cpp"], "fixing_code_end_loc": [47, 53, 80, 2294, 474, 1511, 2372, 1103], "fixing_code_start_loc": [46, 52, 79, 599, 58, 1510, 2371, 1099], "message": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:winscp:winscp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C081564B-8EF8-4C8A-9EB0-1C50D5A8F18B", "versionEndExcluding": "5.17.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)"}, {"lang": "es", "value": "WinSCP anterior a la versi\u00f3n 5.17.10 permite a los atacantes remotos ejecutar programas arbitrarios cuando el manejador de URLs encuentra una URL manipulada que carga la configuraci\u00f3n de la sesi\u00f3n. (Por ejemplo, esto es explotable en una instalaci\u00f3n por defecto en la que WinSCP es el manejador de URLs sftp://)"}], "evaluatorComment": null, "id": "CVE-2021-3331", "lastModified": "2021-02-04T15:59:24.960", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-01-27T21:15:16.840", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://winscp.net/eng/docs/history#5.17.10"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://winscp.net/eng/docs/rawsettings"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://winscp.net/tracker/1943"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, "type": "NVD-CWE-Other"}
177
Determine whether the {function_name} code is vulnerable or not.
[ "//---------------------------------------------------------------------------\r\n#include <vcl.h>\r\n#pragma hdrstop\r\n\r\n#include <Common.h>\r\n#include <Exceptions.h>\r\n#include <Script.h>\r\n#include <CoreMain.h>\r\n#include <Terminal.h>\r\n#include <PuttyTools.h>\r\n#include <Queue.h>\r\n#include <HierarchicalStorage.h>\r\n#include <Tools.h>\r\n\r\n#include <Consts.hpp>\r\n#include <StrUtils.hpp>\r\n\r\n#include \"Console.h\"\r\n#include \"WinInterface.h\"\r\n#include \"ProgParams.h\"\r\n#include \"TextsWin.h\"\r\n#include \"TextsCore.h\"\r\n#include \"WinConfiguration.h\"\r\n#include \"SynchronizeController.h\"\r\n#include \"GUITools.h\"\r\n#include \"VCLCommon.h\"\r\n#include \"Setup.h\"\r\n//---------------------------------------------------------------------------\r\n#define WM_INTERUPT_IDLE (WM_WINSCP_USER + 3)\r\n#define BATCH_INPUT_TIMEOUT 10000\r\n//---------------------------------------------------------------------------\r\n#pragma package(smart_init)\r\n//---------------------------------------------------------------------------\r\nvoid TrimNewLine(UnicodeString & Str)\r\n{\r\n while (!Str.IsEmpty() &&\r\n ((Str[Str.Length()] == L'\\n') || (Str[Str.Length()] == L'\\r')))\r\n {\r\n Str.SetLength(Str.Length() - 1);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsole::PrintLine(const UnicodeString & Str, bool Error)\r\n{\r\n Print(Str + L\"\\n\", false, Error);\r\n};\r\n//---------------------------------------------------------------------------\r\nclass TOwnConsole : public TConsole\r\n{\r\npublic:\r\n static TOwnConsole * __fastcall Instance();\r\n\r\n virtual void __fastcall Print(UnicodeString Str, bool FromBeginning = false, bool Error = false);\r\n virtual bool __fastcall Input(UnicodeString & Str, bool Echo, unsigned int Timer);\r\n virtual int __fastcall Choice(\r\n UnicodeString Options, int Cancel, int Break, int Continue, int Timeouted, bool Timeouting, unsigned int Timer,\r\n UnicodeString Message);\r\n virtual bool __fastcall PendingAbort();\r\n virtual void __fastcall SetTitle(UnicodeString Title);\r\n virtual bool __fastcall LimitedOutput();\r\n virtual bool __fastcall LiveOutput();\r\n virtual bool __fastcall NoInteractiveInput();\r\n virtual bool __fastcall Interactive();\r\n virtual void __fastcall WaitBeforeExit();\r\n virtual bool __fastcall CommandLineOnly();\r\n virtual bool __fastcall WantsProgress();\r\n virtual void __fastcall Progress(TScriptProgress & Progress);\r\n virtual UnicodeString __fastcall FinalLogMessage();\r\n\r\nprotected:\r\n static TOwnConsole * FInstance;\r\n friend class TConsoleInputThread;\r\n\r\n __fastcall TOwnConsole();\r\n virtual __fastcall ~TOwnConsole();\r\n\r\n void __fastcall BreakInput();\r\n void __fastcall CancelInput();\r\n static BOOL WINAPI HandlerRoutine(DWORD CtrlType);\r\n void __fastcall WindowStateTimer(TObject * Sender);\r\n void __fastcall ProcessMessages();\r\n void __fastcall TrayIconClick(TObject * Sender);\r\n\r\nprivate:\r\n HANDLE FInput;\r\n HANDLE FOutput;\r\n HWND FConsoleWindow;\r\n TTimer * FWindowStateTimer;\r\n bool FMinimized;\r\n ::TTrayIcon * FTrayIcon;\r\n static std::unique_ptr<TCriticalSection> FSection;\r\n\r\n bool FPendingAbort;\r\n};\r\n//---------------------------------------------------------------------------\r\nTOwnConsole * TOwnConsole::FInstance = NULL;\r\nstd::unique_ptr<TCriticalSection> TOwnConsole::FSection(TraceInitPtr(new TCriticalSection()));\r\n//---------------------------------------------------------------------------\r\n__fastcall TOwnConsole::TOwnConsole()\r\n{\r\n DebugAssert(FInstance == NULL);\r\n FInstance = this;\r\n\r\n AllocConsole();\r\n SetConsoleCtrlHandler(HandlerRoutine, true);\r\n\r\n FInput = GetStdHandle(STD_INPUT_HANDLE);\r\n FOutput = GetStdHandle(STD_OUTPUT_HANDLE);\r\n FPendingAbort = false;\r\n FConsoleWindow = NULL;\r\n FWindowStateTimer = NULL;\r\n FMinimized = false;\r\n FTrayIcon = new ::TTrayIcon(0);\r\n FTrayIcon->OnClick = TrayIconClick;\r\n\r\n if (WinConfiguration->MinimizeToTray)\r\n {\r\n FConsoleWindow = GetConsoleWindow();\r\n if (DebugAlwaysTrue(FConsoleWindow != NULL))\r\n {\r\n FWindowStateTimer = new TTimer(Application);\r\n FWindowStateTimer->OnTimer = WindowStateTimer;\r\n FWindowStateTimer->Interval = 250;\r\n FWindowStateTimer->Enabled = true;\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\n__fastcall TOwnConsole::~TOwnConsole()\r\n{\r\n TGuard Guard(FSection.get());\r\n\r\n delete FTrayIcon;\r\n delete FWindowStateTimer;\r\n\r\n // deliberately do not remove ConsoleCtrlHandler as it causes\r\n // failures while exiting\r\n\r\n FreeConsole();\r\n\r\n DebugAssert(FInstance == this);\r\n FInstance = NULL;\r\n}\r\n//---------------------------------------------------------------------------\r\nTOwnConsole * __fastcall TOwnConsole::Instance()\r\n{\r\n return new TOwnConsole();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::WindowStateTimer(TObject * /*Sender*/)\r\n{\r\n DebugAssert(FConsoleWindow != NULL);\r\n WINDOWPLACEMENT Placement;\r\n memset(&Placement, 0, sizeof(Placement));\r\n Placement.length = sizeof(Placement);\r\n if (GetWindowPlacement(FConsoleWindow, &Placement))\r\n {\r\n bool Minimized = (Placement.showCmd == SW_SHOWMINIMIZED);\r\n if (FMinimized != Minimized)\r\n {\r\n FMinimized = Minimized;\r\n\r\n if (FMinimized && WinConfiguration->MinimizeToTray)\r\n {\r\n FTrayIcon->Visible = true;\r\n ShowWindow(FConsoleWindow, SW_HIDE);\r\n }\r\n else\r\n {\r\n FTrayIcon->Visible = false;\r\n ShowWindow(FConsoleWindow, SW_SHOW);\r\n }\r\n }\r\n }\r\n else\r\n {\r\n DebugFail();\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::ProcessMessages()\r\n{\r\n // as of now, there's no point doing this unless we have icon tray\r\n // (i.e. we need to monitor window state and eventually process tray icon messages)\r\n if (FWindowStateTimer != NULL)\r\n {\r\n DebugAssert(WinConfiguration->MinimizeToTray);\r\n\r\n Application->ProcessMessages();\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::TrayIconClick(TObject * /*Sender*/)\r\n{\r\n DebugAssert(FConsoleWindow != NULL);\r\n SetForegroundWindow(FConsoleWindow);\r\n ShowWindow(FConsoleWindow, SW_RESTORE);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::BreakInput()\r\n{\r\n FlushConsoleInputBuffer(FInput);\r\n INPUT_RECORD InputRecord;\r\n memset(&InputRecord, 0, sizeof(InputRecord));\r\n InputRecord.EventType = KEY_EVENT;\r\n InputRecord.Event.KeyEvent.bKeyDown = true;\r\n InputRecord.Event.KeyEvent.wRepeatCount = 1;\r\n InputRecord.Event.KeyEvent.uChar.UnicodeChar = L'\\r';\r\n\r\n unsigned long Written;\r\n // this assertion occasionally fails (when console is being exited)\r\n DebugCheck(WriteConsoleInput(FInput, &InputRecord, 1, &Written));\r\n DebugAssert(Written == 1);\r\n\r\n CancelInput();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::CancelInput()\r\n{\r\n FPendingAbort = true;\r\n\r\n PostMessage(Application->Handle, WM_INTERUPT_IDLE, 0, 0);\r\n}\r\n//---------------------------------------------------------------------------\r\nBOOL WINAPI TOwnConsole::HandlerRoutine(DWORD CtrlType)\r\n{\r\n if ((CtrlType == CTRL_C_EVENT) || (CtrlType == CTRL_BREAK_EVENT))\r\n {\r\n {\r\n TGuard Guard(FSection.get());\r\n\r\n // just to be real thread-safe\r\n if (FInstance != NULL)\r\n {\r\n FInstance->CancelInput();\r\n }\r\n }\r\n\r\n return true;\r\n }\r\n else\r\n {\r\n return false;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TOwnConsole::PendingAbort()\r\n{\r\n if (FPendingAbort)\r\n {\r\n FPendingAbort = false;\r\n return true;\r\n }\r\n else\r\n {\r\n return FPendingAbort;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::Print(UnicodeString Str, bool FromBeginning, bool /*Error*/)\r\n{\r\n if (FromBeginning)\r\n {\r\n CONSOLE_SCREEN_BUFFER_INFO BufferInfo;\r\n GetConsoleScreenBufferInfo(FOutput, &BufferInfo);\r\n BufferInfo.dwCursorPosition.X = 0;\r\n SetConsoleCursorPosition(FOutput, BufferInfo.dwCursorPosition);\r\n }\r\n unsigned long Written;\r\n bool Result = WriteConsole(FOutput, Str.c_str(), Str.Length(), &Written, NULL);\r\n DebugAssert(Result);\r\n DebugUsedParam(Result);\r\n DebugAssert(Str.Length() == static_cast<long>(Written));\r\n ProcessMessages();\r\n}\r\n//---------------------------------------------------------------------------\r\nclass TConsoleInputThread : public TSimpleThread\r\n{\r\npublic:\r\n __fastcall TConsoleInputThread(HANDLE Input, UnicodeString & Str, bool & Result) :\r\n FInput(Input),\r\n FStr(Str),\r\n FResult(Result)\r\n {\r\n }\r\n\r\n virtual __fastcall ~TConsoleInputThread()\r\n {\r\n Close();\r\n }\r\n\r\nprotected:\r\n virtual void __fastcall Execute()\r\n {\r\n unsigned long Read;\r\n FStr.SetLength(10240);\r\n FResult = ReadConsole(FInput, FStr.c_str(), FStr.Length(), &Read, NULL);\r\n DebugAssert(FResult);\r\n FStr.SetLength(Read);\r\n TrimNewLine(FStr);\r\n }\r\n\r\n virtual void __fastcall Terminate()\r\n {\r\n TOwnConsole::FInstance->BreakInput();\r\n }\r\n\r\nprivate:\r\n HANDLE FInput;\r\n UnicodeString & FStr;\r\n bool & FResult;\r\n};\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TOwnConsole::Input(UnicodeString & Str, bool Echo, unsigned int Timer)\r\n{\r\n unsigned long PrevMode, NewMode;\r\n GetConsoleMode(FInput, &PrevMode);\r\n NewMode = PrevMode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;\r\n if (Echo)\r\n {\r\n NewMode |= ENABLE_ECHO_INPUT;\r\n }\r\n else\r\n {\r\n NewMode &= ~ENABLE_ECHO_INPUT;\r\n }\r\n SetConsoleMode(FInput, NewMode);\r\n\r\n bool Result = false;\r\n\r\n try\r\n {\r\n {\r\n const int FirstKey = VK_LBUTTON; // 0x01\r\n const int LastKey = VK_OEM_CLEAR; // 0xFE\r\n\r\n // reset key state\r\n for (int Key = FirstKey; Key <= LastKey; Key++)\r\n {\r\n GetAsyncKeyState(Key);\r\n }\r\n\r\n TConsoleInputThread InputThread(FInput, Str, Result);\r\n\r\n InputThread.Start();\r\n\r\n double TimerD = double(Timer)/MSecsPerDay;\r\n double End = Now() + TimerD;\r\n while (!InputThread.IsFinished() &&\r\n ((Timer == 0) || (double(Now()) < End)))\r\n {\r\n ProcessMessages();\r\n InputThread.WaitFor(50);\r\n\r\n for (int Key = FirstKey; Key <= LastKey; Key++)\r\n {\r\n if ((GetAsyncKeyState(Key) & 0x01) != 0)\r\n {\r\n End = Now() + TimerD;\r\n // Finishing the loop nevertheless to reset state of all keys\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (FPendingAbort || !Echo)\r\n {\r\n Print(L\"\\n\");\r\n }\r\n\r\n if (FPendingAbort || (Str.Length() == 0))\r\n {\r\n Result = false;\r\n FPendingAbort = false;\r\n }\r\n }\r\n __finally\r\n {\r\n SetConsoleMode(FInput, PrevMode);\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall TOwnConsole::Choice(\r\n UnicodeString Options, int Cancel, int Break, int /*Continue*/, int Timeouted, bool /*Timeouting*/, unsigned int Timer,\r\n UnicodeString Message)\r\n{\r\n unsigned int ATimer = Timer;\r\n int Result = 0;\r\n unsigned long PrevMode, NewMode;\r\n GetConsoleMode(FInput, &PrevMode);\r\n NewMode = (PrevMode | ENABLE_PROCESSED_INPUT) & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);\r\n SetConsoleMode(FInput, NewMode);\r\n\r\n try\r\n {\r\n do\r\n {\r\n unsigned long Read;\r\n INPUT_RECORD Record;\r\n if ((PeekConsoleInput(FInput, &Record, 1, &Read) != 0) &&\r\n (Read == 1))\r\n {\r\n if ((ReadConsoleInput(FInput, &Record, 1, &Read) != 0) &&\r\n (Read == 1))\r\n {\r\n if (PendingAbort())\r\n {\r\n Result = Break;\r\n }\r\n else if ((Record.EventType == KEY_EVENT) &&\r\n Record.Event.KeyEvent.bKeyDown)\r\n {\r\n wchar_t C = AnsiUpperCase(Record.Event.KeyEvent.uChar.UnicodeChar)[1];\r\n if (C == 27)\r\n {\r\n Result = Cancel;\r\n }\r\n else if ((Options.Pos(C) > 0) &&\r\n FLAGCLEAR(Record.Event.KeyEvent.dwControlKeyState,\r\n LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED | LEFT_ALT_PRESSED |\r\n RIGHT_ALT_PRESSED))\r\n\r\n {\r\n Result = Options.Pos(C);\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (Result == 0)\r\n {\r\n unsigned int TimerSlice = 50;\r\n Sleep(TimerSlice);\r\n if (Timer > 0)\r\n {\r\n if (ATimer > TimerSlice)\r\n {\r\n ATimer -= TimerSlice;\r\n }\r\n else\r\n {\r\n Result = Timeouted;\r\n }\r\n }\r\n }\r\n\r\n ProcessMessages();\r\n }\r\n while (Result == 0);\r\n }\r\n __finally\r\n {\r\n SetConsoleMode(FInput, PrevMode);\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::SetTitle(UnicodeString Title)\r\n{\r\n FTrayIcon->Hint = Title;\r\n SetConsoleTitle(Title.c_str());\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TOwnConsole::LimitedOutput()\r\n{\r\n return true;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TOwnConsole::LiveOutput()\r\n{\r\n return true;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TOwnConsole::NoInteractiveInput()\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TOwnConsole::Interactive()\r\n{\r\n return true;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::WaitBeforeExit()\r\n{\r\n unsigned long Read;\r\n INPUT_RECORD Record;\r\n while (true)\r\n {\r\n if (PeekConsoleInput(FInput, &Record, 1, &Read) && (Read == 1) &&\r\n ReadConsoleInput(FInput, &Record, 1, &Read) &&\r\n (Read == 1) && (Record.EventType == KEY_EVENT) &&\r\n (Record.Event.KeyEvent.uChar.UnicodeChar != 0) &&\r\n Record.Event.KeyEvent.bKeyDown)\r\n {\r\n break;\r\n }\r\n Sleep(50);\r\n ProcessMessages();\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TOwnConsole::CommandLineOnly()\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TOwnConsole::WantsProgress()\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TOwnConsole::Progress(TScriptProgress & /*Progress*/)\r\n{\r\n DebugFail();\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TOwnConsole::FinalLogMessage()\r\n{\r\n return UnicodeString();\r\n}\r\n//---------------------------------------------------------------------------\r\nclass TExternalConsole : public TConsole\r\n{\r\npublic:\r\n __fastcall TExternalConsole(const UnicodeString Instance, bool NoInteractiveInput);\r\n virtual __fastcall ~TExternalConsole();\r\n\r\n virtual void __fastcall Print(UnicodeString Str, bool FromBeginning = false, bool Error = false);\r\n virtual bool __fastcall Input(UnicodeString & Str, bool Echo, unsigned int Timer);\r\n virtual int __fastcall Choice(\r\n UnicodeString Options, int Cancel, int Break, int Continue, int Timeouted, bool Timeouting, unsigned int Timer,\r\n UnicodeString Message);\r\n virtual bool __fastcall PendingAbort();\r\n virtual void __fastcall SetTitle(UnicodeString Title);\r\n virtual bool __fastcall LimitedOutput();\r\n virtual bool __fastcall LiveOutput();\r\n virtual bool __fastcall NoInteractiveInput();\r\n virtual void __fastcall WaitBeforeExit();\r\n virtual bool __fastcall Interactive();\r\n virtual bool __fastcall CommandLineOnly();\r\n virtual bool __fastcall WantsProgress();\r\n virtual void __fastcall Progress(TScriptProgress & Progress);\r\n virtual UnicodeString __fastcall FinalLogMessage();\r\n\r\nprivate:\r\n bool FPendingAbort;\r\n HANDLE FRequestEvent;\r\n HANDLE FResponseEvent;\r\n HANDLE FCancelEvent;\r\n HANDLE FFileMapping;\r\n bool FLimitedOutput;\r\n bool FLiveOutput;\r\n bool FPipeOutput;\r\n bool FNoInteractiveInput;\r\n bool FWantsProgress;\r\n bool FInteractive;\r\n unsigned int FMaxSend;\r\n\r\n inline TConsoleCommStruct * __fastcall GetCommStruct();\r\n inline void __fastcall FreeCommStruct(TConsoleCommStruct * CommStruct);\r\n inline void __fastcall SendEvent(int Timeout);\r\n void __fastcall Init();\r\n void __fastcall CheckHandle(HANDLE Handle, const UnicodeString & Desc);\r\n};\r\n//---------------------------------------------------------------------------\r\n__fastcall TExternalConsole::TExternalConsole(\r\n const UnicodeString Instance, bool NoInteractiveInput)\r\n{\r\n UnicodeString Name;\r\n Name = FORMAT(L\"%s%s\", (CONSOLE_EVENT_REQUEST, (Instance)));\r\n CheckHandle(FRequestEvent = OpenEvent(EVENT_ALL_ACCESS, false, Name.c_str()), L\"Request event\");\r\n Name = FORMAT(L\"%s%s\", (CONSOLE_EVENT_RESPONSE, (Instance)));\r\n CheckHandle(FResponseEvent = OpenEvent(EVENT_ALL_ACCESS, false, Name.c_str()), L\"Response event\");\r\n Name = FORMAT(L\"%s%s\", (CONSOLE_EVENT_CANCEL, (Instance)));\r\n CheckHandle(FCancelEvent = OpenEvent(EVENT_ALL_ACCESS, false, Name.c_str()), L\"Cancel event\");\r\n Name = FORMAT(L\"%s%s\", (CONSOLE_MAPPING, (Instance)));\r\n CheckHandle(FFileMapping = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, Name.c_str()), L\"File mapping\");\r\n\r\n HANDLE Job = OpenJobObject(JOB_OBJECT_ASSIGN_PROCESS, FALSE,\r\n FORMAT(L\"%s%s\", (CONSOLE_JOB, Instance)).c_str());\r\n if (DebugAlwaysTrue(Job != NULL))\r\n {\r\n AssignProcessToJobObject(Job, GetCurrentProcess());\r\n // winscp.com/winscp.dll keeps the only reference to the job.\r\n // once it gets closed (because winscp.com if forcefully terminated),\r\n // we get terminated as well\r\n CloseHandle(Job);\r\n }\r\n\r\n TConsoleCommStruct * CommStruct = GetCommStruct();\r\n try\r\n {\r\n if (CommStruct->Version != TConsoleCommStruct::CurrentVersion)\r\n {\r\n throw Exception(FMTLOAD(EXTERNAL_CONSOLE_INCOMPATIBLE, (CommStruct->Version)));\r\n }\r\n\r\n CommStruct->Version = TConsoleCommStruct::CurrentVersionConfirmed;\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n\r\n // to break application event loop regularly during \"watching for changes\"\r\n // to allow user to abort it\r\n SetTimer(Application->Handle, 1, 500, NULL);\r\n\r\n FNoInteractiveInput = NoInteractiveInput;\r\n FMaxSend = 0;\r\n\r\n Init();\r\n}\r\n//---------------------------------------------------------------------------\r\n__fastcall TExternalConsole::~TExternalConsole()\r\n{\r\n CloseHandle(FRequestEvent);\r\n CloseHandle(FResponseEvent);\r\n CloseHandle(FCancelEvent);\r\n CloseHandle(FFileMapping);\r\n KillTimer(Application->Handle, 1);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TExternalConsole::CheckHandle(HANDLE Handle, const UnicodeString & Desc)\r\n{\r\n if (Handle == NULL)\r\n {\r\n throw ExtException(LoadStr(EXTERNAL_CONSOLE_INIT_ERROR), FORMAT(L\"%s\\n%s\", (Desc, LastSysErrorMessage())));\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nTConsoleCommStruct * __fastcall TExternalConsole::GetCommStruct()\r\n{\r\n TConsoleCommStruct * Result;\r\n Result = static_cast<TConsoleCommStruct*>(MapViewOfFile(FFileMapping,\r\n FILE_MAP_ALL_ACCESS, 0, 0, 0));\r\n if (Result == NULL)\r\n {\r\n throw Exception(LoadStr(CONSOLE_COMM_ERROR));\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TExternalConsole::FreeCommStruct(TConsoleCommStruct * CommStruct)\r\n{\r\n UnmapViewOfFile(CommStruct);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TExternalConsole::SendEvent(int Timeout)\r\n{\r\n SetEvent(FRequestEvent);\r\n unsigned int Start = 0; // shut up\r\n if (Configuration->LogProtocol >= 1)\r\n {\r\n Start = GetTickCount();\r\n }\r\n unsigned int Result = WaitForSingleObject(FResponseEvent, Timeout);\r\n if (Configuration->LogProtocol >= 1)\r\n {\r\n unsigned int End = GetTickCount();\r\n unsigned int Duration = End - Start;\r\n FMaxSend = std::max(Duration, FMaxSend);\r\n }\r\n if (Result != WAIT_OBJECT_0)\r\n {\r\n UnicodeString Message = LoadStr(CONSOLE_SEND_TIMEOUT);\r\n if (FPipeOutput)\r\n {\r\n Message = FORMAT(\"%s %s\", (Message, LoadStr(CONSOLE_SEND_PIPE)));\r\n }\r\n throw Exception(Message);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TExternalConsole::FinalLogMessage()\r\n{\r\n return FORMAT(L\"Max roundtrip: %d\", (static_cast<int>(FMaxSend)));\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TExternalConsole::Print(UnicodeString Str, bool FromBeginning, bool Error)\r\n{\r\n // need to do at least one iteration, even when Str is empty (new line)\r\n do\r\n {\r\n TConsoleCommStruct * CommStruct = GetCommStruct();\r\n try\r\n {\r\n size_t MaxLen = LENOF(CommStruct->PrintEvent.Message) - 1;\r\n UnicodeString Piece = Str.SubString(1, MaxLen);\r\n Str.Delete(1, MaxLen);\r\n\r\n CommStruct->Event = TConsoleCommStruct::PRINT;\r\n wcscpy(CommStruct->PrintEvent.Message, Piece.c_str());\r\n CommStruct->PrintEvent.FromBeginning = FromBeginning;\r\n CommStruct->PrintEvent.Error = Error;\r\n\r\n // In the next iteration we need to append never overwrite.\r\n // Note that this won't work properly for disk/pipe outputs,\r\n // when the next line is also FromBeginning,\r\n // as !FromBeginning print effectively commits previous FromBeginning print.\r\n // On the other hand, FromBeginning print is always initiated by us,\r\n // and it's not likely we ever issue print over 10 KB.\r\n FromBeginning = false;\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n\r\n SendEvent(INFINITE);\r\n }\r\n while (!Str.IsEmpty());\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TExternalConsole::Input(UnicodeString & Str, bool Echo, unsigned int Timer)\r\n{\r\n TConsoleCommStruct * CommStruct = GetCommStruct();\r\n try\r\n {\r\n CommStruct->Event = TConsoleCommStruct::INPUT;\r\n CommStruct->InputEvent.Echo = Echo;\r\n CommStruct->InputEvent.Result = false;\r\n CommStruct->InputEvent.Str[0] = L'\\0';\r\n CommStruct->InputEvent.Timer = Timer;\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n\r\n SendEvent(INFINITE);\r\n\r\n bool Result;\r\n CommStruct = GetCommStruct();\r\n try\r\n {\r\n Result = CommStruct->InputEvent.Result;\r\n Str = CommStruct->InputEvent.Str;\r\n TrimNewLine(Str);\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall TExternalConsole::Choice(\r\n UnicodeString Options, int Cancel, int Break, int Continue, int Timeouted, bool Timeouting, unsigned int Timer,\r\n UnicodeString Message)\r\n{\r\n TConsoleCommStruct * CommStruct = GetCommStruct();\r\n try\r\n {\r\n CommStruct->Event = TConsoleCommStruct::CHOICE;\r\n\r\n DebugAssert(Options.Length() < static_cast<int>(LENOF(CommStruct->ChoiceEvent.Options)));\r\n wcscpy(CommStruct->ChoiceEvent.Options, Options.c_str());\r\n CommStruct->ChoiceEvent.Cancel = Cancel;\r\n CommStruct->ChoiceEvent.Break = Break;\r\n CommStruct->ChoiceEvent.Result = Break;\r\n CommStruct->ChoiceEvent.Continue = Continue;\r\n CommStruct->ChoiceEvent.Timeouted = Timeouted;\r\n CommStruct->ChoiceEvent.Timer = Timer;\r\n CommStruct->ChoiceEvent.Timeouting = Timeouting;\r\n size_t MaxLen = LENOF(CommStruct->ChoiceEvent.Message) - 1;\r\n Message = Message.SubString(1, MaxLen);\r\n wcscpy(CommStruct->ChoiceEvent.Message, Message.c_str());\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n\r\n SendEvent(INFINITE);\r\n\r\n int Result;\r\n CommStruct = GetCommStruct();\r\n try\r\n {\r\n Result = CommStruct->ChoiceEvent.Result;\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TExternalConsole::PendingAbort()\r\n{\r\n return (WaitForSingleObject(FCancelEvent, 0) == WAIT_OBJECT_0);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TExternalConsole::SetTitle(UnicodeString Title)\r\n{\r\n TConsoleCommStruct * CommStruct = GetCommStruct();\r\n try\r\n {\r\n // Truncate to maximum allowed. Title over 10 KB won't fit to screen anyway\r\n Title = Title.SubString(1, LENOF(CommStruct->TitleEvent.Title) - 1);\r\n\r\n CommStruct->Event = TConsoleCommStruct::TITLE;\r\n wcscpy(CommStruct->TitleEvent.Title, Title.c_str());\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n\r\n SendEvent(INFINITE);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TExternalConsole::Init()\r\n{\r\n TConsoleCommStruct * CommStruct = GetCommStruct();\r\n try\r\n {\r\n CommStruct->Event = TConsoleCommStruct::INIT;\r\n CommStruct->InitEvent.WantsProgress = false;\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n SendEvent(INFINITE);\r\n\r\n CommStruct = GetCommStruct();\r\n try\r\n {\r\n FLimitedOutput = (CommStruct->InitEvent.OutputType == FILE_TYPE_CHAR);\r\n FLiveOutput =\r\n (CommStruct->InitEvent.OutputType != FILE_TYPE_DISK) &&\r\n (CommStruct->InitEvent.OutputType != FILE_TYPE_PIPE);\r\n FPipeOutput = (CommStruct->InitEvent.OutputType != FILE_TYPE_PIPE);\r\n FInteractive =\r\n (CommStruct->InitEvent.InputType != FILE_TYPE_DISK) &&\r\n (CommStruct->InitEvent.InputType != FILE_TYPE_PIPE);\r\n FWantsProgress = CommStruct->InitEvent.WantsProgress;\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TExternalConsole::LimitedOutput()\r\n{\r\n return FLimitedOutput;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TExternalConsole::LiveOutput()\r\n{\r\n return FLiveOutput;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TExternalConsole::NoInteractiveInput()\r\n{\r\n return FNoInteractiveInput;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TExternalConsole::Interactive()\r\n{\r\n return FInteractive;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TExternalConsole::WaitBeforeExit()\r\n{\r\n // noop\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TExternalConsole::CommandLineOnly()\r\n{\r\n return true;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TExternalConsole::WantsProgress()\r\n{\r\n return FWantsProgress;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TExternalConsole::Progress(TScriptProgress & Progress)\r\n{\r\n TConsoleCommStruct * CommStruct = GetCommStruct();\r\n\r\n typedef TConsoleCommStruct::TProgressEvent TProgressEvent;\r\n\r\n try\r\n {\r\n TProgressEvent & ProgressEvent = CommStruct->ProgressEvent;\r\n\r\n CommStruct->Event = TConsoleCommStruct::PROGRESS;\r\n\r\n switch (Progress.Operation)\r\n {\r\n case foCopy:\r\n case foMove:\r\n ProgressEvent.Operation = TProgressEvent::COPY;\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n }\r\n\r\n switch (Progress.Side)\r\n {\r\n case osLocal:\r\n ProgressEvent.Side = TProgressEvent::LOCAL;\r\n break;\r\n\r\n case osRemote:\r\n ProgressEvent.Side = TProgressEvent::REMOTE;\r\n break;\r\n\r\n default:\r\n DebugFail();\r\n }\r\n\r\n wcsncpy(ProgressEvent.FileName, Progress.FileName.c_str(), LENOF(ProgressEvent.FileName));\r\n NULL_TERMINATE(ProgressEvent.FileName);\r\n\r\n wcsncpy(ProgressEvent.Directory, Progress.Directory.c_str(), LENOF(ProgressEvent.Directory));\r\n NULL_TERMINATE(ProgressEvent.Directory);\r\n\r\n ProgressEvent.OverallProgress = Progress.OverallProgress;\r\n ProgressEvent.FileProgress = Progress.FileProgress;\r\n ProgressEvent.CPS = Progress.CPS;\r\n ProgressEvent.Cancel = Progress.Cancel;\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n SendEvent(INFINITE);\r\n\r\n CommStruct = GetCommStruct();\r\n try\r\n {\r\n TProgressEvent & ProgressEvent = CommStruct->ProgressEvent;\r\n Progress.Cancel = ProgressEvent.Cancel;\r\n }\r\n __finally\r\n {\r\n FreeCommStruct(CommStruct);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nclass TNullConsole : public TConsole\r\n{\r\npublic:\r\n __fastcall TNullConsole();\r\n\r\n virtual void __fastcall Print(UnicodeString Str, bool FromBeginning = false, bool Error = false);\r\n virtual bool __fastcall Input(UnicodeString & Str, bool Echo, unsigned int Timer);\r\n virtual int __fastcall Choice(\r\n UnicodeString Options, int Cancel, int Break, int Continue, int Timeouted, bool Timeouting, unsigned int Timer,\r\n UnicodeString Message);\r\n virtual bool __fastcall PendingAbort();\r\n virtual void __fastcall SetTitle(UnicodeString Title);\r\n virtual bool __fastcall LimitedOutput();\r\n virtual bool __fastcall LiveOutput();\r\n virtual bool __fastcall NoInteractiveInput();\r\n virtual bool __fastcall Interactive();\r\n virtual void __fastcall WaitBeforeExit();\r\n virtual bool __fastcall CommandLineOnly();\r\n\r\n virtual bool __fastcall WantsProgress();\r\n virtual void __fastcall Progress(TScriptProgress & Progress);\r\n virtual UnicodeString __fastcall FinalLogMessage();\r\n};\r\n//---------------------------------------------------------------------------\r\n__fastcall TNullConsole::TNullConsole()\r\n{\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TNullConsole::Print(UnicodeString /*Str*/, bool /*FromBeginning*/, bool /*Error*/)\r\n{\r\n // noop\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TNullConsole::Input(UnicodeString & /*Str*/, bool /*Echo*/,\r\n unsigned int /*Timer*/)\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall TNullConsole::Choice(\r\n UnicodeString /*Options*/, int /*Cancel*/, int Break, int /*Continue*/, int Timeouted, bool Timeouting,\r\n unsigned int Timer, UnicodeString /*Message*/)\r\n{\r\n int Result;\r\n if (Timeouting)\r\n {\r\n Sleep(Timer);\r\n Result = Timeouted;\r\n }\r\n else\r\n {\r\n Result = Break;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TNullConsole::PendingAbort()\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TNullConsole::SetTitle(UnicodeString /*Title*/)\r\n{\r\n // noop\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TNullConsole::LimitedOutput()\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TNullConsole::LiveOutput()\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TNullConsole::NoInteractiveInput()\r\n{\r\n // do not matter, even if we return false,\r\n // it fails immediately afterwards in TNullConsole::Input\r\n return true;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TNullConsole::Interactive()\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TNullConsole::WaitBeforeExit()\r\n{\r\n DebugFail();\r\n // noop\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TNullConsole::CommandLineOnly()\r\n{\r\n DebugFail();\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TNullConsole::WantsProgress()\r\n{\r\n return false;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TNullConsole::Progress(TScriptProgress & /*Progress*/)\r\n{\r\n DebugFail();\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString __fastcall TNullConsole::FinalLogMessage()\r\n{\r\n return UnicodeString();\r\n}\r\n//---------------------------------------------------------------------------\r\nstatic UnicodeString TimestampVarName(L\"TIMESTAMP\");\r\n//---------------------------------------------------------------------------\r\nclass TConsoleRunner\r\n{\r\npublic:\r\n TConsoleRunner(TConsole * Console);\r\n ~TConsoleRunner();\r\n\r\n int __fastcall Run(const UnicodeString Session, TOptions * Options,\r\n TStrings * ScriptCommands, TStrings * ScriptParameters);\r\n void __fastcall ShowException(Exception * E);\r\n inline void __fastcall PrintMessage(const UnicodeString & Str, bool Error = false);\r\n\r\nprotected:\r\n bool __fastcall DoInput(UnicodeString & Str, bool Echo, unsigned int Timer,\r\n bool Interactive);\r\n void __fastcall Input(const UnicodeString Prompt, UnicodeString & Str,\r\n bool Echo, bool Interactive);\r\n inline void __fastcall Print(const UnicodeString & Str, bool FromBeginning = false, bool Error = false);\r\n void __fastcall UpdateTitle();\r\n inline bool __fastcall NotifyAbort();\r\n inline bool __fastcall Aborted(bool AllowCompleteAbort = true);\r\n void __fastcall MasterPasswordPrompt();\r\n void __fastcall DoShowException(TTerminal * Terminal, Exception * E);\r\n\r\nprivate:\r\n TManagementScript * FScript;\r\n TConsole * FConsole;\r\n TSynchronizeController FSynchronizeController;\r\n int FLastProgressLen;\r\n bool FSynchronizeAborted;\r\n bool FCommandError;\r\n bool FBatchScript;\r\n bool FAborted;\r\n TTimer * Timer;\r\n bool FExternalTimestampVar;\r\n\r\n void __fastcall ScriptPrint(TScript * Script, const UnicodeString Str, bool Error);\r\n void __fastcall ScriptPrintProgress(TScript * Script, bool First, const UnicodeString Str);\r\n void __fastcall ScriptInput(TScript * Script, const UnicodeString Prompt, UnicodeString & Str);\r\n void __fastcall ScriptTerminalPromptUser(TTerminal * Terminal,\r\n TPromptKind Kind, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,\r\n TStrings * Results, bool & Result, void * Arg);\r\n void __fastcall ScriptShowExtendedException(TTerminal * Terminal,\r\n Exception * E, void * Arg);\r\n void __fastcall ScriptTerminalQueryUser(TObject * Sender, const UnicodeString Query,\r\n TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params, unsigned int & Answer,\r\n TQueryType QueryType, void * Arg);\r\n void __fastcall ScriptQueryCancel(TScript * Script, bool & Cancel);\r\n void __fastcall SynchronizeControllerAbort(TObject * Sender, bool Close);\r\n void __fastcall SynchronizeControllerLog(TSynchronizeController * Controller,\r\n TSynchronizeLogEntry Entry, const UnicodeString Message);\r\n void __fastcall ScriptSynchronizeStartStop(TScript * Script,\r\n const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,\r\n const TCopyParamType & CopyParam, int SynchronizeParams);\r\n void __fastcall SynchronizeControllerSynchronize(TSynchronizeController * Sender,\r\n const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,\r\n const TCopyParamType & CopyParam, const TSynchronizeParamType & Params,\r\n TSynchronizeChecklist ** Checklist, TSynchronizeOptions * Options, bool Full);\r\n void __fastcall SynchronizeControllerSynchronizeInvalid(TSynchronizeController * Sender,\r\n const UnicodeString Directory, const UnicodeString ErrorStr);\r\n void __fastcall SynchronizeControllerTooManyDirectories(TSynchronizeController * Sender,\r\n int & MaxDirectories);\r\n unsigned int InputTimeout();\r\n void __fastcall TimerTimer(TObject * Sender);\r\n UnicodeString ExpandCommand(UnicodeString Command, TStrings * ScriptParameters);\r\n void __fastcall Failed(bool & AnyError);\r\n void __fastcall ScriptProgress(TScript * Script, TScriptProgress & Progress);\r\n void __fastcall ConfigurationChange(TObject * Sender);\r\n};\r\n//---------------------------------------------------------------------------\r\nTConsoleRunner::TConsoleRunner(TConsole * Console) :\r\n FSynchronizeController(&SynchronizeControllerSynchronize,\r\n &SynchronizeControllerSynchronizeInvalid,\r\n &SynchronizeControllerTooManyDirectories)\r\n{\r\n FConsole = Console;\r\n FLastProgressLen = 0;\r\n FScript = NULL;\r\n FAborted = false;\r\n FBatchScript = false;\r\n Timer = new TTimer(Application);\r\n Timer->OnTimer = TimerTimer;\r\n Timer->Interval = MSecsPerSec;\r\n Timer->Enabled = true;\r\n DebugAssert(WinConfiguration->OnMasterPasswordPrompt == NULL);\r\n WinConfiguration->OnMasterPasswordPrompt = MasterPasswordPrompt;\r\n DebugAssert(Configuration->OnChange == NULL);\r\n FExternalTimestampVar = !GetEnvironmentVariable(TimestampVarName).IsEmpty();\r\n Configuration->OnChange = ConfigurationChange;\r\n Configuration->Scripting = true;\r\n}\r\n//---------------------------------------------------------------------------\r\nTConsoleRunner::~TConsoleRunner()\r\n{\r\n DebugAssert(WinConfiguration->OnMasterPasswordPrompt == MasterPasswordPrompt);\r\n WinConfiguration->OnMasterPasswordPrompt = NULL;\r\n DebugAssert(Configuration->OnChange == ConfigurationChange);\r\n Configuration->OnChange = NULL;\r\n delete Timer;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::TimerTimer(TObject * /*Sender*/)\r\n{\r\n // sole presence of timer causes message to be dispatched,\r\n // hence breaks the loops\r\n}\r\n//---------------------------------------------------------------------------\r\nunsigned int TConsoleRunner::InputTimeout()\r\n{\r\n return ((FScript != NULL) && (FScript->Batch != TScript::BatchOff) ? BATCH_INPUT_TIMEOUT : 0);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::Input(\r\n const UnicodeString Prompt, UnicodeString & Str, bool Echo, bool Interactive)\r\n{\r\n Print(Prompt);\r\n\r\n if (!DoInput(Str, Echo, InputTimeout(), Interactive))\r\n {\r\n Abort();\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptInput(TScript * /*Script*/,\r\n const UnicodeString Prompt, UnicodeString & Str)\r\n{\r\n Input(Prompt, Str, true, true);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::Print(const UnicodeString & Str, bool FromBeginning, bool Error)\r\n{\r\n if (FLastProgressLen > 0)\r\n {\r\n FConsole->Print(L\"\\n\" + Str, FromBeginning, Error);\r\n FLastProgressLen = 0;\r\n }\r\n else\r\n {\r\n FConsole->Print(Str, FromBeginning, Error);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::PrintMessage(const UnicodeString & Str, bool Error)\r\n{\r\n UnicodeString Line = RemoveEmptyLines(Str);\r\n\r\n if (FScript != NULL)\r\n {\r\n // this also logs the message\r\n FScript->PrintLine(Line, Error);\r\n }\r\n else\r\n {\r\n FConsole->PrintLine(Line, Error);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TConsoleRunner::NotifyAbort()\r\n{\r\n bool Result = FBatchScript;\r\n if (Result)\r\n {\r\n FAborted = true;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TConsoleRunner::Aborted(bool AllowCompleteAbort)\r\n{\r\n bool Result;\r\n if (FAborted)\r\n {\r\n Result = true;\r\n }\r\n else\r\n {\r\n Result = FConsole->PendingAbort();\r\n if (Result)\r\n {\r\n PrintMessage(LoadStr(USER_TERMINATED), true);\r\n\r\n if (AllowCompleteAbort && NotifyAbort())\r\n {\r\n if (FScript->Terminal != NULL)\r\n {\r\n std::unique_ptr<TStringList> Failure(TextToStringList(LoadStr(USER_TERMINATED)));\r\n FScript->Terminal->ActionLog->AddFailure(Failure.get());\r\n }\r\n }\r\n }\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptPrint(TScript * /*Script*/,\r\n const UnicodeString Str, bool Error)\r\n{\r\n Print(Str, false, Error);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptPrintProgress(TScript * /*Script*/,\r\n bool First, const UnicodeString Str)\r\n{\r\n UnicodeString S = Str;\r\n if (First && (FLastProgressLen > 0))\r\n {\r\n S = L\"\\n\" + S;\r\n }\r\n else if (S.Length() < FLastProgressLen)\r\n {\r\n int Padding = FLastProgressLen - S.Length();\r\n S += UnicodeString::StringOfChar(L' ', Padding) +\r\n UnicodeString::StringOfChar(L'\\b', Padding);\r\n }\r\n FConsole->Print(S, true);\r\n FLastProgressLen = Str.Length();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptTerminalPromptUser(TTerminal * /*Terminal*/,\r\n TPromptKind /*Kind*/, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,\r\n TStrings * Results, bool & Result, void * /*Arg*/)\r\n{\r\n if (!Instructions.IsEmpty())\r\n {\r\n PrintMessage(Instructions);\r\n }\r\n\r\n // if there are no prompts, success is default\r\n Result = true;\r\n\r\n for (int Index = 0; Index < Prompts->Count; Index++)\r\n {\r\n UnicodeString Prompt = Prompts->Strings[Index];\r\n if (!Prompt.IsEmpty() && (Prompt[Prompt.Length()] != L' '))\r\n {\r\n Prompt += L' ';\r\n }\r\n int P = Prompt.Pos(L'&');\r\n if (P > 0)\r\n {\r\n Prompt.Delete(P, 1);\r\n }\r\n Print(Prompt);\r\n\r\n UnicodeString AResult = Results->Strings[Index]; // useless\r\n bool Echo = FLAGSET(int(Prompts->Objects[Index]), pupEcho);\r\n Result = DoInput(AResult, Echo, InputTimeout(), true);\r\n Results->Strings[Index] = AResult;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptShowExtendedException(\r\n TTerminal * Terminal, Exception * E, void * /*Arg*/)\r\n{\r\n DoShowException(Terminal, E);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptTerminalQueryUser(TObject * /*Sender*/,\r\n const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,\r\n const TQueryParams * Params, unsigned int & Answer, TQueryType /*QueryType*/,\r\n void * /*Arg*/)\r\n{\r\n UnicodeString AQuery = Query;\r\n unsigned int Timer = 0;\r\n unsigned int Timeout = 0;\r\n unsigned int TimeoutA = 0;\r\n unsigned int NoBatchA = 0;\r\n\r\n if (Params != NULL)\r\n {\r\n if (Params->Timeout > 0)\r\n {\r\n Timeout = Params->Timeout;\r\n TimeoutA = Params->TimeoutAnswer;\r\n }\r\n\r\n if (Params->Timer > 0)\r\n {\r\n Timer = Params->Timer;\r\n if (Params->TimerAnswers > 0)\r\n {\r\n Answers = Params->TimerAnswers;\r\n }\r\n // not considering TimerQueryType as we do not use QueryType anyway\r\n if (!Params->TimerMessage.IsEmpty())\r\n {\r\n AQuery = Params->TimerMessage;\r\n }\r\n }\r\n\r\n if (FLAGSET(Params->Params, qpFatalAbort))\r\n {\r\n AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));\r\n }\r\n\r\n NoBatchA = Params->NoBatchAnswers;\r\n\r\n if (FLAGSET(Params->Params, qpWaitInBatch))\r\n {\r\n DebugAssert(Timeout == 0);\r\n Timeout = InputTimeout();\r\n if (Timeout != 0)\r\n {\r\n // See a duplicate AbortAnswer call below\r\n TimeoutA = AbortAnswer(Answers & ~NoBatchA);\r\n }\r\n }\r\n }\r\n\r\n AQuery = UnformatMessage(AQuery);\r\n AQuery = RemoveInteractiveMsgTag(AQuery);\r\n\r\n ApplyTabs(AQuery, L' ', NULL, NULL);\r\n\r\n unsigned int AAnswers = Answers;\r\n\r\n UnicodeString Message = AQuery;\r\n PrintMessage(AQuery);\r\n if ((MoreMessages != NULL) && (MoreMessages->Count > 0))\r\n {\r\n PrintMessage(MoreMessages->Text);\r\n Message += L\"\\n\" + MoreMessages->Text;\r\n }\r\n\r\n std::vector<unsigned int> Buttons;\r\n std::vector<UnicodeString> Captions;\r\n std::vector<TButtonSubmitEvent> OnSubmits;\r\n\r\n for (unsigned int Answer = qaFirst; Answer <= qaLast; Answer = Answer << 1)\r\n {\r\n if (FLAGSET(Answers, Answer))\r\n {\r\n UnicodeString Name; // unused\r\n UnicodeString Caption;\r\n AnswerNameAndCaption(Answer, Name, Caption);\r\n Captions.push_back(Caption);\r\n Buttons.push_back(Answer);\r\n OnSubmits.push_back(NULL);\r\n AAnswers -= Answer;\r\n }\r\n }\r\n\r\n DebugUsedParam(AAnswers);\r\n DebugAssert(AAnswers == 0);\r\n DebugAssert(!Buttons.empty());\r\n\r\n if ((Params != NULL) && (Params->Aliases != NULL))\r\n {\r\n for (unsigned int bi = 0; bi < Buttons.size(); bi++)\r\n {\r\n for (unsigned int ai = 0; ai < Params->AliasesCount; ai++)\r\n {\r\n if (Params->Aliases[ai].Button == Buttons[bi])\r\n {\r\n if (!Params->Aliases[ai].Alias.IsEmpty())\r\n {\r\n Captions[bi] = Params->Aliases[ai].Alias;\r\n }\r\n OnSubmits[bi] = Params->Aliases[ai].OnSubmit;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n UnicodeString Accels;\r\n for (unsigned int Index = 0; Index < Buttons.size(); Index++)\r\n {\r\n UnicodeString & Caption = Captions[Index];\r\n int P = Caption.Pos(L'&');\r\n if ((P > 0) && (P < Caption.Length()))\r\n {\r\n wchar_t Accel = AnsiUpperCase(Caption)[P + 1];\r\n if (Accels.Pos(Accel) > 0)\r\n {\r\n Caption.Delete(P, 1);\r\n Accels += L' ';\r\n }\r\n else\r\n {\r\n Accels += Accel;\r\n }\r\n }\r\n else\r\n {\r\n Accels += L' ';\r\n }\r\n }\r\n\r\n DebugAssert(Accels.Length() == static_cast<int>(Buttons.size()));\r\n int NumberAccel = 0;\r\n unsigned int CancelA = CancelAnswer(Answers);\r\n int CancelIndex;\r\n // AbortAnswer call duplicated in qpWaitInBatch branch above\r\n unsigned int AbortA = AbortAnswer(Answers & ~NoBatchA);\r\n int AbortIndex;\r\n unsigned int ContinueA = ContinueAnswer(Answers & ~NoBatchA);\r\n int ContinueIndex;\r\n int TimeoutIndex = 0;\r\n\r\n for (unsigned int Index = 0; Index < Buttons.size(); Index++)\r\n {\r\n UnicodeString & Caption = Captions[Index];\r\n\r\n if (Accels[Index + 1] == L' ')\r\n {\r\n for (int Index2 = 1; Index2 <= Caption.Length(); Index2++)\r\n {\r\n wchar_t C = AnsiUpperCase(Caption)[Index2];\r\n if (IsLetter(C) && (Accels.Pos(C) == 0))\r\n {\r\n Caption.Insert(L\"&\", Index2);\r\n Accels[Index + 1] = C;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (Accels[Index + 1] == L' ')\r\n {\r\n for (int Index2 = 1; Index2 <= Caption.Length(); Index2++)\r\n {\r\n wchar_t C = AnsiUpperCase(Caption)[Index2];\r\n if ((C != L' ') && (Accels.Pos(C) == 0))\r\n {\r\n Caption.Insert(L\"&\", Index2);\r\n Accels[Index + 1] = C;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (Accels[Index + 1] == L' ')\r\n {\r\n NumberAccel++;\r\n DebugAssert(NumberAccel <= 9);\r\n Caption = FORMAT(L\"&%d%s\", (NumberAccel, Caption));\r\n Accels[Index + 1] = Caption[2];\r\n }\r\n\r\n if (Buttons[Index] == CancelA)\r\n {\r\n CancelIndex = Index + 1;\r\n }\r\n if (Buttons[Index] == AbortA)\r\n {\r\n AbortIndex = Index + 1;\r\n }\r\n if (Buttons[Index] == ContinueA)\r\n {\r\n ContinueIndex = Index + 1;\r\n }\r\n if (Buttons[Index] == TimeoutA)\r\n {\r\n TimeoutIndex = Index + 1;\r\n }\r\n }\r\n\r\n DebugAssert(Accels.Pos(L' ') == 0);\r\n\r\n bool Timeouting = (Timeout > 0);\r\n bool FirstOutput = true;\r\n\r\n do\r\n {\r\n Answer = 0;\r\n int AnswerIndex;\r\n bool Retry;\r\n\r\n do\r\n {\r\n Retry = false;\r\n\r\n if (FirstOutput || FConsole->LiveOutput())\r\n {\r\n UnicodeString Output;\r\n for (unsigned int i = 0; i < Buttons.size(); i++)\r\n {\r\n if (i > 0)\r\n {\r\n Output += L\", \";\r\n }\r\n\r\n UnicodeString Caption = Captions[i];\r\n int P = Caption.Pos(L'&');\r\n if (DebugAlwaysTrue(P >= 0))\r\n {\r\n Caption[P] = L'(';\r\n Caption.Insert(L\")\", P + 2);\r\n }\r\n\r\n if (i + 1 == static_cast<unsigned int>(TimeoutIndex))\r\n {\r\n DebugAssert(Timeouting);\r\n Caption = FMTLOAD(TIMEOUT_BUTTON, (Caption, int(Timeout / MSecsPerSec)));\r\n }\r\n\r\n Output += Caption;\r\n }\r\n Output += L\": \";\r\n\r\n // note that length of string may decrease over time due to number of\r\n // seconds length, but supposing it decreases by one character at time\r\n // at most, we do not mind as the prompt is terminated with space\r\n\r\n // If output is not live (file or pipe), do not use 'from beginning'\r\n // as it means that the output is not actually stored until new line\r\n // is sent (and we will not [because we cannot] rewrite the output anyway)\r\n Print(Output, !FirstOutput);\r\n FirstOutput = false;\r\n }\r\n\r\n if (!Timeouting && (FScript->Batch == TScript::BatchContinue))\r\n {\r\n AnswerIndex = ContinueIndex;\r\n }\r\n else if (!Timeouting && (FScript->Batch != TScript::BatchOff))\r\n {\r\n AnswerIndex = AbortIndex;\r\n }\r\n else if (Timeouting && (Timeout < MSecsPerSec))\r\n {\r\n AnswerIndex = TimeoutIndex;\r\n }\r\n else\r\n {\r\n unsigned int ActualTimer;\r\n if (Timeouting)\r\n {\r\n if (Timer == 0)\r\n {\r\n if (FConsole->NoInteractiveInput())\r\n {\r\n ActualTimer = Timeout;\r\n }\r\n else\r\n {\r\n ActualTimer = MSecsPerSec;\r\n }\r\n }\r\n else\r\n {\r\n if (Timer < MSecsPerSec)\r\n {\r\n ActualTimer = Timer;\r\n }\r\n else\r\n {\r\n ActualTimer = MSecsPerSec;\r\n }\r\n }\r\n }\r\n else\r\n {\r\n ActualTimer = Timer;\r\n }\r\n // Not to get preliminary \"host is not responding\" messages to .NET assembly\r\n if (FConsole->NoInteractiveInput() && (Timer > 0))\r\n {\r\n Sleep(Timer);\r\n AnswerIndex = -2;\r\n }\r\n else\r\n {\r\n AnswerIndex =\r\n FConsole->Choice(Accels, CancelIndex, -1, ContinueIndex, -2, Timeouting, ActualTimer, Message);\r\n }\r\n if (AnswerIndex == -1)\r\n {\r\n NotifyAbort();\r\n AnswerIndex = AbortIndex;\r\n }\r\n else if (AnswerIndex == -2)\r\n {\r\n if (Timeouting)\r\n {\r\n DebugAssert(Timeout >= MSecsPerSec);\r\n Timeout -= ActualTimer;\r\n Retry = true;\r\n }\r\n\r\n // this does not take Timer into account,\r\n // but as of now Timer is used for TSecureShell timeout prompt only,\r\n // where Timer is less than MSecsPerSec\r\n if (Timer > 0)\r\n {\r\n DebugAssert((Params != NULL) && (Params->TimerEvent != NULL));\r\n if ((Params != NULL) && (Params->TimerEvent != NULL))\r\n {\r\n unsigned int AAnswer = 0;\r\n Params->TimerEvent(AAnswer);\r\n if (AAnswer != 0)\r\n {\r\n Answer = AAnswer;\r\n Retry = false;\r\n }\r\n else\r\n {\r\n Retry = true;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n while (Retry);\r\n\r\n if (Answer == 0)\r\n {\r\n DebugAssert((AnswerIndex >= 1) && (AnswerIndex <= Accels.Length()));\r\n UnicodeString AnswerCaption = Captions[AnswerIndex - 1];\r\n int P = AnswerCaption.Pos(L\"&\");\r\n DebugAssert(P >= 0);\r\n AnswerCaption.Delete(P, 1);\r\n FConsole->PrintLine(AnswerCaption);\r\n FirstOutput = true;\r\n\r\n if (OnSubmits[AnswerIndex - 1] != NULL)\r\n {\r\n OnSubmits[AnswerIndex - 1](NULL, Answer);\r\n }\r\n else\r\n {\r\n Answer = Buttons[AnswerIndex - 1];\r\n }\r\n }\r\n else\r\n {\r\n FConsole->PrintLine();\r\n }\r\n }\r\n while (Answer == 0);\r\n\r\n if ((Answer == AbortA) &&\r\n ((Params == NULL) || FLAGCLEAR(Params->Params, qpIgnoreAbort)))\r\n {\r\n if (FScript->Terminal != NULL)\r\n {\r\n TStrings * Messages = new TStringList();\r\n try\r\n {\r\n Messages->Add(Query);\r\n if (MoreMessages != NULL)\r\n {\r\n Messages->AddStrings(MoreMessages);\r\n }\r\n FScript->Terminal->ActionLog->AddFailure(Messages);\r\n }\r\n __finally\r\n {\r\n delete Messages;\r\n }\r\n }\r\n\r\n FCommandError = true;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptQueryCancel(TScript * /*Script*/, bool & Cancel)\r\n{\r\n if (Aborted())\r\n {\r\n Cancel = true;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptSynchronizeStartStop(TScript * /*Script*/,\r\n const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,\r\n const TCopyParamType & CopyParam, int SynchronizeParams)\r\n{\r\n TSynchronizeParamType Params;\r\n Params.LocalDirectory = LocalDirectory;\r\n Params.RemoteDirectory = RemoteDirectory;\r\n Params.Params = SynchronizeParams;\r\n Params.Options = soRecurse;\r\n\r\n FSynchronizeController.StartStop(Application, true, Params,\r\n CopyParam, NULL, SynchronizeControllerAbort, NULL,\r\n SynchronizeControllerLog);\r\n\r\n try\r\n {\r\n FSynchronizeAborted = false;\r\n\r\n while (!FSynchronizeAborted && !Aborted(false))\r\n {\r\n Application->HandleMessage();\r\n FScript->Terminal->Idle();\r\n }\r\n }\r\n __finally\r\n {\r\n FSynchronizeController.StartStop(Application, false, Params,\r\n CopyParam, NULL, SynchronizeControllerAbort, NULL,\r\n SynchronizeControllerLog);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ScriptProgress(TScript * /*Script*/, TScriptProgress & Progress)\r\n{\r\n FConsole->Progress(Progress);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::SynchronizeControllerLog(\r\n TSynchronizeController * /*Controller*/, TSynchronizeLogEntry /*Entry*/,\r\n const UnicodeString Message)\r\n{\r\n PrintMessage(Message);\r\n LogSynchronizeEvent(FScript->Terminal, Message);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::SynchronizeControllerAbort(TObject * /*Sender*/,\r\n bool /*Close*/)\r\n{\r\n FSynchronizeAborted = true;\r\n NotifyAbort();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::SynchronizeControllerSynchronize(\r\n TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,\r\n const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,\r\n const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,\r\n TSynchronizeOptions * /*Options*/, bool Full)\r\n{\r\n if (!Full)\r\n {\r\n try\r\n {\r\n FScript->Synchronize(LocalDirectory, RemoteDirectory, CopyParam,\r\n Params.Params, Checklist);\r\n }\r\n catch (Exception & E)\r\n {\r\n if ((FScript->Batch == TScript::BatchContinue) &&\r\n FScript->Terminal->Active)\r\n {\r\n // noop\r\n }\r\n else\r\n {\r\n throw;\r\n }\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::SynchronizeControllerSynchronizeInvalid(\r\n TSynchronizeController * /*Sender*/, const UnicodeString Directory, const UnicodeString ErrorStr)\r\n{\r\n if (!Directory.IsEmpty())\r\n {\r\n PrintMessage(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), true);\r\n }\r\n else\r\n {\r\n PrintMessage(LoadStr(WATCH_ERROR_GENERAL), true);\r\n }\r\n\r\n if (!ErrorStr.IsEmpty())\r\n {\r\n PrintMessage(ErrorStr, true);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::SynchronizeControllerTooManyDirectories(\r\n TSynchronizeController * /*Sender*/, int & MaxDirectories)\r\n{\r\n if (Aborted())\r\n {\r\n Abort();\r\n }\r\n\r\n if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)\r\n {\r\n MaxDirectories = GUIConfiguration->MaxWatchDirectories;\r\n }\r\n else\r\n {\r\n MaxDirectories *= 2;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ShowException(Exception * E)\r\n{\r\n DoShowException(NULL, E);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::DoShowException(TTerminal * Terminal, Exception * E)\r\n{\r\n if ((Terminal == NULL) && (FScript != NULL))\r\n {\r\n Terminal = FScript->Terminal;\r\n }\r\n\r\n UnicodeString Message;\r\n if (ExceptionFullMessage(E, Message))\r\n {\r\n FCommandError = true;\r\n PrintMessage(Message, true);\r\n }\r\n\r\n TTerminal * LoggingTerminal = Terminal;\r\n TSecondaryTerminal * SecondaryTerminal = dynamic_cast<TSecondaryTerminal *>(LoggingTerminal);\r\n if (SecondaryTerminal != NULL)\r\n {\r\n LoggingTerminal = SecondaryTerminal->MainTerminal;\r\n }\r\n\r\n if (LoggingTerminal != NULL)\r\n {\r\n LoggingTerminal->ActionLog->AddFailure(E);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall TConsoleRunner::DoInput(UnicodeString & Str, bool Echo,\r\n unsigned int Timeout, bool Interactive)\r\n{\r\n bool Result;\r\n if (Interactive && FConsole->NoInteractiveInput())\r\n {\r\n Result = false;\r\n }\r\n else\r\n {\r\n Result = FConsole->Input(Str, Echo, Timeout);\r\n }\r\n\r\n if (!Result)\r\n {\r\n NotifyAbort();\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::MasterPasswordPrompt()\r\n{\r\n bool Retry;\r\n do\r\n {\r\n UnicodeString Password;\r\n Input(LoadStr(CONSOLE_MASTER_PASSWORD_PROMPT), Password, false, true);\r\n Retry = !WinConfiguration->ValidateMasterPassword(Password);\r\n if (Retry)\r\n {\r\n FConsole->PrintLine(LoadStr(MASTER_PASSWORD_INCORRECT));\r\n }\r\n else\r\n {\r\n WinConfiguration->SetMasterPassword(Password);\r\n }\r\n }\r\n while (Retry);\r\n\r\n}\r\n//---------------------------------------------------------------------------\r\nUnicodeString TConsoleRunner::ExpandCommand(UnicodeString Command, TStrings * ScriptParameters)\r\n{\r\n DebugAssert(ScriptParameters != NULL);\r\n for (int Index = 0; Index < ScriptParameters->Count; Index++)\r\n {\r\n Command = ReplaceStr(Command, FORMAT(L\"%%%d%%\", (Index+1)),\r\n ScriptParameters->Strings[Index]);\r\n }\r\n\r\n TDateTime N = Now();\r\n\r\n if (!FExternalTimestampVar)\r\n {\r\n Command =\r\n ReplaceStr(Command, FORMAT(L\"%%%s%%\", (TimestampVarName)), FormatDateTime(L\"yyyymmddhhnnss\", N));\r\n }\r\n\r\n int Offset = 1;\r\n int P2;\r\n do\r\n {\r\n int P = Pos(UpperCase(L\"%\" + TimestampVarName), UpperCase(Command), Offset);\r\n if (P > 0)\r\n {\r\n Offset = P + 1 + TimestampVarName.Length();\r\n P2 = Pos(L\"%\", Command, Offset);\r\n int P3 = Pos(L\"#\", Command, Offset);\r\n if ((P2 > 0) && (P3 > 0) && (P3 < P2) &&\r\n ((P3 == Offset) || (Command[Offset] == L'+') || (Command[Offset] == L'-')))\r\n {\r\n bool Valid = true;\r\n TDateTime T = N;\r\n if (P3 > Offset)\r\n {\r\n bool Add = (Command[Offset] == L'+');\r\n Offset++;\r\n Valid = TryRelativeStrToDateTime(Command.SubString(Offset, P3 - Offset), T, Add);\r\n }\r\n\r\n Offset = P3 + 1;\r\n if (Valid)\r\n {\r\n UnicodeString TimestampFormat = Command.SubString(Offset, P2 - Offset);\r\n UnicodeString TimestampValue = FormatDateTime(TimestampFormat, T);\r\n Command = Command.SubString(1, P - 1) + TimestampValue + Command.SubString(P2 + 1, Command.Length() - P2);\r\n Offset = P + TimestampValue.Length();\r\n }\r\n }\r\n }\r\n else\r\n {\r\n P2 = 0;\r\n }\r\n }\r\n while (P2 > 0);\r\n\r\n Command = ExpandEnvironmentVariables(Command);\r\n return Command;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::Failed(bool & AnyError)\r\n{\r\n if (FScript != NULL)\r\n {\r\n FScript->Log(llMessage, L\"Failed\");\r\n }\r\n AnyError = true;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall TConsoleRunner::Run(const UnicodeString Session, TOptions * Options,\r\n TStrings * ScriptCommands, TStrings * ScriptParameters)\r\n{\r\n int ExitCode;\r\n try\r\n {\r\n bool AnyError = false;\r\n\r\n try\r\n {\r\n FScript = new TManagementScript(StoredSessions, FConsole->LimitedOutput());\r\n\r\n FScript->CopyParam = GUIConfiguration->DefaultCopyParam;\r\n FScript->SynchronizeParams = GUIConfiguration->SynchronizeParams;\r\n FScript->WantsProgress = FConsole->WantsProgress();\r\n FScript->OnPrint = ScriptPrint;\r\n FScript->OnPrintProgress = ScriptPrintProgress;\r\n FScript->OnInput = ScriptInput;\r\n FScript->OnTerminalPromptUser = ScriptTerminalPromptUser;\r\n FScript->OnShowExtendedException = ScriptShowExtendedException;\r\n FScript->OnTerminalQueryUser = ScriptTerminalQueryUser;\r\n FScript->OnQueryCancel = ScriptQueryCancel;\r\n FScript->OnSynchronizeStartStop = ScriptSynchronizeStartStop;\r\n FScript->OnProgress = ScriptProgress;\r\n FScript->Interactive = (ScriptCommands == NULL) && FConsole->Interactive();\r\n\r\n UpdateTitle();\r\n\r\n // everything until the first manually entered command is \"batch\"\r\n // (including opening session from command line and script file)\r\n FBatchScript = true;\r\n\r\n if (!Session.IsEmpty())\r\n {\r\n if (!FScript->Interactive)\r\n {\r\n PrintMessage(LoadStr(SCRIPT_CMDLINE_SESSION));\r\n }\r\n FCommandError = false;\r\n FScript->Connect(Session, Options, false);\r\n if (FCommandError)\r\n {\r\n Failed(AnyError);\r\n }\r\n }\r\n\r\n FScript->Groups = Options->SwitchValue(L\"xmlgroups\", true, false);\r\n\r\n int ScriptPos = 0;\r\n bool Result;\r\n do\r\n {\r\n UpdateTitle();\r\n\r\n UnicodeString Command;\r\n if ((ScriptCommands != NULL) && (ScriptPos < ScriptCommands->Count))\r\n {\r\n Result = true;\r\n Command = ScriptCommands->Strings[ScriptPos];\r\n ScriptPos++;\r\n }\r\n else\r\n {\r\n if (FBatchScript)\r\n {\r\n // no longer batch\r\n FBatchScript = false;\r\n FScript->StartInteractive();\r\n }\r\n Print(L\"winscp> \");\r\n Result = DoInput(Command, true, 0, false);\r\n }\r\n\r\n if (Result)\r\n {\r\n FCommandError = false;\r\n FScript->Command(ExpandCommand(Command, ScriptParameters));\r\n\r\n if (FCommandError)\r\n {\r\n Failed(AnyError);\r\n if (FScript->Batch == TScript::BatchAbort)\r\n {\r\n Result = false;\r\n }\r\n }\r\n\r\n if (FScript->Terminal != NULL)\r\n {\r\n FScript->Terminal->Idle();\r\n }\r\n }\r\n }\r\n while (Result && FScript->Continue && !Aborted());\r\n }\r\n catch(Exception & E)\r\n {\r\n Failed(AnyError);\r\n ShowException(&E);\r\n }\r\n\r\n if (FLastProgressLen > 0)\r\n {\r\n FConsole->Print(L\"\\n\");\r\n FLastProgressLen = 0;\r\n }\r\n\r\n ExitCode = (AnyError || FAborted) ? RESULT_ANY_ERROR : RESULT_SUCCESS;\r\n\r\n if (FScript != NULL)\r\n {\r\n UnicodeString ExitCodeMessage = FORMAT(L\"Exit code: %d\", (ExitCode));\r\n FScript->Log(llMessage, ExitCodeMessage);\r\n if (Configuration->LogProtocol >= 1)\r\n {\r\n FConsole->Print(ExitCodeMessage + L\"\\n\");\r\n UnicodeString LogMessage = FConsole->FinalLogMessage();\r\n if (!LogMessage.IsEmpty())\r\n {\r\n FScript->Log(llMessage, LogMessage);\r\n FConsole->Print(LogMessage + L\"\\n\");\r\n }\r\n }\r\n }\r\n }\r\n __finally\r\n {\r\n delete FScript;\r\n FScript = NULL;\r\n }\r\n\r\n return ExitCode;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::UpdateTitle()\r\n{\r\n UnicodeString NewTitle;\r\n if (FScript->Terminal != NULL)\r\n {\r\n NewTitle = FormatMainFormCaption(FScript->Terminal->SessionData->SessionName);\r\n }\r\n else\r\n {\r\n NewTitle = FormatMainFormCaption(L\"\");\r\n }\r\n FConsole->SetTitle(NewTitle);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall TConsoleRunner::ConfigurationChange(TObject * /*Sender*/)\r\n{\r\n if (FScript != NULL)\r\n {\r\n FScript->ReflectSettings();\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nstatic UnicodeString __fastcall GetExeBaseName()\r\n{\r\n return ExtractFileBaseName(Application->ExeName);\r\n}\r\n//---------------------------------------------------------------------------\r\nstatic void __fastcall PrintUsageSyntax(TConsole * Console, const UnicodeString & Str)\r\n{\r\n Console->PrintLine(GetExeBaseName() + L\" \" + Str);\r\n}\r\n//---------------------------------------------------------------------------\r\ntypedef std::vector<std::pair<UnicodeString, UnicodeString> > TSwitchesUsage;\r\n//---------------------------------------------------------------------------\r\nstatic void __fastcall RegisterSwitch(\r\n TSwitchesUsage & SwitchesUsage, const UnicodeString & Name, const UnicodeString & Desc)\r\n{\r\n SwitchesUsage.push_back(std::make_pair(LowerCase(Name), Desc));\r\n}\r\n//---------------------------------------------------------------------------\r\nstatic void __fastcall RegisterSwitch(\r\n TSwitchesUsage & SwitchesUsage, const UnicodeString & Name, int DescID)\r\n{\r\n UnicodeString Desc = LoadStr(DescID);\r\n Desc = ReplaceText(Desc, L\"%APP%\", GetExeBaseName());\r\n RegisterSwitch(SwitchesUsage, Name, Desc);\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall Usage(TConsole * Console)\r\n{\r\n Console->PrintLine(FORMAT(L\"WinSCP, %s\", (Configuration->VersionStr)));\r\n UnicodeString Copyright =\r\n ReplaceText(LoadStr(WINSCP_COPYRIGHT), L\"©\", L\"(c)\");\r\n Console->PrintLine(Copyright);\r\n Console->PrintLine();\r\n Console->PrintLine(LoadStr(USAGE_SYNTAX_LABEL));\r\n\r\n if (!Console->CommandLineOnly())\r\n {\r\n PrintUsageSyntax(Console, L\"site|workspace|folder\");\r\n PrintUsageSyntax(Console, L\"(sftp|scp|ftp[es]|dav[s]|s3)://[user[:password]@]host[:port][/path/[file]]\");\r\n PrintUsageSyntax(Console, FORMAT(L\"[mysession] /%s=<name>\", (LowerCase(SESSIONNAME_SWICH))));\r\n PrintUsageSyntax(Console, L\"[mysession] /newinstance\");\r\n PrintUsageSyntax(Console, L\"[mysession] /edit <path>\");\r\n PrintUsageSyntax(Console, FORMAT(L\"[mysession] /%s[=<file>]\", (LowerCase(BROWSE_SWITCH))));\r\n PrintUsageSyntax(Console, FORMAT(L\"[mysession] /%s [local_dir] [remote_dir] [/%s]\", (LowerCase(SYNCHRONIZE_SWITCH), LowerCase(DEFAULTS_SWITCH))));\r\n PrintUsageSyntax(Console, FORMAT(L\"[mysession] /%s [local_dir] [remote_dir] [/%s]\", (LowerCase(KEEP_UP_TO_DATE_SWITCH), LowerCase(DEFAULTS_SWITCH))));\r\n PrintUsageSyntax(Console, FORMAT(L\"[mysession] /%s [path]\", (LowerCase(REFRESH_SWITCH))));\r\n PrintUsageSyntax(Console, FORMAT(L\"[mysession] [/privatekey=<file> [/%s=<passphrase>]]\", (PassphraseOption)));\r\n PrintUsageSyntax(Console, L\"[mysession] [/hostkey=<fingerprint>]\");\r\n PrintUsageSyntax(Console, FORMAT(L\"[mysession] [/clientcert=<file> [/%s=<passphrase>]]\", (PassphraseOption)));\r\n PrintUsageSyntax(Console, L\"[mysession] [/certificate=<fingerprint>]\");\r\n PrintUsageSyntax(Console, L\"[mysession] [/passive[=on|off]] [/implicit|explicit]\");\r\n PrintUsageSyntax(Console, L\"[mysession] [/timeout=<sec>]\");\r\n PrintUsageSyntax(Console, L\"[mysession] [/rawsettings setting1=value1 setting2=value2 ...]\");\r\n }\r\n PrintUsageSyntax(Console,\r\n UnicodeString(!Console->CommandLineOnly() ? L\"[/console] \" : L\"\") +\r\n FORMAT(L\"[/script=<file>] [/%s cmd1...] [/parameter // param1...]\", (LowerCase(COMMAND_SWITCH))));\r\n PrintUsageSyntax(Console,\r\n FORMAT(L\"[/%s=<logfile> [/loglevel=<level>]] [/%s=[<count>%s]<size>]\", (LowerCase(LOG_SWITCH), LowerCase(LOGSIZE_SWITCH), LOGSIZE_SEPARATOR)));\r\n PrintUsageSyntax(Console, L\"[/xmllog=<logfile> [/xmlgroups]]\");\r\n PrintUsageSyntax(Console,\r\n FORMAT(L\"[/%s=<inifile>]\", (LowerCase(INI_SWITCH))));\r\n PrintUsageSyntax(Console, FORMAT(L\"[/%s config1=value1 config2=value2 ...]\", (LowerCase(RAW_CONFIG_SWITCH))));\r\n PrintUsageSyntax(Console, FORMAT(L\"[/%s setting1=value1 setting2=value2 ...]\", (LowerCase(RAWTRANSFERSETTINGS_SWITCH))));\r\n PrintUsageSyntax(Console, L\"/batchsettings <site_mask> setting1=value1 setting2=value2 ...\");\r\n PrintUsageSyntax(Console, FORMAT(L\"/%s keyfile [/%s=<file>] [/%s] [/%s=<text>]\",\r\n (LowerCase(KEYGEN_SWITCH), LowerCase(KEYGEN_OUTPUT_SWITCH), LowerCase(KEYGEN_CHANGE_PASSPHRASE_SWITCH), LowerCase(KEYGEN_COMMENT_SWITCH))));\r\n if (!Console->CommandLineOnly())\r\n {\r\n PrintUsageSyntax(Console, L\"/update\");\r\n }\r\n PrintUsageSyntax(Console, TProgramParams::FormatSwitch(LowerCase(INFO_SWITCH)));\r\n PrintUsageSyntax(Console, L\"/help\");\r\n\r\n Console->PrintLine();\r\n\r\n TSwitchesUsage SwitchesUsage;\r\n if (!Console->CommandLineOnly())\r\n {\r\n RegisterSwitch(SwitchesUsage, L\"session\", USAGE_SESSION);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(SESSIONNAME_SWICH) + L\"=\", USAGE_SESSIONNAME);\r\n RegisterSwitch(SwitchesUsage, L\"/newinstance\", USAGE_NEWINSTANCE);\r\n RegisterSwitch(SwitchesUsage, L\"/edit\", USAGE_EDIT);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(BROWSE_SWITCH), USAGE_BROWSE);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH), USAGE_SYNCHRONIZE);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH), USAGE_KEEPUPTODATE);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(REFRESH_SWITCH), USAGE_REFRESH);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(DEFAULTS_SWITCH), USAGE_DEFAULTS);\r\n RegisterSwitch(SwitchesUsage, L\"/privatekey=\", USAGE_PRIVATEKEY);\r\n RegisterSwitch(SwitchesUsage, L\"/hostkey=\", USAGE_HOSTKEY);\r\n RegisterSwitch(SwitchesUsage, L\"/clientcert=\", USAGE_CLIENTCERT);\r\n RegisterSwitch(SwitchesUsage, L\"/certificate=\", USAGE_CERTIFICATE);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(PassphraseOption) + L\"=\", USAGE_PASSPHRASE);\r\n RegisterSwitch(SwitchesUsage, L\"/passive=\", USAGE_PASSIVE);\r\n RegisterSwitch(SwitchesUsage, L\"/implicit\", USAGE_IMPLICIT);\r\n RegisterSwitch(SwitchesUsage, L\"/explicit\", USAGE_EXPLICIT);\r\n RegisterSwitch(SwitchesUsage, L\"/timeout=\", USAGE_TIMEOUT);\r\n RegisterSwitch(SwitchesUsage, L\"/rawsettings\", USAGE_RAWSETTINGS);\r\n RegisterSwitch(SwitchesUsage, L\"/console\", USAGE_CONSOLE);\r\n }\r\n RegisterSwitch(SwitchesUsage, L\"/script=\", USAGE_SCRIPT);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(COMMAND_SWITCH), USAGE_COMMAND);\r\n RegisterSwitch(SwitchesUsage, L\"/parameter\", USAGE_PARAMETER);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(LOG_SWITCH) + L\"=\", USAGE_LOG);\r\n RegisterSwitch(SwitchesUsage, L\"/loglevel=\", USAGE_LOGLEVEL);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(LOGSIZE_SWITCH) + L\"=\", USAGE_LOGSIZE);\r\n RegisterSwitch(SwitchesUsage, L\"/xmllog=\", USAGE_XMLLOG);\r\n RegisterSwitch(SwitchesUsage, L\"/xmlgroups\", USAGE_XMLGROUPS);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(INI_SWITCH) + L\"=\", USAGE_INI);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(RAW_CONFIG_SWITCH), USAGE_RAWCONFIG);\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), USAGE_RAWTRANSFERSETTINGS);\r\n RegisterSwitch(SwitchesUsage, L\"/batchsettings\", USAGE_BATCHSETTINGS);\r\n UnicodeString KeyGenDesc =\r\n FMTLOAD(USAGE_KEYGEN, (\r\n TProgramParams::FormatSwitch(LowerCase(KEYGEN_OUTPUT_SWITCH)) + L\"=\",\r\n TProgramParams::FormatSwitch(LowerCase(KEYGEN_CHANGE_PASSPHRASE_SWITCH)),\r\n TProgramParams::FormatSwitch(LowerCase(KEYGEN_COMMENT_SWITCH)) + L\"=\"));\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(KEYGEN_SWITCH), KeyGenDesc);\r\n if (!Console->CommandLineOnly())\r\n {\r\n RegisterSwitch(SwitchesUsage, L\"/update\", USAGE_UPDATE);\r\n }\r\n RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(INFO_SWITCH), USAGE_INFO);\r\n RegisterSwitch(SwitchesUsage, L\"/help\", USAGE_HELP);\r\n\r\n int MaxSwitchLen = 0;\r\n TSwitchesUsage::const_iterator Index = SwitchesUsage.begin();\r\n while (Index != SwitchesUsage.end())\r\n {\r\n MaxSwitchLen = std::max(Index->first.Length(), MaxSwitchLen);\r\n ++Index;\r\n }\r\n\r\n Index = SwitchesUsage.begin();\r\n while (Index != SwitchesUsage.end())\r\n {\r\n UnicodeString Label =\r\n UnicodeString(L\" \") +\r\n Index->first +\r\n UnicodeString::StringOfChar(L' ', MaxSwitchLen - Index->first.Length()) +\r\n L\" \";\r\n Console->Print(Label);\r\n\r\n const int ConsoleWidth = 80;\r\n int DescWidth = ConsoleWidth - Label.Length() - 1;\r\n\r\n bool FirstLine = true;\r\n UnicodeString Desc = Index->second;\r\n while (!Desc.IsEmpty())\r\n {\r\n UnicodeString DescLine = CutToChar(Desc, L'\\n', true);\r\n DescLine = WrapText(DescLine, L\"\\n\", TSysCharSet() << L' ', DescWidth);\r\n while (!DescLine.IsEmpty())\r\n {\r\n UnicodeString DescLineLine = CutToChar(DescLine, L'\\n', true);\r\n if (!FirstLine)\r\n {\r\n DescLineLine =\r\n UnicodeString::StringOfChar(L' ', Label.Length()) +\r\n DescLineLine;\r\n }\r\n FirstLine = false;\r\n Console->PrintLine(DescLineLine);\r\n }\r\n }\r\n ++Index;\r\n }\r\n\r\n Console->WaitBeforeExit();\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall HandleException(TConsole * Console, Exception & E)\r\n{\r\n UnicodeString Message;\r\n if (ExceptionFullMessage(&E, Message))\r\n {\r\n Console->Print(Message);\r\n }\r\n return RESULT_ANY_ERROR;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall BatchSettings(TConsole * Console, TProgramParams * Params)\r\n{\r\n int Result = RESULT_SUCCESS;\r\n try\r\n {\r\n std::unique_ptr<TStrings> Arguments(new TStringList());\r\n if (!DebugAlwaysTrue(Params->FindSwitch(L\"batchsettings\", Arguments.get())))\r\n {\r\n Abort();\r\n }\r\n else\r\n {\r\n if (Arguments->Count < 1)\r\n {\r\n throw Exception(LoadStr(BATCH_SET_NO_MASK));\r\n }\r\n else if (Arguments->Count < 2)\r\n {\r\n throw Exception(LoadStr(BATCH_SET_NO_SETTINGS));\r\n }\r\n else\r\n {\r\n TFileMasks Mask(Arguments->Strings[0]);\r\n Arguments->Delete(0);\r\n\r\n std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Arguments.get(), false));\r\n\r\n int Matches = 0;\r\n int Changes = 0;\r\n\r\n for (int Index = 0; Index < StoredSessions->Count; Index++)\r\n {\r\n TSessionData * Data = StoredSessions->Sessions[Index];\r\n if (!Data->IsWorkspace &&\r\n Mask.Matches(Data->Name, false, false))\r\n {\r\n Matches++;\r\n std::unique_ptr<TSessionData> OriginalData(new TSessionData(L\"\"));\r\n OriginalData->CopyDataNoRecrypt(Data);\r", " Data->ApplyRawSettings(OptionsStorage.get(), false);\r", " bool Changed = !OriginalData->IsSame(Data, false);\r\n if (Changed)\r\n {\r\n Changes++;\r\n }\r\n UnicodeString StateStr = LoadStr(Changed ? BATCH_SET_CHANGED : BATCH_SET_NOT_CHANGED);\r\n Console->PrintLine(FORMAT(L\"%s - %s\", (Data->Name, StateStr)));\r\n }\r\n }\r\n\r\n StoredSessions->Save(false, true); // explicit\r\n Console->PrintLine(FMTLOAD(BATCH_SET_SUMMARY, (Matches, Changes)));\r\n }\r\n }\r\n }\r\n catch (Exception & E)\r\n {\r\n Result = HandleException(Console, E);\r\n }\r\n\r\n Console->WaitBeforeExit();\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall FindPuttygenCompatibleSwitch(\r\n TProgramParams * Params, const UnicodeString & Name, const UnicodeString & PuttygenName, UnicodeString & Value, bool & Set)\r\n{\r\n bool Result = Params->FindSwitch(Name, Value, Set);\r\n if (!Result)\r\n {\r\n std::unique_ptr<TStrings> Args(new TStringList());\r\n Result = Params->FindSwitchCaseSensitive(PuttygenName, Args.get(), 1);\r\n if (Result && (Args->Count >= 1))\r\n {\r\n Value = Args->Strings[0];\r\n Set = true;\r\n }\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall KeyGen(TConsole * Console, TProgramParams * Params)\r\n{\r\n int Result = RESULT_SUCCESS;\r\n UnicodeString Passphrase;\r\n UnicodeString NewPassphrase;\r\n try\r\n {\r\n UnicodeString InputFileName;\r\n std::unique_ptr<TStrings> Args(new TStringList());\r\n if (!Params->FindSwitch(KEYGEN_SWITCH, Args.get(), 1) ||\r\n (Args->Count < 1) ||\r\n Args->Strings[0].IsEmpty())\r\n {\r\n throw Exception(LoadStr(KEYGEN_NO_INPUT));\r\n }\r\n InputFileName = Args->Strings[0];\r\n\r\n bool ValueSet;\r\n UnicodeString OutputFileName;\r\n FindPuttygenCompatibleSwitch(Params, KEYGEN_OUTPUT_SWITCH, L\"o\", OutputFileName, ValueSet);\r\n\r\n UnicodeString NewComment;\r\n FindPuttygenCompatibleSwitch(Params, KEYGEN_COMMENT_SWITCH, L\"C\", NewComment, ValueSet);\r\n\r\n bool NewPassphraseSet;\r\n bool ChangePassphrase =\r\n FindPuttygenCompatibleSwitch(Params, KEYGEN_CHANGE_PASSPHRASE_SWITCH, L\"P\", NewPassphrase, NewPassphraseSet);\r\n\r\n TKeyType Type = KeyType(InputFileName);\r\n int Error = errno;\r\n switch (Type)\r\n {\r\n case ktSSH1:\r\n throw Exception(LoadStr(KEYGEN_SSH1));\r\n\r\n case ktSSH2:\r\n if (NewComment.IsEmpty() && !ChangePassphrase)\r\n {\r\n throw Exception(LoadStr(KEYGEN_NO_ACTION));\r\n }\r\n break;\r\n\r\n case ktOpenSSHPEM:\r\n case ktOpenSSHNew:\r\n case ktSSHCom:\r\n if (OutputFileName.IsEmpty())\r\n {\r\n throw Exception(LoadStr(KEYGEN_NO_OUTPUT));\r\n }\r\n break;\r\n\r\n case ktSSH1Public:\r\n case ktSSH2PublicRFC4716:\r\n case ktSSH2PublicOpenSSH:\r\n throw Exception(LoadStr(KEYGEN_PUBLIC));\r\n\r\n case ktUnopenable:\r\n throw EOSExtException(FMTLOAD(KEY_TYPE_UNOPENABLE, (InputFileName)), Error);\r\n\r\n case ktOpenSSHAuto:\r\n default:\r\n DebugFail();\r\n // fallthru\r\n case ktUnknown:\r\n throw Exception(FMTLOAD(KEY_TYPE_UNKNOWN2, (InputFileName)));\r\n }\r\n\r\n UnicodeString Comment;\r\n if (IsKeyEncrypted(Type, InputFileName, Comment))\r\n {\r\n Passphrase = Params->SwitchValue(PassphraseOption);\r\n if (Passphrase.IsEmpty())\r\n {\r\n Console->Print(StripHotkey(FMTLOAD(PROMPT_KEY_PASSPHRASE, (Comment))) + L\" \");\r\n if (!Console->Input(Passphrase, false, 0) ||\r\n Passphrase.IsEmpty())\r\n {\r\n Abort();\r\n }\r\n }\r\n }\r\n\r\n TPrivateKey * PrivateKey = LoadKey(Type, InputFileName, Passphrase);\r\n\r\n try\r\n {\r\n if (!NewComment.IsEmpty())\r\n {\r\n ChangeKeyComment(PrivateKey, NewComment);\r\n }\r\n\r\n if (ChangePassphrase)\r\n {\r\n if (!NewPassphraseSet)\r\n {\r\n Console->Print(LoadStr(KEYGEN_PASSPHRASE) + L\" \");\r\n if (!Console->Input(NewPassphrase, false, 0))\r\n {\r\n Abort();\r\n }\r\n\r\n Console->Print(LoadStr(KEYGEN_PASSPHRASE2) + L\" \");\r\n UnicodeString NewPassphrase2;\r\n if (!Console->Input(NewPassphrase2, false, 0))\r\n {\r\n Abort();\r\n }\r\n\r\n if (NewPassphrase != NewPassphrase2)\r\n {\r\n Shred(NewPassphrase2);\r\n throw Exception(LoadStr(KEYGEN_PASSPHRASES_MISMATCH));\r\n }\r\n }\r\n }\r\n else\r\n {\r\n NewPassphrase = Passphrase;\r\n }\r\n\r\n if (OutputFileName.IsEmpty())\r\n {\r\n OutputFileName = InputFileName;\r\n }\r\n\r\n SaveKey(ktSSH2, OutputFileName, NewPassphrase, PrivateKey);\r\n\r\n Console->PrintLine(FMTLOAD(KEYGEN_SAVED, (OutputFileName)));\r\n }\r\n __finally\r\n {\r\n FreeKey(PrivateKey);\r\n }\r\n }\r\n catch (Exception & E)\r\n {\r\n Result = HandleException(Console, E);\r\n }\r\n\r\n Shred(Passphrase);\r\n Shred(NewPassphrase);\r\n\r\n Console->WaitBeforeExit();\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall FingerprintScan(TConsole * Console, TProgramParams * Params)\r\n{\r\n int Result = RESULT_SUCCESS;\r\n try\r\n {\r\n CheckLogParam(Params);\r\n\r\n std::unique_ptr<TSessionData> SessionData;\r\n\r\n if (Params->ParamCount > 0)\r\n {\r\n UnicodeString SessionUrl = Params->Param[1];\r\n bool DefaultsOnly;\r\n SessionData.reset(StoredSessions->ParseUrl(SessionUrl, Params, DefaultsOnly));\r\n if (DefaultsOnly || !SessionData->CanLogin ||\r\n (!SessionData->UsesSsh && (SessionData->Ftps == ftpsNone)))\r\n {\r\n SessionData.reset(NULL);\r\n }\r\n }\r\n\r\n if (!SessionData)\r\n {\r\n throw Exception(LoadStr(FINGERPRINTSCAN_NEED_SECURE_SESSION));\r\n }\r\n\r\n std::unique_ptr<TTerminal> Terminal(new TTerminal(SessionData.get(), Configuration));\r\n UnicodeString SHA256;\r\n UnicodeString SHA1;\r\n UnicodeString MD5;\r\n Terminal->FingerprintScan(SHA256, SHA1, MD5);\r\n if (!SHA256.IsEmpty())\r\n {\r\n Console->PrintLine(FORMAT(L\"SHA-256: %s\", (SHA256)));\r\n }\r\n if (!SHA1.IsEmpty())\r\n {\r\n Console->PrintLine(FORMAT(L\"SHA-1: %s\", (SHA1)));\r\n }\r\n if (!MD5.IsEmpty())\r\n {\r\n Console->PrintLine(FORMAT(L\"MD5: %s\", (MD5)));\r\n }\r\n }\r\n catch (Exception & E)\r\n {\r\n Result = HandleException(Console, E);\r\n }\r\n\r\n Console->WaitBeforeExit();\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall DumpCallstack(TConsole * Console, TProgramParams * Params)\r\n{\r\n int Result = RESULT_SUCCESS;\r\n try\r\n {\r\n int ProcessId = StrToInt(Params->SwitchValue(DUMPCALLSTACK_SWITCH));\r\n UnicodeString EventName = DumpCallstackEventName(ProcessId);\r\n UnicodeString FileName = DumpCallstackFileName(ProcessId);\r\n if (FileExists(FileName))\r\n {\r\n DeleteFileChecked(FileName);\r\n }\r\n\r\n HANDLE Event = OpenEvent(EVENT_ALL_ACCESS, false, EventName.c_str());\r\n if (Event == NULL)\r\n {\r\n throw ExtException(FORMAT(L\"Error communicating with process %d.\", (ProcessId)), LastSysErrorMessage());\r\n }\r\n\r\n SetEvent(Event);\r\n CloseHandle(Event);\r\n\r\n Console->PrintLine(FORMAT(L\"Requested callstack dump for process %d...\", (ProcessId)));\r\n\r\n int Timeout = 30;\r\n while (!FileExists(FileName))\r\n {\r\n Sleep(1000);\r\n Timeout--;\r\n if (Timeout == 0)\r\n {\r\n throw Exception(L\"Timeout\");\r\n }\r\n }\r\n\r\n Console->PrintLine(FORMAT(L\"Callstack dumped to file \\\"%s\\\".\", (FileName)));\r\n }\r\n catch (Exception & E)\r\n {\r\n Result = HandleException(Console, E);\r\n }\r\n\r\n Console->WaitBeforeExit();\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid static PrintList(TConsole * Console, const UnicodeString & Caption, TStrings * List)\r\n{\r\n Console->PrintLine(Caption);\r\n for (int Index = 0; Index < List->Count; Index++)\r\n {\r\n Console->PrintLine(List->Strings[Index]);\r\n }\r\n Console->PrintLine();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid static PrintListAndFree(TConsole * Console, const UnicodeString & Caption, TStrings * List)\r\n{\r\n std::unique_ptr<TStrings> Owner(List);\r\n PrintList(Console, Caption, List);\r\n}\r\n//---------------------------------------------------------------------------\r\nint Info(TConsole * Console)\r\n{\r\n int Result = RESULT_SUCCESS;\r\n try\r\n {\r\n PrintListAndFree(Console, L\"SSH encryption ciphers:\", SshCipherList());\r\n PrintListAndFree(Console, L\"SSH key exchange algorithms:\", SshKexList());\r\n PrintListAndFree(Console, L\"SSH host key algorithms:\", SshHostKeyList());\r\n PrintListAndFree(Console, L\"SSH MAC algorithms:\", SshMacList());\r\n PrintListAndFree(Console, L\"TLS/SSL cipher suites:\", TlsCipherList());\r\n }\r\n catch (Exception & E)\r\n {\r\n Result = HandleException(Console, E);\r\n }\r\n\r\n Console->WaitBeforeExit();\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall Console(TConsoleMode Mode)\r\n{\r\n DebugAssert(Mode != cmNone);\r\n TProgramParams * Params = TProgramParams::Instance();\r\n int Result = RESULT_SUCCESS;\r\n TConsole * Console = NULL;\r\n TConsoleRunner * Runner = NULL;\r\n TStrings * ScriptCommands = new TStringList();\r\n TStrings * ScriptParameters = new TStringList();\r\n try\r\n {\r\n UnicodeString ConsoleInstance;\r\n // First check for /consoleinstance as /console is always used by winscp.com\r\n if (Params->FindSwitch(L\"consoleinstance\", ConsoleInstance))\r\n {\r\n Configuration->Usage->Inc(L\"ConsoleExternal\");\r\n Console = new TExternalConsole(ConsoleInstance, Params->FindSwitch(L\"nointeractiveinput\"));\r\n }\r\n else if (Params->FindSwitch(L\"Console\") || (Mode != cmScripting))\r\n {\r\n Configuration->Usage->Inc(L\"ConsoleOwn\");\r\n Console = TOwnConsole::Instance();\r\n }\r\n else\r\n {\r\n Configuration->Usage->Inc(L\"ConsoleNull\");\r\n Console = new TNullConsole();\r\n }\r\n\r\n SetNoGUI();\r\n\r\n if (Mode == cmHelp)\r\n {\r\n Configuration->Usage->Inc(L\"UsageShown\");\r\n Usage(Console);\r\n }\r\n else if (Mode == cmBatchSettings)\r\n {\r\n if (CheckSafe(Params))\r\n {\r\n Configuration->Usage->Inc(L\"BatchSettings\");\r\n Result = BatchSettings(Console, Params);\r\n }\r\n }\r\n else if (Mode == cmKeyGen)\r\n {\r\n if (CheckSafe(Params))\r\n {\r\n Configuration->Usage->Inc(L\"KeyGen\");\r\n Result = KeyGen(Console, Params);\r\n }\r\n }\r\n else if (Mode == cmFingerprintScan)\r\n {\r\n if (CheckSafe(Params))\r\n {\r\n Configuration->Usage->Inc(L\"FingerprintScan\");\r\n Result = FingerprintScan(Console, Params);\r\n }\r\n }\r\n else if (Mode == cmDumpCallstack)\r\n {\r\n Result = DumpCallstack(Console, Params);\r\n }\r\n else if (Mode == cmInfo)\r\n {\r\n Result = Info(Console);\r\n }\r\n else if (Mode == cmComRegistration)\r\n {\r\n if (CheckSafe(Params))\r\n {\r\n Result = ComRegistration(Console);\r\n }\r\n }\r\n else\r\n {\r\n Runner = new TConsoleRunner(Console);\r\n\r\n try\r\n {\r\n if (CheckSafe(Params))\r\n {\r\n UnicodeString Value;\r\n if (Params->FindSwitch(SCRIPT_SWITCH, Value) && !Value.IsEmpty())\r\n {\r\n Configuration->Usage->Inc(L\"ScriptFile\");\r\n LoadScriptFromFile(Value, ScriptCommands);\r\n }\r\n Params->FindSwitch(COMMAND_SWITCH, ScriptCommands);\r\n if (ScriptCommands->Count > 0)\r\n {\r\n Configuration->Usage->Inc(L\"ScriptCommands\");\r\n }\r\n Params->FindSwitch(L\"parameter\", ScriptParameters);\r\n if (ScriptParameters->Count > 0)\r\n {\r\n Configuration->Usage->Inc(L\"ScriptParameters\");\r\n }\r\n }\r\n\r\n UnicodeString Session;\r\n if (Params->ParamCount >= 1)\r\n {\r\n Session = Params->Param[1];\r\n if (Params->ParamCount > 1)\r\n {\r\n Runner->PrintMessage(LoadStr(SCRIPT_CMDLINE_PARAMETERS));\r\n }\r\n }\r\n\r\n CheckLogParam(Params);\r\n CheckXmlLogParam(Params);\r\n\r\n Result = Runner->Run(Session, Params,\r\n (ScriptCommands->Count > 0 ? ScriptCommands : NULL),\r\n ScriptParameters);\r\n }\r\n catch(Exception & E)\r\n {\r\n Runner->ShowException(&E);\r\n Result = RESULT_ANY_ERROR;\r\n }\r\n }\r\n }\r\n __finally\r\n {\r\n delete Runner;\r\n delete Console;\r\n delete ScriptCommands;\r\n delete ScriptParameters;\r\n }\r\n\r\n return Result;\r\n}" ]
[ 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 53, 80, 2275, 473, 1511, 2372, 1100], "buggy_code_start_loc": [46, 52, 79, 599, 57, 1510, 2371, 1099], "filenames": ["source/Console.cbproj", "source/DragExt.cbproj", "source/WinSCP.cbproj", "source/core/SessionData.cpp", "source/core/SessionData.h", "source/forms/Custom.cpp", "source/windows/ConsoleRunner.cpp", "source/windows/WinMain.cpp"], "fixing_code_end_loc": [47, 53, 80, 2294, 474, 1511, 2372, 1103], "fixing_code_start_loc": [46, 52, 79, 599, 58, 1510, 2371, 1099], "message": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:winscp:winscp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C081564B-8EF8-4C8A-9EB0-1C50D5A8F18B", "versionEndExcluding": "5.17.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)"}, {"lang": "es", "value": "WinSCP anterior a la versi\u00f3n 5.17.10 permite a los atacantes remotos ejecutar programas arbitrarios cuando el manejador de URLs encuentra una URL manipulada que carga la configuraci\u00f3n de la sesi\u00f3n. (Por ejemplo, esto es explotable en una instalaci\u00f3n por defecto en la que WinSCP es el manejador de URLs sftp://)"}], "evaluatorComment": null, "id": "CVE-2021-3331", "lastModified": "2021-02-04T15:59:24.960", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-01-27T21:15:16.840", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://winscp.net/eng/docs/history#5.17.10"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://winscp.net/eng/docs/rawsettings"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://winscp.net/tracker/1943"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, "type": "NVD-CWE-Other"}
177
Determine whether the {function_name} code is vulnerable or not.
[ "//---------------------------------------------------------------------------\r\n#include <vcl.h>\r\n#pragma hdrstop\r\n\r\n#include <CoreMain.h>\r\n\r\n#include <TextsWin.h>\r\n#include <TextsCore.h>\r\n#include <HelpWin.h>\r\n\r\n#include \"CustomScpExplorer.h\"\r\n#include \"TerminalManager.h\"\r\n#include \"NonVisual.h\"\r\n#include \"Glyphs.h\"\r\n#include \"ProgParams.h\"\r\n#include \"Setup.h\"\r\n#include \"WinConfiguration.h\"\r\n#include \"GUITools.h\"\r\n#include \"Tools.h\"\r\n#include \"WinApi.h\"\r\n#include <DateUtils.hpp>\r\n//---------------------------------------------------------------------------\r\n#pragma package(smart_init)\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall GetLoginData(UnicodeString SessionName, TOptions * Options,\r\n TObjectList * DataList, UnicodeString & DownloadFile, bool NeedSession, TForm * LinkedForm, int Flags)\r\n{\r\n bool DefaultsOnly = false;\r\n\r\n UnicodeString FolderOrWorkspaceName = DecodeUrlChars(SessionName);\r\n if (StoredSessions->IsFolder(FolderOrWorkspaceName) ||\r\n StoredSessions->IsWorkspace(FolderOrWorkspaceName))\r\n {\r\n StoredSessions->GetFolderOrWorkspace(FolderOrWorkspaceName, DataList);\r\n }\r\n else\r\n {\r\n TSessionData * SessionData =\r\n StoredSessions->ParseUrl(SessionName, Options, DefaultsOnly, &DownloadFile, NULL, NULL, Flags);\r\n DataList->Add(SessionData);\r\n\r\n if (DataList->Count == 1)\r\n {\r\n TSessionData * SessionData = DebugNotNull(dynamic_cast<TSessionData *>(DataList->Items[0]));\r\n if (SessionData->SaveOnly)\r\n {\r\n Configuration->Usage->Inc(L\"CommandLineSessionSave\");\r\n TSessionData * SavedSession = DoSaveSession(SessionData, NULL, true, NULL);\r\n if (SavedSession == NULL)\r\n {\r\n Abort();\r\n }\r\n WinConfiguration->LastStoredSession = SavedSession->Name;\r\n DataList->Clear();\r\n }\r\n else if (!SessionData->PuttyProtocol.IsEmpty())\r\n {\r\n // putty does not support resolving environment variables in session settings\r\n // though it's hardly of any use here.\r\n SessionData->ExpandEnvironmentVariables();\r\n OpenSessionInPutty(GUIConfiguration->PuttyPath, SessionData);\r\n DataList->Clear();\r\n Abort();\r\n }\r\n }\r\n }\r\n\r\n if (DefaultsOnly && !NeedSession)\r\n {\r\n // No URL specified on command-line and no explicit command-line parameter\r\n // that requires session was specified => noop\r\n DataList->Clear();\r\n }\r\n else if ((DataList->Count == 0) ||\r\n !dynamic_cast<TSessionData *>(DataList->Items[0])->CanLogin ||\r\n DefaultsOnly)\r\n {\r\n // Note that GetFolderOrWorkspace never returns sites that !CanLogin,\r\n // so we should not get here with more then one site.\r\n // Though we should be good, if we ever do.\r\n\r\n // We get here when:\r\n // - we need session for explicit command-line operation\r\n // - after we handle \"save\" URL.\r\n // - the specified session does not contain enough information to login [= not even hostname]\r\n\r\n DebugAssert(DataList->Count <= 1);\r\n if (!DoLoginDialog(DataList, LinkedForm))\r\n {\r\n Abort();\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall Upload(TTerminal * Terminal, TStrings * FileList, int UseDefaults)\r\n{\r\n UnicodeString TargetDirectory;\r\n TGUICopyParamType CopyParam = GUIConfiguration->DefaultCopyParam;\r\n\r\n TargetDirectory = UnixIncludeTrailingBackslash(Terminal->CurrentDirectory);\r\n\r\n std::unique_ptr<TSessionData> Data(Terminal->SessionData->Clone());\r\n Terminal->FillSessionDataForCode(Data.get());\r\n\r\n int Options = coDisableQueue;\r\n int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;\r\n if ((UseDefaults == 0) ||\r\n DoCopyDialog(true, false, FileList, TargetDirectory, &CopyParam, Options,\r\n CopyParamAttrs, Data.get(), NULL, UseDefaults))\r\n {\r\n // Setting parameter overrides only now, otherwise the dialog would present the parametes as non-default\r\n CopyParam.OnceDoneOperation = odoDisconnect;\r\n\r\n Terminal->CopyToRemote(FileList, TargetDirectory, &CopyParam, 0, NULL);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall Download(TTerminal * Terminal, const UnicodeString FileName, int UseDefaults)\r\n{\r\n TRemoteFile * File = NULL;\r\n\r\n try\r\n {\r\n Terminal->ExceptionOnFail = true;\r\n try\r\n {\r\n Terminal->ReadFile(FileName, File);\r\n }\r\n __finally\r\n {\r\n Terminal->ExceptionOnFail = false;\r\n }\r\n File->FullFileName = FileName;\r\n UnicodeString LocalDirectory = Terminal->SessionData->LocalDirectoryExpanded;\r\n if (LocalDirectory.IsEmpty())\r\n {\r\n LocalDirectory = GetPersonalFolder();\r\n }\r\n UnicodeString TargetDirectory = IncludeTrailingBackslash(LocalDirectory);\r\n\r\n TGUICopyParamType CopyParam = GUIConfiguration->DefaultCopyParam;\r\n UnicodeString DisplayName = File->FileName;\r\n\r\n bool CustomDisplayName =\r\n !File->DisplayName.IsEmpty() &&\r\n (File->DisplayName != DisplayName);\r\n if (CustomDisplayName)\r\n {\r\n DisplayName = File->DisplayName;\r\n }\r\n\r\n UnicodeString FriendyFileName = UnixIncludeTrailingBackslash(UnixExtractFilePath(FileName)) + DisplayName;\r\n std::unique_ptr<TStrings> FileListFriendly(new TStringList());\r\n FileListFriendly->AddObject(FriendyFileName, File);\r\n\r\n int Options = coDisableQueue;\r\n int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Download;\r\n if ((UseDefaults == 0) ||\r\n DoCopyDialog(false, false, FileListFriendly.get(), TargetDirectory, &CopyParam,\r\n Options, CopyParamAttrs, NULL, NULL, UseDefaults))\r\n {\r\n // Setting parameter overrides only now, otherwise the dialog would present the parametes as non-default\r\n\r\n if (CustomDisplayName)\r\n {\r\n // Set only now, so that it is not redundantly displayed on the copy dialog.\r\n // We should escape the * and ?'s.\r\n CopyParam.FileMask = DisplayName;\r\n }\r\n\r\n CopyParam.OnceDoneOperation = odoDisconnect;\r\n\r\n std::unique_ptr<TStrings> FileList(new TStringList());\r\n FileList->AddObject(FileName, File);\r\n Terminal->CopyToLocal(FileList.get(), TargetDirectory, &CopyParam, 0, NULL);\r\n }\r\n\r\n UnicodeString Directory = UnixExtractFilePath(FileName);\r\n Terminal->AutoReadDirectory = true;\r\n Terminal->ChangeDirectory(Directory);\r\n }\r\n __finally\r\n {\r\n delete File;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall Edit(TCustomScpExplorerForm * ScpExplorer, TStrings * FileList)\r\n{\r\n ScpExplorer->StandaloneEdit(FileList->Strings[0]);\r\n Abort();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall SynchronizeDirectories(TTerminal * Terminal,\r\n TStrings * CommandParams,\r\n UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory)\r\n{\r\n if (CommandParams->Count >= 1)\r\n {\r\n LocalDirectory = CommandParams->Strings[0];\r\n }\r\n else if (!Terminal->SessionData->LocalDirectory.IsEmpty())\r\n {\r\n LocalDirectory = Terminal->SessionData->LocalDirectoryExpanded;\r\n }\r\n else\r\n {\r\n LocalDirectory = WinConfiguration->ScpExplorer.LastLocalTargetDirectory;\r\n }\r\n\r\n if (CommandParams->Count >= 2)\r\n {\r\n RemoteDirectory = CommandParams->Strings[1];\r\n }\r\n else\r\n {\r\n RemoteDirectory = Terminal->CurrentDirectory;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall FullSynchronize(\r\n TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer, TStrings * CommandParams, int UseDefaults)\r\n{\r\n UnicodeString LocalDirectory;\r\n UnicodeString RemoteDirectory;\r\n\r\n SynchronizeDirectories(Terminal, CommandParams, LocalDirectory, RemoteDirectory);\r\n\r\n bool SaveMode = true;\r\n // bit ugly\r\n TSynchronizeMode Mode = (TSynchronizeMode)GUIConfiguration->SynchronizeMode;\r\n int Params = GUIConfiguration->SynchronizeParams;\r\n\r\n // Undocumented syntax for \"Start in New Window\"\r\n if (CommandParams->Count >= 4)\r\n {\r\n Mode = (TSynchronizeMode)StrToIntDef(CommandParams->Strings[2], Mode);\r\n Params = StrToIntDef(CommandParams->Strings[3], Params);\r\n }\r\n\r\n int Result =\r\n ScpExplorer->DoFullSynchronizeDirectories(LocalDirectory, RemoteDirectory, Mode, Params, SaveMode, UseDefaults);\r\n if ((Result >= 0) && SaveMode)\r\n {\r\n GUIConfiguration->SynchronizeMode = Mode;\r\n }\r\n\r\n Abort();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall Synchronize(\r\n TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer, TStrings * CommandParams, int UseDefaults)\r\n{\r\n UnicodeString LocalDirectory;\r\n UnicodeString RemoteDirectory;\r\n\r\n SynchronizeDirectories(Terminal, CommandParams, LocalDirectory, RemoteDirectory);\r\n\r\n // Undocumented syntax for \"Start in New Window\"\r\n if (CommandParams->Count >= 4)\r\n {\r\n GUIConfiguration->SynchronizeParams = StrToIntDef(CommandParams->Strings[2], -1);\r\n GUIConfiguration->SynchronizeOptions = StrToIntDef(CommandParams->Strings[3], -1);\r\n\r\n Configuration->DontSave();\r\n }\r\n\r\n ScpExplorer->DoSynchronizeDirectories(LocalDirectory, RemoteDirectory, UseDefaults);\r\n Abort();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall ImportSitesIfAny()\r\n{\r\n if (!WinConfiguration->AutoImportedFromPuttyOrFilezilla)\r\n {\r\n bool AnyPuttySession = GUIConfiguration->AnyPuttySessionForImport(StoredSessions);\r\n bool AnyFilezillaSession = GUIConfiguration->AnyFilezillaSessionForImport(StoredSessions);\r\n\r\n if (AnyPuttySession || AnyFilezillaSession)\r\n {\r\n UnicodeString PuttySource = LoadStrPart(IMPORT_SESSIONS2, 2);\r\n UnicodeString FilezillaSource = LoadStrPart(IMPORT_SESSIONS2, 3);\r\n UnicodeString Source;\r\n if (AnyPuttySession && AnyFilezillaSession)\r\n {\r\n Source = FORMAT(LoadStrPart(IMPORT_SESSIONS2, 4), (PuttySource, FilezillaSource));\r\n }\r\n else if (AnyPuttySession)\r\n {\r\n Source = PuttySource;\r\n }\r\n else if (AnyFilezillaSession)\r\n {\r\n Source = FilezillaSource;\r\n }\r\n else\r\n {\r\n DebugFail();\r\n }\r\n\r\n UnicodeString Message = FORMAT(LoadStrPart(IMPORT_SESSIONS2, 1), (Source));\r\n\r\n if (MessageDialog(Message, qtConfirmation,\r\n qaYes | qaNo, HELP_IMPORT_SESSIONS) == qaYes)\r\n {\r\n DoImportSessionsDialog(NULL);\r\n }\r\n\r\n WinConfiguration->AutoImportedFromPuttyOrFilezilla = true;\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall Usage(UnicodeString Param)\r\n{\r\n while (!Param.IsEmpty())\r\n {\r\n UnicodeString Pair = CutToChar(Param, L',', true);\r\n if (!Pair.IsEmpty())\r\n {\r\n if (Pair[Pair.Length()] == L'+')\r\n {\r\n UnicodeString Key = Pair.SubString(1, Pair.Length() - 1).Trim();\r\n Configuration->Usage->Inc(Key);\r\n }\r\n else\r\n {\r\n UnicodeString Key = CutToChar(Pair, L':', true);\r\n Configuration->Usage->Set(Key, Pair.Trim());\r\n }\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall RecordWrapperVersions(UnicodeString ConsoleVersion, UnicodeString DotNetVersion)\r\n{\r\n TUpdatesConfiguration Updates = WinConfiguration->Updates;\r\n if (!DotNetVersion.IsEmpty())\r\n {\r\n Updates.DotNetVersion = DotNetVersion;\r\n }\r\n if (!ConsoleVersion.IsEmpty())\r\n {\r\n Updates.ConsoleVersion = ConsoleVersion;\r\n }\r\n WinConfiguration->Updates = Updates;\r\n\r\n if (Configuration->Storage == stNul)\r\n {\r\n Configuration->SetDefaultStorage();\r\n try\r\n {\r\n THierarchicalStorage * Storage = Configuration->CreateConfigStorage();\r\n try\r\n {\r\n Storage->AccessMode = smReadWrite;\r\n if (Storage->OpenSubKey(Configuration->ConfigurationSubKey, true) &&\r\n Storage->OpenSubKeyPath(L\"Interface\\\\Updates\", true))\r\n {\r\n if (!DotNetVersion.IsEmpty())\r\n {\r\n Storage->WriteString(L\"DotNetVersion\", DotNetVersion);\r\n }\r\n if (!ConsoleVersion.IsEmpty())\r\n {\r\n Storage->WriteString(L\"ConsoleVersion\", ConsoleVersion);\r\n }\r\n }\r\n }\r\n __finally\r\n {\r\n delete Storage;\r\n }\r\n }\r\n __finally\r\n {\r\n Configuration->SetNulStorage();\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nstatic UnicodeString ColorToRGBStr(TColor Color)\r\n{\r\n int RGB = ColorToRGB(Color);\r\n int R = GetRValue(RGB);\r\n int G = GetGValue(RGB);\r\n int B = GetBValue(RGB);\r\n UnicodeString Result = FORMAT(L\"%.2x%.2x%.2x\", (R, G, B));\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nTDateTime Started(Now());\r\nint LifetimeRuns = -1;\r\n//---------------------------------------------------------------------------\r\nvoid InterfaceStarted()\r\n{\r\n // deliberate downcast\r\n int StartupSeconds = static_cast<int>(SecondsBetween(Now(), Started));\r\n if (LifetimeRuns > 0)\r\n {\r\n if (LifetimeRuns == 1)\r\n {\r\n Configuration->Usage->Set(L\"StartupSeconds1\", StartupSeconds);\r\n }\r\n else if (LifetimeRuns == 2)\r\n {\r\n Configuration->Usage->Set(L\"StartupSeconds2\", StartupSeconds);\r\n }\r\n Configuration->Usage->Set(L\"StartupSecondsLast\", StartupSeconds);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall UpdateStaticUsage()\r\n{\r\n LifetimeRuns = Configuration->Usage->Inc(L\"Runs\");\r\n\r\n Configuration->Usage->UpdateCurrentVersion();\r\n\r\n Configuration->Usage->Set(L\"WindowsVersion\", (WindowsVersionLong()));\r\n Configuration->Usage->Set(L\"WindowsProductName\", (WindowsProductName()));\r\n DWORD Type;\r\n GetWindowsProductType(Type);\r\n Configuration->Usage->Set(L\"WindowsProductType\", (static_cast<int>(Type)));\r\n Configuration->Usage->Set(L\"Windows64\", IsWin64());\r\n Configuration->Usage->Set(L\"UWP\", IsUWP());\r\n Configuration->Usage->Set(L\"DefaultLocale\",\r\n // See TGUIConfiguration::GetAppliedLocaleHex()\r\n IntToHex(static_cast<int>(GetDefaultLCID()), 4));\r\n Configuration->Usage->Set(L\"Locale\", WinConfiguration->AppliedLocaleHex);\r\n Configuration->Usage->Set(L\"EncodingMultiByteAnsi\", !TEncoding::Default->IsSingleByte);\r\n Configuration->Usage->Set(L\"PixelsPerInch\", Screen->PixelsPerInch);\r\n\r\n bool PixelsPerInchSystemDiffers = false;\r\n bool PixelsPerInchMonitorsDiffer = false;\r\n bool PixelsPerInchAxesDiffer = false;\r\n\r\n HINSTANCE ShCoreLibrary = LoadLibrary(L\"shcore.dll\");\r\n if (ShCoreLibrary != NULL)\r\n {\r\n GetDpiForMonitorProc GetDpiForMonitor =\r\n (GetDpiForMonitorProc)GetProcAddress(ShCoreLibrary, \"GetDpiForMonitor\");\r\n\r\n if (GetDpiForMonitor != NULL)\r\n {\r\n unsigned int PrimaryDpiX;\r\n unsigned int PrimaryDpiY;\r\n\r\n for (int Index = 0; Index < Screen->MonitorCount; Index++)\r\n {\r\n unsigned int DpiX;\r\n unsigned int DpiY;\r\n GetDpiForMonitor(Screen->Monitors[Index]->Handle, MDT_Default, &DpiX, &DpiY);\r\n\r\n if (DpiX != DpiY)\r\n {\r\n PixelsPerInchAxesDiffer = true;\r\n }\r\n\r\n if (Index == 0)\r\n {\r\n PrimaryDpiX = DpiX;\r\n PrimaryDpiY = DpiY;\r\n\r\n // PixelsPerInch is GetDeviceCaps(DC, LOGPIXELSY)\r\n if (DpiY != (unsigned int)Screen->PixelsPerInch)\r\n {\r\n PixelsPerInchSystemDiffers = true;\r\n }\r\n }\r\n else\r\n {\r\n if ((DpiX != PrimaryDpiX) ||\r\n (DpiY != PrimaryDpiY))\r\n {\r\n PixelsPerInchMonitorsDiffer = true;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (PixelsPerInchSystemDiffers)\r\n {\r\n Configuration->Usage->Inc(L\"PixelsPerInchSystemDiffered\");\r\n }\r\n Configuration->Usage->Set(L\"PixelsPerInchMonitorsDiffer\", PixelsPerInchMonitorsDiffer);\r\n Configuration->Usage->Set(L\"PixelsPerInchAxesDiffer\", PixelsPerInchAxesDiffer);\r\n\r\n Configuration->Usage->Set(L\"WorkAreaWidth\", Screen->WorkAreaWidth);\r\n Configuration->Usage->Set(L\"WorkAreaHeight\", Screen->WorkAreaHeight);\r\n HDC DC = GetDC(NULL);\r\n int Planes = GetDeviceCaps(DC, PLANES);\r\n int BitsPixel = GetDeviceCaps(DC, BITSPIXEL);\r\n Configuration->Usage->Set(L\"ColorDepth\", Planes * BitsPixel);\r\n Configuration->Usage->Set(L\"MonitorCount\", Screen->MonitorCount);\r\n Configuration->Usage->Set(L\"NotUseThemes\", !UseThemes());\r\n Configuration->Usage->Set(L\"ThemeDefaultFontSize\", Application->DefaultFont->Size);\r\n Configuration->Usage->Set(L\"ThemeIconFontSize\", Screen->IconFont->Size);\r\n\r\n Configuration->Usage->Set(L\"SysColorWindow\", ColorToRGBStr(clWindow));\r\n Configuration->Usage->Set(L\"SysColorBtnFace\", ColorToRGBStr(clBtnFace));\r\n Configuration->Usage->Set(L\"SysColorWindowText\", ColorToRGBStr(clWindowText));\r\n\r\n UnicodeString ProgramsFolder;\r\n ::SpecialFolderLocation(CSIDL_PROGRAM_FILES, ProgramsFolder);\r\n ProgramsFolder = IncludeTrailingBackslash(ExpandFileName(ProgramsFolder));\r\n UnicodeString ExeName = ExpandFileName(Application->ExeName);\r\n bool InProgramFiles = AnsiSameText(ExeName.SubString(1, ProgramsFolder.Length()), ProgramsFolder);\r\n Configuration->Usage->Set(L\"InProgramFiles\", InProgramFiles);\r\n Configuration->Usage->Set(L\"IsInstalled\", IsInstalled());\r\n Configuration->Usage->Set(L\"Wine\", IsWine());\r\n Configuration->Usage->Set(L\"NetFrameworkVersion\", GetNetVersionStr());\r\n Configuration->Usage->Set(L\"PowerShellVersion\", GetPowerShellVersionStr());\r\n\r\n WinConfiguration->UpdateStaticUsage();\r\n\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall MaintenanceTask()\r\n{\r\n CoreMaintenanceTask();\r\n}\r\n//---------------------------------------------------------------------------\r\ntypedef std::vector<HWND> THandles;\r\ntypedef std::map<unsigned long, THandles> TProcesses;\r\n//---------------------------------------------------------------------------\r\nBOOL __stdcall EnumOtherInstances(HWND Handle, LPARAM AParam)\r\n{\r\n TProcesses & Processes = *reinterpret_cast<TProcesses *>(AParam);\r\n\r\n unsigned long ProcessId;\r\n if (GetWindowThreadProcessId(Handle, &ProcessId) != 0)\r\n {\r\n Processes[ProcessId].push_back(Handle);\r\n }\r\n\r\n return TRUE;\r\n}\r\n//---------------------------------------------------------------------------\r\nstatic bool __fastcall SendCopyDataMessage(HWND Window, TCopyDataMessage & Message)\r\n{\r\n COPYDATASTRUCT CopyData;\r\n CopyData.cbData = sizeof(Message);\r\n CopyData.lpData = &Message;\r\n\r\n LRESULT SendResult =\r\n SendMessage(Window, WM_COPYDATA,\r\n reinterpret_cast<WPARAM>(HInstance), reinterpret_cast<LPARAM>(&CopyData));\r\n bool Result = (SendResult > 0);\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nstatic void __fastcall FindOtherInstances(THandles & OtherInstances)\r\n{\r\n TProcesses Processes;\r\n\r\n // FindWindow is optimization (if there's no hidden window, no point enumerating all windows to find some)\r\n if ((FindWindow(HIDDEN_WINDOW_NAME, NULL) != NULL) &&\r\n EnumWindows(EnumOtherInstances, reinterpret_cast<LPARAM>(&Processes)))\r\n {\r\n TCopyDataMessage Message;\r\n\r\n Message.Command = TCopyDataMessage::MainWindowCheck;\r\n\r\n TProcesses::const_iterator ProcessI = Processes.begin();\r\n while (ProcessI != Processes.end())\r\n {\r\n HWND HiddenWindow = NULL;\r\n THandles::const_iterator WindowI = ProcessI->second.begin();\r\n\r\n while ((HiddenWindow == NULL) && (WindowI != ProcessI->second.end()))\r\n {\r\n wchar_t ClassName[1024];\r\n if (GetClassName(*WindowI, ClassName, LENOF(ClassName)) != 0)\r\n {\r\n NULL_TERMINATE(ClassName);\r\n\r\n if (wcscmp(ClassName, HIDDEN_WINDOW_NAME) == 0)\r\n {\r\n HiddenWindow = *WindowI;\r\n }\r\n }\r\n WindowI++;\r\n }\r\n\r\n if (HiddenWindow != NULL)\r\n {\r\n WindowI = ProcessI->second.begin();\r\n\r\n while (WindowI != ProcessI->second.end())\r\n {\r\n if (*WindowI != HiddenWindow) // optimization\r\n {\r\n if (SendCopyDataMessage(*WindowI, Message))\r\n {\r\n OtherInstances.push_back(*WindowI);\r\n break;\r\n }\r\n }\r\n WindowI++;\r\n }\r\n }\r\n\r\n ProcessI++;\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall SendToAnotherInstance()\r\n{\r\n THandles OtherInstances;\r\n FindOtherInstances(OtherInstances);\r\n\r\n bool Result = false;\r\n THandles::const_iterator I = OtherInstances.begin();\r\n while (!Result && (I != OtherInstances.end()))\r\n {\r\n HWND Handle = *I;\r\n\r\n TCopyDataMessage Message;\r\n Message.Command = TCopyDataMessage::CommandCanCommandLine;\r\n\r\n if (SendCopyDataMessage(Handle, Message))\r\n {\r\n // Restore window, if minimized\r\n ShowWindow(Handle, SW_RESTORE);\r\n // bring it to foreground\r\n SetForegroundWindow(Handle);\r\n\r\n Message.Command = TCopyDataMessage::CommandCommandLine;\r\n wcsncpy(Message.CommandLine, CmdLine, LENOF(Message.CommandLine));\r\n NULL_TERMINATE(Message.CommandLine);\r\n\r\n Result = SendCopyDataMessage(Handle, Message);\r\n }\r\n\r\n I++;\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall Refresh(const UnicodeString & Session, const UnicodeString & Path)\r\n{\r\n THandles OtherInstances;\r\n FindOtherInstances(OtherInstances);\r\n\r\n THandles::const_iterator I = OtherInstances.begin();\r\n while (I != OtherInstances.end())\r\n {\r\n HWND Handle = *I;\r\n\r\n TCopyDataMessage Message;\r\n Message.Command = TCopyDataMessage::RefreshPanel;\r\n wcsncpy(Message.Refresh.Session, Session.c_str(), LENOF(Message.Refresh.Session));\r\n NULL_TERMINATE(Message.Refresh.Session);\r\n wcsncpy(Message.Refresh.Path, Path.c_str(), LENOF(Message.Refresh.Path));\r\n NULL_TERMINATE(Message.Refresh.Path);\r\n\r\n SendCopyDataMessage(Handle, Message);\r\n\r\n I++;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall ShowUpdatesIfAvailable()\r\n{\r\n TUpdatesConfiguration Updates = WinConfiguration->Updates;\r\n int CurrentCompoundVer = Configuration->CompoundVersion;\r\n bool NoPopup = true;\r\n bool Result =\r\n !IsUWP() &&\r\n Updates.ShowOnStartup &&\r\n Updates.HaveValidResultsForVersion(CurrentCompoundVer) &&\r\n !Updates.Results.Disabled &&\r\n ((Updates.Results.Version > CurrentCompoundVer) || !Updates.Results.Message.IsEmpty()) &&\r\n !Updates.ShownResults;\r\n if (Result)\r\n {\r\n Configuration->Usage->Inc(L\"UpdateStartup\");\r\n Result = CheckForUpdates(true);\r\n if (Result)\r\n {\r\n Configuration->Usage->Inc(L\"UpdateDownloadOpensStartup\");\r\n }\r\n NoPopup = false;\r\n }\r\n else if (WinConfiguration->ShowTips)\r\n {\r\n int Days = DaysBetween(WinConfiguration->TipsShown, Now());\r\n if ((Days >= Updates.Results.TipsIntervalDays) &&\r\n (WinConfiguration->RunsSinceLastTip >= Updates.Results.TipsIntervalDays))\r\n {\r\n UnicodeString Tip = FirstUnshownTip();\r\n if (!Tip.IsEmpty())\r\n {\r\n AutoShowNewTip();\r\n NoPopup = false;\r\n }\r\n else\r\n {\r\n Configuration->Usage->Inc(L\"TipsNoUnseen\");\r\n }\r\n }\r\n }\r\n\r\n if (NoPopup)\r\n {\r\n WinConfiguration->RunsSinceLastTip = WinConfiguration->RunsSinceLastTip + 1;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall Execute()\r\n{\r\n DebugAssert(StoredSessions);\r\n TProgramParams * Params = TProgramParams::Instance();\r\n DebugAssert(Params);\r\n\r\n // do not flash message boxes on startup\r\n SetOnForeground(true);\r\n\r\n // let installer know, that some instance of application is running\r\n CreateMutex(NULL, False, AppName.c_str());\r\n bool OnlyInstance = (GetLastError() == 0);\r\n\r\n UpdateStaticUsage();\r\n\r\n UnicodeString KeyFile;\r\n if (Params->FindSwitch(L\"PrivateKey\", KeyFile))\r\n {\r\n WinConfiguration->DefaultKeyFile = KeyFile;\r\n }\r\n\r\n UnicodeString ConsoleVersion;\r\n UnicodeString DotNetVersion;\r\n Params->FindSwitch(L\"Console\", ConsoleVersion);\r\n Params->FindSwitch(L\"DotNet\", DotNetVersion);\r\n if (!ConsoleVersion.IsEmpty() || !DotNetVersion.IsEmpty())\r\n {\r\n RecordWrapperVersions(ConsoleVersion, DotNetVersion);\r\n }\r\n if (!DotNetVersion.IsEmpty())\r\n {\r\n Configuration->Usage->Inc(L\"ConsoleDotNet\");\r\n }\r\n\r\n UnicodeString SwitchValue;\r\n if (Params->FindSwitch(L\"loglevel\", SwitchValue))\r\n {\r\n int StarPos = SwitchValue.Pos(L\"*\");\r\n if (StarPos > 0)\r\n {\r\n bool LogSensitive = true;\r\n SwitchValue.Delete(StarPos, 1);\r\n\r\n if ((StarPos <= SwitchValue.Length()) &&\r\n (SwitchValue[StarPos] == L'-'))\r\n {\r\n LogSensitive = false;\r\n SwitchValue.Delete(StarPos, 1);\r\n }\r\n\r\n SwitchValue = SwitchValue.Trim();\r\n\r\n Configuration->TemporaryLogSensitive(LogSensitive);\r\n }\r\n int LogProtocol;\r\n if (!SwitchValue.IsEmpty() && TryStrToInt(SwitchValue, LogProtocol) && (LogProtocol >= -1))\r\n {\r\n Configuration->TemporaryLogProtocol(LogProtocol);\r\n }\r\n }\r\n\r\n if (Params->FindSwitch(LOGSIZE_SWITCH, SwitchValue))\r\n {\r\n int StarPos = SwitchValue.Pos(LOGSIZE_SEPARATOR);\r\n int LogMaxCount = 0;\r\n if (StarPos > 1)\r\n {\r\n if (!TryStrToInt(SwitchValue.SubString(1, StarPos - 1), LogMaxCount))\r\n {\r\n LogMaxCount = -1;\r\n }\r\n SwitchValue.Delete(1, StarPos);\r\n SwitchValue = SwitchValue.Trim();\r\n }\r\n\r\n __int64 LogMaxSize;\r\n if ((LogMaxCount >= 0) &&\r\n !SwitchValue.IsEmpty() &&\r\n TryStrToSize(SwitchValue, LogMaxSize))\r\n {\r\n Configuration->TemporaryLogMaxCount(LogMaxCount);\r\n Configuration->TemporaryLogMaxSize(LogMaxSize);\r\n }\r\n }\r\n\r\n std::unique_ptr<TStrings> RawSettings(new TStringList());\r\n if (Params->FindSwitch(RAWTRANSFERSETTINGS_SWITCH, RawSettings.get()))\r\n {\r\n std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings.get(), false));\r\n GUIConfiguration->LoadDefaultCopyParam(OptionsStorage.get());\r\n }\r\n\r\n TConsoleMode Mode = cmNone;\r\n if (Params->FindSwitch(L\"help\") || Params->FindSwitch(L\"h\") || Params->FindSwitch(L\"?\"))\r\n {\r\n Mode = cmHelp;\r\n }\r\n else if (Params->FindSwitch(L\"batchsettings\"))\r\n {\r\n Mode = cmBatchSettings;\r\n }\r\n else if (Params->FindSwitch(KEYGEN_SWITCH))\r\n {\r\n Mode = cmKeyGen;\r\n }\r\n else if (Params->FindSwitch(FINGERPRINTSCAN_SWITCH))\r\n {\r\n Mode = cmFingerprintScan;\r\n }\r\n else if (Params->FindSwitch(DUMPCALLSTACK_SWITCH))\r\n {\r\n Mode = cmDumpCallstack;\r\n }\r\n else if (Params->FindSwitch(INFO_SWITCH))\r\n {\r\n Mode = cmInfo;\r\n }\r\n else if (Params->FindSwitch(COMREGISTRATION_SWITCH))\r\n {\r\n Mode = cmComRegistration;\r\n }\r\n // We have to check for /console only after the other options,\r\n // as the /console is always used when we are run by winscp.com\r\n // (ambiguous use to pass console version)\r\n else if (Params->FindSwitch(L\"Console\") || Params->FindSwitch(SCRIPT_SWITCH) ||\r\n Params->FindSwitch(COMMAND_SWITCH))\r\n {\r\n Mode = cmScripting;\r\n }\r\n\r\n if (Mode != cmNone)\r\n {\r\n return Console(Mode);\r\n }\r\n\r\n TTerminalManager * TerminalManager = NULL;\r\n GlyphsModule = NULL;\r\n NonVisualDataModule = NULL;\r\n TStrings * CommandParams = new TStringList;\r\n try\r\n {\r\n TerminalManager = TTerminalManager::Instance();\r\n HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();\r\n try\r\n {\r\n GlyphsModule = new TGlyphsModule(Application);\r\n }\r\n __finally\r\n {\r\n GUIConfiguration->ChangeResourceModule(ResourceModule);\r\n }\r\n NonVisualDataModule = new TNonVisualDataModule(Application);\r\n\r\n // The default is 2.5s.\r\n // 20s is used by Office 2010 and Windows 10 Explorer.\r\n // Some applications use an infinite (Thunderbird, Firefox).\r\n // Overriden for some controls using THintInfo.HideTimeout\r\n Application->HintHidePause = 20000;\r\n HintWindowClass = __classid(TScreenTipHintWindow);\r\n\r\n UnicodeString IniFileName = Params->SwitchValue(INI_SWITCH);\r\n if (!IniFileName.IsEmpty() && (IniFileName != INI_NUL))\r\n {\r\n UnicodeString IniFileNameExpanded = ExpandEnvironmentVariables(IniFileName);\r\n if (!FileExists(ApiPath(IniFileNameExpanded)))\r\n {\r\n // this should be displayed rather at the very beginning.\r\n // however for simplicity (GUI-only), we do it only here.\r\n MessageDialog(FMTLOAD(FILE_NOT_EXISTS, (IniFileNameExpanded)), qtError, qaOK);\r\n }\r\n }\r\n\r\n if (Params->FindSwitch(L\"UninstallCleanup\"))\r\n {\r\n MaintenanceTask();\r\n Configuration->DontSave();\r\n // The innosetup cannot skip UninstallCleanup run task for silent uninstalls,\r\n // workaround is that we create mutex in uninstaller, if it runs silent, and\r\n // ignore the UninstallCleanup, when the mutex exists.\r\n if (OpenMutex(SYNCHRONIZE, false, L\"WinSCPSilentUninstall\") == NULL)\r\n {\r\n DoCleanupDialogIfAnyDataAndWanted();\r\n }\r\n }\r\n else if (Params->FindSwitch(L\"RegisterForDefaultProtocols\") ||\r\n Params->FindSwitch(L\"RegisterAsUrlHandler\")) // BACKWARD COMPATIBILITY\r\n {\r\n MaintenanceTask();\r\n if (CheckSafe(Params))\r\n {\r\n RegisterForDefaultProtocols();\r\n Configuration->DontSave();\r\n }\r\n }\r\n else if (Params->FindSwitch(L\"UnregisterForProtocols\"))\r\n {\r\n MaintenanceTask();\r\n if (CheckSafe(Params))\r\n {\r\n UnregisterForProtocols();\r\n Configuration->DontSave();\r\n }\r\n }\r\n else if (Params->FindSwitch(L\"AddSearchPath\"))\r\n {\r\n MaintenanceTask();\r\n if (CheckSafe(Params))\r\n {\r\n AddSearchPath(ExtractFilePath(Application->ExeName));\r\n Configuration->DontSave();\r\n }\r\n }\r\n else if (Params->FindSwitch(L\"RemoveSearchPath\"))\r\n {\r\n MaintenanceTask();\r\n if (CheckSafe(Params))\r\n {\r\n try\r\n {\r\n RemoveSearchPath(ExtractFilePath(Application->ExeName));\r\n }\r\n catch(...)\r\n {\r\n // ignore errors\r\n // (RemoveSearchPath is called always on uninstallation,\r\n // even if AddSearchPath was not used, so we would get the error\r\n // always for non-priviledged user)\r\n }\r\n Configuration->DontSave();\r\n }\r\n }\r\n else if (Params->FindSwitch(L\"ImportSitesIfAny\"))\r\n {\r\n MaintenanceTask();\r\n ImportSitesIfAny();\r\n }\r\n else if (Params->FindSwitch(L\"Usage\", SwitchValue))\r\n {\r\n MaintenanceTask();\r\n Usage(SwitchValue);\r\n }\r\n else if (Params->FindSwitch(L\"Update\"))\r\n {\r\n MaintenanceTask();\r\n CheckForUpdates(false);\r\n }\r\n else if (ShowUpdatesIfAvailable())\r\n {\r\n // noop\r\n }\r\n else if (Params->FindSwitch(L\"Exit\"))\r\n {\r\n // noop\r\n MaintenanceTask();\r\n Configuration->DontSave();\r\n }\r\n else if (Params->FindSwitch(L\"MaintenanceTask\"))\r\n {\r\n // Parameter /MaintenanceTask can be added to command-line when executing maintenance tasks\r\n // (e.g. from installer) just in case old version of WinSCP is called by mistake\r\n MaintenanceTask();\r\n Configuration->DontSave();\r\n }\r\n else\r\n {\r\n enum { pcNone, pcUpload, pcFullSynchronize, pcSynchronize, pcEdit, pcRefresh } ParamCommand;\r\n ParamCommand = pcNone;\r\n UnicodeString AutoStartSession;\r\n UnicodeString DownloadFile;\r\n int UseDefaults = -1;\r\n\r\n // do not check for temp dirs for service tasks (like RegisterAsUrlHandler)\r\n if (OnlyInstance &&\r\n WinConfiguration->TemporaryDirectoryCleanup)\r\n {\r\n TemporaryDirectoryCleanup();\r\n }\r\n\r\n WinConfiguration->CheckDefaultTranslation();\r\n // Loading shell image lists here (rather than only on demand when file controls are being created)\r\n // reduces risk of an occasional crash.\r\n // It seems that the point is to load the lists before any call to SHGetFileInfoWithTimeout.\r\n InitFileControls();\r\n\r\n if (!Params->Empty)\r\n {\r\n UnicodeString Value;\r\n if (Params->FindSwitch(DEFAULTS_SWITCH, Value) && CheckSafe(Params))\r\n {\r\n UseDefaults = StrToIntDef(Value, 0);\r\n }\r\n\r\n if (Params->FindSwitch(UPLOAD_SWITCH, CommandParams))\r\n {\r\n ParamCommand = pcUpload;\r\n if (CommandParams->Count == 0)\r\n {\r\n throw Exception(NO_UPLOAD_LIST_ERROR);\r\n }\r\n }\r\n if (Params->FindSwitch(UPLOAD_IF_ANY_SWITCH, CommandParams))\r\n {\r\n if (CommandParams->Count > 0)\r\n {\r\n ParamCommand = pcUpload;\r\n }\r\n }\r\n else if (Params->FindSwitch(SYNCHRONIZE_SWITCH, CommandParams, 4))\r\n {\r\n ParamCommand = pcFullSynchronize;\r\n }\r\n else if (Params->FindSwitch(KEEP_UP_TO_DATE_SWITCH, CommandParams, 4))\r\n {\r\n ParamCommand = pcSynchronize;\r\n }\r\n else if (Params->FindSwitch(L\"Edit\", CommandParams, 1) &&\r\n (CommandParams->Count == 1))\r\n {\r\n ParamCommand = pcEdit;\r\n }\r\n else if (Params->FindSwitch(REFRESH_SWITCH, CommandParams, 1))\r\n {\r\n ParamCommand = pcRefresh;\r\n }\r\n }\r\n\r\n if (Params->ParamCount > 0)\r\n {\r\n AutoStartSession = Params->Param[1];\r\n Params->ParamsProcessed(1, 1);\r\n\r\n if ((ParamCommand == pcNone) &&\r\n (WinConfiguration->ExternalSessionInExistingInstance != OpenInNewWindow()) &&\r\n !Params->FindSwitch(NEWINSTANCE_SWICH) &&\r\n SendToAnotherInstance())\r\n {\r\n Configuration->Usage->Inc(L\"SendToAnotherInstance\");\r\n return 0;\r\n }\r\n UnicodeString CounterName;\r\n if (Params->FindSwitch(JUMPLIST_SWITCH))\r\n {\r\n CounterName = L\"CommandLineJumpList\";\r\n }\r\n else if (Params->FindSwitch(DESKTOP_SWITCH))\r\n {\r\n CounterName = L\"CommandLineDesktop\";\r\n }\r\n else if (Params->FindSwitch(SEND_TO_HOOK_SWITCH))\r\n {\r\n CounterName = L\"CommandLineSendToHook\";\r\n }\r\n else\r\n {\r\n CounterName = L\"CommandLineSession2\";\r\n }\r\n Configuration->Usage->Inc(CounterName);\r\n }\r\n else if (WinConfiguration->EmbeddedSessions && StoredSessions->Count)\r\n {\r\n AutoStartSession = StoredSessions->Sessions[0]->Name;\r\n }\r\n else\r\n {\r\n AutoStartSession = WinConfiguration->AutoStartSession;\r\n }\r\n\r\n if (ParamCommand == pcRefresh)\r\n {\r\n Refresh(AutoStartSession, (CommandParams->Count > 0 ? CommandParams->Strings[0] : UnicodeString()));\r\n return 0;\r\n }\r\n\r\n // from now flash message boxes on background\r\n SetOnForeground(false);\r\n\r\n bool NeedSession = (ParamCommand != pcNone);\r\n\r\n bool Retry;\r\n do\r\n {\r\n Retry = false;\r\n std::unique_ptr<TObjectList> DataList(new TObjectList());\r\n try\r\n {\r", " GetLoginData(AutoStartSession, Params, DataList.get(), DownloadFile, NeedSession, NULL, pufAllowStoredSiteWithProtocol);\r", " // GetLoginData now Aborts when session is needed and none is selected\r\n if (DebugAlwaysTrue(!NeedSession || (DataList->Count > 0)))\r\n {\r\n if (CheckSafe(Params))\r\n {\r\n UnicodeString LogFile;\r\n if (Params->FindSwitch(LOG_SWITCH, LogFile))\r\n {\r\n Configuration->TemporaryLogging(LogFile);\r\n }\r\n if (Params->FindSwitch(L\"XmlLog\", LogFile))\r\n {\r\n Configuration->TemporaryActionsLogging(LogFile);\r\n }\r\n }\r\n\r\n try\r\n {\r\n DebugAssert(!TerminalManager->ActiveTerminal);\r\n\r\n bool CanStart;\r\n bool Browse = false;\r\n if (DataList->Count > 0)\r\n {\r\n TManagedTerminal * Terminal = TerminalManager->NewTerminals(DataList.get());\r\n UnicodeString BrowseFile;\r\n if (Params->FindSwitch(BROWSE_SWITCH, BrowseFile) &&\r\n (!BrowseFile.IsEmpty() || !DownloadFile.IsEmpty()))\r\n {\r\n if (BrowseFile.IsEmpty())\r\n {\r\n BrowseFile = DownloadFile;\r\n }\r\n DebugAssert(Terminal->RemoteExplorerState == NULL);\r\n Terminal->RemoteExplorerState = CreateDirViewStateForFocusedItem(BrowseFile);\r\n DebugAssert(Terminal->LocalExplorerState == NULL);\r\n Terminal->LocalExplorerState = CreateDirViewStateForFocusedItem(BrowseFile);\r\n DownloadFile = UnicodeString();\r\n Browse = true;\r\n }\r\n if (!DownloadFile.IsEmpty())\r\n {\r\n Terminal->AutoReadDirectory = false;\r\n DownloadFile = UnixIncludeTrailingBackslash(Terminal->SessionData->RemoteDirectory) + DownloadFile;\r\n Terminal->SessionData->RemoteDirectory = L\"\";\r\n Terminal->StateData->RemoteDirectory = Terminal->SessionData->RemoteDirectory;\r\n }\r\n TerminalManager->ActiveTerminal = Terminal;\r\n CanStart = (TerminalManager->Count > 0);\r\n }\r\n else\r\n {\r\n DebugAssert(!NeedSession);\r\n CanStart = true;\r\n }\r\n\r\n if (!CanStart)\r\n {\r\n // do not prompt with login dialog, if connection of\r\n // auto-start session (typically from command line) failed\r\n if (AutoStartSession.IsEmpty())\r\n {\r\n Retry = true;\r\n }\r\n }\r\n else\r\n {\r\n // from now on, we do not support runtime interface change\r\n CustomWinConfiguration->CanApplyInterfaceImmediately = false;\r\n TCustomScpExplorerForm * ScpExplorer = CreateScpExplorer();\r\n CustomWinConfiguration->AppliedInterface = CustomWinConfiguration->Interface;\r\n try\r\n {\r\n // moved inside try .. __finally, because it can fail as well\r\n TerminalManager->ScpExplorer = ScpExplorer;\r\n\r\n if ((ParamCommand != pcNone) || !DownloadFile.IsEmpty())\r\n {\r\n Configuration->Usage->Inc(L\"CommandLineOperation\");\r\n }\r\n\r\n if (ParamCommand == pcUpload)\r\n {\r\n Upload(TerminalManager->ActiveTerminal, CommandParams, UseDefaults);\r\n }\r\n else if (ParamCommand == pcFullSynchronize)\r\n {\r\n FullSynchronize(TerminalManager->ActiveTerminal, ScpExplorer,\r\n CommandParams, UseDefaults);\r\n }\r\n else if (ParamCommand == pcSynchronize)\r\n {\r\n Synchronize(TerminalManager->ActiveTerminal, ScpExplorer,\r\n CommandParams, UseDefaults);\r\n }\r\n else if (ParamCommand == pcEdit)\r\n {\r\n Edit(ScpExplorer, CommandParams);\r\n }\r\n else if (!DownloadFile.IsEmpty())\r\n {\r\n Download(TerminalManager->ActiveTerminal, DownloadFile,\r\n UseDefaults);\r\n }\r\n\r\n if (Browse)\r\n {\r\n ScpExplorer->BrowseFile();\r\n }\r\n\r\n Application->Run();\r\n // to allow dialog boxes show later (like from CheckConfigurationForceSave)\r\n SetAppTerminated(False);\r\n }\r\n __finally\r\n {\r\n TerminalManager->ScpExplorer = NULL;\r\n SAFE_DESTROY(ScpExplorer);\r\n }\r\n }\r\n }\r\n catch (Exception &E)\r\n {\r\n ShowExtendedException(&E);\r\n }\r\n }\r\n }\r\n // Catch EAbort from Synchronize() and similar functions, so that CheckConfigurationForceSave is processed\r\n catch (EAbort & E)\r\n {\r\n Retry = false; // unlikely to be true, but just in case\r\n }\r\n }\r\n while (Retry);\r\n }\r\n\r\n // In GUI mode only\r\n CheckConfigurationForceSave();\r\n }\r\n __finally\r\n {\r\n delete NonVisualDataModule;\r\n NonVisualDataModule = NULL;\r\n ReleaseImagesModules();\r\n delete GlyphsModule;\r\n GlyphsModule = NULL;\r\n TTerminalManager::DestroyInstance();\r\n delete CommandParams;\r\n }\r\n\r\n return 0;\r\n}" ]
[ 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 53, 80, 2275, 473, 1511, 2372, 1100], "buggy_code_start_loc": [46, 52, 79, 599, 57, 1510, 2371, 1099], "filenames": ["source/Console.cbproj", "source/DragExt.cbproj", "source/WinSCP.cbproj", "source/core/SessionData.cpp", "source/core/SessionData.h", "source/forms/Custom.cpp", "source/windows/ConsoleRunner.cpp", "source/windows/WinMain.cpp"], "fixing_code_end_loc": [47, 53, 80, 2294, 474, 1511, 2372, 1103], "fixing_code_start_loc": [46, 52, 79, 599, 58, 1510, 2371, 1099], "message": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:winscp:winscp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C081564B-8EF8-4C8A-9EB0-1C50D5A8F18B", "versionEndExcluding": "5.17.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)"}, {"lang": "es", "value": "WinSCP anterior a la versi\u00f3n 5.17.10 permite a los atacantes remotos ejecutar programas arbitrarios cuando el manejador de URLs encuentra una URL manipulada que carga la configuraci\u00f3n de la sesi\u00f3n. (Por ejemplo, esto es explotable en una instalaci\u00f3n por defecto en la que WinSCP es el manejador de URLs sftp://)"}], "evaluatorComment": null, "id": "CVE-2021-3331", "lastModified": "2021-02-04T15:59:24.960", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-01-27T21:15:16.840", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://winscp.net/eng/docs/history#5.17.10"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://winscp.net/eng/docs/rawsettings"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://winscp.net/tracker/1943"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, "type": "NVD-CWE-Other"}
177
Determine whether the {function_name} code is vulnerable or not.
[ "//---------------------------------------------------------------------------\r\n#include <vcl.h>\r\n#pragma hdrstop\r\n\r\n#include <CoreMain.h>\r\n\r\n#include <TextsWin.h>\r\n#include <TextsCore.h>\r\n#include <HelpWin.h>\r\n\r\n#include \"CustomScpExplorer.h\"\r\n#include \"TerminalManager.h\"\r\n#include \"NonVisual.h\"\r\n#include \"Glyphs.h\"\r\n#include \"ProgParams.h\"\r\n#include \"Setup.h\"\r\n#include \"WinConfiguration.h\"\r\n#include \"GUITools.h\"\r\n#include \"Tools.h\"\r\n#include \"WinApi.h\"\r\n#include <DateUtils.hpp>\r\n//---------------------------------------------------------------------------\r\n#pragma package(smart_init)\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall GetLoginData(UnicodeString SessionName, TOptions * Options,\r\n TObjectList * DataList, UnicodeString & DownloadFile, bool NeedSession, TForm * LinkedForm, int Flags)\r\n{\r\n bool DefaultsOnly = false;\r\n\r\n UnicodeString FolderOrWorkspaceName = DecodeUrlChars(SessionName);\r\n if (StoredSessions->IsFolder(FolderOrWorkspaceName) ||\r\n StoredSessions->IsWorkspace(FolderOrWorkspaceName))\r\n {\r\n StoredSessions->GetFolderOrWorkspace(FolderOrWorkspaceName, DataList);\r\n }\r\n else\r\n {\r\n TSessionData * SessionData =\r\n StoredSessions->ParseUrl(SessionName, Options, DefaultsOnly, &DownloadFile, NULL, NULL, Flags);\r\n DataList->Add(SessionData);\r\n\r\n if (DataList->Count == 1)\r\n {\r\n TSessionData * SessionData = DebugNotNull(dynamic_cast<TSessionData *>(DataList->Items[0]));\r\n if (SessionData->SaveOnly)\r\n {\r\n Configuration->Usage->Inc(L\"CommandLineSessionSave\");\r\n TSessionData * SavedSession = DoSaveSession(SessionData, NULL, true, NULL);\r\n if (SavedSession == NULL)\r\n {\r\n Abort();\r\n }\r\n WinConfiguration->LastStoredSession = SavedSession->Name;\r\n DataList->Clear();\r\n }\r\n else if (!SessionData->PuttyProtocol.IsEmpty())\r\n {\r\n // putty does not support resolving environment variables in session settings\r\n // though it's hardly of any use here.\r\n SessionData->ExpandEnvironmentVariables();\r\n OpenSessionInPutty(GUIConfiguration->PuttyPath, SessionData);\r\n DataList->Clear();\r\n Abort();\r\n }\r\n }\r\n }\r\n\r\n if (DefaultsOnly && !NeedSession)\r\n {\r\n // No URL specified on command-line and no explicit command-line parameter\r\n // that requires session was specified => noop\r\n DataList->Clear();\r\n }\r\n else if ((DataList->Count == 0) ||\r\n !dynamic_cast<TSessionData *>(DataList->Items[0])->CanLogin ||\r\n DefaultsOnly)\r\n {\r\n // Note that GetFolderOrWorkspace never returns sites that !CanLogin,\r\n // so we should not get here with more then one site.\r\n // Though we should be good, if we ever do.\r\n\r\n // We get here when:\r\n // - we need session for explicit command-line operation\r\n // - after we handle \"save\" URL.\r\n // - the specified session does not contain enough information to login [= not even hostname]\r\n\r\n DebugAssert(DataList->Count <= 1);\r\n if (!DoLoginDialog(DataList, LinkedForm))\r\n {\r\n Abort();\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall Upload(TTerminal * Terminal, TStrings * FileList, int UseDefaults)\r\n{\r\n UnicodeString TargetDirectory;\r\n TGUICopyParamType CopyParam = GUIConfiguration->DefaultCopyParam;\r\n\r\n TargetDirectory = UnixIncludeTrailingBackslash(Terminal->CurrentDirectory);\r\n\r\n std::unique_ptr<TSessionData> Data(Terminal->SessionData->Clone());\r\n Terminal->FillSessionDataForCode(Data.get());\r\n\r\n int Options = coDisableQueue;\r\n int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;\r\n if ((UseDefaults == 0) ||\r\n DoCopyDialog(true, false, FileList, TargetDirectory, &CopyParam, Options,\r\n CopyParamAttrs, Data.get(), NULL, UseDefaults))\r\n {\r\n // Setting parameter overrides only now, otherwise the dialog would present the parametes as non-default\r\n CopyParam.OnceDoneOperation = odoDisconnect;\r\n\r\n Terminal->CopyToRemote(FileList, TargetDirectory, &CopyParam, 0, NULL);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall Download(TTerminal * Terminal, const UnicodeString FileName, int UseDefaults)\r\n{\r\n TRemoteFile * File = NULL;\r\n\r\n try\r\n {\r\n Terminal->ExceptionOnFail = true;\r\n try\r\n {\r\n Terminal->ReadFile(FileName, File);\r\n }\r\n __finally\r\n {\r\n Terminal->ExceptionOnFail = false;\r\n }\r\n File->FullFileName = FileName;\r\n UnicodeString LocalDirectory = Terminal->SessionData->LocalDirectoryExpanded;\r\n if (LocalDirectory.IsEmpty())\r\n {\r\n LocalDirectory = GetPersonalFolder();\r\n }\r\n UnicodeString TargetDirectory = IncludeTrailingBackslash(LocalDirectory);\r\n\r\n TGUICopyParamType CopyParam = GUIConfiguration->DefaultCopyParam;\r\n UnicodeString DisplayName = File->FileName;\r\n\r\n bool CustomDisplayName =\r\n !File->DisplayName.IsEmpty() &&\r\n (File->DisplayName != DisplayName);\r\n if (CustomDisplayName)\r\n {\r\n DisplayName = File->DisplayName;\r\n }\r\n\r\n UnicodeString FriendyFileName = UnixIncludeTrailingBackslash(UnixExtractFilePath(FileName)) + DisplayName;\r\n std::unique_ptr<TStrings> FileListFriendly(new TStringList());\r\n FileListFriendly->AddObject(FriendyFileName, File);\r\n\r\n int Options = coDisableQueue;\r\n int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Download;\r\n if ((UseDefaults == 0) ||\r\n DoCopyDialog(false, false, FileListFriendly.get(), TargetDirectory, &CopyParam,\r\n Options, CopyParamAttrs, NULL, NULL, UseDefaults))\r\n {\r\n // Setting parameter overrides only now, otherwise the dialog would present the parametes as non-default\r\n\r\n if (CustomDisplayName)\r\n {\r\n // Set only now, so that it is not redundantly displayed on the copy dialog.\r\n // We should escape the * and ?'s.\r\n CopyParam.FileMask = DisplayName;\r\n }\r\n\r\n CopyParam.OnceDoneOperation = odoDisconnect;\r\n\r\n std::unique_ptr<TStrings> FileList(new TStringList());\r\n FileList->AddObject(FileName, File);\r\n Terminal->CopyToLocal(FileList.get(), TargetDirectory, &CopyParam, 0, NULL);\r\n }\r\n\r\n UnicodeString Directory = UnixExtractFilePath(FileName);\r\n Terminal->AutoReadDirectory = true;\r\n Terminal->ChangeDirectory(Directory);\r\n }\r\n __finally\r\n {\r\n delete File;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall Edit(TCustomScpExplorerForm * ScpExplorer, TStrings * FileList)\r\n{\r\n ScpExplorer->StandaloneEdit(FileList->Strings[0]);\r\n Abort();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall SynchronizeDirectories(TTerminal * Terminal,\r\n TStrings * CommandParams,\r\n UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory)\r\n{\r\n if (CommandParams->Count >= 1)\r\n {\r\n LocalDirectory = CommandParams->Strings[0];\r\n }\r\n else if (!Terminal->SessionData->LocalDirectory.IsEmpty())\r\n {\r\n LocalDirectory = Terminal->SessionData->LocalDirectoryExpanded;\r\n }\r\n else\r\n {\r\n LocalDirectory = WinConfiguration->ScpExplorer.LastLocalTargetDirectory;\r\n }\r\n\r\n if (CommandParams->Count >= 2)\r\n {\r\n RemoteDirectory = CommandParams->Strings[1];\r\n }\r\n else\r\n {\r\n RemoteDirectory = Terminal->CurrentDirectory;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall FullSynchronize(\r\n TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer, TStrings * CommandParams, int UseDefaults)\r\n{\r\n UnicodeString LocalDirectory;\r\n UnicodeString RemoteDirectory;\r\n\r\n SynchronizeDirectories(Terminal, CommandParams, LocalDirectory, RemoteDirectory);\r\n\r\n bool SaveMode = true;\r\n // bit ugly\r\n TSynchronizeMode Mode = (TSynchronizeMode)GUIConfiguration->SynchronizeMode;\r\n int Params = GUIConfiguration->SynchronizeParams;\r\n\r\n // Undocumented syntax for \"Start in New Window\"\r\n if (CommandParams->Count >= 4)\r\n {\r\n Mode = (TSynchronizeMode)StrToIntDef(CommandParams->Strings[2], Mode);\r\n Params = StrToIntDef(CommandParams->Strings[3], Params);\r\n }\r\n\r\n int Result =\r\n ScpExplorer->DoFullSynchronizeDirectories(LocalDirectory, RemoteDirectory, Mode, Params, SaveMode, UseDefaults);\r\n if ((Result >= 0) && SaveMode)\r\n {\r\n GUIConfiguration->SynchronizeMode = Mode;\r\n }\r\n\r\n Abort();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall Synchronize(\r\n TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer, TStrings * CommandParams, int UseDefaults)\r\n{\r\n UnicodeString LocalDirectory;\r\n UnicodeString RemoteDirectory;\r\n\r\n SynchronizeDirectories(Terminal, CommandParams, LocalDirectory, RemoteDirectory);\r\n\r\n // Undocumented syntax for \"Start in New Window\"\r\n if (CommandParams->Count >= 4)\r\n {\r\n GUIConfiguration->SynchronizeParams = StrToIntDef(CommandParams->Strings[2], -1);\r\n GUIConfiguration->SynchronizeOptions = StrToIntDef(CommandParams->Strings[3], -1);\r\n\r\n Configuration->DontSave();\r\n }\r\n\r\n ScpExplorer->DoSynchronizeDirectories(LocalDirectory, RemoteDirectory, UseDefaults);\r\n Abort();\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall ImportSitesIfAny()\r\n{\r\n if (!WinConfiguration->AutoImportedFromPuttyOrFilezilla)\r\n {\r\n bool AnyPuttySession = GUIConfiguration->AnyPuttySessionForImport(StoredSessions);\r\n bool AnyFilezillaSession = GUIConfiguration->AnyFilezillaSessionForImport(StoredSessions);\r\n\r\n if (AnyPuttySession || AnyFilezillaSession)\r\n {\r\n UnicodeString PuttySource = LoadStrPart(IMPORT_SESSIONS2, 2);\r\n UnicodeString FilezillaSource = LoadStrPart(IMPORT_SESSIONS2, 3);\r\n UnicodeString Source;\r\n if (AnyPuttySession && AnyFilezillaSession)\r\n {\r\n Source = FORMAT(LoadStrPart(IMPORT_SESSIONS2, 4), (PuttySource, FilezillaSource));\r\n }\r\n else if (AnyPuttySession)\r\n {\r\n Source = PuttySource;\r\n }\r\n else if (AnyFilezillaSession)\r\n {\r\n Source = FilezillaSource;\r\n }\r\n else\r\n {\r\n DebugFail();\r\n }\r\n\r\n UnicodeString Message = FORMAT(LoadStrPart(IMPORT_SESSIONS2, 1), (Source));\r\n\r\n if (MessageDialog(Message, qtConfirmation,\r\n qaYes | qaNo, HELP_IMPORT_SESSIONS) == qaYes)\r\n {\r\n DoImportSessionsDialog(NULL);\r\n }\r\n\r\n WinConfiguration->AutoImportedFromPuttyOrFilezilla = true;\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall Usage(UnicodeString Param)\r\n{\r\n while (!Param.IsEmpty())\r\n {\r\n UnicodeString Pair = CutToChar(Param, L',', true);\r\n if (!Pair.IsEmpty())\r\n {\r\n if (Pair[Pair.Length()] == L'+')\r\n {\r\n UnicodeString Key = Pair.SubString(1, Pair.Length() - 1).Trim();\r\n Configuration->Usage->Inc(Key);\r\n }\r\n else\r\n {\r\n UnicodeString Key = CutToChar(Pair, L':', true);\r\n Configuration->Usage->Set(Key, Pair.Trim());\r\n }\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall RecordWrapperVersions(UnicodeString ConsoleVersion, UnicodeString DotNetVersion)\r\n{\r\n TUpdatesConfiguration Updates = WinConfiguration->Updates;\r\n if (!DotNetVersion.IsEmpty())\r\n {\r\n Updates.DotNetVersion = DotNetVersion;\r\n }\r\n if (!ConsoleVersion.IsEmpty())\r\n {\r\n Updates.ConsoleVersion = ConsoleVersion;\r\n }\r\n WinConfiguration->Updates = Updates;\r\n\r\n if (Configuration->Storage == stNul)\r\n {\r\n Configuration->SetDefaultStorage();\r\n try\r\n {\r\n THierarchicalStorage * Storage = Configuration->CreateConfigStorage();\r\n try\r\n {\r\n Storage->AccessMode = smReadWrite;\r\n if (Storage->OpenSubKey(Configuration->ConfigurationSubKey, true) &&\r\n Storage->OpenSubKeyPath(L\"Interface\\\\Updates\", true))\r\n {\r\n if (!DotNetVersion.IsEmpty())\r\n {\r\n Storage->WriteString(L\"DotNetVersion\", DotNetVersion);\r\n }\r\n if (!ConsoleVersion.IsEmpty())\r\n {\r\n Storage->WriteString(L\"ConsoleVersion\", ConsoleVersion);\r\n }\r\n }\r\n }\r\n __finally\r\n {\r\n delete Storage;\r\n }\r\n }\r\n __finally\r\n {\r\n Configuration->SetNulStorage();\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nstatic UnicodeString ColorToRGBStr(TColor Color)\r\n{\r\n int RGB = ColorToRGB(Color);\r\n int R = GetRValue(RGB);\r\n int G = GetGValue(RGB);\r\n int B = GetBValue(RGB);\r\n UnicodeString Result = FORMAT(L\"%.2x%.2x%.2x\", (R, G, B));\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nTDateTime Started(Now());\r\nint LifetimeRuns = -1;\r\n//---------------------------------------------------------------------------\r\nvoid InterfaceStarted()\r\n{\r\n // deliberate downcast\r\n int StartupSeconds = static_cast<int>(SecondsBetween(Now(), Started));\r\n if (LifetimeRuns > 0)\r\n {\r\n if (LifetimeRuns == 1)\r\n {\r\n Configuration->Usage->Set(L\"StartupSeconds1\", StartupSeconds);\r\n }\r\n else if (LifetimeRuns == 2)\r\n {\r\n Configuration->Usage->Set(L\"StartupSeconds2\", StartupSeconds);\r\n }\r\n Configuration->Usage->Set(L\"StartupSecondsLast\", StartupSeconds);\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall UpdateStaticUsage()\r\n{\r\n LifetimeRuns = Configuration->Usage->Inc(L\"Runs\");\r\n\r\n Configuration->Usage->UpdateCurrentVersion();\r\n\r\n Configuration->Usage->Set(L\"WindowsVersion\", (WindowsVersionLong()));\r\n Configuration->Usage->Set(L\"WindowsProductName\", (WindowsProductName()));\r\n DWORD Type;\r\n GetWindowsProductType(Type);\r\n Configuration->Usage->Set(L\"WindowsProductType\", (static_cast<int>(Type)));\r\n Configuration->Usage->Set(L\"Windows64\", IsWin64());\r\n Configuration->Usage->Set(L\"UWP\", IsUWP());\r\n Configuration->Usage->Set(L\"DefaultLocale\",\r\n // See TGUIConfiguration::GetAppliedLocaleHex()\r\n IntToHex(static_cast<int>(GetDefaultLCID()), 4));\r\n Configuration->Usage->Set(L\"Locale\", WinConfiguration->AppliedLocaleHex);\r\n Configuration->Usage->Set(L\"EncodingMultiByteAnsi\", !TEncoding::Default->IsSingleByte);\r\n Configuration->Usage->Set(L\"PixelsPerInch\", Screen->PixelsPerInch);\r\n\r\n bool PixelsPerInchSystemDiffers = false;\r\n bool PixelsPerInchMonitorsDiffer = false;\r\n bool PixelsPerInchAxesDiffer = false;\r\n\r\n HINSTANCE ShCoreLibrary = LoadLibrary(L\"shcore.dll\");\r\n if (ShCoreLibrary != NULL)\r\n {\r\n GetDpiForMonitorProc GetDpiForMonitor =\r\n (GetDpiForMonitorProc)GetProcAddress(ShCoreLibrary, \"GetDpiForMonitor\");\r\n\r\n if (GetDpiForMonitor != NULL)\r\n {\r\n unsigned int PrimaryDpiX;\r\n unsigned int PrimaryDpiY;\r\n\r\n for (int Index = 0; Index < Screen->MonitorCount; Index++)\r\n {\r\n unsigned int DpiX;\r\n unsigned int DpiY;\r\n GetDpiForMonitor(Screen->Monitors[Index]->Handle, MDT_Default, &DpiX, &DpiY);\r\n\r\n if (DpiX != DpiY)\r\n {\r\n PixelsPerInchAxesDiffer = true;\r\n }\r\n\r\n if (Index == 0)\r\n {\r\n PrimaryDpiX = DpiX;\r\n PrimaryDpiY = DpiY;\r\n\r\n // PixelsPerInch is GetDeviceCaps(DC, LOGPIXELSY)\r\n if (DpiY != (unsigned int)Screen->PixelsPerInch)\r\n {\r\n PixelsPerInchSystemDiffers = true;\r\n }\r\n }\r\n else\r\n {\r\n if ((DpiX != PrimaryDpiX) ||\r\n (DpiY != PrimaryDpiY))\r\n {\r\n PixelsPerInchMonitorsDiffer = true;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (PixelsPerInchSystemDiffers)\r\n {\r\n Configuration->Usage->Inc(L\"PixelsPerInchSystemDiffered\");\r\n }\r\n Configuration->Usage->Set(L\"PixelsPerInchMonitorsDiffer\", PixelsPerInchMonitorsDiffer);\r\n Configuration->Usage->Set(L\"PixelsPerInchAxesDiffer\", PixelsPerInchAxesDiffer);\r\n\r\n Configuration->Usage->Set(L\"WorkAreaWidth\", Screen->WorkAreaWidth);\r\n Configuration->Usage->Set(L\"WorkAreaHeight\", Screen->WorkAreaHeight);\r\n HDC DC = GetDC(NULL);\r\n int Planes = GetDeviceCaps(DC, PLANES);\r\n int BitsPixel = GetDeviceCaps(DC, BITSPIXEL);\r\n Configuration->Usage->Set(L\"ColorDepth\", Planes * BitsPixel);\r\n Configuration->Usage->Set(L\"MonitorCount\", Screen->MonitorCount);\r\n Configuration->Usage->Set(L\"NotUseThemes\", !UseThemes());\r\n Configuration->Usage->Set(L\"ThemeDefaultFontSize\", Application->DefaultFont->Size);\r\n Configuration->Usage->Set(L\"ThemeIconFontSize\", Screen->IconFont->Size);\r\n\r\n Configuration->Usage->Set(L\"SysColorWindow\", ColorToRGBStr(clWindow));\r\n Configuration->Usage->Set(L\"SysColorBtnFace\", ColorToRGBStr(clBtnFace));\r\n Configuration->Usage->Set(L\"SysColorWindowText\", ColorToRGBStr(clWindowText));\r\n\r\n UnicodeString ProgramsFolder;\r\n ::SpecialFolderLocation(CSIDL_PROGRAM_FILES, ProgramsFolder);\r\n ProgramsFolder = IncludeTrailingBackslash(ExpandFileName(ProgramsFolder));\r\n UnicodeString ExeName = ExpandFileName(Application->ExeName);\r\n bool InProgramFiles = AnsiSameText(ExeName.SubString(1, ProgramsFolder.Length()), ProgramsFolder);\r\n Configuration->Usage->Set(L\"InProgramFiles\", InProgramFiles);\r\n Configuration->Usage->Set(L\"IsInstalled\", IsInstalled());\r\n Configuration->Usage->Set(L\"Wine\", IsWine());\r\n Configuration->Usage->Set(L\"NetFrameworkVersion\", GetNetVersionStr());\r\n Configuration->Usage->Set(L\"PowerShellVersion\", GetPowerShellVersionStr());\r\n\r\n WinConfiguration->UpdateStaticUsage();\r\n\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall MaintenanceTask()\r\n{\r\n CoreMaintenanceTask();\r\n}\r\n//---------------------------------------------------------------------------\r\ntypedef std::vector<HWND> THandles;\r\ntypedef std::map<unsigned long, THandles> TProcesses;\r\n//---------------------------------------------------------------------------\r\nBOOL __stdcall EnumOtherInstances(HWND Handle, LPARAM AParam)\r\n{\r\n TProcesses & Processes = *reinterpret_cast<TProcesses *>(AParam);\r\n\r\n unsigned long ProcessId;\r\n if (GetWindowThreadProcessId(Handle, &ProcessId) != 0)\r\n {\r\n Processes[ProcessId].push_back(Handle);\r\n }\r\n\r\n return TRUE;\r\n}\r\n//---------------------------------------------------------------------------\r\nstatic bool __fastcall SendCopyDataMessage(HWND Window, TCopyDataMessage & Message)\r\n{\r\n COPYDATASTRUCT CopyData;\r\n CopyData.cbData = sizeof(Message);\r\n CopyData.lpData = &Message;\r\n\r\n LRESULT SendResult =\r\n SendMessage(Window, WM_COPYDATA,\r\n reinterpret_cast<WPARAM>(HInstance), reinterpret_cast<LPARAM>(&CopyData));\r\n bool Result = (SendResult > 0);\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nstatic void __fastcall FindOtherInstances(THandles & OtherInstances)\r\n{\r\n TProcesses Processes;\r\n\r\n // FindWindow is optimization (if there's no hidden window, no point enumerating all windows to find some)\r\n if ((FindWindow(HIDDEN_WINDOW_NAME, NULL) != NULL) &&\r\n EnumWindows(EnumOtherInstances, reinterpret_cast<LPARAM>(&Processes)))\r\n {\r\n TCopyDataMessage Message;\r\n\r\n Message.Command = TCopyDataMessage::MainWindowCheck;\r\n\r\n TProcesses::const_iterator ProcessI = Processes.begin();\r\n while (ProcessI != Processes.end())\r\n {\r\n HWND HiddenWindow = NULL;\r\n THandles::const_iterator WindowI = ProcessI->second.begin();\r\n\r\n while ((HiddenWindow == NULL) && (WindowI != ProcessI->second.end()))\r\n {\r\n wchar_t ClassName[1024];\r\n if (GetClassName(*WindowI, ClassName, LENOF(ClassName)) != 0)\r\n {\r\n NULL_TERMINATE(ClassName);\r\n\r\n if (wcscmp(ClassName, HIDDEN_WINDOW_NAME) == 0)\r\n {\r\n HiddenWindow = *WindowI;\r\n }\r\n }\r\n WindowI++;\r\n }\r\n\r\n if (HiddenWindow != NULL)\r\n {\r\n WindowI = ProcessI->second.begin();\r\n\r\n while (WindowI != ProcessI->second.end())\r\n {\r\n if (*WindowI != HiddenWindow) // optimization\r\n {\r\n if (SendCopyDataMessage(*WindowI, Message))\r\n {\r\n OtherInstances.push_back(*WindowI);\r\n break;\r\n }\r\n }\r\n WindowI++;\r\n }\r\n }\r\n\r\n ProcessI++;\r\n }\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall SendToAnotherInstance()\r\n{\r\n THandles OtherInstances;\r\n FindOtherInstances(OtherInstances);\r\n\r\n bool Result = false;\r\n THandles::const_iterator I = OtherInstances.begin();\r\n while (!Result && (I != OtherInstances.end()))\r\n {\r\n HWND Handle = *I;\r\n\r\n TCopyDataMessage Message;\r\n Message.Command = TCopyDataMessage::CommandCanCommandLine;\r\n\r\n if (SendCopyDataMessage(Handle, Message))\r\n {\r\n // Restore window, if minimized\r\n ShowWindow(Handle, SW_RESTORE);\r\n // bring it to foreground\r\n SetForegroundWindow(Handle);\r\n\r\n Message.Command = TCopyDataMessage::CommandCommandLine;\r\n wcsncpy(Message.CommandLine, CmdLine, LENOF(Message.CommandLine));\r\n NULL_TERMINATE(Message.CommandLine);\r\n\r\n Result = SendCopyDataMessage(Handle, Message);\r\n }\r\n\r\n I++;\r\n }\r\n\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nvoid __fastcall Refresh(const UnicodeString & Session, const UnicodeString & Path)\r\n{\r\n THandles OtherInstances;\r\n FindOtherInstances(OtherInstances);\r\n\r\n THandles::const_iterator I = OtherInstances.begin();\r\n while (I != OtherInstances.end())\r\n {\r\n HWND Handle = *I;\r\n\r\n TCopyDataMessage Message;\r\n Message.Command = TCopyDataMessage::RefreshPanel;\r\n wcsncpy(Message.Refresh.Session, Session.c_str(), LENOF(Message.Refresh.Session));\r\n NULL_TERMINATE(Message.Refresh.Session);\r\n wcsncpy(Message.Refresh.Path, Path.c_str(), LENOF(Message.Refresh.Path));\r\n NULL_TERMINATE(Message.Refresh.Path);\r\n\r\n SendCopyDataMessage(Handle, Message);\r\n\r\n I++;\r\n }\r\n}\r\n//---------------------------------------------------------------------------\r\nbool __fastcall ShowUpdatesIfAvailable()\r\n{\r\n TUpdatesConfiguration Updates = WinConfiguration->Updates;\r\n int CurrentCompoundVer = Configuration->CompoundVersion;\r\n bool NoPopup = true;\r\n bool Result =\r\n !IsUWP() &&\r\n Updates.ShowOnStartup &&\r\n Updates.HaveValidResultsForVersion(CurrentCompoundVer) &&\r\n !Updates.Results.Disabled &&\r\n ((Updates.Results.Version > CurrentCompoundVer) || !Updates.Results.Message.IsEmpty()) &&\r\n !Updates.ShownResults;\r\n if (Result)\r\n {\r\n Configuration->Usage->Inc(L\"UpdateStartup\");\r\n Result = CheckForUpdates(true);\r\n if (Result)\r\n {\r\n Configuration->Usage->Inc(L\"UpdateDownloadOpensStartup\");\r\n }\r\n NoPopup = false;\r\n }\r\n else if (WinConfiguration->ShowTips)\r\n {\r\n int Days = DaysBetween(WinConfiguration->TipsShown, Now());\r\n if ((Days >= Updates.Results.TipsIntervalDays) &&\r\n (WinConfiguration->RunsSinceLastTip >= Updates.Results.TipsIntervalDays))\r\n {\r\n UnicodeString Tip = FirstUnshownTip();\r\n if (!Tip.IsEmpty())\r\n {\r\n AutoShowNewTip();\r\n NoPopup = false;\r\n }\r\n else\r\n {\r\n Configuration->Usage->Inc(L\"TipsNoUnseen\");\r\n }\r\n }\r\n }\r\n\r\n if (NoPopup)\r\n {\r\n WinConfiguration->RunsSinceLastTip = WinConfiguration->RunsSinceLastTip + 1;\r\n }\r\n return Result;\r\n}\r\n//---------------------------------------------------------------------------\r\nint __fastcall Execute()\r\n{\r\n DebugAssert(StoredSessions);\r\n TProgramParams * Params = TProgramParams::Instance();\r\n DebugAssert(Params);\r\n\r\n // do not flash message boxes on startup\r\n SetOnForeground(true);\r\n\r\n // let installer know, that some instance of application is running\r\n CreateMutex(NULL, False, AppName.c_str());\r\n bool OnlyInstance = (GetLastError() == 0);\r\n\r\n UpdateStaticUsage();\r\n\r\n UnicodeString KeyFile;\r\n if (Params->FindSwitch(L\"PrivateKey\", KeyFile))\r\n {\r\n WinConfiguration->DefaultKeyFile = KeyFile;\r\n }\r\n\r\n UnicodeString ConsoleVersion;\r\n UnicodeString DotNetVersion;\r\n Params->FindSwitch(L\"Console\", ConsoleVersion);\r\n Params->FindSwitch(L\"DotNet\", DotNetVersion);\r\n if (!ConsoleVersion.IsEmpty() || !DotNetVersion.IsEmpty())\r\n {\r\n RecordWrapperVersions(ConsoleVersion, DotNetVersion);\r\n }\r\n if (!DotNetVersion.IsEmpty())\r\n {\r\n Configuration->Usage->Inc(L\"ConsoleDotNet\");\r\n }\r\n\r\n UnicodeString SwitchValue;\r\n if (Params->FindSwitch(L\"loglevel\", SwitchValue))\r\n {\r\n int StarPos = SwitchValue.Pos(L\"*\");\r\n if (StarPos > 0)\r\n {\r\n bool LogSensitive = true;\r\n SwitchValue.Delete(StarPos, 1);\r\n\r\n if ((StarPos <= SwitchValue.Length()) &&\r\n (SwitchValue[StarPos] == L'-'))\r\n {\r\n LogSensitive = false;\r\n SwitchValue.Delete(StarPos, 1);\r\n }\r\n\r\n SwitchValue = SwitchValue.Trim();\r\n\r\n Configuration->TemporaryLogSensitive(LogSensitive);\r\n }\r\n int LogProtocol;\r\n if (!SwitchValue.IsEmpty() && TryStrToInt(SwitchValue, LogProtocol) && (LogProtocol >= -1))\r\n {\r\n Configuration->TemporaryLogProtocol(LogProtocol);\r\n }\r\n }\r\n\r\n if (Params->FindSwitch(LOGSIZE_SWITCH, SwitchValue))\r\n {\r\n int StarPos = SwitchValue.Pos(LOGSIZE_SEPARATOR);\r\n int LogMaxCount = 0;\r\n if (StarPos > 1)\r\n {\r\n if (!TryStrToInt(SwitchValue.SubString(1, StarPos - 1), LogMaxCount))\r\n {\r\n LogMaxCount = -1;\r\n }\r\n SwitchValue.Delete(1, StarPos);\r\n SwitchValue = SwitchValue.Trim();\r\n }\r\n\r\n __int64 LogMaxSize;\r\n if ((LogMaxCount >= 0) &&\r\n !SwitchValue.IsEmpty() &&\r\n TryStrToSize(SwitchValue, LogMaxSize))\r\n {\r\n Configuration->TemporaryLogMaxCount(LogMaxCount);\r\n Configuration->TemporaryLogMaxSize(LogMaxSize);\r\n }\r\n }\r\n\r\n std::unique_ptr<TStrings> RawSettings(new TStringList());\r\n if (Params->FindSwitch(RAWTRANSFERSETTINGS_SWITCH, RawSettings.get()))\r\n {\r\n std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings.get(), false));\r\n GUIConfiguration->LoadDefaultCopyParam(OptionsStorage.get());\r\n }\r\n\r\n TConsoleMode Mode = cmNone;\r\n if (Params->FindSwitch(L\"help\") || Params->FindSwitch(L\"h\") || Params->FindSwitch(L\"?\"))\r\n {\r\n Mode = cmHelp;\r\n }\r\n else if (Params->FindSwitch(L\"batchsettings\"))\r\n {\r\n Mode = cmBatchSettings;\r\n }\r\n else if (Params->FindSwitch(KEYGEN_SWITCH))\r\n {\r\n Mode = cmKeyGen;\r\n }\r\n else if (Params->FindSwitch(FINGERPRINTSCAN_SWITCH))\r\n {\r\n Mode = cmFingerprintScan;\r\n }\r\n else if (Params->FindSwitch(DUMPCALLSTACK_SWITCH))\r\n {\r\n Mode = cmDumpCallstack;\r\n }\r\n else if (Params->FindSwitch(INFO_SWITCH))\r\n {\r\n Mode = cmInfo;\r\n }\r\n else if (Params->FindSwitch(COMREGISTRATION_SWITCH))\r\n {\r\n Mode = cmComRegistration;\r\n }\r\n // We have to check for /console only after the other options,\r\n // as the /console is always used when we are run by winscp.com\r\n // (ambiguous use to pass console version)\r\n else if (Params->FindSwitch(L\"Console\") || Params->FindSwitch(SCRIPT_SWITCH) ||\r\n Params->FindSwitch(COMMAND_SWITCH))\r\n {\r\n Mode = cmScripting;\r\n }\r\n\r\n if (Mode != cmNone)\r\n {\r\n return Console(Mode);\r\n }\r\n\r\n TTerminalManager * TerminalManager = NULL;\r\n GlyphsModule = NULL;\r\n NonVisualDataModule = NULL;\r\n TStrings * CommandParams = new TStringList;\r\n try\r\n {\r\n TerminalManager = TTerminalManager::Instance();\r\n HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();\r\n try\r\n {\r\n GlyphsModule = new TGlyphsModule(Application);\r\n }\r\n __finally\r\n {\r\n GUIConfiguration->ChangeResourceModule(ResourceModule);\r\n }\r\n NonVisualDataModule = new TNonVisualDataModule(Application);\r\n\r\n // The default is 2.5s.\r\n // 20s is used by Office 2010 and Windows 10 Explorer.\r\n // Some applications use an infinite (Thunderbird, Firefox).\r\n // Overriden for some controls using THintInfo.HideTimeout\r\n Application->HintHidePause = 20000;\r\n HintWindowClass = __classid(TScreenTipHintWindow);\r\n\r\n UnicodeString IniFileName = Params->SwitchValue(INI_SWITCH);\r\n if (!IniFileName.IsEmpty() && (IniFileName != INI_NUL))\r\n {\r\n UnicodeString IniFileNameExpanded = ExpandEnvironmentVariables(IniFileName);\r\n if (!FileExists(ApiPath(IniFileNameExpanded)))\r\n {\r\n // this should be displayed rather at the very beginning.\r\n // however for simplicity (GUI-only), we do it only here.\r\n MessageDialog(FMTLOAD(FILE_NOT_EXISTS, (IniFileNameExpanded)), qtError, qaOK);\r\n }\r\n }\r\n\r\n if (Params->FindSwitch(L\"UninstallCleanup\"))\r\n {\r\n MaintenanceTask();\r\n Configuration->DontSave();\r\n // The innosetup cannot skip UninstallCleanup run task for silent uninstalls,\r\n // workaround is that we create mutex in uninstaller, if it runs silent, and\r\n // ignore the UninstallCleanup, when the mutex exists.\r\n if (OpenMutex(SYNCHRONIZE, false, L\"WinSCPSilentUninstall\") == NULL)\r\n {\r\n DoCleanupDialogIfAnyDataAndWanted();\r\n }\r\n }\r\n else if (Params->FindSwitch(L\"RegisterForDefaultProtocols\") ||\r\n Params->FindSwitch(L\"RegisterAsUrlHandler\")) // BACKWARD COMPATIBILITY\r\n {\r\n MaintenanceTask();\r\n if (CheckSafe(Params))\r\n {\r\n RegisterForDefaultProtocols();\r\n Configuration->DontSave();\r\n }\r\n }\r\n else if (Params->FindSwitch(L\"UnregisterForProtocols\"))\r\n {\r\n MaintenanceTask();\r\n if (CheckSafe(Params))\r\n {\r\n UnregisterForProtocols();\r\n Configuration->DontSave();\r\n }\r\n }\r\n else if (Params->FindSwitch(L\"AddSearchPath\"))\r\n {\r\n MaintenanceTask();\r\n if (CheckSafe(Params))\r\n {\r\n AddSearchPath(ExtractFilePath(Application->ExeName));\r\n Configuration->DontSave();\r\n }\r\n }\r\n else if (Params->FindSwitch(L\"RemoveSearchPath\"))\r\n {\r\n MaintenanceTask();\r\n if (CheckSafe(Params))\r\n {\r\n try\r\n {\r\n RemoveSearchPath(ExtractFilePath(Application->ExeName));\r\n }\r\n catch(...)\r\n {\r\n // ignore errors\r\n // (RemoveSearchPath is called always on uninstallation,\r\n // even if AddSearchPath was not used, so we would get the error\r\n // always for non-priviledged user)\r\n }\r\n Configuration->DontSave();\r\n }\r\n }\r\n else if (Params->FindSwitch(L\"ImportSitesIfAny\"))\r\n {\r\n MaintenanceTask();\r\n ImportSitesIfAny();\r\n }\r\n else if (Params->FindSwitch(L\"Usage\", SwitchValue))\r\n {\r\n MaintenanceTask();\r\n Usage(SwitchValue);\r\n }\r\n else if (Params->FindSwitch(L\"Update\"))\r\n {\r\n MaintenanceTask();\r\n CheckForUpdates(false);\r\n }\r\n else if (ShowUpdatesIfAvailable())\r\n {\r\n // noop\r\n }\r\n else if (Params->FindSwitch(L\"Exit\"))\r\n {\r\n // noop\r\n MaintenanceTask();\r\n Configuration->DontSave();\r\n }\r\n else if (Params->FindSwitch(L\"MaintenanceTask\"))\r\n {\r\n // Parameter /MaintenanceTask can be added to command-line when executing maintenance tasks\r\n // (e.g. from installer) just in case old version of WinSCP is called by mistake\r\n MaintenanceTask();\r\n Configuration->DontSave();\r\n }\r\n else\r\n {\r\n enum { pcNone, pcUpload, pcFullSynchronize, pcSynchronize, pcEdit, pcRefresh } ParamCommand;\r\n ParamCommand = pcNone;\r\n UnicodeString AutoStartSession;\r\n UnicodeString DownloadFile;\r\n int UseDefaults = -1;\r\n\r\n // do not check for temp dirs for service tasks (like RegisterAsUrlHandler)\r\n if (OnlyInstance &&\r\n WinConfiguration->TemporaryDirectoryCleanup)\r\n {\r\n TemporaryDirectoryCleanup();\r\n }\r\n\r\n WinConfiguration->CheckDefaultTranslation();\r\n // Loading shell image lists here (rather than only on demand when file controls are being created)\r\n // reduces risk of an occasional crash.\r\n // It seems that the point is to load the lists before any call to SHGetFileInfoWithTimeout.\r\n InitFileControls();\r\n\r\n if (!Params->Empty)\r\n {\r\n UnicodeString Value;\r\n if (Params->FindSwitch(DEFAULTS_SWITCH, Value) && CheckSafe(Params))\r\n {\r\n UseDefaults = StrToIntDef(Value, 0);\r\n }\r\n\r\n if (Params->FindSwitch(UPLOAD_SWITCH, CommandParams))\r\n {\r\n ParamCommand = pcUpload;\r\n if (CommandParams->Count == 0)\r\n {\r\n throw Exception(NO_UPLOAD_LIST_ERROR);\r\n }\r\n }\r\n if (Params->FindSwitch(UPLOAD_IF_ANY_SWITCH, CommandParams))\r\n {\r\n if (CommandParams->Count > 0)\r\n {\r\n ParamCommand = pcUpload;\r\n }\r\n }\r\n else if (Params->FindSwitch(SYNCHRONIZE_SWITCH, CommandParams, 4))\r\n {\r\n ParamCommand = pcFullSynchronize;\r\n }\r\n else if (Params->FindSwitch(KEEP_UP_TO_DATE_SWITCH, CommandParams, 4))\r\n {\r\n ParamCommand = pcSynchronize;\r\n }\r\n else if (Params->FindSwitch(L\"Edit\", CommandParams, 1) &&\r\n (CommandParams->Count == 1))\r\n {\r\n ParamCommand = pcEdit;\r\n }\r\n else if (Params->FindSwitch(REFRESH_SWITCH, CommandParams, 1))\r\n {\r\n ParamCommand = pcRefresh;\r\n }\r\n }\r\n\r\n if (Params->ParamCount > 0)\r\n {\r\n AutoStartSession = Params->Param[1];\r\n Params->ParamsProcessed(1, 1);\r\n\r\n if ((ParamCommand == pcNone) &&\r\n (WinConfiguration->ExternalSessionInExistingInstance != OpenInNewWindow()) &&\r\n !Params->FindSwitch(NEWINSTANCE_SWICH) &&\r\n SendToAnotherInstance())\r\n {\r\n Configuration->Usage->Inc(L\"SendToAnotherInstance\");\r\n return 0;\r\n }\r\n UnicodeString CounterName;\r\n if (Params->FindSwitch(JUMPLIST_SWITCH))\r\n {\r\n CounterName = L\"CommandLineJumpList\";\r\n }\r\n else if (Params->FindSwitch(DESKTOP_SWITCH))\r\n {\r\n CounterName = L\"CommandLineDesktop\";\r\n }\r\n else if (Params->FindSwitch(SEND_TO_HOOK_SWITCH))\r\n {\r\n CounterName = L\"CommandLineSendToHook\";\r\n }\r\n else\r\n {\r\n CounterName = L\"CommandLineSession2\";\r\n }\r\n Configuration->Usage->Inc(CounterName);\r\n }\r\n else if (WinConfiguration->EmbeddedSessions && StoredSessions->Count)\r\n {\r\n AutoStartSession = StoredSessions->Sessions[0]->Name;\r\n }\r\n else\r\n {\r\n AutoStartSession = WinConfiguration->AutoStartSession;\r\n }\r\n\r\n if (ParamCommand == pcRefresh)\r\n {\r\n Refresh(AutoStartSession, (CommandParams->Count > 0 ? CommandParams->Strings[0] : UnicodeString()));\r\n return 0;\r\n }\r\n\r\n // from now flash message boxes on background\r\n SetOnForeground(false);\r\n\r\n bool NeedSession = (ParamCommand != pcNone);\r\n\r\n bool Retry;\r\n do\r\n {\r\n Retry = false;\r\n std::unique_ptr<TObjectList> DataList(new TObjectList());\r\n try\r\n {\r", " int Flags =\r\n pufAllowStoredSiteWithProtocol |\r\n FLAGMASK(!CheckSafe(Params), pufUnsafe);\r\n GetLoginData(AutoStartSession, Params, DataList.get(), DownloadFile, NeedSession, NULL, Flags);\r", " // GetLoginData now Aborts when session is needed and none is selected\r\n if (DebugAlwaysTrue(!NeedSession || (DataList->Count > 0)))\r\n {\r\n if (CheckSafe(Params))\r\n {\r\n UnicodeString LogFile;\r\n if (Params->FindSwitch(LOG_SWITCH, LogFile))\r\n {\r\n Configuration->TemporaryLogging(LogFile);\r\n }\r\n if (Params->FindSwitch(L\"XmlLog\", LogFile))\r\n {\r\n Configuration->TemporaryActionsLogging(LogFile);\r\n }\r\n }\r\n\r\n try\r\n {\r\n DebugAssert(!TerminalManager->ActiveTerminal);\r\n\r\n bool CanStart;\r\n bool Browse = false;\r\n if (DataList->Count > 0)\r\n {\r\n TManagedTerminal * Terminal = TerminalManager->NewTerminals(DataList.get());\r\n UnicodeString BrowseFile;\r\n if (Params->FindSwitch(BROWSE_SWITCH, BrowseFile) &&\r\n (!BrowseFile.IsEmpty() || !DownloadFile.IsEmpty()))\r\n {\r\n if (BrowseFile.IsEmpty())\r\n {\r\n BrowseFile = DownloadFile;\r\n }\r\n DebugAssert(Terminal->RemoteExplorerState == NULL);\r\n Terminal->RemoteExplorerState = CreateDirViewStateForFocusedItem(BrowseFile);\r\n DebugAssert(Terminal->LocalExplorerState == NULL);\r\n Terminal->LocalExplorerState = CreateDirViewStateForFocusedItem(BrowseFile);\r\n DownloadFile = UnicodeString();\r\n Browse = true;\r\n }\r\n if (!DownloadFile.IsEmpty())\r\n {\r\n Terminal->AutoReadDirectory = false;\r\n DownloadFile = UnixIncludeTrailingBackslash(Terminal->SessionData->RemoteDirectory) + DownloadFile;\r\n Terminal->SessionData->RemoteDirectory = L\"\";\r\n Terminal->StateData->RemoteDirectory = Terminal->SessionData->RemoteDirectory;\r\n }\r\n TerminalManager->ActiveTerminal = Terminal;\r\n CanStart = (TerminalManager->Count > 0);\r\n }\r\n else\r\n {\r\n DebugAssert(!NeedSession);\r\n CanStart = true;\r\n }\r\n\r\n if (!CanStart)\r\n {\r\n // do not prompt with login dialog, if connection of\r\n // auto-start session (typically from command line) failed\r\n if (AutoStartSession.IsEmpty())\r\n {\r\n Retry = true;\r\n }\r\n }\r\n else\r\n {\r\n // from now on, we do not support runtime interface change\r\n CustomWinConfiguration->CanApplyInterfaceImmediately = false;\r\n TCustomScpExplorerForm * ScpExplorer = CreateScpExplorer();\r\n CustomWinConfiguration->AppliedInterface = CustomWinConfiguration->Interface;\r\n try\r\n {\r\n // moved inside try .. __finally, because it can fail as well\r\n TerminalManager->ScpExplorer = ScpExplorer;\r\n\r\n if ((ParamCommand != pcNone) || !DownloadFile.IsEmpty())\r\n {\r\n Configuration->Usage->Inc(L\"CommandLineOperation\");\r\n }\r\n\r\n if (ParamCommand == pcUpload)\r\n {\r\n Upload(TerminalManager->ActiveTerminal, CommandParams, UseDefaults);\r\n }\r\n else if (ParamCommand == pcFullSynchronize)\r\n {\r\n FullSynchronize(TerminalManager->ActiveTerminal, ScpExplorer,\r\n CommandParams, UseDefaults);\r\n }\r\n else if (ParamCommand == pcSynchronize)\r\n {\r\n Synchronize(TerminalManager->ActiveTerminal, ScpExplorer,\r\n CommandParams, UseDefaults);\r\n }\r\n else if (ParamCommand == pcEdit)\r\n {\r\n Edit(ScpExplorer, CommandParams);\r\n }\r\n else if (!DownloadFile.IsEmpty())\r\n {\r\n Download(TerminalManager->ActiveTerminal, DownloadFile,\r\n UseDefaults);\r\n }\r\n\r\n if (Browse)\r\n {\r\n ScpExplorer->BrowseFile();\r\n }\r\n\r\n Application->Run();\r\n // to allow dialog boxes show later (like from CheckConfigurationForceSave)\r\n SetAppTerminated(False);\r\n }\r\n __finally\r\n {\r\n TerminalManager->ScpExplorer = NULL;\r\n SAFE_DESTROY(ScpExplorer);\r\n }\r\n }\r\n }\r\n catch (Exception &E)\r\n {\r\n ShowExtendedException(&E);\r\n }\r\n }\r\n }\r\n // Catch EAbort from Synchronize() and similar functions, so that CheckConfigurationForceSave is processed\r\n catch (EAbort & E)\r\n {\r\n Retry = false; // unlikely to be true, but just in case\r\n }\r\n }\r\n while (Retry);\r\n }\r\n\r\n // In GUI mode only\r\n CheckConfigurationForceSave();\r\n }\r\n __finally\r\n {\r\n delete NonVisualDataModule;\r\n NonVisualDataModule = NULL;\r\n ReleaseImagesModules();\r\n delete GlyphsModule;\r\n GlyphsModule = NULL;\r\n TTerminalManager::DestroyInstance();\r\n delete CommandParams;\r\n }\r\n\r\n return 0;\r\n}" ]
[ 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 53, 80, 2275, 473, 1511, 2372, 1100], "buggy_code_start_loc": [46, 52, 79, 599, 57, 1510, 2371, 1099], "filenames": ["source/Console.cbproj", "source/DragExt.cbproj", "source/WinSCP.cbproj", "source/core/SessionData.cpp", "source/core/SessionData.h", "source/forms/Custom.cpp", "source/windows/ConsoleRunner.cpp", "source/windows/WinMain.cpp"], "fixing_code_end_loc": [47, 53, 80, 2294, 474, 1511, 2372, 1103], "fixing_code_start_loc": [46, 52, 79, 599, 58, 1510, 2371, 1099], "message": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:winscp:winscp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C081564B-8EF8-4C8A-9EB0-1C50D5A8F18B", "versionEndExcluding": "5.17.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "WinSCP before 5.17.10 allows remote attackers to execute arbitrary programs when the URL handler encounters a crafted URL that loads session settings. (For example, this is exploitable in a default installation in which WinSCP is the handler for sftp:// URLs.)"}, {"lang": "es", "value": "WinSCP anterior a la versi\u00f3n 5.17.10 permite a los atacantes remotos ejecutar programas arbitrarios cuando el manejador de URLs encuentra una URL manipulada que carga la configuraci\u00f3n de la sesi\u00f3n. (Por ejemplo, esto es explotable en una instalaci\u00f3n por defecto en la que WinSCP es el manejador de URLs sftp://)"}], "evaluatorComment": null, "id": "CVE-2021-3331", "lastModified": "2021-02-04T15:59:24.960", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-01-27T21:15:16.840", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://winscp.net/eng/docs/history#5.17.10"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://winscp.net/eng/docs/rawsettings"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://winscp.net/tracker/1943"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/winscp/winscp/commit/faa96e8144e6925a380f94a97aa382c9427f688d"}, "type": "NVD-CWE-Other"}
177
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n+---------------------------------------------------------------------------+\n| Revive Adserver |\n| http://www.revive-adserver.com |\n| |\n| Copyright: See the COPYRIGHT.txt file. |\n| License: GPLv2 or later, see the LICENSE.txt file. |\n+---------------------------------------------------------------------------+\n*/", "/**\n * @package MaxPlugins\n * @subpackage InvocationTags\n */", "require_once MAX_PATH . '/lib/Max.php';\nrequire_once LIB_PATH . '/Extension/invocationTags/InvocationTags.php';\nrequire_once MAX_PATH . '/lib/max/Plugin/Translation.php';\nrequire_once MAX_PATH . '/lib/max/Delivery/common.php';\nrequire_once MAX_PATH . '/lib/JSON/JSON.php';", "require_once OX_PATH . '/lib/OX.php';", "/**\n *\n * Invocation tag plugin.\n *\n */\nclass Plugins_InvocationTags_OxInvocationTags_Spc extends Plugins_InvocationTags\n{\n /**\n * Set default values for options used by this plugin\n *\n * @var array Array of $key => $defaultValue\n */\n var $defaultOptionValues = array(\n 'block' => 0,\n 'blockcampaign' => 0,\n 'target' => '',\n 'source' => '',\n 'withtext' => 0,\n 'noscript' => 1,\n 'ssl' => 0,\n 'charset' => '',\n );", " /**\n * Make this the default publisher plugin\n *\n * @var boolean\n */\n var $default = true;", " var $varprefix;\n var $appname;", " /**\n * Constructor\n *\n */\n function __construct()\n {\n $conf = $GLOBALS['_MAX']['CONF'];\n $this->publisherPlugin = true;\n $this->varprefix = $conf['var']['prefix'];\n $this->appname = PRODUCT_NAME . \" v\" . VERSION;\n }", " /**\n * Return name of plugin\n *\n * @return string\n */\n function getName()\n {\n return $this->translate(\"Publisher code - Single Page Call\");\n }", " /**\n * Return the English name of the plugin. Used when\n * generating translation keys based on the plugin\n * name.\n *\n * @return string An English string describing the class.\n */\n function getNameEN()\n {\n return 'Publisher code - Single Page Call';\n }", " /**\n * Check if plugin is allowed\n *\n * @return boolean True - allowed, false - not allowed\n */\n function isAllowed($extra = null)\n {\n return false;\n }", " /**\n * Return invocation code for this plugin (codetype)\n *\n * @return string\n */\n function generateInvocationCode()\n {\n $conf = $GLOBALS['_MAX']['CONF'];\n $pref = $GLOBALS['_MAX']['CONF'];", " $mi = &$this->maxInvocation;", " // Get the affiliate information\n $doAffiliates = OA_Dal::factoryDO('affiliates');\n if ($doAffiliates->get($mi->affiliateid)) {\n $affiliate = $doAffiliates->toArray();\n }\n $doZones = OA_Dal::factoryDO('zones');\n $doZones->affiliateid = $mi->affiliateid;\n $doZones->find();\n while ($doZones->fetch() && $row = $doZones->toArray()) {\n // Email/Newsletter and DHTML and Video zones are not included in SPC\n if ($row['delivery'] != MAX_ZoneEmail\n && $row['delivery'] != phpAds_ZoneInterstitial\n && $row['delivery'] != OX_ZoneVideoInstream\n && $row['delivery'] != OX_ZoneVideoOverlay) {\n $aZones[] = $row;\n }\n }", " if(count($aZones) == 0) {\n return 'No Zones Available!';\n }", "\n $channel = (!empty($mi->source)) ? $mi->source : $affiliate['mnemonic'] . \"/test/preview\";", " $script = \"<?xml version='1.0' encoding='UTF-8' ?><!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>\n<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>\n<head>\n <title>Tags for [id{$affiliate['affiliateid']}] \".htmlspecialchars($affiliate['name']).\"</title>\n <link rel='stylesheet' type='text/css' href='\" . OX::assetPath() . \"/css/preview.css' />\n <script type='text/javascript' src='\" . OX::assetPath() . \"/js/jquery-1.2.3.js'></script>", " <script type='text/javascript'>\n <!--", " function selectElement() {\n if (window.getSelection) {\n var r = document.createRange();\n r.selectNodeContents($(this)[0]);\n var s = window.getSelection();\n if (s.rangeCount) {\n s.collapseToStart();\n s.removeAllRanges();\n }\n s.addRange(r);\n } else if (document.body.createTextRange) {\n var r = document.body.createTextRange();\n r.moveToElementText($(this)[0]);\n r.select();\n }\n }", " $(document).ready(function() {\n $('pre').bind('mousedown', selectElement);\n $('pre').bind('click', selectElement);\n $('pre').bind('mousemove', selectElement);", " $('#closeWindow').click(function() {\n window.close();\n });\n });", " //-->\n </script>\n </head>", " <body class='invocationCodes'>\n <div class='header'>\n <h1>\" . PRODUCT_NAME . \"</h1>\n </div>\n \";", " $script .= \"\n <div class='settings'>\n <h2>Tags <small>for <span class='inlinePublisher'>[id{$affiliate['affiliateid']}] \".htmlspecialchars($affiliate['name']).\"</span></small></h2>\n <p>\n This page contains all the information you need to show banners on your website.\n Please follow the instructions carefully and ensure that you copied the scripts <strong>exactly</strong> as shown below.\n </p>", " <h3>The following settings were used to generate this page:</h3>\n <table class='horizontalSummary' summary=''>\n \";", " reset ($this->defaultOptionValues);\n foreach ($this->defaultOptionValues as $feature => $default) {\n switch ($feature) {\n case 'block':\n $optionName = $GLOBALS['strInvocationDontShowAgain'];\n $optionValue = intval($mi->$feature) ? $GLOBALS['strYes'] : $GLOBALS['strNo'];\n break;\n case 'blockcampaign':\n $optionName = $GLOBALS['strInvocationDontShowAgainCampaign'];\n $optionValue = intval($mi->$feature) ? $GLOBALS['strYes'] : $GLOBALS['strNo'];\n break;\n case 'target':\n $optionName = $GLOBALS['strInvocationTarget'];\n switch($mi->$feature) {\n case '_blank': $optionValue = 'New window'; break;\n case '_top': $optionValue = 'Same window'; break;\n default: $optionValue = $GLOBALS['strDefault']; break;\n }\n break;\n case 'source':\n $optionName = $GLOBALS['strInvocationSource'];\n $optionValue = $mi->$feature != '' ? htmlspecialchars(stripslashes($mi->$feature)) : '-';\n break;\n case 'withtext':\n $optionName = $GLOBALS['strInvocationWithText'];\n $optionValue = intval($mi->$feature) ? $GLOBALS['strYes'] : $GLOBALS['strNo'];\n break;\n case 'noscript':\n $optionName = $this->translate(\"Option - noscript\");\n $optionValue = intval($mi->$feature) ? $GLOBALS['strYes'] : $GLOBALS['strNo'];\n break;\n case 'ssl':\n $optionName = $this->translate(\"Option - SSL\");\n $optionValue = intval($mi->$feature) ? $GLOBALS['strYes'] : $GLOBALS['strNo'];\n break;\n case 'charset':\n $optionName = $GLOBALS['strCharset'];", " $optionValue = empty($mi->$feature) ? $GLOBALS['strAutoDetect'] : $mi->$feature;", " break;\n default:\n $optionName = $feature;\n $optionValue = htmlspecialchars(stripslashes($mi->$feature));\n break;\n }", " $script .= \"\n <tr>\n <th>{$optionName}</th>\n <td>{$optionValue}</td>\n </tr>\n \";\n }", " $script .= \"\n </table>\n </div>\n \";", " /* Common script at the top of the page */\n $codeblock = $this->getHeaderCode();", " $script .= \"\n <div class='step'>\n <h2>\n <div class='number'><span>1</span></div>\n Header script\n </h2>\n <p>\n Insert the following script at the top of every page on the {$affiliate['website']} website. This code\n belongs between the <code>&lt;head&gt;</code> and <code>&lt;/head&gt;</code> tags, before any ad scripts\n on the page:\n </p>", " <pre>\". htmlspecialchars($codeblock) .\"</pre>\n </div>\n \";", " $i = 2;", "", "\n foreach($aZones as $zone) {\n $width = $zone['width'] > -1 ? $zone['width'] : 150;\n $widthLabel = $zone['width'] > -1 ? $zone['width'] : '*';", " $height = $zone['height'] > -1 ? $zone['height'] : 150;\n $heightLabel = $zone['height'] > -1 ? $zone['height'] : '*';", " $customClass = array();", " if ($zone['width'] == -1 && $zone['height'] == -1) {\n $customClass[] = 'customBoth';\n } elseif ($zone['height'] == -1) {\n $customClass[] = 'customHeight';\n } elseif ($zone['width'] == -1) {\n $customClass[] = 'customWidth';\n }", " // Labels are roughly 80 x 30 pixels...\n // width < 80 || height < 30 => No room for even a single label, drop the OpenX logo and show the size outside\n // width < 160 && height < 60 => No room for both labels... drop the OpenX logo\n if (($zone['width'] > -1 && $zone['width'] < 80) || ($zone['height'] > -1 && $zone['height'] < 30)) {\n $customClass[] = 'labelsMicro';\n } elseif ($zone['width'] > -1 && $zone['width'] < 160 && $zone['height'] > -1 && $zone['height'] < 60) {\n $customClass[] = 'labelsMini';\n }", " $codeblock = $this->getZoneCode($zone, $affiliate);", " $script .= \"\n <div class='step'>\n <h2>\n <div class='number'><span>{$i}</span></div>\n Ad script <small>for <span class='inlineZone'>[id{$zone['zoneid']}] \".htmlspecialchars($zone['zonename']).\"</span></small>\n </h2>\n <p>\n Copy the following script and place it in the site where you want the ad to display:\n </p>", " <pre>\" . htmlspecialchars($codeblock) . \"</pre>", " <p>\n Example\" . ($zone['width'] == -1 || $zone['height'] == -1 ? ' (actual size may vary)' : '') . \":\n </p>", " <div class='sizePreview \" . (count($customClass) ? ' ' . implode(' ', $customClass) : '') . \"' style='width: {$width}px; height: {$height}px;'>\n <img src='\" . OX::assetPath() . \"/images/logo-adserver-small.png' alt='' />\n <span>{$widthLabel} x {$heightLabel}</span>\n </div>", " </div>\n \";", " $i++;\n }", " $script .= \"\n <div class='step'>\n <h2>\n <div class='number'><span>{$i}</span></div>\n Done\n </h2>\n <p>\n Banners should now appear on your website\n </p>", " <button id='closeWindow'><img src='\" . OX::assetPath() . \"/images/cross.png' alt='' />Close this window</button>\n </div>", " <div class='generated'>\n Generated by {$this->appname}\n </div>\n </body>\n</html>\n \";", " return $script;\n }", " /**\n * Return list of options\n *\n * @return array Group of options\n */\n function getOptionsList()\n {\n // Publisher Invocation doesn't require a lot of the default options...\n if (is_array($this->defaultOptions)) {\n // JS code generates it's own cacheBuster\n unset($this->defaultOptions['cacheBuster']);\n // Publisher invocation is not designed for loading into another adserver\n unset($this->defaultOptions['3thirdPartyServer']);\n }\n $options = array (\n 'spacer' => MAX_PLUGINS_INVOCATION_TAGS_STANDARD,\n 'block' => MAX_PLUGINS_INVOCATION_TAGS_STANDARD,\n 'blockcampaign' => MAX_PLUGINS_INVOCATION_TAGS_STANDARD,\n 'spacer' => MAX_PLUGINS_INVOCATION_TAGS_STANDARD,\n 'target' => MAX_PLUGINS_INVOCATION_TAGS_STANDARD,\n 'source' => MAX_PLUGINS_INVOCATION_TAGS_STANDARD,\n 'withtext' => MAX_PLUGINS_INVOCATION_TAGS_STANDARD,\n 'charset' => MAX_PLUGINS_INVOCATION_TAGS_STANDARD,\n 'noscript' => MAX_PLUGINS_INVOCATION_TAGS_CUSTOM,\n 'ssl' => MAX_PLUGINS_INVOCATION_TAGS_CUSTOM,\n );", " return $options;\n }", " /**\n * A custom handler for the <noscript> option\n *\n * @return string HTML to show the <noscript> option\n */\n function noscript()\n {\n $maxInvocation = &$this->maxInvocation;\n $noscript = (isset($maxInvocation->noscript)) ? $maxInvocation->noscript : $this->defaultOptionValues['noscript'];", " $option = '';\n $option .= \"<tr><td width='30'>&nbsp;</td>\";\n $option .= \"<td width='200'>\" . $this->translate(\"Option - noscript\") . \"</td>\";\n $option .= \"<td width='370'><input type='radio' id='noscript-y' name='noscript' value='1'\".($noscript == 1 ? \" checked='checked'\" : '').\" tabindex='\".($maxInvocation->tabindex++).\"'>&nbsp;<label for='noscript-y'>\".$GLOBALS['strYes'].\"</label><br />\";\n $option .= \"<input type='radio' id='noscript-n' name='noscript' value='0'\".($noscript == 0 ? \" checked='checked'\" : '').\" tabindex='\".($maxInvocation->tabindex++).\"'>&nbsp;<label for='noscript-n'>\".$GLOBALS['strNo'].\"</label></td>\";\n $option .= \"</tr>\";\n $option .= \"<tr><td width='30'><img src='\" . OX::assetPath() . \"/images/spacer.gif' height='1' width='100%'></td>\";\n return $option;\n }", " function ssl()\n {\n $maxInvocation = &$this->maxInvocation;\n $ssl = (isset($maxInvocation->ssl)) ? $maxInvocation->ssl : $this->defaultOptionValues['ssl'];", " $option = '';\n $option .= \"<tr><td width='30'>&nbsp;</td>\";\n $option .= \"<td width='200'>\" . $this->translate(\"Option - SSL\") . \"</td>\";\n $option .= \"<td width='370'><input type='radio' id='ssl-y' name='ssl' value='1'\".($ssl == 1 ? \" checked='checked'\" : '').\" tabindex='\".($maxInvocation->tabindex++).\"'>&nbsp;<label for='ssl-y'>\".$GLOBALS['strYes'].\"</label><br />\";\n $option .= \"<input type='radio' name='ssl' id='ssl-y' value='0'\".($ssl == 0 ? \" checked='checked'\" : '').\" tabindex='\".($maxInvocation->tabindex++).\"'>&nbsp;<label for='ssl-n'>\".$GLOBALS['strNo'].\"</label></td>\";\n $option .= \"</tr>\";\n $option .= \"<tr><td width='30'><img src='\" . OX::assetPath() . \"/images/spacer.gif' height='1' width='100%'></td>\";\n return $option;\n }", " function setInvocation(&$invocation) {\n $this->maxInvocation = &$invocation;\n $this->maxInvocation->canDetectCharset = true;\n }", " /**\n * Generates header spc tag.\n * If optional $aZoneAliases is given, additional zone aliasing array will be generated.\n *\n * @param array $aZoneAliases zone id => array of alias names\n * @return unknown\n */\n function getHeaderCode($aZoneAliases = null)\n {\n $mi = &$this->maxInvocation;\n $conf = $GLOBALS['_MAX']['CONF'];", " $additionalParams = \"\";\n foreach ($this->defaultOptionValues as $feature => $default) {\n // Skip invocation code settings here if they don't affect delivery\n if ($feature == 'source' || $feature == 'noscript' || $feature == 'ssl') { continue; }\n if ($mi->$feature != $this->defaultOptionValues[$feature]) {\n $additionalParams .= \"&amp;{$feature}=\" . $mi->$feature;\n }\n }", " $codeblock = \"\";\n if ($mi->comments) {\n $codeblock .= \"<!-- Generated by {$this->appname} -->\\n\";\n }\n if ($mi->source) {\n $source = stripslashes($mi->source);\n $source = addcslashes($source, \"\\x00..\\x1F\\'\\\\\");\n $codeblock .= \"<script type='text/javascript'><!--// <![CDATA[\\n\";\n $codeblock .= \" var {$this->varprefix}source = '{$source}';\\n\";\n $codeblock .= \"// ]]> --></script>\";\n }", " $aliasesBlock = '';\n if (!empty($aZoneAliases)) {\n $aliasesBlock = $this->generateAliasesCode($aZoneAliases);\n $codeblock .= !empty($aliasesBlock) ? $aliasesBlock : '';\n }\n $url = (!empty($mi->ssl)) ? MAX_commonConstructSecureDeliveryUrl($conf['file']['spcjs']) : MAX_commonConstructDeliveryUrl($conf['file']['spcjs']);\n $codeblock .= \"<script type='text/javascript' src='{$url}?id={$mi->affiliateid}{$additionalParams}'></script>\";", " return $codeblock;\n }", "\n private function generateAliasesCode($aZoneAliases)\n {\n $oJson = new Services_JSON();", " $aStruct = array();\n foreach ($aZoneAliases as $zoneId => $aAliases) {\n foreach($aAliases as $alias) {\n $aStruct[$alias] = $zoneId;\n }\n }\n $aliasesCode.= $oJson->encode($aStruct);", " $codeblock .= \"<script type='text/javascript'><!--// <![CDATA[\\n\";\n $codeblock .= \" var {$this->varprefix}zones = \";\n $codeblock .= $aliasesCode;\n $codeblock .= \" \\n\";\n $codeblock .= \"// ]]> --></script>\\n\";", " return $codeblock;\n }", "\n function getZoneCode($zone, $affiliate, $zoneAlias = null)\n {\n $mi = &$this->maxInvocation;\n $conf = $GLOBALS['_MAX']['CONF'];", " $zone['n'] = $affiliate['mnemonic'] . substr(md5(uniqid('', 1)), 0, 7);", " $uri = (!empty($mi->ssl)) ? MAX_commonConstructSecureDeliveryUrl('') : MAX_commonConstructDeliveryUrl('');", " $codeblock = \"<script type='text/javascript'><!--// <![CDATA[\";\n $js_func = $this->varprefix . (($zone['delivery'] == phpAds_ZonePopup) ? 'showpop' : 'show');\n if ($mi->comments) {\n $codeblock .= \"\\n /* \".($zoneAlias ? addcslashes($zoneAlias).\" - \" : '').\"[id{$zone['zoneid']}] \".addcslashes($zone['zonename'], '/').\" */\";\n }\n $codeblock .= \"\\n {$js_func}(\".($zoneAlias ? \"'\".$zoneAlias.\"'\" : $zone['zoneid']).\");\\n// ]]> --></script>\";\n if ($zone['delivery'] != phpAds_ZoneText && $mi->noscript) {\n $codeblock .= \"<noscript><a target='_blank' href='{$uri}{$conf['file']['click']}?n={$zone['n']}'>\";\n $codeblock .= \"<img border='0' alt='' src='{$uri}{$conf['file']['view']}?zoneid={$zone['zoneid']}&amp;n={$zone['n']}' /></a>\";\n $codeblock .= \"</noscript>\";\n }", " return $codeblock;\n }\n}", "?>" ]
[ 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [237], "buggy_code_start_loc": [236], "filenames": ["plugins_repo/openXInvocationTags/plugins/invocationTags/oxInvocationTags/spc.class.php"], "fixing_code_end_loc": [237], "fixing_code_start_loc": [236], "message": "Revive Adserver before 3.2.3 suffers from reflected XSS. The affiliate-preview.php script in www/admin is vulnerable to a reflected XSS attack. This vulnerability could be used by an attacker to steal the session ID of an authenticated user, by tricking them into visiting a specifically crafted URL.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:revive-adserver:revive_adserver:*:*:*:*:*:*:*:*", "matchCriteriaId": "94F64F5A-ACD3-4AED-82BE-832D7B4801DA", "versionEndExcluding": null, "versionEndIncluding": "3.2.2", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Revive Adserver before 3.2.3 suffers from reflected XSS. The affiliate-preview.php script in www/admin is vulnerable to a reflected XSS attack. This vulnerability could be used by an attacker to steal the session ID of an authenticated user, by tricking them into visiting a specifically crafted URL."}, {"lang": "es", "value": "Revive Adserver en versiones anteriores a 3.2.3 sufre de XSS reflejado. El script affiliate-preview.php en www/admin es vulnerable a un ataque XSS reflejado. Esta vulnerabilidad podr\u00eda ser utilizada por un atacante para robar el identificador de sesi\u00f3n de un usuario autenticado, enga\u00f1\u00e1ndolos para que visiten una direcci\u00f3n URL espec\u00edfica."}], "evaluatorComment": null, "id": "CVE-2016-9128", "lastModified": "2019-10-09T23:20:19.227", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-03-28T02:59:00.480", "references": [{"source": "support@hackerone.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/revive-adserver/revive-adserver/commit/a323fd626627e8d42819fd5b7e2829196b5c54a3"}, {"source": "support@hackerone.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/revive-adserver/revive-adserver/commit/e17a7ec3412ded751cda50b82338de471d656d74"}, {"source": "support@hackerone.com", "tags": ["Permissions Required"], "url": "https://hackerone.com/reports/99004"}, {"source": "support@hackerone.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://www.revive-adserver.com/security/revive-sa-2016-001/"}], "sourceIdentifier": "support@hackerone.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "support@hackerone.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/revive-adserver/revive-adserver/commit/a323fd626627e8d42819fd5b7e2829196b5c54a3"}, "type": "CWE-79"}
178
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n+---------------------------------------------------------------------------+\n| Revive Adserver |\n| http://www.revive-adserver.com |\n| |\n| Copyright: See the COPYRIGHT.txt file. |\n| License: GPLv2 or later, see the LICENSE.txt file. |\n+---------------------------------------------------------------------------+\n*/", "/**\n * @package MaxPlugins\n * @subpackage InvocationTags\n */", "require_once MAX_PATH . '/lib/Max.php';\nrequire_once LIB_PATH . '/Extension/invocationTags/InvocationTags.php';\nrequire_once MAX_PATH . '/lib/max/Plugin/Translation.php';\nrequire_once MAX_PATH . '/lib/max/Delivery/common.php';\nrequire_once MAX_PATH . '/lib/JSON/JSON.php';", "require_once OX_PATH . '/lib/OX.php';", "/**\n *\n * Invocation tag plugin.\n *\n */\nclass Plugins_InvocationTags_OxInvocationTags_Spc extends Plugins_InvocationTags\n{\n /**\n * Set default values for options used by this plugin\n *\n * @var array Array of $key => $defaultValue\n */\n var $defaultOptionValues = array(\n 'block' => 0,\n 'blockcampaign' => 0,\n 'target' => '',\n 'source' => '',\n 'withtext' => 0,\n 'noscript' => 1,\n 'ssl' => 0,\n 'charset' => '',\n );", " /**\n * Make this the default publisher plugin\n *\n * @var boolean\n */\n var $default = true;", " var $varprefix;\n var $appname;", " /**\n * Constructor\n *\n */\n function __construct()\n {\n $conf = $GLOBALS['_MAX']['CONF'];\n $this->publisherPlugin = true;\n $this->varprefix = $conf['var']['prefix'];\n $this->appname = PRODUCT_NAME . \" v\" . VERSION;\n }", " /**\n * Return name of plugin\n *\n * @return string\n */\n function getName()\n {\n return $this->translate(\"Publisher code - Single Page Call\");\n }", " /**\n * Return the English name of the plugin. Used when\n * generating translation keys based on the plugin\n * name.\n *\n * @return string An English string describing the class.\n */\n function getNameEN()\n {\n return 'Publisher code - Single Page Call';\n }", " /**\n * Check if plugin is allowed\n *\n * @return boolean True - allowed, false - not allowed\n */\n function isAllowed($extra = null)\n {\n return false;\n }", " /**\n * Return invocation code for this plugin (codetype)\n *\n * @return string\n */\n function generateInvocationCode()\n {\n $conf = $GLOBALS['_MAX']['CONF'];\n $pref = $GLOBALS['_MAX']['CONF'];", " $mi = &$this->maxInvocation;", " // Get the affiliate information\n $doAffiliates = OA_Dal::factoryDO('affiliates');\n if ($doAffiliates->get($mi->affiliateid)) {\n $affiliate = $doAffiliates->toArray();\n }\n $doZones = OA_Dal::factoryDO('zones');\n $doZones->affiliateid = $mi->affiliateid;\n $doZones->find();\n while ($doZones->fetch() && $row = $doZones->toArray()) {\n // Email/Newsletter and DHTML and Video zones are not included in SPC\n if ($row['delivery'] != MAX_ZoneEmail\n && $row['delivery'] != phpAds_ZoneInterstitial\n && $row['delivery'] != OX_ZoneVideoInstream\n && $row['delivery'] != OX_ZoneVideoOverlay) {\n $aZones[] = $row;\n }\n }", " if(count($aZones) == 0) {\n return 'No Zones Available!';\n }", "\n $channel = (!empty($mi->source)) ? $mi->source : $affiliate['mnemonic'] . \"/test/preview\";", " $script = \"<?xml version='1.0' encoding='UTF-8' ?><!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>\n<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>\n<head>\n <title>Tags for [id{$affiliate['affiliateid']}] \".htmlspecialchars($affiliate['name']).\"</title>\n <link rel='stylesheet' type='text/css' href='\" . OX::assetPath() . \"/css/preview.css' />\n <script type='text/javascript' src='\" . OX::assetPath() . \"/js/jquery-1.2.3.js'></script>", " <script type='text/javascript'>\n <!--", " function selectElement() {\n if (window.getSelection) {\n var r = document.createRange();\n r.selectNodeContents($(this)[0]);\n var s = window.getSelection();\n if (s.rangeCount) {\n s.collapseToStart();\n s.removeAllRanges();\n }\n s.addRange(r);\n } else if (document.body.createTextRange) {\n var r = document.body.createTextRange();\n r.moveToElementText($(this)[0]);\n r.select();\n }\n }", " $(document).ready(function() {\n $('pre').bind('mousedown', selectElement);\n $('pre').bind('click', selectElement);\n $('pre').bind('mousemove', selectElement);", " $('#closeWindow').click(function() {\n window.close();\n });\n });", " //-->\n </script>\n </head>", " <body class='invocationCodes'>\n <div class='header'>\n <h1>\" . PRODUCT_NAME . \"</h1>\n </div>\n \";", " $script .= \"\n <div class='settings'>\n <h2>Tags <small>for <span class='inlinePublisher'>[id{$affiliate['affiliateid']}] \".htmlspecialchars($affiliate['name']).\"</span></small></h2>\n <p>\n This page contains all the information you need to show banners on your website.\n Please follow the instructions carefully and ensure that you copied the scripts <strong>exactly</strong> as shown below.\n </p>", " <h3>The following settings were used to generate this page:</h3>\n <table class='horizontalSummary' summary=''>\n \";", " reset ($this->defaultOptionValues);\n foreach ($this->defaultOptionValues as $feature => $default) {\n switch ($feature) {\n case 'block':\n $optionName = $GLOBALS['strInvocationDontShowAgain'];\n $optionValue = intval($mi->$feature) ? $GLOBALS['strYes'] : $GLOBALS['strNo'];\n break;\n case 'blockcampaign':\n $optionName = $GLOBALS['strInvocationDontShowAgainCampaign'];\n $optionValue = intval($mi->$feature) ? $GLOBALS['strYes'] : $GLOBALS['strNo'];\n break;\n case 'target':\n $optionName = $GLOBALS['strInvocationTarget'];\n switch($mi->$feature) {\n case '_blank': $optionValue = 'New window'; break;\n case '_top': $optionValue = 'Same window'; break;\n default: $optionValue = $GLOBALS['strDefault']; break;\n }\n break;\n case 'source':\n $optionName = $GLOBALS['strInvocationSource'];\n $optionValue = $mi->$feature != '' ? htmlspecialchars(stripslashes($mi->$feature)) : '-';\n break;\n case 'withtext':\n $optionName = $GLOBALS['strInvocationWithText'];\n $optionValue = intval($mi->$feature) ? $GLOBALS['strYes'] : $GLOBALS['strNo'];\n break;\n case 'noscript':\n $optionName = $this->translate(\"Option - noscript\");\n $optionValue = intval($mi->$feature) ? $GLOBALS['strYes'] : $GLOBALS['strNo'];\n break;\n case 'ssl':\n $optionName = $this->translate(\"Option - SSL\");\n $optionValue = intval($mi->$feature) ? $GLOBALS['strYes'] : $GLOBALS['strNo'];\n break;\n case 'charset':\n $optionName = $GLOBALS['strCharset'];", " $optionValue = empty($mi->$feature) ? $GLOBALS['strAutoDetect'] : htmlspecialchars($mi->$feature);", " break;\n default:\n $optionName = $feature;\n $optionValue = htmlspecialchars(stripslashes($mi->$feature));\n break;\n }", " $script .= \"\n <tr>\n <th>{$optionName}</th>\n <td>{$optionValue}</td>\n </tr>\n \";\n }", " $script .= \"\n </table>\n </div>\n \";", " /* Common script at the top of the page */\n $codeblock = $this->getHeaderCode();", " $script .= \"\n <div class='step'>\n <h2>\n <div class='number'><span>1</span></div>\n Header script\n </h2>\n <p>\n Insert the following script at the top of every page on the {$affiliate['website']} website. This code\n belongs between the <code>&lt;head&gt;</code> and <code>&lt;/head&gt;</code> tags, before any ad scripts\n on the page:\n </p>", " <pre>\". htmlspecialchars($codeblock) .\"</pre>\n </div>\n \";", " $i = 2;", "", "\n foreach($aZones as $zone) {\n $width = $zone['width'] > -1 ? $zone['width'] : 150;\n $widthLabel = $zone['width'] > -1 ? $zone['width'] : '*';", " $height = $zone['height'] > -1 ? $zone['height'] : 150;\n $heightLabel = $zone['height'] > -1 ? $zone['height'] : '*';", " $customClass = array();", " if ($zone['width'] == -1 && $zone['height'] == -1) {\n $customClass[] = 'customBoth';\n } elseif ($zone['height'] == -1) {\n $customClass[] = 'customHeight';\n } elseif ($zone['width'] == -1) {\n $customClass[] = 'customWidth';\n }", " // Labels are roughly 80 x 30 pixels...\n // width < 80 || height < 30 => No room for even a single label, drop the OpenX logo and show the size outside\n // width < 160 && height < 60 => No room for both labels... drop the OpenX logo\n if (($zone['width'] > -1 && $zone['width'] < 80) || ($zone['height'] > -1 && $zone['height'] < 30)) {\n $customClass[] = 'labelsMicro';\n } elseif ($zone['width'] > -1 && $zone['width'] < 160 && $zone['height'] > -1 && $zone['height'] < 60) {\n $customClass[] = 'labelsMini';\n }", " $codeblock = $this->getZoneCode($zone, $affiliate);", " $script .= \"\n <div class='step'>\n <h2>\n <div class='number'><span>{$i}</span></div>\n Ad script <small>for <span class='inlineZone'>[id{$zone['zoneid']}] \".htmlspecialchars($zone['zonename']).\"</span></small>\n </h2>\n <p>\n Copy the following script and place it in the site where you want the ad to display:\n </p>", " <pre>\" . htmlspecialchars($codeblock) . \"</pre>", " <p>\n Example\" . ($zone['width'] == -1 || $zone['height'] == -1 ? ' (actual size may vary)' : '') . \":\n </p>", " <div class='sizePreview \" . (count($customClass) ? ' ' . implode(' ', $customClass) : '') . \"' style='width: {$width}px; height: {$height}px;'>\n <img src='\" . OX::assetPath() . \"/images/logo-adserver-small.png' alt='' />\n <span>{$widthLabel} x {$heightLabel}</span>\n </div>", " </div>\n \";", " $i++;\n }", " $script .= \"\n <div class='step'>\n <h2>\n <div class='number'><span>{$i}</span></div>\n Done\n </h2>\n <p>\n Banners should now appear on your website\n </p>", " <button id='closeWindow'><img src='\" . OX::assetPath() . \"/images/cross.png' alt='' />Close this window</button>\n </div>", " <div class='generated'>\n Generated by {$this->appname}\n </div>\n </body>\n</html>\n \";", " return $script;\n }", " /**\n * Return list of options\n *\n * @return array Group of options\n */\n function getOptionsList()\n {\n // Publisher Invocation doesn't require a lot of the default options...\n if (is_array($this->defaultOptions)) {\n // JS code generates it's own cacheBuster\n unset($this->defaultOptions['cacheBuster']);\n // Publisher invocation is not designed for loading into another adserver\n unset($this->defaultOptions['3thirdPartyServer']);\n }\n $options = array (\n 'spacer' => MAX_PLUGINS_INVOCATION_TAGS_STANDARD,\n 'block' => MAX_PLUGINS_INVOCATION_TAGS_STANDARD,\n 'blockcampaign' => MAX_PLUGINS_INVOCATION_TAGS_STANDARD,\n 'spacer' => MAX_PLUGINS_INVOCATION_TAGS_STANDARD,\n 'target' => MAX_PLUGINS_INVOCATION_TAGS_STANDARD,\n 'source' => MAX_PLUGINS_INVOCATION_TAGS_STANDARD,\n 'withtext' => MAX_PLUGINS_INVOCATION_TAGS_STANDARD,\n 'charset' => MAX_PLUGINS_INVOCATION_TAGS_STANDARD,\n 'noscript' => MAX_PLUGINS_INVOCATION_TAGS_CUSTOM,\n 'ssl' => MAX_PLUGINS_INVOCATION_TAGS_CUSTOM,\n );", " return $options;\n }", " /**\n * A custom handler for the <noscript> option\n *\n * @return string HTML to show the <noscript> option\n */\n function noscript()\n {\n $maxInvocation = &$this->maxInvocation;\n $noscript = (isset($maxInvocation->noscript)) ? $maxInvocation->noscript : $this->defaultOptionValues['noscript'];", " $option = '';\n $option .= \"<tr><td width='30'>&nbsp;</td>\";\n $option .= \"<td width='200'>\" . $this->translate(\"Option - noscript\") . \"</td>\";\n $option .= \"<td width='370'><input type='radio' id='noscript-y' name='noscript' value='1'\".($noscript == 1 ? \" checked='checked'\" : '').\" tabindex='\".($maxInvocation->tabindex++).\"'>&nbsp;<label for='noscript-y'>\".$GLOBALS['strYes'].\"</label><br />\";\n $option .= \"<input type='radio' id='noscript-n' name='noscript' value='0'\".($noscript == 0 ? \" checked='checked'\" : '').\" tabindex='\".($maxInvocation->tabindex++).\"'>&nbsp;<label for='noscript-n'>\".$GLOBALS['strNo'].\"</label></td>\";\n $option .= \"</tr>\";\n $option .= \"<tr><td width='30'><img src='\" . OX::assetPath() . \"/images/spacer.gif' height='1' width='100%'></td>\";\n return $option;\n }", " function ssl()\n {\n $maxInvocation = &$this->maxInvocation;\n $ssl = (isset($maxInvocation->ssl)) ? $maxInvocation->ssl : $this->defaultOptionValues['ssl'];", " $option = '';\n $option .= \"<tr><td width='30'>&nbsp;</td>\";\n $option .= \"<td width='200'>\" . $this->translate(\"Option - SSL\") . \"</td>\";\n $option .= \"<td width='370'><input type='radio' id='ssl-y' name='ssl' value='1'\".($ssl == 1 ? \" checked='checked'\" : '').\" tabindex='\".($maxInvocation->tabindex++).\"'>&nbsp;<label for='ssl-y'>\".$GLOBALS['strYes'].\"</label><br />\";\n $option .= \"<input type='radio' name='ssl' id='ssl-y' value='0'\".($ssl == 0 ? \" checked='checked'\" : '').\" tabindex='\".($maxInvocation->tabindex++).\"'>&nbsp;<label for='ssl-n'>\".$GLOBALS['strNo'].\"</label></td>\";\n $option .= \"</tr>\";\n $option .= \"<tr><td width='30'><img src='\" . OX::assetPath() . \"/images/spacer.gif' height='1' width='100%'></td>\";\n return $option;\n }", " function setInvocation(&$invocation) {\n $this->maxInvocation = &$invocation;\n $this->maxInvocation->canDetectCharset = true;\n }", " /**\n * Generates header spc tag.\n * If optional $aZoneAliases is given, additional zone aliasing array will be generated.\n *\n * @param array $aZoneAliases zone id => array of alias names\n * @return unknown\n */\n function getHeaderCode($aZoneAliases = null)\n {\n $mi = &$this->maxInvocation;\n $conf = $GLOBALS['_MAX']['CONF'];", " $additionalParams = \"\";\n foreach ($this->defaultOptionValues as $feature => $default) {\n // Skip invocation code settings here if they don't affect delivery\n if ($feature == 'source' || $feature == 'noscript' || $feature == 'ssl') { continue; }\n if ($mi->$feature != $this->defaultOptionValues[$feature]) {\n $additionalParams .= \"&amp;{$feature}=\" . $mi->$feature;\n }\n }", " $codeblock = \"\";\n if ($mi->comments) {\n $codeblock .= \"<!-- Generated by {$this->appname} -->\\n\";\n }\n if ($mi->source) {\n $source = stripslashes($mi->source);\n $source = addcslashes($source, \"\\x00..\\x1F\\'\\\\\");\n $codeblock .= \"<script type='text/javascript'><!--// <![CDATA[\\n\";\n $codeblock .= \" var {$this->varprefix}source = '{$source}';\\n\";\n $codeblock .= \"// ]]> --></script>\";\n }", " $aliasesBlock = '';\n if (!empty($aZoneAliases)) {\n $aliasesBlock = $this->generateAliasesCode($aZoneAliases);\n $codeblock .= !empty($aliasesBlock) ? $aliasesBlock : '';\n }\n $url = (!empty($mi->ssl)) ? MAX_commonConstructSecureDeliveryUrl($conf['file']['spcjs']) : MAX_commonConstructDeliveryUrl($conf['file']['spcjs']);\n $codeblock .= \"<script type='text/javascript' src='{$url}?id={$mi->affiliateid}{$additionalParams}'></script>\";", " return $codeblock;\n }", "\n private function generateAliasesCode($aZoneAliases)\n {\n $oJson = new Services_JSON();", " $aStruct = array();\n foreach ($aZoneAliases as $zoneId => $aAliases) {\n foreach($aAliases as $alias) {\n $aStruct[$alias] = $zoneId;\n }\n }\n $aliasesCode.= $oJson->encode($aStruct);", " $codeblock .= \"<script type='text/javascript'><!--// <![CDATA[\\n\";\n $codeblock .= \" var {$this->varprefix}zones = \";\n $codeblock .= $aliasesCode;\n $codeblock .= \" \\n\";\n $codeblock .= \"// ]]> --></script>\\n\";", " return $codeblock;\n }", "\n function getZoneCode($zone, $affiliate, $zoneAlias = null)\n {\n $mi = &$this->maxInvocation;\n $conf = $GLOBALS['_MAX']['CONF'];", " $zone['n'] = $affiliate['mnemonic'] . substr(md5(uniqid('', 1)), 0, 7);", " $uri = (!empty($mi->ssl)) ? MAX_commonConstructSecureDeliveryUrl('') : MAX_commonConstructDeliveryUrl('');", " $codeblock = \"<script type='text/javascript'><!--// <![CDATA[\";\n $js_func = $this->varprefix . (($zone['delivery'] == phpAds_ZonePopup) ? 'showpop' : 'show');\n if ($mi->comments) {\n $codeblock .= \"\\n /* \".($zoneAlias ? addcslashes($zoneAlias).\" - \" : '').\"[id{$zone['zoneid']}] \".addcslashes($zone['zonename'], '/').\" */\";\n }\n $codeblock .= \"\\n {$js_func}(\".($zoneAlias ? \"'\".$zoneAlias.\"'\" : $zone['zoneid']).\");\\n// ]]> --></script>\";\n if ($zone['delivery'] != phpAds_ZoneText && $mi->noscript) {\n $codeblock .= \"<noscript><a target='_blank' href='{$uri}{$conf['file']['click']}?n={$zone['n']}'>\";\n $codeblock .= \"<img border='0' alt='' src='{$uri}{$conf['file']['view']}?zoneid={$zone['zoneid']}&amp;n={$zone['n']}' /></a>\";\n $codeblock .= \"</noscript>\";\n }", " return $codeblock;\n }\n}", "?>" ]
[ 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [237], "buggy_code_start_loc": [236], "filenames": ["plugins_repo/openXInvocationTags/plugins/invocationTags/oxInvocationTags/spc.class.php"], "fixing_code_end_loc": [237], "fixing_code_start_loc": [236], "message": "Revive Adserver before 3.2.3 suffers from reflected XSS. The affiliate-preview.php script in www/admin is vulnerable to a reflected XSS attack. This vulnerability could be used by an attacker to steal the session ID of an authenticated user, by tricking them into visiting a specifically crafted URL.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:revive-adserver:revive_adserver:*:*:*:*:*:*:*:*", "matchCriteriaId": "94F64F5A-ACD3-4AED-82BE-832D7B4801DA", "versionEndExcluding": null, "versionEndIncluding": "3.2.2", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Revive Adserver before 3.2.3 suffers from reflected XSS. The affiliate-preview.php script in www/admin is vulnerable to a reflected XSS attack. This vulnerability could be used by an attacker to steal the session ID of an authenticated user, by tricking them into visiting a specifically crafted URL."}, {"lang": "es", "value": "Revive Adserver en versiones anteriores a 3.2.3 sufre de XSS reflejado. El script affiliate-preview.php en www/admin es vulnerable a un ataque XSS reflejado. Esta vulnerabilidad podr\u00eda ser utilizada por un atacante para robar el identificador de sesi\u00f3n de un usuario autenticado, enga\u00f1\u00e1ndolos para que visiten una direcci\u00f3n URL espec\u00edfica."}], "evaluatorComment": null, "id": "CVE-2016-9128", "lastModified": "2019-10-09T23:20:19.227", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-03-28T02:59:00.480", "references": [{"source": "support@hackerone.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/revive-adserver/revive-adserver/commit/a323fd626627e8d42819fd5b7e2829196b5c54a3"}, {"source": "support@hackerone.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/revive-adserver/revive-adserver/commit/e17a7ec3412ded751cda50b82338de471d656d74"}, {"source": "support@hackerone.com", "tags": ["Permissions Required"], "url": "https://hackerone.com/reports/99004"}, {"source": "support@hackerone.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://www.revive-adserver.com/security/revive-sa-2016-001/"}], "sourceIdentifier": "support@hackerone.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "support@hackerone.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/revive-adserver/revive-adserver/commit/a323fd626627e8d42819fd5b7e2829196b5c54a3"}, "type": "CWE-79"}
178
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright © 2007,2008,2009,2010 Red Hat, Inc.\n * Copyright © 2010,2012 Google, Inc.\n *\n * This is part of HarfBuzz, a text shaping library.\n *\n * Permission is hereby granted, without written agreement and without\n * license or royalty fees, to use, copy, modify, and distribute this\n * software and its documentation for any purpose, provided that the\n * above copyright notice and the following two paragraphs appear in\n * all copies of this software.\n *\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR\n * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES\n * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN\n * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\n * DAMAGE.\n *\n * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS\n * ON AN \"AS IS\" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO\n * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n *\n * Red Hat Author(s): Behdad Esfahbod\n * Google Author(s): Behdad Esfahbod\n */", "#ifndef HB_OT_LAYOUT_GSUBGPOS_HH\n#define HB_OT_LAYOUT_GSUBGPOS_HH", "#include \"hb.hh\"\n#include \"hb-buffer.hh\"\n#include \"hb-map.hh\"\n#include \"hb-set.hh\"\n#include \"hb-ot-map.hh\"\n#include \"hb-ot-layout-common.hh\"\n#include \"hb-ot-layout-gdef-table.hh\"", "\nnamespace OT {", "\nstruct hb_intersects_context_t :\n hb_dispatch_context_t<hb_intersects_context_t, bool>\n{\n template <typename T>\n return_t dispatch (const T &obj) { return obj.intersects (this->glyphs); }\n static return_t default_return_value () { return false; }\n bool stop_sublookup_iteration (return_t r) const { return r; }", " const hb_set_t *glyphs;", " hb_intersects_context_t (const hb_set_t *glyphs_) :\n glyphs (glyphs_) {}\n};", "struct hb_have_non_1to1_context_t :\n hb_dispatch_context_t<hb_have_non_1to1_context_t, bool>\n{\n template <typename T>\n return_t dispatch (const T &obj) { return obj.may_have_non_1to1 (); }\n static return_t default_return_value () { return false; }\n bool stop_sublookup_iteration (return_t r) const { return r; }\n};", "struct hb_closure_context_t :\n hb_dispatch_context_t<hb_closure_context_t>\n{\n typedef return_t (*recurse_func_t) (hb_closure_context_t *c, unsigned lookup_index, hb_set_t *covered_seq_indicies, unsigned seq_index, unsigned end_index);\n template <typename T>\n return_t dispatch (const T &obj) { obj.closure (this); return hb_empty_t (); }\n static return_t default_return_value () { return hb_empty_t (); }\n void recurse (unsigned lookup_index, hb_set_t *covered_seq_indicies, unsigned seq_index, unsigned end_index)\n {\n if (unlikely (nesting_level_left == 0 || !recurse_func))\n return;", " nesting_level_left--;\n recurse_func (this, lookup_index, covered_seq_indicies, seq_index, end_index);\n nesting_level_left++;\n }", " void reset_lookup_visit_count ()\n { lookup_count = 0; }", " bool lookup_limit_exceeded ()\n { return lookup_count > HB_MAX_LOOKUP_VISIT_COUNT; }", " bool should_visit_lookup (unsigned int lookup_index)\n {\n if (lookup_count++ > HB_MAX_LOOKUP_VISIT_COUNT)\n return false;", " if (is_lookup_done (lookup_index))\n return false;", " return true;\n }", " bool is_lookup_done (unsigned int lookup_index)\n {\n if (unlikely (done_lookups_glyph_count->in_error () ||\n\t\t done_lookups_glyph_set->in_error ()))\n return true;", " /* Have we visited this lookup with the current set of glyphs? */\n if (done_lookups_glyph_count->get (lookup_index) != glyphs->get_population ())\n {\n done_lookups_glyph_count->set (lookup_index, glyphs->get_population ());", " if (!done_lookups_glyph_set->has (lookup_index))\n {\n\tif (unlikely (!done_lookups_glyph_set->set (lookup_index, hb::unique_ptr<hb_set_t> {hb_set_create ()})))\n\t return true;\n }", " done_lookups_glyph_set->get (lookup_index)->clear ();\n }", " hb_set_t *covered_glyph_set = done_lookups_glyph_set->get (lookup_index);\n if (unlikely (covered_glyph_set->in_error ()))\n return true;\n if (parent_active_glyphs ().is_subset (*covered_glyph_set))\n return true;", " covered_glyph_set->union_ (parent_active_glyphs ());\n return false;\n }", " const hb_set_t& previous_parent_active_glyphs () {\n if (active_glyphs_stack.length <= 1)\n return *glyphs;", " return active_glyphs_stack[active_glyphs_stack.length - 2];\n }", " const hb_set_t& parent_active_glyphs ()\n {\n if (!active_glyphs_stack)\n return *glyphs;", " return active_glyphs_stack.tail ();\n }", " hb_set_t& push_cur_active_glyphs ()\n {\n return *active_glyphs_stack.push ();\n }", " bool pop_cur_done_glyphs ()\n {\n if (!active_glyphs_stack)\n return false;", " active_glyphs_stack.pop ();\n return true;\n }", " hb_face_t *face;\n hb_set_t *glyphs;\n hb_set_t output[1];\n hb_vector_t<hb_set_t> active_glyphs_stack;\n recurse_func_t recurse_func = nullptr;\n unsigned int nesting_level_left;", " hb_closure_context_t (hb_face_t *face_,\n\t\t\thb_set_t *glyphs_,\n\t\t\thb_map_t *done_lookups_glyph_count_,\n\t\t\thb_hashmap_t<unsigned, hb::unique_ptr<hb_set_t>> *done_lookups_glyph_set_,\n\t\t\tunsigned int nesting_level_left_ = HB_MAX_NESTING_LEVEL) :\n\t\t\t face (face_),\n\t\t\t glyphs (glyphs_),\n\t\t\t nesting_level_left (nesting_level_left_),\n\t\t\t done_lookups_glyph_count (done_lookups_glyph_count_),\n\t\t\t done_lookups_glyph_set (done_lookups_glyph_set_)\n {}", " ~hb_closure_context_t () { flush (); }", " void set_recurse_func (recurse_func_t func) { recurse_func = func; }", " void flush ()\n {\n output->del_range (face->get_num_glyphs (), HB_SET_VALUE_INVALID);\t/* Remove invalid glyphs. */\n glyphs->union_ (*output);\n output->clear ();\n active_glyphs_stack.pop ();\n active_glyphs_stack.reset ();\n }", " private:\n hb_map_t *done_lookups_glyph_count;\n hb_hashmap_t<unsigned, hb::unique_ptr<hb_set_t>> *done_lookups_glyph_set;\n unsigned int lookup_count = 0;\n};", "", "struct hb_closure_lookups_context_t :\n hb_dispatch_context_t<hb_closure_lookups_context_t>\n{\n typedef return_t (*recurse_func_t) (hb_closure_lookups_context_t *c, unsigned lookup_index);\n template <typename T>\n return_t dispatch (const T &obj) { obj.closure_lookups (this); return hb_empty_t (); }\n static return_t default_return_value () { return hb_empty_t (); }\n void recurse (unsigned lookup_index)\n {\n if (unlikely (nesting_level_left == 0 || !recurse_func))\n return;", " /* Return if new lookup was recursed to before. */\n if (lookup_limit_exceeded ()\n || visited_lookups->in_error ()\n || visited_lookups->has (lookup_index))\n // Don't increment lookup count here, that will be done in the call to closure_lookups()\n // made by recurse_func.\n return;", " nesting_level_left--;\n recurse_func (this, lookup_index);\n nesting_level_left++;\n }", " void set_lookup_visited (unsigned lookup_index)\n { visited_lookups->add (lookup_index); }", " void set_lookup_inactive (unsigned lookup_index)\n { inactive_lookups->add (lookup_index); }", " bool lookup_limit_exceeded ()\n {\n bool ret = lookup_count > HB_MAX_LOOKUP_VISIT_COUNT;\n if (ret)\n DEBUG_MSG (SUBSET, nullptr, \"lookup visit count limit exceeded in lookup closure!\");\n return ret; }", " bool is_lookup_visited (unsigned lookup_index)\n {\n if (unlikely (lookup_count++ > HB_MAX_LOOKUP_VISIT_COUNT))\n {\n DEBUG_MSG (SUBSET, nullptr, \"total visited lookup count %u exceeds max limit, lookup %u is dropped.\",\n lookup_count, lookup_index);\n return true;\n }", " if (unlikely (visited_lookups->in_error ()))\n return true;", " return visited_lookups->has (lookup_index);\n }", " hb_face_t *face;\n const hb_set_t *glyphs;\n recurse_func_t recurse_func;\n unsigned int nesting_level_left;", " hb_closure_lookups_context_t (hb_face_t *face_,\n\t\t\t\tconst hb_set_t *glyphs_,\n\t\t\t\thb_set_t *visited_lookups_,\n\t\t\t\thb_set_t *inactive_lookups_,\n\t\t\t\tunsigned nesting_level_left_ = HB_MAX_NESTING_LEVEL) :\n\t\t\t\tface (face_),\n\t\t\t\tglyphs (glyphs_),\n\t\t\t\trecurse_func (nullptr),\n\t\t\t\tnesting_level_left (nesting_level_left_),\n\t\t\t\tvisited_lookups (visited_lookups_),\n\t\t\t\tinactive_lookups (inactive_lookups_),\n\t\t\t\tlookup_count (0) {}", " void set_recurse_func (recurse_func_t func) { recurse_func = func; }", " private:\n hb_set_t *visited_lookups;\n hb_set_t *inactive_lookups;\n unsigned int lookup_count;\n};", "struct hb_would_apply_context_t :\n hb_dispatch_context_t<hb_would_apply_context_t, bool>\n{\n template <typename T>\n return_t dispatch (const T &obj) { return obj.would_apply (this); }\n static return_t default_return_value () { return false; }\n bool stop_sublookup_iteration (return_t r) const { return r; }", " hb_face_t *face;\n const hb_codepoint_t *glyphs;\n unsigned int len;\n bool zero_context;", " hb_would_apply_context_t (hb_face_t *face_,\n\t\t\t const hb_codepoint_t *glyphs_,\n\t\t\t unsigned int len_,\n\t\t\t bool zero_context_) :\n\t\t\t face (face_),\n\t\t\t glyphs (glyphs_),\n\t\t\t len (len_),\n\t\t\t zero_context (zero_context_) {}\n};", "struct hb_collect_glyphs_context_t :\n hb_dispatch_context_t<hb_collect_glyphs_context_t>\n{\n typedef return_t (*recurse_func_t) (hb_collect_glyphs_context_t *c, unsigned int lookup_index);\n template <typename T>\n return_t dispatch (const T &obj) { obj.collect_glyphs (this); return hb_empty_t (); }\n static return_t default_return_value () { return hb_empty_t (); }\n void recurse (unsigned int lookup_index)\n {\n if (unlikely (nesting_level_left == 0 || !recurse_func))\n return;", " /* Note that GPOS sets recurse_func to nullptr already, so it doesn't get\n * past the previous check. For GSUB, we only want to collect the output\n * glyphs in the recursion. If output is not requested, we can go home now.\n *\n * Note further, that the above is not exactly correct. A recursed lookup\n * is allowed to match input that is not matched in the context, but that's\n * not how most fonts are built. It's possible to relax that and recurse\n * with all sets here if it proves to be an issue.\n */", " if (output == hb_set_get_empty ())\n return;", " /* Return if new lookup was recursed to before. */\n if (recursed_lookups->has (lookup_index))\n return;", " hb_set_t *old_before = before;\n hb_set_t *old_input = input;\n hb_set_t *old_after = after;\n before = input = after = hb_set_get_empty ();", " nesting_level_left--;\n recurse_func (this, lookup_index);\n nesting_level_left++;", " before = old_before;\n input = old_input;\n after = old_after;", " recursed_lookups->add (lookup_index);\n }", " hb_face_t *face;\n hb_set_t *before;\n hb_set_t *input;\n hb_set_t *after;\n hb_set_t *output;\n recurse_func_t recurse_func;\n hb_set_t *recursed_lookups;\n unsigned int nesting_level_left;", " hb_collect_glyphs_context_t (hb_face_t *face_,\n\t\t\t hb_set_t *glyphs_before, /* OUT. May be NULL */\n\t\t\t hb_set_t *glyphs_input, /* OUT. May be NULL */\n\t\t\t hb_set_t *glyphs_after, /* OUT. May be NULL */\n\t\t\t hb_set_t *glyphs_output, /* OUT. May be NULL */\n\t\t\t unsigned int nesting_level_left_ = HB_MAX_NESTING_LEVEL) :\n\t\t\t face (face_),\n\t\t\t before (glyphs_before ? glyphs_before : hb_set_get_empty ()),\n\t\t\t input (glyphs_input ? glyphs_input : hb_set_get_empty ()),\n\t\t\t after (glyphs_after ? glyphs_after : hb_set_get_empty ()),\n\t\t\t output (glyphs_output ? glyphs_output : hb_set_get_empty ()),\n\t\t\t recurse_func (nullptr),\n\t\t\t recursed_lookups (hb_set_create ()),\n\t\t\t nesting_level_left (nesting_level_left_) {}\n ~hb_collect_glyphs_context_t () { hb_set_destroy (recursed_lookups); }", " void set_recurse_func (recurse_func_t func) { recurse_func = func; }\n};", "", "template <typename set_t>\nstruct hb_collect_coverage_context_t :\n hb_dispatch_context_t<hb_collect_coverage_context_t<set_t>, const Coverage &>\n{\n typedef const Coverage &return_t; // Stoopid that we have to dupe this here.\n template <typename T>\n return_t dispatch (const T &obj) { return obj.get_coverage (); }\n static return_t default_return_value () { return Null (Coverage); }\n bool stop_sublookup_iteration (return_t r) const\n {\n r.collect_coverage (set);\n return false;\n }", " hb_collect_coverage_context_t (set_t *set_) :\n\t\t\t\t set (set_) {}", " set_t *set;\n};", "struct hb_ot_apply_context_t :\n hb_dispatch_context_t<hb_ot_apply_context_t, bool, HB_DEBUG_APPLY>\n{\n struct matcher_t\n {\n matcher_t () :\n\t lookup_props (0),\n\t mask (-1),\n\t ignore_zwnj (false),\n\t ignore_zwj (false),\n\t per_syllable (false),\n\t syllable {0},\n\t match_func (nullptr),\n\t match_data (nullptr) {}", " typedef bool (*match_func_t) (hb_glyph_info_t &info, unsigned value, const void *data);", " void set_ignore_zwnj (bool ignore_zwnj_) { ignore_zwnj = ignore_zwnj_; }\n void set_ignore_zwj (bool ignore_zwj_) { ignore_zwj = ignore_zwj_; }\n void set_lookup_props (unsigned int lookup_props_) { lookup_props = lookup_props_; }\n void set_mask (hb_mask_t mask_) { mask = mask_; }\n void set_per_syllable (bool per_syllable_) { per_syllable = per_syllable_; }\n void set_syllable (uint8_t syllable_) { syllable = per_syllable ? syllable_ : 0; }\n void set_match_func (match_func_t match_func_,\n\t\t\t const void *match_data_)\n { match_func = match_func_; match_data = match_data_; }", " enum may_match_t {\n MATCH_NO,\n MATCH_YES,\n MATCH_MAYBE\n };", " may_match_t may_match (hb_glyph_info_t &info,\n\t\t\t hb_codepoint_t glyph_data) const\n {\n if (!(info.mask & mask) ||\n\t (syllable && syllable != info.syllable ()))\n\treturn MATCH_NO;", " if (match_func)\n\treturn match_func (info, glyph_data, match_data) ? MATCH_YES : MATCH_NO;", " return MATCH_MAYBE;\n }", " enum may_skip_t {\n SKIP_NO,\n SKIP_YES,\n SKIP_MAYBE\n };", " may_skip_t may_skip (const hb_ot_apply_context_t *c,\n\t\t\t const hb_glyph_info_t &info) const\n {\n if (!c->check_glyph_property (&info, lookup_props))\n\treturn SKIP_YES;", " if (unlikely (_hb_glyph_info_is_default_ignorable_and_not_hidden (&info) &&\n\t\t (ignore_zwnj || !_hb_glyph_info_is_zwnj (&info)) &&\n\t\t (ignore_zwj || !_hb_glyph_info_is_zwj (&info))))\n\treturn SKIP_MAYBE;", " return SKIP_NO;\n }", " protected:\n unsigned int lookup_props;\n hb_mask_t mask;\n bool ignore_zwnj;\n bool ignore_zwj;\n bool per_syllable;\n uint8_t syllable;\n match_func_t match_func;\n const void *match_data;\n };", " struct skipping_iterator_t\n {\n void init (hb_ot_apply_context_t *c_, bool context_match = false)\n {\n c = c_;\n match_glyph_data16 = nullptr;\n#ifndef HB_NO_BEYOND_64K\n match_glyph_data24 = nullptr;\n#endif\n matcher.set_match_func (nullptr, nullptr);\n matcher.set_lookup_props (c->lookup_props);\n /* Ignore ZWNJ if we are matching GPOS, or matching GSUB context and asked to. */\n matcher.set_ignore_zwnj (c->table_index == 1 || (context_match && c->auto_zwnj));\n /* Ignore ZWJ if we are matching context, or asked to. */\n matcher.set_ignore_zwj (context_match || c->auto_zwj);\n matcher.set_mask (context_match ? -1 : c->lookup_mask);\n matcher.set_per_syllable (c->per_syllable);\n }\n void set_lookup_props (unsigned int lookup_props)\n {\n matcher.set_lookup_props (lookup_props);\n }\n void set_match_func (matcher_t::match_func_t match_func_,\n\t\t\t const void *match_data_)\n {\n matcher.set_match_func (match_func_, match_data_);\n }\n void set_glyph_data (const HBUINT16 glyph_data[])\n {\n match_glyph_data16 = glyph_data;\n#ifndef HB_NO_BEYOND_64K\n match_glyph_data24 = nullptr;\n#endif\n }\n#ifndef HB_NO_BEYOND_64K\n void set_glyph_data (const HBUINT24 glyph_data[])\n {\n match_glyph_data16 = nullptr;\n match_glyph_data24 = glyph_data;\n }\n#endif", " void reset (unsigned int start_index_,\n\t\tunsigned int num_items_)\n {\n idx = start_index_;\n num_items = num_items_;\n end = c->buffer->len;\n matcher.set_syllable (start_index_ == c->buffer->idx ? c->buffer->cur().syllable () : 0);\n }", " void reject ()\n {\n num_items++;\n backup_glyph_data ();\n }", " matcher_t::may_skip_t\n may_skip (const hb_glyph_info_t &info) const\n { return matcher.may_skip (c, info); }", " bool next (unsigned *unsafe_to = nullptr)\n {\n assert (num_items > 0);\n /* The alternate condition below is faster at string boundaries,\n * but produces subpar \"unsafe-to-concat\" values. */\n signed stop = (signed) end - (signed) num_items;\n if (c->buffer->flags & HB_BUFFER_FLAG_PRODUCE_UNSAFE_TO_CONCAT)\n stop = (signed) end - 1;\n while ((signed) idx < stop)\n {\n\tidx++;\n\thb_glyph_info_t &info = c->buffer->info[idx];", "\tmatcher_t::may_skip_t skip = matcher.may_skip (c, info);\n\tif (unlikely (skip == matcher_t::SKIP_YES))\n\t continue;", "\tmatcher_t::may_match_t match = matcher.may_match (info, get_glyph_data ());\n\tif (match == matcher_t::MATCH_YES ||\n\t (match == matcher_t::MATCH_MAYBE &&\n\t skip == matcher_t::SKIP_NO))\n\t{\n\t num_items--;\n\t advance_glyph_data ();\n\t return true;\n\t}", "\tif (skip == matcher_t::SKIP_NO)\n\t{\n\t if (unsafe_to)\n\t *unsafe_to = idx + 1;\n\t return false;\n\t}\n }\n if (unsafe_to)\n *unsafe_to = end;\n return false;\n }\n bool prev (unsigned *unsafe_from = nullptr)\n {\n assert (num_items > 0);\n /* The alternate condition below is faster at string boundaries,\n * but produces subpar \"unsafe-to-concat\" values. */\n unsigned stop = num_items - 1;\n if (c->buffer->flags & HB_BUFFER_FLAG_PRODUCE_UNSAFE_TO_CONCAT)\n stop = 1 - 1;", "", " while (idx > stop)\n {\n\tidx--;\n\thb_glyph_info_t &info = c->buffer->out_info[idx];", "\tmatcher_t::may_skip_t skip = matcher.may_skip (c, info);\n\tif (unlikely (skip == matcher_t::SKIP_YES))\n\t continue;", "\tmatcher_t::may_match_t match = matcher.may_match (info, get_glyph_data ());\n\tif (match == matcher_t::MATCH_YES ||\n\t (match == matcher_t::MATCH_MAYBE &&\n\t skip == matcher_t::SKIP_NO))\n\t{\n\t num_items--;\n\t advance_glyph_data ();\n\t return true;\n\t}", "\tif (skip == matcher_t::SKIP_NO)\n\t{\n\t if (unsafe_from)\n\t *unsafe_from = hb_max (1u, idx) - 1u;\n\t return false;\n\t}\n }\n if (unsafe_from)\n *unsafe_from = 0;\n return false;\n }", " hb_codepoint_t\n get_glyph_data ()\n {\n if (match_glyph_data16) return *match_glyph_data16;\n#ifndef HB_NO_BEYOND_64K\n else\n if (match_glyph_data24) return *match_glyph_data24;\n#endif\n return 0;\n }\n void\n advance_glyph_data ()\n {\n if (match_glyph_data16) match_glyph_data16++;\n#ifndef HB_NO_BEYOND_64K\n else\n if (match_glyph_data24) match_glyph_data24++;\n#endif\n }\n void\n backup_glyph_data ()\n {\n if (match_glyph_data16) match_glyph_data16--;\n#ifndef HB_NO_BEYOND_64K\n else\n if (match_glyph_data24) match_glyph_data24--;\n#endif\n }", " unsigned int idx;\n protected:\n hb_ot_apply_context_t *c;\n matcher_t matcher;\n const HBUINT16 *match_glyph_data16;\n#ifndef HB_NO_BEYOND_64K\n const HBUINT24 *match_glyph_data24;\n#endif", " unsigned int num_items;\n unsigned int end;\n };", "\n const char *get_name () { return \"APPLY\"; }\n typedef return_t (*recurse_func_t) (hb_ot_apply_context_t *c, unsigned int lookup_index);\n template <typename T>\n return_t dispatch (const T &obj) { return obj.apply (this); }\n static return_t default_return_value () { return false; }\n bool stop_sublookup_iteration (return_t r) const { return r; }\n return_t recurse (unsigned int sub_lookup_index)\n {\n if (unlikely (nesting_level_left == 0 || !recurse_func || buffer->max_ops-- <= 0))\n {\n buffer->shaping_failed = true;\n return default_return_value ();\n }", " nesting_level_left--;\n bool ret = recurse_func (this, sub_lookup_index);\n nesting_level_left++;\n return ret;\n }", " skipping_iterator_t iter_input, iter_context;", " unsigned int table_index; /* GSUB/GPOS */\n hb_font_t *font;\n hb_face_t *face;\n hb_buffer_t *buffer;\n recurse_func_t recurse_func = nullptr;\n const GDEF &gdef;\n const VariationStore &var_store;\n VariationStore::cache_t *var_store_cache;\n hb_set_digest_t digest;", " hb_direction_t direction;\n hb_mask_t lookup_mask = 1;\n unsigned int lookup_index = (unsigned) -1;\n unsigned int lookup_props = 0;\n unsigned int nesting_level_left = HB_MAX_NESTING_LEVEL;", " bool has_glyph_classes;\n bool auto_zwnj = true;\n bool auto_zwj = true;\n bool per_syllable = false;\n bool random = false;\n uint32_t random_state = 1;\n unsigned new_syllables = (unsigned) -1;", " hb_ot_apply_context_t (unsigned int table_index_,\n\t\t\t hb_font_t *font_,\n\t\t\t hb_buffer_t *buffer_) :\n\t\t\ttable_index (table_index_),\n\t\t\tfont (font_), face (font->face), buffer (buffer_),\n\t\t\tgdef (\n#ifndef HB_NO_OT_LAYOUT\n\t\t\t *face->table.GDEF->table\n#else\n\t\t\t Null (GDEF)\n#endif\n\t\t\t ),\n\t\t\tvar_store (gdef.get_var_store ()),\n\t\t\tvar_store_cache (\n#ifndef HB_NO_VAR\n\t\t\t\t\t table_index == 1 && font->num_coords ? var_store.create_cache () : nullptr\n#else\n\t\t\t\t\t nullptr\n#endif\n\t\t\t\t\t),\n\t\t\tdigest (buffer_->digest ()),\n\t\t\tdirection (buffer_->props.direction),\n\t\t\thas_glyph_classes (gdef.has_glyph_classes ())\n { init_iters (); }", " ~hb_ot_apply_context_t ()\n {\n#ifndef HB_NO_VAR\n VariationStore::destroy_cache (var_store_cache);\n#endif\n }", " void init_iters ()\n {\n iter_input.init (this, false);\n iter_context.init (this, true);\n }", " void set_lookup_mask (hb_mask_t mask) { lookup_mask = mask; init_iters (); }\n void set_auto_zwj (bool auto_zwj_) { auto_zwj = auto_zwj_; init_iters (); }\n void set_auto_zwnj (bool auto_zwnj_) { auto_zwnj = auto_zwnj_; init_iters (); }\n void set_per_syllable (bool per_syllable_) { per_syllable = per_syllable_; init_iters (); }\n void set_random (bool random_) { random = random_; }\n void set_recurse_func (recurse_func_t func) { recurse_func = func; }\n void set_lookup_index (unsigned int lookup_index_) { lookup_index = lookup_index_; }\n void set_lookup_props (unsigned int lookup_props_) { lookup_props = lookup_props_; init_iters (); }", " uint32_t random_number ()\n {\n /* http://www.cplusplus.com/reference/random/minstd_rand/ */\n random_state = random_state * 48271 % 2147483647;\n return random_state;\n }", " bool match_properties_mark (hb_codepoint_t glyph,\n\t\t\t unsigned int glyph_props,\n\t\t\t unsigned int match_props) const\n {\n /* If using mark filtering sets, the high short of\n * match_props has the set index.\n */\n if (match_props & LookupFlag::UseMarkFilteringSet)\n return gdef.mark_set_covers (match_props >> 16, glyph);", " /* The second byte of match_props has the meaning\n * \"ignore marks of attachment type different than\n * the attachment type specified.\"\n */\n if (match_props & LookupFlag::MarkAttachmentType)\n return (match_props & LookupFlag::MarkAttachmentType) == (glyph_props & LookupFlag::MarkAttachmentType);", " return true;\n }", " bool check_glyph_property (const hb_glyph_info_t *info,\n\t\t\t unsigned int match_props) const\n {\n hb_codepoint_t glyph = info->codepoint;\n unsigned int glyph_props = _hb_glyph_info_get_glyph_props (info);", " /* Not covered, if, for example, glyph class is ligature and\n * match_props includes LookupFlags::IgnoreLigatures\n */\n if (glyph_props & match_props & LookupFlag::IgnoreFlags)\n return false;", " if (unlikely (glyph_props & HB_OT_LAYOUT_GLYPH_PROPS_MARK))\n return match_properties_mark (glyph, glyph_props, match_props);", " return true;\n }", " void _set_glyph_class (hb_codepoint_t glyph_index,\n\t\t\t unsigned int class_guess = 0,\n\t\t\t bool ligature = false,\n\t\t\t bool component = false)\n {\n digest.add (glyph_index);", " if (new_syllables != (unsigned) -1)\n buffer->cur().syllable() = new_syllables;", " unsigned int props = _hb_glyph_info_get_glyph_props (&buffer->cur());\n props |= HB_OT_LAYOUT_GLYPH_PROPS_SUBSTITUTED;\n if (ligature)\n {\n props |= HB_OT_LAYOUT_GLYPH_PROPS_LIGATED;\n /* In the only place that the MULTIPLIED bit is used, Uniscribe\n * seems to only care about the \"last\" transformation between\n * Ligature and Multiple substitutions. Ie. if you ligate, expand,\n * and ligate again, it forgives the multiplication and acts as\n * if only ligation happened. As such, clear MULTIPLIED bit.\n */\n props &= ~HB_OT_LAYOUT_GLYPH_PROPS_MULTIPLIED;\n }\n if (component)\n props |= HB_OT_LAYOUT_GLYPH_PROPS_MULTIPLIED;\n if (likely (has_glyph_classes))\n {\n props &= HB_OT_LAYOUT_GLYPH_PROPS_PRESERVE;\n _hb_glyph_info_set_glyph_props (&buffer->cur(), props | gdef.get_glyph_props (glyph_index));\n }\n else if (class_guess)\n {\n props &= HB_OT_LAYOUT_GLYPH_PROPS_PRESERVE;\n _hb_glyph_info_set_glyph_props (&buffer->cur(), props | class_guess);\n }\n else\n _hb_glyph_info_set_glyph_props (&buffer->cur(), props);\n }", " void replace_glyph (hb_codepoint_t glyph_index)\n {\n _set_glyph_class (glyph_index);\n (void) buffer->replace_glyph (glyph_index);\n }\n void replace_glyph_inplace (hb_codepoint_t glyph_index)\n {\n _set_glyph_class (glyph_index);\n buffer->cur().codepoint = glyph_index;\n }\n void replace_glyph_with_ligature (hb_codepoint_t glyph_index,\n\t\t\t\t unsigned int class_guess)\n {\n _set_glyph_class (glyph_index, class_guess, true);\n (void) buffer->replace_glyph (glyph_index);\n }\n void output_glyph_for_component (hb_codepoint_t glyph_index,\n\t\t\t\t unsigned int class_guess)\n {\n _set_glyph_class (glyph_index, class_guess, false, true);\n (void) buffer->output_glyph (glyph_index);\n }\n};", "\nstruct hb_accelerate_subtables_context_t :\n hb_dispatch_context_t<hb_accelerate_subtables_context_t>\n{\n template <typename Type>\n static inline bool apply_to (const void *obj, hb_ot_apply_context_t *c)\n {\n const Type *typed_obj = (const Type *) obj;\n return typed_obj->apply (c);\n }", "#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n template <typename T>\n static inline auto apply_cached_ (const T *obj, hb_ot_apply_context_t *c, hb_priority<1>) HB_RETURN (bool, obj->apply (c, true) )\n template <typename T>\n static inline auto apply_cached_ (const T *obj, hb_ot_apply_context_t *c, hb_priority<0>) HB_RETURN (bool, obj->apply (c) )\n template <typename Type>\n static inline bool apply_cached_to (const void *obj, hb_ot_apply_context_t *c)\n {\n const Type *typed_obj = (const Type *) obj;\n return apply_cached_ (typed_obj, c, hb_prioritize);\n }", " template <typename T>\n static inline auto cache_func_ (const T *obj, hb_ot_apply_context_t *c, bool enter, hb_priority<1>) HB_RETURN (bool, obj->cache_func (c, enter) )\n template <typename T>\n static inline bool cache_func_ (const T *obj, hb_ot_apply_context_t *c, bool enter, hb_priority<0>) { return false; }\n template <typename Type>\n static inline bool cache_func_to (const void *obj, hb_ot_apply_context_t *c, bool enter)\n {\n const Type *typed_obj = (const Type *) obj;\n return cache_func_ (typed_obj, c, enter, hb_prioritize);\n }\n#endif", " typedef bool (*hb_apply_func_t) (const void *obj, hb_ot_apply_context_t *c);\n typedef bool (*hb_cache_func_t) (const void *obj, hb_ot_apply_context_t *c, bool enter);", " struct hb_applicable_t\n {\n friend struct hb_accelerate_subtables_context_t;\n friend struct hb_ot_layout_lookup_accelerator_t;", " template <typename T>\n void init (const T &obj_,\n\t hb_apply_func_t apply_func_\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n\t , hb_apply_func_t apply_cached_func_\n\t , hb_cache_func_t cache_func_\n#endif\n\t\t)\n {\n obj = &obj_;\n apply_func = apply_func_;\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n apply_cached_func = apply_cached_func_;\n cache_func = cache_func_;\n#endif\n digest.init ();\n obj_.get_coverage ().collect_coverage (&digest);\n }", " bool apply (hb_ot_apply_context_t *c) const\n {\n return digest.may_have (c->buffer->cur().codepoint) && apply_func (obj, c);\n }\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n bool apply_cached (hb_ot_apply_context_t *c) const\n {\n return digest.may_have (c->buffer->cur().codepoint) && apply_cached_func (obj, c);\n }\n bool cache_enter (hb_ot_apply_context_t *c) const\n {\n return cache_func (obj, c, true);\n }\n void cache_leave (hb_ot_apply_context_t *c) const\n {\n cache_func (obj, c, false);\n }\n#endif", " private:\n const void *obj;\n hb_apply_func_t apply_func;\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n hb_apply_func_t apply_cached_func;\n hb_cache_func_t cache_func;\n#endif\n hb_set_digest_t digest;\n };", "#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n template <typename T>\n auto cache_cost (const T &obj, hb_priority<1>) HB_AUTO_RETURN ( obj.cache_cost () )\n template <typename T>\n auto cache_cost (const T &obj, hb_priority<0>) HB_AUTO_RETURN ( 0u )\n#endif", " /* Dispatch interface. */\n template <typename T>\n return_t dispatch (const T &obj)\n {\n hb_applicable_t *entry = &array[i++];", " entry->init (obj,\n\t\t apply_to<T>\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n\t\t , apply_cached_to<T>\n\t\t , cache_func_to<T>\n#endif\n\t\t );", "#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n /* Cache handling\n *\n * We allow one subtable from each lookup to use a cache. The assumption\n * being that multiple subtables of the same lookup cannot use a cache\n * because the resources they would use will collide. As such, we ask\n * each subtable to tell us how much it costs (which a cache would avoid),\n * and we allocate the cache opportunity to the costliest subtable.\n */\n unsigned cost = cache_cost (obj, hb_prioritize);\n if (cost > cache_user_cost)\n {\n cache_user_idx = i - 1;\n cache_user_cost = cost;\n }\n#endif", " return hb_empty_t ();\n }\n static return_t default_return_value () { return hb_empty_t (); }", " hb_accelerate_subtables_context_t (hb_applicable_t *array_) :\n\t\t\t\t array (array_) {}", " hb_applicable_t *array;\n unsigned i = 0;", "#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n unsigned cache_user_idx = (unsigned) -1;\n unsigned cache_user_cost = 0;\n#endif\n};", "\ntypedef bool (*intersects_func_t) (const hb_set_t *glyphs, unsigned value, const void *data, void *cache);\ntypedef void (*intersected_glyphs_func_t) (const hb_set_t *glyphs, const void *data, unsigned value, hb_set_t *intersected_glyphs, void *cache);\ntypedef void (*collect_glyphs_func_t) (hb_set_t *glyphs, unsigned value, const void *data);\ntypedef bool (*match_func_t) (hb_glyph_info_t &info, unsigned value, const void *data);", "struct ContextClosureFuncs\n{\n intersects_func_t intersects;\n intersected_glyphs_func_t intersected_glyphs;\n};\nstruct ContextCollectGlyphsFuncs\n{\n collect_glyphs_func_t collect;\n};\nstruct ContextApplyFuncs\n{\n match_func_t match;\n};\nstruct ChainContextApplyFuncs\n{\n match_func_t match[3];\n};", "\nstatic inline bool intersects_glyph (const hb_set_t *glyphs, unsigned value, const void *data HB_UNUSED, void *cache HB_UNUSED)\n{\n return glyphs->has (value);\n}\nstatic inline bool intersects_class (const hb_set_t *glyphs, unsigned value, const void *data, void *cache)\n{\n const ClassDef &class_def = *reinterpret_cast<const ClassDef *>(data);\n hb_map_t *map = (hb_map_t *) cache;", " hb_codepoint_t *cached_v;\n if (map->has (value, &cached_v))\n return *cached_v;", " bool v = class_def.intersects_class (glyphs, value);\n map->set (value, v);", " return v;\n}\nstatic inline bool intersects_coverage (const hb_set_t *glyphs, unsigned value, const void *data, void *cache HB_UNUSED)\n{\n Offset16To<Coverage> coverage;\n coverage = value;\n return (data+coverage).intersects (glyphs);\n}", "\nstatic inline void intersected_glyph (const hb_set_t *glyphs HB_UNUSED, const void *data, unsigned value, hb_set_t *intersected_glyphs, HB_UNUSED void *cache)\n{\n unsigned g = reinterpret_cast<const HBUINT16 *>(data)[value];\n intersected_glyphs->add (g);\n}", "using intersected_class_cache_t = hb_hashmap_t<unsigned, hb_set_t>;", "static inline void intersected_class_glyphs (const hb_set_t *glyphs, const void *data, unsigned value, hb_set_t *intersected_glyphs, void *cache)\n{\n const ClassDef &class_def = *reinterpret_cast<const ClassDef *>(data);", " intersected_class_cache_t *map = (intersected_class_cache_t *) cache;", " hb_set_t *cached_v;\n if (map->has (value, &cached_v))\n {\n intersected_glyphs->union_ (*cached_v);\n return;\n }", " hb_set_t v;\n class_def.intersected_class_glyphs (glyphs, value, &v);", " intersected_glyphs->union_ (v);", " map->set (value, std::move (v));\n}", "static inline void intersected_coverage_glyphs (const hb_set_t *glyphs, const void *data, unsigned value, hb_set_t *intersected_glyphs, HB_UNUSED void *cache)\n{\n Offset16To<Coverage> coverage;\n coverage = value;\n (data+coverage).intersect_set (*glyphs, *intersected_glyphs);\n}", "\ntemplate <typename HBUINT>\nstatic inline bool array_is_subset_of (const hb_set_t *glyphs,\n\t\t\t\t unsigned int count,\n\t\t\t\t const HBUINT values[],\n\t\t\t\t intersects_func_t intersects_func,\n\t\t\t\t const void *intersects_data,\n\t\t\t\t void *cache)\n{\n for (const auto &_ : + hb_iter (values, count))\n if (!intersects_func (glyphs, _, intersects_data, cache)) return false;\n return true;\n}", "\nstatic inline void collect_glyph (hb_set_t *glyphs, unsigned value, const void *data HB_UNUSED)\n{\n glyphs->add (value);\n}\nstatic inline void collect_class (hb_set_t *glyphs, unsigned value, const void *data)\n{\n const ClassDef &class_def = *reinterpret_cast<const ClassDef *>(data);\n class_def.collect_class (glyphs, value);\n}\nstatic inline void collect_coverage (hb_set_t *glyphs, unsigned value, const void *data)\n{\n Offset16To<Coverage> coverage;\n coverage = value;\n (data+coverage).collect_coverage (glyphs);\n}\ntemplate <typename HBUINT>\nstatic inline void collect_array (hb_collect_glyphs_context_t *c HB_UNUSED,\n\t\t\t\t hb_set_t *glyphs,\n\t\t\t\t unsigned int count,\n\t\t\t\t const HBUINT values[],\n\t\t\t\t collect_glyphs_func_t collect_func,\n\t\t\t\t const void *collect_data)\n{\n return\n + hb_iter (values, count)\n | hb_apply ([&] (const HBUINT &_) { collect_func (glyphs, _, collect_data); })\n ;\n}", "\nstatic inline bool match_glyph (hb_glyph_info_t &info, unsigned value, const void *data HB_UNUSED)\n{\n return info.codepoint == value;\n}\nstatic inline bool match_class (hb_glyph_info_t &info, unsigned value, const void *data)\n{\n const ClassDef &class_def = *reinterpret_cast<const ClassDef *>(data);\n return class_def.get_class (info.codepoint) == value;\n}\nstatic inline bool match_class_cached (hb_glyph_info_t &info, unsigned value, const void *data)\n{\n unsigned klass = info.syllable();\n if (klass < 255)\n return klass == value;\n const ClassDef &class_def = *reinterpret_cast<const ClassDef *>(data);\n klass = class_def.get_class (info.codepoint);\n if (likely (klass < 255))\n info.syllable() = klass;\n return klass == value;\n}\nstatic inline bool match_coverage (hb_glyph_info_t &info, unsigned value, const void *data)\n{\n Offset16To<Coverage> coverage;\n coverage = value;\n return (data+coverage).get_coverage (info.codepoint) != NOT_COVERED;\n}", "template <typename HBUINT>\nstatic inline bool would_match_input (hb_would_apply_context_t *c,\n\t\t\t\t unsigned int count, /* Including the first glyph (not matched) */\n\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t match_func_t match_func,\n\t\t\t\t const void *match_data)\n{\n if (count != c->len)\n return false;", " for (unsigned int i = 1; i < count; i++)\n {\n hb_glyph_info_t info;\n info.codepoint = c->glyphs[i];\n if (likely (!match_func (info, input[i - 1], match_data)))\n return false;\n }", " return true;\n}\ntemplate <typename HBUINT>\nstatic inline bool match_input (hb_ot_apply_context_t *c,\n\t\t\t\tunsigned int count, /* Including the first glyph (not matched) */\n\t\t\t\tconst HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\tmatch_func_t match_func,\n\t\t\t\tconst void *match_data,\n\t\t\t\tunsigned int *end_position,\n\t\t\t\tunsigned int match_positions[HB_MAX_CONTEXT_LENGTH],\n\t\t\t\tunsigned int *p_total_component_count = nullptr)\n{\n TRACE_APPLY (nullptr);", " if (unlikely (count > HB_MAX_CONTEXT_LENGTH)) return_trace (false);", " hb_buffer_t *buffer = c->buffer;", " hb_ot_apply_context_t::skipping_iterator_t &skippy_iter = c->iter_input;\n skippy_iter.reset (buffer->idx, count - 1);\n skippy_iter.set_match_func (match_func, match_data);\n skippy_iter.set_glyph_data (input);", " /*\n * This is perhaps the trickiest part of OpenType... Remarks:\n *\n * - If all components of the ligature were marks, we call this a mark ligature.\n *\n * - If there is no GDEF, and the ligature is NOT a mark ligature, we categorize\n * it as a ligature glyph.\n *\n * - Ligatures cannot be formed across glyphs attached to different components\n * of previous ligatures. Eg. the sequence is LAM,SHADDA,LAM,FATHA,HEH, and\n * LAM,LAM,HEH form a ligature, leaving SHADDA,FATHA next to eachother.\n * However, it would be wrong to ligate that SHADDA,FATHA sequence.\n * There are a couple of exceptions to this:\n *\n * o If a ligature tries ligating with marks that belong to it itself, go ahead,\n * assuming that the font designer knows what they are doing (otherwise it can\n * break Indic stuff when a matra wants to ligate with a conjunct,\n *\n * o If two marks want to ligate and they belong to different components of the\n * same ligature glyph, and said ligature glyph is to be ignored according to\n * mark-filtering rules, then allow.\n * https://github.com/harfbuzz/harfbuzz/issues/545\n */", " unsigned int total_component_count = 0;\n total_component_count += _hb_glyph_info_get_lig_num_comps (&buffer->cur());", " unsigned int first_lig_id = _hb_glyph_info_get_lig_id (&buffer->cur());\n unsigned int first_lig_comp = _hb_glyph_info_get_lig_comp (&buffer->cur());", " enum {\n LIGBASE_NOT_CHECKED,\n LIGBASE_MAY_NOT_SKIP,\n LIGBASE_MAY_SKIP\n } ligbase = LIGBASE_NOT_CHECKED;", " match_positions[0] = buffer->idx;\n for (unsigned int i = 1; i < count; i++)\n {\n unsigned unsafe_to;\n if (!skippy_iter.next (&unsafe_to))\n {\n *end_position = unsafe_to;\n return_trace (false);\n }", " match_positions[i] = skippy_iter.idx;", " unsigned int this_lig_id = _hb_glyph_info_get_lig_id (&buffer->info[skippy_iter.idx]);\n unsigned int this_lig_comp = _hb_glyph_info_get_lig_comp (&buffer->info[skippy_iter.idx]);", " if (first_lig_id && first_lig_comp)\n {\n /* If first component was attached to a previous ligature component,\n * all subsequent components should be attached to the same ligature\n * component, otherwise we shouldn't ligate them... */\n if (first_lig_id != this_lig_id || first_lig_comp != this_lig_comp)\n {\n\t/* ...unless, we are attached to a base ligature and that base\n\t * ligature is ignorable. */\n\tif (ligbase == LIGBASE_NOT_CHECKED)\n\t{\n\t bool found = false;\n\t const auto *out = buffer->out_info;\n\t unsigned int j = buffer->out_len;\n\t while (j && _hb_glyph_info_get_lig_id (&out[j - 1]) == first_lig_id)\n\t {\n\t if (_hb_glyph_info_get_lig_comp (&out[j - 1]) == 0)\n\t {\n\t j--;\n\t found = true;\n\t break;\n\t }\n\t j--;\n\t }", "\t if (found && skippy_iter.may_skip (out[j]) == hb_ot_apply_context_t::matcher_t::SKIP_YES)\n\t ligbase = LIGBASE_MAY_SKIP;\n\t else\n\t ligbase = LIGBASE_MAY_NOT_SKIP;\n\t}", "\tif (ligbase == LIGBASE_MAY_NOT_SKIP)\n\t return_trace (false);\n }\n }\n else\n {\n /* If first component was NOT attached to a previous ligature component,\n * all subsequent components should also NOT be attached to any ligature\n * component, unless they are attached to the first component itself! */\n if (this_lig_id && this_lig_comp && (this_lig_id != first_lig_id))\n\treturn_trace (false);\n }", " total_component_count += _hb_glyph_info_get_lig_num_comps (&buffer->info[skippy_iter.idx]);\n }", " *end_position = skippy_iter.idx + 1;", " if (p_total_component_count)\n *p_total_component_count = total_component_count;", " return_trace (true);\n}\nstatic inline bool ligate_input (hb_ot_apply_context_t *c,\n\t\t\t\t unsigned int count, /* Including the first glyph */\n\t\t\t\t const unsigned int match_positions[HB_MAX_CONTEXT_LENGTH], /* Including the first glyph */\n\t\t\t\t unsigned int match_end,\n\t\t\t\t hb_codepoint_t lig_glyph,\n\t\t\t\t unsigned int total_component_count)\n{\n TRACE_APPLY (nullptr);", " hb_buffer_t *buffer = c->buffer;", " buffer->merge_clusters (buffer->idx, match_end);", " /* - If a base and one or more marks ligate, consider that as a base, NOT\n * ligature, such that all following marks can still attach to it.\n * https://github.com/harfbuzz/harfbuzz/issues/1109\n *\n * - If all components of the ligature were marks, we call this a mark ligature.\n * If it *is* a mark ligature, we don't allocate a new ligature id, and leave\n * the ligature to keep its old ligature id. This will allow it to attach to\n * a base ligature in GPOS. Eg. if the sequence is: LAM,LAM,SHADDA,FATHA,HEH,\n * and LAM,LAM,HEH for a ligature, they will leave SHADDA and FATHA with a\n * ligature id and component value of 2. Then if SHADDA,FATHA form a ligature\n * later, we don't want them to lose their ligature id/component, otherwise\n * GPOS will fail to correctly position the mark ligature on top of the\n * LAM,LAM,HEH ligature. See:\n * https://bugzilla.gnome.org/show_bug.cgi?id=676343\n *\n * - If a ligature is formed of components that some of which are also ligatures\n * themselves, and those ligature components had marks attached to *their*\n * components, we have to attach the marks to the new ligature component\n * positions! Now *that*'s tricky! And these marks may be following the\n * last component of the whole sequence, so we should loop forward looking\n * for them and update them.\n *\n * Eg. the sequence is LAM,LAM,SHADDA,FATHA,HEH, and the font first forms a\n * 'calt' ligature of LAM,HEH, leaving the SHADDA and FATHA with a ligature\n * id and component == 1. Now, during 'liga', the LAM and the LAM-HEH ligature\n * form a LAM-LAM-HEH ligature. We need to reassign the SHADDA and FATHA to\n * the new ligature with a component value of 2.\n *\n * This in fact happened to a font... See:\n * https://bugzilla.gnome.org/show_bug.cgi?id=437633\n */", " bool is_base_ligature = _hb_glyph_info_is_base_glyph (&buffer->info[match_positions[0]]);\n bool is_mark_ligature = _hb_glyph_info_is_mark (&buffer->info[match_positions[0]]);\n for (unsigned int i = 1; i < count; i++)\n if (!_hb_glyph_info_is_mark (&buffer->info[match_positions[i]]))\n {\n is_base_ligature = false;\n is_mark_ligature = false;\n break;\n }\n bool is_ligature = !is_base_ligature && !is_mark_ligature;", " unsigned int klass = is_ligature ? HB_OT_LAYOUT_GLYPH_PROPS_LIGATURE : 0;\n unsigned int lig_id = is_ligature ? _hb_allocate_lig_id (buffer) : 0;\n unsigned int last_lig_id = _hb_glyph_info_get_lig_id (&buffer->cur());\n unsigned int last_num_components = _hb_glyph_info_get_lig_num_comps (&buffer->cur());\n unsigned int components_so_far = last_num_components;", " if (is_ligature)\n {\n _hb_glyph_info_set_lig_props_for_ligature (&buffer->cur(), lig_id, total_component_count);\n if (_hb_glyph_info_get_general_category (&buffer->cur()) == HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK)\n {\n _hb_glyph_info_set_general_category (&buffer->cur(), HB_UNICODE_GENERAL_CATEGORY_OTHER_LETTER);\n }\n }\n c->replace_glyph_with_ligature (lig_glyph, klass);", " for (unsigned int i = 1; i < count; i++)\n {\n while (buffer->idx < match_positions[i] && buffer->successful)\n {\n if (is_ligature)\n {\n\tunsigned int this_comp = _hb_glyph_info_get_lig_comp (&buffer->cur());\n\tif (this_comp == 0)\n\t this_comp = last_num_components;\n\tunsigned int new_lig_comp = components_so_far - last_num_components +\n\t\t\t\t hb_min (this_comp, last_num_components);\n\t _hb_glyph_info_set_lig_props_for_mark (&buffer->cur(), lig_id, new_lig_comp);\n }\n (void) buffer->next_glyph ();\n }", " last_lig_id = _hb_glyph_info_get_lig_id (&buffer->cur());\n last_num_components = _hb_glyph_info_get_lig_num_comps (&buffer->cur());\n components_so_far += last_num_components;", " /* Skip the base glyph */\n buffer->idx++;\n }", " if (!is_mark_ligature && last_lig_id)\n {\n /* Re-adjust components for any marks following. */\n for (unsigned i = buffer->idx; i < buffer->len; ++i)\n {\n if (last_lig_id != _hb_glyph_info_get_lig_id (&buffer->info[i])) break;", " unsigned this_comp = _hb_glyph_info_get_lig_comp (&buffer->info[i]);\n if (!this_comp) break;", " unsigned new_lig_comp = components_so_far - last_num_components +\n\t\t\t hb_min (this_comp, last_num_components);\n _hb_glyph_info_set_lig_props_for_mark (&buffer->info[i], lig_id, new_lig_comp);\n }\n }\n return_trace (true);\n}", "template <typename HBUINT>\nstatic inline bool match_backtrack (hb_ot_apply_context_t *c,\n\t\t\t\t unsigned int count,\n\t\t\t\t const HBUINT backtrack[],\n\t\t\t\t match_func_t match_func,\n\t\t\t\t const void *match_data,\n\t\t\t\t unsigned int *match_start)\n{\n TRACE_APPLY (nullptr);", " hb_ot_apply_context_t::skipping_iterator_t &skippy_iter = c->iter_context;\n skippy_iter.reset (c->buffer->backtrack_len (), count);\n skippy_iter.set_match_func (match_func, match_data);\n skippy_iter.set_glyph_data (backtrack);", " for (unsigned int i = 0; i < count; i++)\n {\n unsigned unsafe_from;\n if (!skippy_iter.prev (&unsafe_from))\n {\n *match_start = unsafe_from;\n return_trace (false);\n }\n }", " *match_start = skippy_iter.idx;\n return_trace (true);\n}", "template <typename HBUINT>\nstatic inline bool match_lookahead (hb_ot_apply_context_t *c,\n\t\t\t\t unsigned int count,\n\t\t\t\t const HBUINT lookahead[],\n\t\t\t\t match_func_t match_func,\n\t\t\t\t const void *match_data,\n\t\t\t\t unsigned int start_index,\n\t\t\t\t unsigned int *end_index)\n{\n TRACE_APPLY (nullptr);", " hb_ot_apply_context_t::skipping_iterator_t &skippy_iter = c->iter_context;\n skippy_iter.reset (start_index - 1, count);\n skippy_iter.set_match_func (match_func, match_data);\n skippy_iter.set_glyph_data (lookahead);", " for (unsigned int i = 0; i < count; i++)\n {\n unsigned unsafe_to;\n if (!skippy_iter.next (&unsafe_to))\n {\n *end_index = unsafe_to;\n return_trace (false);\n }\n }", " *end_index = skippy_iter.idx + 1;\n return_trace (true);\n}", "", "struct LookupRecord\n{\n bool serialize (hb_serialize_context_t *c,\n\t\t const hb_map_t *lookup_map) const\n {\n TRACE_SERIALIZE (this);\n auto *out = c->embed (*this);\n if (unlikely (!out)) return_trace (false);", " return_trace (c->check_assign (out->lookupListIndex, lookup_map->get (lookupListIndex), HB_SERIALIZE_ERROR_INT_OVERFLOW));\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (c->check_struct (this));\n }", " HBUINT16\tsequenceIndex;\t\t/* Index into current glyph\n\t\t\t\t\t * sequence--first glyph = 0 */\n HBUINT16\tlookupListIndex;\t/* Lookup to apply to that\n\t\t\t\t\t * position--zero--based */\n public:\n DEFINE_SIZE_STATIC (4);\n};", "static unsigned serialize_lookuprecord_array (hb_serialize_context_t *c,\n\t\t\t\t\t const hb_array_t<const LookupRecord> lookupRecords,\n\t\t\t\t\t const hb_map_t *lookup_map)\n{\n unsigned count = 0;\n for (const LookupRecord& r : lookupRecords)\n {\n if (!lookup_map->has (r.lookupListIndex))\n continue;", " if (!r.serialize (c, lookup_map))\n return 0;", " count++;\n }\n return count;\n}", "enum ContextFormat { SimpleContext = 1, ClassBasedContext = 2, CoverageBasedContext = 3 };", "template <typename HBUINT>\nstatic void context_closure_recurse_lookups (hb_closure_context_t *c,\n\t\t\t\t\t unsigned inputCount, const HBUINT input[],\n\t\t\t\t\t unsigned lookupCount,\n\t\t\t\t\t const LookupRecord lookupRecord[] /* Array of LookupRecords--in design order */,\n\t\t\t\t\t unsigned value,\n\t\t\t\t\t ContextFormat context_format,\n\t\t\t\t\t const void *data,\n\t\t\t\t\t intersected_glyphs_func_t intersected_glyphs_func,\n\t\t\t\t\t void *cache)\n{\n hb_set_t covered_seq_indicies;\n hb_set_t pos_glyphs;\n for (unsigned int i = 0; i < lookupCount; i++)\n {\n unsigned seqIndex = lookupRecord[i].sequenceIndex;\n if (seqIndex >= inputCount) continue;", " bool has_pos_glyphs = false;", " if (!covered_seq_indicies.has (seqIndex))\n {\n has_pos_glyphs = true;\n pos_glyphs.clear ();\n if (seqIndex == 0)\n {\n switch (context_format) {\n case ContextFormat::SimpleContext:\n pos_glyphs.add (value);\n break;\n case ContextFormat::ClassBasedContext:\n intersected_glyphs_func (&c->parent_active_glyphs (), data, value, &pos_glyphs, cache);\n break;\n case ContextFormat::CoverageBasedContext:\n pos_glyphs.set (c->parent_active_glyphs ());\n break;\n }\n }\n else\n {\n const void *input_data = input;\n unsigned input_value = seqIndex - 1;\n if (context_format != ContextFormat::SimpleContext)\n {\n input_data = data;\n input_value = input[seqIndex - 1];\n }", " intersected_glyphs_func (c->glyphs, input_data, input_value, &pos_glyphs, cache);\n }\n }", " covered_seq_indicies.add (seqIndex);\n if (has_pos_glyphs) {\n c->push_cur_active_glyphs () = std::move (pos_glyphs);\n } else {\n c->push_cur_active_glyphs ().set (*c->glyphs);\n }", " unsigned endIndex = inputCount;\n if (context_format == ContextFormat::CoverageBasedContext)\n endIndex += 1;", " c->recurse (lookupRecord[i].lookupListIndex, &covered_seq_indicies, seqIndex, endIndex);", " c->pop_cur_done_glyphs ();\n }\n}", "template <typename context_t>\nstatic inline void recurse_lookups (context_t *c,\n unsigned int lookupCount,\n const LookupRecord lookupRecord[] /* Array of LookupRecords--in design order */)\n{\n for (unsigned int i = 0; i < lookupCount; i++)\n c->recurse (lookupRecord[i].lookupListIndex);\n}", "static inline void apply_lookup (hb_ot_apply_context_t *c,\n\t\t\t\t unsigned int count, /* Including the first glyph */\n\t\t\t\t unsigned int match_positions[HB_MAX_CONTEXT_LENGTH], /* Including the first glyph */\n\t\t\t\t unsigned int lookupCount,\n\t\t\t\t const LookupRecord lookupRecord[], /* Array of LookupRecords--in design order */\n\t\t\t\t unsigned int match_end)\n{\n hb_buffer_t *buffer = c->buffer;\n int end;", " /* All positions are distance from beginning of *output* buffer.\n * Adjust. */\n {\n unsigned int bl = buffer->backtrack_len ();\n end = bl + match_end - buffer->idx;", " int delta = bl - buffer->idx;\n /* Convert positions to new indexing. */\n for (unsigned int j = 0; j < count; j++)\n match_positions[j] += delta;\n }", " for (unsigned int i = 0; i < lookupCount && buffer->successful; i++)\n {\n unsigned int idx = lookupRecord[i].sequenceIndex;\n if (idx >= count)\n continue;", " unsigned int orig_len = buffer->backtrack_len () + buffer->lookahead_len ();", " /* This can happen if earlier recursed lookups deleted many entries. */\n if (unlikely (match_positions[idx] >= orig_len))\n continue;", " if (unlikely (!buffer->move_to (match_positions[idx])))\n break;", " if (unlikely (buffer->max_ops <= 0))\n break;", " if (HB_BUFFER_MESSAGE_MORE && c->buffer->messaging ())\n {\n if (buffer->have_output)\n c->buffer->sync_so_far ();\n c->buffer->message (c->font,\n\t\t\t \"recursing to lookup %u at %u\",\n\t\t\t (unsigned) lookupRecord[i].lookupListIndex,\n\t\t\t buffer->idx);\n }", " if (!c->recurse (lookupRecord[i].lookupListIndex))\n continue;", " if (HB_BUFFER_MESSAGE_MORE && c->buffer->messaging ())\n {\n if (buffer->have_output)\n c->buffer->sync_so_far ();\n c->buffer->message (c->font,\n\t\t\t \"recursed to lookup %u\",\n\t\t\t (unsigned) lookupRecord[i].lookupListIndex);\n }", " unsigned int new_len = buffer->backtrack_len () + buffer->lookahead_len ();\n int delta = new_len - orig_len;", " if (!delta)\n continue;", " /* Recursed lookup changed buffer len. Adjust.\n *\n * TODO:\n *\n * Right now, if buffer length increased by n, we assume n new glyphs\n * were added right after the current position, and if buffer length\n * was decreased by n, we assume n match positions after the current\n * one where removed. The former (buffer length increased) case is\n * fine, but the decrease case can be improved in at least two ways,\n * both of which are significant:\n *\n * - If recursed-to lookup is MultipleSubst and buffer length\n * decreased, then it's current match position that was deleted,\n * NOT the one after it.\n *\n * - If buffer length was decreased by n, it does not necessarily\n * mean that n match positions where removed, as there recursed-to\n * lookup might had a different LookupFlag. Here's a constructed\n * case of that:\n * https://github.com/harfbuzz/harfbuzz/discussions/3538\n *\n * It should be possible to construct tests for both of these cases.\n */", " end += delta;\n if (end < int (match_positions[idx]))\n {\n /* End might end up being smaller than match_positions[idx] if the recursed\n * lookup ended up removing many items.\n * Just never rewind end beyond start of current position, since that is\n * not possible in the recursed lookup. Also adjust delta as such.\n *\n * https://bugs.chromium.org/p/chromium/issues/detail?id=659496\n * https://github.com/harfbuzz/harfbuzz/issues/1611\n */\n delta += match_positions[idx] - end;\n end = match_positions[idx];\n }", " unsigned int next = idx + 1; /* next now is the position after the recursed lookup. */", " if (delta > 0)\n {\n if (unlikely (delta + count > HB_MAX_CONTEXT_LENGTH))\n\tbreak;\n }\n else\n {\n /* NOTE: delta is non-positive. */\n delta = hb_max (delta, (int) next - (int) count);\n next -= delta;\n }", " /* Shift! */\n memmove (match_positions + next + delta, match_positions + next,\n\t (count - next) * sizeof (match_positions[0]));\n next += delta;\n count += delta;", " /* Fill in new entries. */\n for (unsigned int j = idx + 1; j < next; j++)\n match_positions[j] = match_positions[j - 1] + 1;", " /* And fixup the rest. */\n for (; next < count; next++)\n match_positions[next] += delta;\n }", " (void) buffer->move_to (end);\n}", "", "/* Contextual lookups */", "struct ContextClosureLookupContext\n{\n ContextClosureFuncs funcs;\n ContextFormat context_format;\n const void *intersects_data;\n void *intersects_cache;\n void *intersected_glyphs_cache;\n};", "struct ContextCollectGlyphsLookupContext\n{\n ContextCollectGlyphsFuncs funcs;\n const void *collect_data;\n};", "struct ContextApplyLookupContext\n{\n ContextApplyFuncs funcs;\n const void *match_data;\n};", "template <typename HBUINT>\nstatic inline bool context_intersects (const hb_set_t *glyphs,\n\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t ContextClosureLookupContext &lookup_context)\n{\n return array_is_subset_of (glyphs,\n\t\t\t inputCount ? inputCount - 1 : 0, input,\n\t\t\t lookup_context.funcs.intersects,\n\t\t\t lookup_context.intersects_data,\n\t\t\t lookup_context.intersects_cache);\n}", "template <typename HBUINT>\nstatic inline void context_closure_lookup (hb_closure_context_t *c,\n\t\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t unsigned int lookupCount,\n\t\t\t\t\t const LookupRecord lookupRecord[],\n\t\t\t\t\t unsigned value, /* Index of first glyph in Coverage or Class value in ClassDef table */\n\t\t\t\t\t ContextClosureLookupContext &lookup_context)\n{\n if (context_intersects (c->glyphs,\n\t\t\t inputCount, input,\n\t\t\t lookup_context))\n context_closure_recurse_lookups (c,\n\t\t\t\t inputCount, input,\n\t\t\t\t lookupCount, lookupRecord,\n\t\t\t\t value,\n\t\t\t\t lookup_context.context_format,\n\t\t\t\t lookup_context.intersects_data,\n\t\t\t\t lookup_context.funcs.intersected_glyphs,\n\t\t\t\t lookup_context.intersected_glyphs_cache);\n}", "template <typename HBUINT>\nstatic inline void context_collect_glyphs_lookup (hb_collect_glyphs_context_t *c,\n\t\t\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t\t unsigned int lookupCount,\n\t\t\t\t\t\t const LookupRecord lookupRecord[],\n\t\t\t\t\t\t ContextCollectGlyphsLookupContext &lookup_context)\n{\n collect_array (c, c->input,\n\t\t inputCount ? inputCount - 1 : 0, input,\n\t\t lookup_context.funcs.collect, lookup_context.collect_data);\n recurse_lookups (c,\n\t\t lookupCount, lookupRecord);\n}", "template <typename HBUINT>\nstatic inline bool context_would_apply_lookup (hb_would_apply_context_t *c,\n\t\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t unsigned int lookupCount HB_UNUSED,\n\t\t\t\t\t const LookupRecord lookupRecord[] HB_UNUSED,\n\t\t\t\t\t const ContextApplyLookupContext &lookup_context)\n{\n return would_match_input (c,\n\t\t\t inputCount, input,\n\t\t\t lookup_context.funcs.match, lookup_context.match_data);\n}", "template <typename HBUINT>\nstatic inline bool context_apply_lookup (hb_ot_apply_context_t *c,\n\t\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t unsigned int lookupCount,\n\t\t\t\t\t const LookupRecord lookupRecord[],\n\t\t\t\t\t const ContextApplyLookupContext &lookup_context)\n{\n unsigned match_end = 0;\n unsigned match_positions[HB_MAX_CONTEXT_LENGTH];\n if (match_input (c,\n\t\t inputCount, input,\n\t\t lookup_context.funcs.match, lookup_context.match_data,\n\t\t &match_end, match_positions))\n {\n c->buffer->unsafe_to_break (c->buffer->idx, match_end);\n apply_lookup (c,\n\t\t inputCount, match_positions,\n\t\t lookupCount, lookupRecord,\n\t\t match_end);\n return true;\n }\n else\n {\n c->buffer->unsafe_to_concat (c->buffer->idx, match_end);\n return false;\n }\n}", "template <typename Types>\nstruct Rule\n{\n bool intersects (const hb_set_t *glyphs, ContextClosureLookupContext &lookup_context) const\n {\n return context_intersects (glyphs,\n\t\t\t inputCount, inputZ.arrayZ,\n\t\t\t lookup_context);\n }", " void closure (hb_closure_context_t *c, unsigned value, ContextClosureLookupContext &lookup_context) const\n {\n if (unlikely (c->lookup_limit_exceeded ())) return;", " const auto &lookupRecord = StructAfter<UnsizedArrayOf<LookupRecord>>\n\t\t\t\t\t (inputZ.as_array ((inputCount ? inputCount - 1 : 0)));\n context_closure_lookup (c,\n\t\t\t inputCount, inputZ.arrayZ,\n\t\t\t lookupCount, lookupRecord.arrayZ,\n\t\t\t value, lookup_context);\n }", " void closure_lookups (hb_closure_lookups_context_t *c,\n ContextClosureLookupContext &lookup_context) const\n {\n if (unlikely (c->lookup_limit_exceeded ())) return;\n if (!intersects (c->glyphs, lookup_context)) return;", " const auto &lookupRecord = StructAfter<UnsizedArrayOf<LookupRecord>>\n\t\t\t\t\t (inputZ.as_array (inputCount ? inputCount - 1 : 0));\n recurse_lookups (c, lookupCount, lookupRecord.arrayZ);\n }", " void collect_glyphs (hb_collect_glyphs_context_t *c,\n\t\t ContextCollectGlyphsLookupContext &lookup_context) const\n {\n const auto &lookupRecord = StructAfter<UnsizedArrayOf<LookupRecord>>\n\t\t\t\t\t (inputZ.as_array (inputCount ? inputCount - 1 : 0));\n context_collect_glyphs_lookup (c,\n\t\t\t\t inputCount, inputZ.arrayZ,\n\t\t\t\t lookupCount, lookupRecord.arrayZ,\n\t\t\t\t lookup_context);\n }", " bool would_apply (hb_would_apply_context_t *c,\n\t\t const ContextApplyLookupContext &lookup_context) const\n {\n const auto &lookupRecord = StructAfter<UnsizedArrayOf<LookupRecord>>\n\t\t\t\t\t (inputZ.as_array (inputCount ? inputCount - 1 : 0));\n return context_would_apply_lookup (c,\n\t\t\t\t inputCount, inputZ.arrayZ,\n\t\t\t\t lookupCount, lookupRecord.arrayZ,\n\t\t\t\t lookup_context);\n }", " bool apply (hb_ot_apply_context_t *c,\n\t const ContextApplyLookupContext &lookup_context) const\n {\n TRACE_APPLY (this);\n const auto &lookupRecord = StructAfter<UnsizedArrayOf<LookupRecord>>\n\t\t\t\t\t (inputZ.as_array (inputCount ? inputCount - 1 : 0));\n return_trace (context_apply_lookup (c, inputCount, inputZ.arrayZ, lookupCount, lookupRecord.arrayZ, lookup_context));\n }", " bool serialize (hb_serialize_context_t *c,\n\t\t const hb_map_t *input_mapping, /* old->new glyphid or class mapping */\n\t\t const hb_map_t *lookup_map) const\n {\n TRACE_SERIALIZE (this);\n auto *out = c->start_embed (this);\n if (unlikely (!c->extend_min (out))) return_trace (false);", " out->inputCount = inputCount;\n const auto input = inputZ.as_array (inputCount - 1);\n for (const auto org : input)\n {\n HBUINT16 d;\n d = input_mapping->get (org);\n c->copy (d);\n }", " const auto &lookupRecord = StructAfter<UnsizedArrayOf<LookupRecord>>\n\t\t\t\t\t (inputZ.as_array ((inputCount ? inputCount - 1 : 0)));", " unsigned count = serialize_lookuprecord_array (c, lookupRecord.as_array (lookupCount), lookup_map);\n return_trace (c->check_assign (out->lookupCount, count, HB_SERIALIZE_ERROR_INT_OVERFLOW));\n }", " bool subset (hb_subset_context_t *c,\n\t const hb_map_t *lookup_map,\n\t const hb_map_t *klass_map = nullptr) const\n {\n TRACE_SUBSET (this);\n if (unlikely (!inputCount)) return_trace (false);\n const auto input = inputZ.as_array (inputCount - 1);", " const hb_map_t *mapping = klass_map == nullptr ? c->plan->glyph_map : klass_map;\n if (!hb_all (input, mapping)) return_trace (false);\n return_trace (serialize (c->serializer, mapping, lookup_map));\n }", " public:\n bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (inputCount.sanitize (c) &&\n\t\t lookupCount.sanitize (c) &&\n\t\t c->check_range (inputZ.arrayZ,\n\t\t\t\t inputZ.item_size * (inputCount ? inputCount - 1 : 0) +\n\t\t\t\t LookupRecord::static_size * lookupCount));\n }", " protected:\n HBUINT16\tinputCount;\t\t/* Total number of glyphs in input\n\t\t\t\t\t * glyph sequence--includes the first\n\t\t\t\t\t * glyph */\n HBUINT16\tlookupCount;\t\t/* Number of LookupRecords */\n UnsizedArrayOf<typename Types::HBUINT>\n\t\tinputZ;\t\t\t/* Array of match inputs--start with\n\t\t\t\t\t * second glyph */\n/*UnsizedArrayOf<LookupRecord>\n\t\tlookupRecordX;*/\t/* Array of LookupRecords--in\n\t\t\t\t\t * design order */\n public:\n DEFINE_SIZE_ARRAY (4, inputZ);\n};", "template <typename Types>\nstruct RuleSet\n{\n using Rule = OT::Rule<Types>;", " bool intersects (const hb_set_t *glyphs,\n\t\t ContextClosureLookupContext &lookup_context) const\n {\n return\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_map ([&] (const Rule &_) { return _.intersects (glyphs, lookup_context); })\n | hb_any\n ;\n }", " void closure (hb_closure_context_t *c, unsigned value,\n\t\tContextClosureLookupContext &lookup_context) const\n {\n if (unlikely (c->lookup_limit_exceeded ())) return;", " return\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const Rule &_) { _.closure (c, value, lookup_context); })\n ;\n }", " void closure_lookups (hb_closure_lookups_context_t *c,\n ContextClosureLookupContext &lookup_context) const\n {\n if (unlikely (c->lookup_limit_exceeded ())) return;\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const Rule &_) { _.closure_lookups (c, lookup_context); })\n ;\n }", " void collect_glyphs (hb_collect_glyphs_context_t *c,\n\t\t ContextCollectGlyphsLookupContext &lookup_context) const\n {\n return\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const Rule &_) { _.collect_glyphs (c, lookup_context); })\n ;\n }", " bool would_apply (hb_would_apply_context_t *c,\n\t\t const ContextApplyLookupContext &lookup_context) const\n {\n return\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_map ([&] (const Rule &_) { return _.would_apply (c, lookup_context); })\n | hb_any\n ;\n }", " bool apply (hb_ot_apply_context_t *c,\n\t const ContextApplyLookupContext &lookup_context) const\n {\n TRACE_APPLY (this);\n return_trace (\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_map ([&] (const Rule &_) { return _.apply (c, lookup_context); })\n | hb_any\n )\n ;\n }", " bool subset (hb_subset_context_t *c,\n\t const hb_map_t *lookup_map,\n\t const hb_map_t *klass_map = nullptr) const\n {\n TRACE_SUBSET (this);", " auto snap = c->serializer->snapshot ();\n auto *out = c->serializer->start_embed (*this);\n if (unlikely (!c->serializer->extend_min (out))) return_trace (false);", " for (const Offset16To<Rule>& _ : rule)\n {\n if (!_) continue;\n auto o_snap = c->serializer->snapshot ();\n auto *o = out->rule.serialize_append (c->serializer);\n if (unlikely (!o)) continue;", " if (!o->serialize_subset (c, _, this, lookup_map, klass_map))\n {\n\tout->rule.pop ();\n\tc->serializer->revert (o_snap);\n }\n }", " bool ret = bool (out->rule);\n if (!ret) c->serializer->revert (snap);", " return_trace (ret);\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (rule.sanitize (c, this));\n }", " protected:\n Array16OfOffset16To<Rule>\n\t\trule;\t\t\t/* Array of Rule tables\n\t\t\t\t\t * ordered by preference */\n public:\n DEFINE_SIZE_ARRAY (2, rule);\n};", "\ntemplate <typename Types>\nstruct ContextFormat1_4\n{\n using RuleSet = OT::RuleSet<Types>;", " bool intersects (const hb_set_t *glyphs) const\n {\n struct ContextClosureLookupContext lookup_context = {\n {intersects_glyph, intersected_glyph},\n ContextFormat::SimpleContext,\n nullptr\n };", " return\n + hb_zip (this+coverage, ruleSet)\n | hb_filter (*glyphs, hb_first)\n | hb_map (hb_second)\n | hb_map (hb_add (this))\n | hb_map ([&] (const RuleSet &_) { return _.intersects (glyphs, lookup_context); })\n | hb_any\n ;\n }", " bool may_have_non_1to1 () const\n { return true; }", " void closure (hb_closure_context_t *c) const\n {\n hb_set_t& cur_active_glyphs = c->push_cur_active_glyphs ();\n get_coverage ().intersect_set (c->previous_parent_active_glyphs (), cur_active_glyphs);", " struct ContextClosureLookupContext lookup_context = {\n {intersects_glyph, intersected_glyph},\n ContextFormat::SimpleContext,\n nullptr\n };", " + hb_zip (this+coverage, hb_range ((unsigned) ruleSet.len))\n | hb_filter ([&] (hb_codepoint_t _) {\n return c->previous_parent_active_glyphs ().has (_);\n }, hb_first)\n | hb_map ([&](const hb_pair_t<hb_codepoint_t, unsigned> _) { return hb_pair_t<unsigned, const RuleSet&> (_.first, this+ruleSet[_.second]); })\n | hb_apply ([&] (const hb_pair_t<unsigned, const RuleSet&>& _) { _.second.closure (c, _.first, lookup_context); })\n ;", " c->pop_cur_done_glyphs ();\n }", " void closure_lookups (hb_closure_lookups_context_t *c) const\n {\n struct ContextClosureLookupContext lookup_context = {\n {intersects_glyph, nullptr},\n ContextFormat::SimpleContext,\n nullptr\n };", " + hb_zip (this+coverage, ruleSet)\n | hb_filter (*c->glyphs, hb_first)\n | hb_map (hb_second)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const RuleSet &_) { _.closure_lookups (c, lookup_context); })\n ;\n }", " void collect_variation_indices (hb_collect_variation_indices_context_t *c) const {}", " void collect_glyphs (hb_collect_glyphs_context_t *c) const\n {\n (this+coverage).collect_coverage (c->input);", " struct ContextCollectGlyphsLookupContext lookup_context = {\n {collect_glyph},\n nullptr\n };", " + hb_iter (ruleSet)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const RuleSet &_) { _.collect_glyphs (c, lookup_context); })\n ;\n }", " bool would_apply (hb_would_apply_context_t *c) const\n {\n const RuleSet &rule_set = this+ruleSet[(this+coverage).get_coverage (c->glyphs[0])];\n struct ContextApplyLookupContext lookup_context = {\n {match_glyph},\n nullptr\n };\n return rule_set.would_apply (c, lookup_context);\n }", " const Coverage &get_coverage () const { return this+coverage; }", " bool apply (hb_ot_apply_context_t *c) const\n {\n TRACE_APPLY (this);\n unsigned int index = (this+coverage).get_coverage (c->buffer->cur().codepoint);\n if (likely (index == NOT_COVERED))\n return_trace (false);", " const RuleSet &rule_set = this+ruleSet[index];\n struct ContextApplyLookupContext lookup_context = {\n {match_glyph},\n nullptr\n };\n return_trace (rule_set.apply (c, lookup_context));\n }", " bool subset (hb_subset_context_t *c) const\n {\n TRACE_SUBSET (this);\n const hb_set_t &glyphset = *c->plan->glyphset_gsub ();\n const hb_map_t &glyph_map = *c->plan->glyph_map;", " auto *out = c->serializer->start_embed (*this);\n if (unlikely (!c->serializer->extend_min (out))) return_trace (false);\n out->format = format;", " const hb_map_t *lookup_map = c->table_tag == HB_OT_TAG_GSUB ? &c->plan->gsub_lookups : &c->plan->gpos_lookups;\n hb_sorted_vector_t<hb_codepoint_t> new_coverage;\n + hb_zip (this+coverage, ruleSet)\n | hb_filter (glyphset, hb_first)\n | hb_filter (subset_offset_array (c, out->ruleSet, this, lookup_map), hb_second)\n | hb_map (hb_first)\n | hb_map (glyph_map)\n | hb_sink (new_coverage)\n ;", " out->coverage.serialize_serialize (c->serializer, new_coverage.iter ());\n return_trace (bool (new_coverage));\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (coverage.sanitize (c, this) && ruleSet.sanitize (c, this));\n }", " protected:\n HBUINT16\tformat;\t\t\t/* Format identifier--format = 1 */\n typename Types::template OffsetTo<Coverage>\n\t\tcoverage;\t\t/* Offset to Coverage table--from\n\t\t\t\t\t * beginning of table */\n Array16Of<typename Types::template OffsetTo<RuleSet>>\n\t\truleSet;\t\t/* Array of RuleSet tables\n\t\t\t\t\t * ordered by Coverage Index */\n public:\n DEFINE_SIZE_ARRAY (2 + 2 * Types::size, ruleSet);\n};", "\ntemplate <typename Types>\nstruct ContextFormat2_5\n{\n using RuleSet = OT::RuleSet<SmallTypes>;", " bool intersects (const hb_set_t *glyphs) const\n {\n if (!(this+coverage).intersects (glyphs))\n return false;", " const ClassDef &class_def = this+classDef;", " hb_map_t cache;\n struct ContextClosureLookupContext lookup_context = {\n {intersects_class, nullptr},\n ContextFormat::ClassBasedContext,\n &class_def,\n &cache\n };", " hb_set_t retained_coverage_glyphs;\n (this+coverage).intersect_set (*glyphs, retained_coverage_glyphs);", " hb_set_t coverage_glyph_classes;\n class_def.intersected_classes (&retained_coverage_glyphs, &coverage_glyph_classes);", "\n return\n + hb_iter (ruleSet)\n | hb_map (hb_add (this))\n | hb_enumerate\n | hb_map ([&] (const hb_pair_t<unsigned, const RuleSet &> p)\n\t { return class_def.intersects_class (glyphs, p.first) &&\n\t\t coverage_glyph_classes.has (p.first) &&\n\t\t p.second.intersects (glyphs, lookup_context); })\n | hb_any\n ;\n }", " bool may_have_non_1to1 () const\n { return true; }", " void closure (hb_closure_context_t *c) const\n {\n if (!(this+coverage).intersects (c->glyphs))\n return;", " hb_set_t& cur_active_glyphs = c->push_cur_active_glyphs ();\n get_coverage ().intersect_set (c->previous_parent_active_glyphs (),\n cur_active_glyphs);", " const ClassDef &class_def = this+classDef;", " hb_map_t cache;\n intersected_class_cache_t intersected_cache;\n struct ContextClosureLookupContext lookup_context = {\n {intersects_class, intersected_class_glyphs},\n ContextFormat::ClassBasedContext,\n &class_def,\n &cache,\n &intersected_cache\n };", " + hb_enumerate (ruleSet)\n | hb_filter ([&] (unsigned _)\n { return class_def.intersects_class (&c->parent_active_glyphs (), _); },\n\t\t hb_first)\n | hb_apply ([&] (const hb_pair_t<unsigned, const typename Types::template OffsetTo<RuleSet>&> _)\n {\n const RuleSet& rule_set = this+_.second;\n rule_set.closure (c, _.first, lookup_context);\n })\n ;", " c->pop_cur_done_glyphs ();\n }", " void closure_lookups (hb_closure_lookups_context_t *c) const\n {\n if (!(this+coverage).intersects (c->glyphs))\n return;", " const ClassDef &class_def = this+classDef;", " hb_map_t cache;\n struct ContextClosureLookupContext lookup_context = {\n {intersects_class, nullptr},\n ContextFormat::ClassBasedContext,\n &class_def,\n &cache\n };", " + hb_iter (ruleSet)\n | hb_map (hb_add (this))\n | hb_enumerate\n | hb_filter ([&] (const hb_pair_t<unsigned, const RuleSet &> p)\n { return class_def.intersects_class (c->glyphs, p.first); })\n | hb_map (hb_second)\n | hb_apply ([&] (const RuleSet & _)\n { _.closure_lookups (c, lookup_context); });\n }", " void collect_variation_indices (hb_collect_variation_indices_context_t *c) const {}", " void collect_glyphs (hb_collect_glyphs_context_t *c) const\n {\n (this+coverage).collect_coverage (c->input);", " const ClassDef &class_def = this+classDef;\n struct ContextCollectGlyphsLookupContext lookup_context = {\n {collect_class},\n &class_def\n };", " + hb_iter (ruleSet)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const RuleSet &_) { _.collect_glyphs (c, lookup_context); })\n ;\n }", " bool would_apply (hb_would_apply_context_t *c) const\n {\n const ClassDef &class_def = this+classDef;\n unsigned int index = class_def.get_class (c->glyphs[0]);\n const RuleSet &rule_set = this+ruleSet[index];\n struct ContextApplyLookupContext lookup_context = {\n {match_class},\n &class_def\n };\n return rule_set.would_apply (c, lookup_context);\n }", " const Coverage &get_coverage () const { return this+coverage; }", " unsigned cache_cost () const\n {\n unsigned c = (this+classDef).cost () * ruleSet.len;\n return c >= 4 ? c : 0;\n }\n bool cache_func (hb_ot_apply_context_t *c, bool enter) const\n {\n if (enter)\n {\n if (!HB_BUFFER_TRY_ALLOCATE_VAR (c->buffer, syllable))\n\treturn false;\n auto &info = c->buffer->info;\n unsigned count = c->buffer->len;\n for (unsigned i = 0; i < count; i++)\n\tinfo[i].syllable() = 255;\n c->new_syllables = 255;\n return true;\n }\n else\n {\n c->new_syllables = (unsigned) -1;\n HB_BUFFER_DEALLOCATE_VAR (c->buffer, syllable);\n return true;\n }\n }", " bool apply (hb_ot_apply_context_t *c, bool cached = false) const\n {\n TRACE_APPLY (this);\n unsigned int index = (this+coverage).get_coverage (c->buffer->cur().codepoint);\n if (likely (index == NOT_COVERED)) return_trace (false);", " const ClassDef &class_def = this+classDef;", " struct ContextApplyLookupContext lookup_context = {\n {cached ? match_class_cached : match_class},\n &class_def\n };", " if (cached && c->buffer->cur().syllable() < 255)\n index = c->buffer->cur().syllable ();\n else\n {\n index = class_def.get_class (c->buffer->cur().codepoint);\n if (cached && index < 255)\n\tc->buffer->cur().syllable() = index;\n }\n const RuleSet &rule_set = this+ruleSet[index];\n return_trace (rule_set.apply (c, lookup_context));\n }", " bool subset (hb_subset_context_t *c) const\n {\n TRACE_SUBSET (this);\n auto *out = c->serializer->start_embed (*this);\n if (unlikely (!c->serializer->extend_min (out))) return_trace (false);\n out->format = format;\n if (unlikely (!out->coverage.serialize_subset (c, coverage, this)))\n return_trace (false);", " hb_map_t klass_map;\n out->classDef.serialize_subset (c, classDef, this, &klass_map);", " const hb_set_t* glyphset = c->plan->glyphset_gsub ();\n hb_set_t retained_coverage_glyphs;\n (this+coverage).intersect_set (*glyphset, retained_coverage_glyphs);", " hb_set_t coverage_glyph_classes;\n (this+classDef).intersected_classes (&retained_coverage_glyphs, &coverage_glyph_classes);", " const hb_map_t *lookup_map = c->table_tag == HB_OT_TAG_GSUB ? &c->plan->gsub_lookups : &c->plan->gpos_lookups;\n bool ret = true;\n int non_zero_index = -1, index = 0;\n auto snapshot = c->serializer->snapshot();\n for (const auto& _ : + hb_enumerate (ruleSet)\n\t\t\t | hb_filter (klass_map, hb_first))\n {\n auto *o = out->ruleSet.serialize_append (c->serializer);\n if (unlikely (!o))\n {\n\tret = false;\n\tbreak;\n }", " if (coverage_glyph_classes.has (_.first) &&\n\t o->serialize_subset (c, _.second, this, lookup_map, &klass_map)) {\n\tnon_zero_index = index;\n snapshot = c->serializer->snapshot();\n }", " index++;\n }", " if (!ret || non_zero_index == -1) return_trace (false);", " //prune empty trailing ruleSets\n --index;\n while (index > non_zero_index)\n {\n out->ruleSet.pop ();\n index--;\n }\n c->serializer->revert (snapshot);", " return_trace (bool (out->ruleSet));\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (coverage.sanitize (c, this) && classDef.sanitize (c, this) && ruleSet.sanitize (c, this));\n }", " protected:\n HBUINT16\tformat;\t\t\t/* Format identifier--format = 2 */\n typename Types::template OffsetTo<Coverage>\n\t\tcoverage;\t\t/* Offset to Coverage table--from\n\t\t\t\t\t * beginning of table */\n typename Types::template OffsetTo<ClassDef>\n\t\tclassDef;\t\t/* Offset to glyph ClassDef table--from\n\t\t\t\t\t * beginning of table */\n Array16Of<typename Types::template OffsetTo<RuleSet>>\n\t\truleSet;\t\t/* Array of RuleSet tables\n\t\t\t\t\t * ordered by class */\n public:\n DEFINE_SIZE_ARRAY (4 + 2 * Types::size, ruleSet);\n};", "\nstruct ContextFormat3\n{\n using RuleSet = OT::RuleSet<SmallTypes>;", " bool intersects (const hb_set_t *glyphs) const\n {\n if (!(this+coverageZ[0]).intersects (glyphs))\n return false;", " struct ContextClosureLookupContext lookup_context = {\n {intersects_coverage, nullptr},\n ContextFormat::CoverageBasedContext,\n this\n };\n return context_intersects (glyphs,\n\t\t\t glyphCount, (const HBUINT16 *) (coverageZ.arrayZ + 1),\n\t\t\t lookup_context);\n }", " bool may_have_non_1to1 () const\n { return true; }", " void closure (hb_closure_context_t *c) const\n {\n if (!(this+coverageZ[0]).intersects (c->glyphs))\n return;", " hb_set_t& cur_active_glyphs = c->push_cur_active_glyphs ();\n get_coverage ().intersect_set (c->previous_parent_active_glyphs (),\n cur_active_glyphs);", "\n const LookupRecord *lookupRecord = &StructAfter<LookupRecord> (coverageZ.as_array (glyphCount));\n struct ContextClosureLookupContext lookup_context = {\n {intersects_coverage, intersected_coverage_glyphs},\n ContextFormat::CoverageBasedContext,\n this\n };\n context_closure_lookup (c,\n\t\t\t glyphCount, (const HBUINT16 *) (coverageZ.arrayZ + 1),\n\t\t\t lookupCount, lookupRecord,\n\t\t\t 0, lookup_context);", " c->pop_cur_done_glyphs ();\n }", " void closure_lookups (hb_closure_lookups_context_t *c) const\n {\n if (!intersects (c->glyphs))\n return;\n const LookupRecord *lookupRecord = &StructAfter<LookupRecord> (coverageZ.as_array (glyphCount));\n recurse_lookups (c, lookupCount, lookupRecord);\n }", " void collect_variation_indices (hb_collect_variation_indices_context_t *c) const {}", " void collect_glyphs (hb_collect_glyphs_context_t *c) const\n {\n (this+coverageZ[0]).collect_coverage (c->input);", " const LookupRecord *lookupRecord = &StructAfter<LookupRecord> (coverageZ.as_array (glyphCount));\n struct ContextCollectGlyphsLookupContext lookup_context = {\n {collect_coverage},\n this\n };", " context_collect_glyphs_lookup (c,\n\t\t\t\t glyphCount, (const HBUINT16 *) (coverageZ.arrayZ + 1),\n\t\t\t\t lookupCount, lookupRecord,\n\t\t\t\t lookup_context);\n }", " bool would_apply (hb_would_apply_context_t *c) const\n {\n const LookupRecord *lookupRecord = &StructAfter<LookupRecord> (coverageZ.as_array (glyphCount));\n struct ContextApplyLookupContext lookup_context = {\n {match_coverage},\n this\n };\n return context_would_apply_lookup (c,\n\t\t\t\t glyphCount, (const HBUINT16 *) (coverageZ.arrayZ + 1),\n\t\t\t\t lookupCount, lookupRecord,\n\t\t\t\t lookup_context);\n }", " const Coverage &get_coverage () const { return this+coverageZ[0]; }", " bool apply (hb_ot_apply_context_t *c) const\n {\n TRACE_APPLY (this);\n unsigned int index = (this+coverageZ[0]).get_coverage (c->buffer->cur().codepoint);\n if (likely (index == NOT_COVERED)) return_trace (false);", " const LookupRecord *lookupRecord = &StructAfter<LookupRecord> (coverageZ.as_array (glyphCount));\n struct ContextApplyLookupContext lookup_context = {\n {match_coverage},\n this\n };\n return_trace (context_apply_lookup (c, glyphCount, (const HBUINT16 *) (coverageZ.arrayZ + 1), lookupCount, lookupRecord, lookup_context));\n }", " bool subset (hb_subset_context_t *c) const\n {\n TRACE_SUBSET (this);\n auto *out = c->serializer->start_embed (this);\n if (unlikely (!c->serializer->extend_min (out))) return_trace (false);", " out->format = format;\n out->glyphCount = glyphCount;", " auto coverages = coverageZ.as_array (glyphCount);", " for (const Offset16To<Coverage>& offset : coverages)\n {\n /* TODO(subset) This looks like should not be necessary to write this way. */\n auto *o = c->serializer->allocate_size<Offset16To<Coverage>> (Offset16To<Coverage>::static_size);\n if (unlikely (!o)) return_trace (false);\n if (!o->serialize_subset (c, offset, this)) return_trace (false);\n }", " const auto& lookupRecord = StructAfter<UnsizedArrayOf<LookupRecord>> (coverageZ.as_array (glyphCount));\n const hb_map_t *lookup_map = c->table_tag == HB_OT_TAG_GSUB ? &c->plan->gsub_lookups : &c->plan->gpos_lookups;", "\n unsigned count = serialize_lookuprecord_array (c->serializer, lookupRecord.as_array (lookupCount), lookup_map);\n return_trace (c->serializer->check_assign (out->lookupCount, count, HB_SERIALIZE_ERROR_INT_OVERFLOW));\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n if (!c->check_struct (this)) return_trace (false);\n unsigned int count = glyphCount;\n if (!count) return_trace (false); /* We want to access coverageZ[0] freely. */\n if (!c->check_array (coverageZ.arrayZ, count)) return_trace (false);\n for (unsigned int i = 0; i < count; i++)\n if (!coverageZ[i].sanitize (c, this)) return_trace (false);\n const LookupRecord *lookupRecord = &StructAfter<LookupRecord> (coverageZ.as_array (glyphCount));\n return_trace (c->check_array (lookupRecord, lookupCount));\n }", " protected:\n HBUINT16\tformat;\t\t\t/* Format identifier--format = 3 */\n HBUINT16\tglyphCount;\t\t/* Number of glyphs in the input glyph\n\t\t\t\t\t * sequence */\n HBUINT16\tlookupCount;\t\t/* Number of LookupRecords */\n UnsizedArrayOf<Offset16To<Coverage>>\n\t\tcoverageZ;\t\t/* Array of offsets to Coverage\n\t\t\t\t\t * table in glyph sequence order */\n/*UnsizedArrayOf<LookupRecord>\n\t\tlookupRecordX;*/\t/* Array of LookupRecords--in\n\t\t\t\t\t * design order */\n public:\n DEFINE_SIZE_ARRAY (6, coverageZ);\n};", "struct Context\n{\n template <typename context_t, typename ...Ts>\n typename context_t::return_t dispatch (context_t *c, Ts&&... ds) const\n {\n if (unlikely (!c->may_dispatch (this, &u.format))) return c->no_dispatch_return_value ();\n TRACE_DISPATCH (this, u.format);\n switch (u.format) {\n case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));\n case 2: return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));\n case 3: return_trace (c->dispatch (u.format3, std::forward<Ts> (ds)...));\n#ifndef HB_NO_BEYOND_64K\n case 4: return_trace (c->dispatch (u.format4, std::forward<Ts> (ds)...));\n case 5: return_trace (c->dispatch (u.format5, std::forward<Ts> (ds)...));\n#endif\n default:return_trace (c->default_return_value ());\n }\n }", " protected:\n union {\n HBUINT16\t\t\tformat;\t\t/* Format identifier */\n ContextFormat1_4<SmallTypes>\tformat1;\n ContextFormat2_5<SmallTypes>\tformat2;\n ContextFormat3\t\tformat3;\n#ifndef HB_NO_BEYOND_64K\n ContextFormat1_4<MediumTypes>\tformat4;\n ContextFormat2_5<MediumTypes>\tformat5;\n#endif\n } u;\n};", "\n/* Chaining Contextual lookups */", "struct ChainContextClosureLookupContext\n{\n ContextClosureFuncs funcs;\n ContextFormat context_format;\n const void *intersects_data[3];\n void *intersects_cache[3];\n void *intersected_glyphs_cache;\n};", "struct ChainContextCollectGlyphsLookupContext\n{\n ContextCollectGlyphsFuncs funcs;\n const void *collect_data[3];\n};", "struct ChainContextApplyLookupContext\n{\n ChainContextApplyFuncs funcs;\n const void *match_data[3];\n};", "template <typename HBUINT>\nstatic inline bool chain_context_intersects (const hb_set_t *glyphs,\n\t\t\t\t\t unsigned int backtrackCount,\n\t\t\t\t\t const HBUINT backtrack[],\n\t\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t unsigned int lookaheadCount,\n\t\t\t\t\t const HBUINT lookahead[],\n\t\t\t\t\t ChainContextClosureLookupContext &lookup_context)\n{\n return array_is_subset_of (glyphs,\n\t\t\t backtrackCount, backtrack,\n\t\t\t lookup_context.funcs.intersects,\n\t\t\t lookup_context.intersects_data[0],\n\t\t\t lookup_context.intersects_cache[0])\n && array_is_subset_of (glyphs,\n\t\t\t inputCount ? inputCount - 1 : 0, input,\n\t\t\t lookup_context.funcs.intersects,\n\t\t\t lookup_context.intersects_data[1],\n\t\t\t lookup_context.intersects_cache[1])\n && array_is_subset_of (glyphs,\n\t\t\t lookaheadCount, lookahead,\n\t\t\t lookup_context.funcs.intersects,\n\t\t\t lookup_context.intersects_data[2],\n\t\t\t lookup_context.intersects_cache[2]);\n}", "template <typename HBUINT>\nstatic inline void chain_context_closure_lookup (hb_closure_context_t *c,\n\t\t\t\t\t\t unsigned int backtrackCount,\n\t\t\t\t\t\t const HBUINT backtrack[],\n\t\t\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t\t unsigned int lookaheadCount,\n\t\t\t\t\t\t const HBUINT lookahead[],\n\t\t\t\t\t\t unsigned int lookupCount,\n\t\t\t\t\t\t const LookupRecord lookupRecord[],\n\t\t\t\t\t\t unsigned value,\n\t\t\t\t\t\t ChainContextClosureLookupContext &lookup_context)\n{\n if (chain_context_intersects (c->glyphs,\n\t\t\t\tbacktrackCount, backtrack,\n\t\t\t\tinputCount, input,\n\t\t\t\tlookaheadCount, lookahead,\n\t\t\t\tlookup_context))\n context_closure_recurse_lookups (c,\n\t\t inputCount, input,\n\t\t lookupCount, lookupRecord,\n\t\t value,\n\t\t lookup_context.context_format,\n\t\t lookup_context.intersects_data[1],\n\t\t lookup_context.funcs.intersected_glyphs,\n\t\t lookup_context.intersected_glyphs_cache);\n}", "template <typename HBUINT>\nstatic inline void chain_context_collect_glyphs_lookup (hb_collect_glyphs_context_t *c,\n\t\t\t\t\t\t\tunsigned int backtrackCount,\n\t\t\t\t\t\t\tconst HBUINT backtrack[],\n\t\t\t\t\t\t\tunsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t\t\tconst HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t\t\tunsigned int lookaheadCount,\n\t\t\t\t\t\t\tconst HBUINT lookahead[],\n\t\t\t\t\t\t\tunsigned int lookupCount,\n\t\t\t\t\t\t\tconst LookupRecord lookupRecord[],\n\t\t\t\t\t\t\tChainContextCollectGlyphsLookupContext &lookup_context)\n{\n collect_array (c, c->before,\n\t\t backtrackCount, backtrack,\n\t\t lookup_context.funcs.collect, lookup_context.collect_data[0]);\n collect_array (c, c->input,\n\t\t inputCount ? inputCount - 1 : 0, input,\n\t\t lookup_context.funcs.collect, lookup_context.collect_data[1]);\n collect_array (c, c->after,\n\t\t lookaheadCount, lookahead,\n\t\t lookup_context.funcs.collect, lookup_context.collect_data[2]);\n recurse_lookups (c,\n\t\t lookupCount, lookupRecord);\n}", "template <typename HBUINT>\nstatic inline bool chain_context_would_apply_lookup (hb_would_apply_context_t *c,\n\t\t\t\t\t\t unsigned int backtrackCount,\n\t\t\t\t\t\t const HBUINT backtrack[] HB_UNUSED,\n\t\t\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t\t unsigned int lookaheadCount,\n\t\t\t\t\t\t const HBUINT lookahead[] HB_UNUSED,\n\t\t\t\t\t\t unsigned int lookupCount HB_UNUSED,\n\t\t\t\t\t\t const LookupRecord lookupRecord[] HB_UNUSED,\n\t\t\t\t\t\t const ChainContextApplyLookupContext &lookup_context)\n{\n return (c->zero_context ? !backtrackCount && !lookaheadCount : true)\n && would_match_input (c,\n\t\t\t inputCount, input,\n\t\t\t lookup_context.funcs.match[1], lookup_context.match_data[1]);\n}", "template <typename HBUINT>\nstatic inline bool chain_context_apply_lookup (hb_ot_apply_context_t *c,\n\t\t\t\t\t unsigned int backtrackCount,\n\t\t\t\t\t const HBUINT backtrack[],\n\t\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t unsigned int lookaheadCount,\n\t\t\t\t\t const HBUINT lookahead[],\n\t\t\t\t\t unsigned int lookupCount,\n\t\t\t\t\t const LookupRecord lookupRecord[],\n\t\t\t\t\t const ChainContextApplyLookupContext &lookup_context)\n{\n unsigned end_index = c->buffer->idx;\n unsigned match_end = 0;\n unsigned match_positions[HB_MAX_CONTEXT_LENGTH];\n if (!(match_input (c,\n\t\t inputCount, input,\n\t\t lookup_context.funcs.match[1], lookup_context.match_data[1],\n\t\t &match_end, match_positions) && (end_index = match_end)\n && match_lookahead (c,\n\t\t\t lookaheadCount, lookahead,\n\t\t\t lookup_context.funcs.match[2], lookup_context.match_data[2],\n\t\t\t match_end, &end_index)))\n {\n c->buffer->unsafe_to_concat (c->buffer->idx, end_index);\n return false;\n }", " unsigned start_index = c->buffer->out_len;\n if (!match_backtrack (c,\n\t\t\tbacktrackCount, backtrack,\n\t\t\tlookup_context.funcs.match[0], lookup_context.match_data[0],\n\t\t\t&start_index))\n {\n c->buffer->unsafe_to_concat_from_outbuffer (start_index, end_index);\n return false;\n }", " c->buffer->unsafe_to_break_from_outbuffer (start_index, end_index);\n apply_lookup (c,\n\t\tinputCount, match_positions,\n\t\tlookupCount, lookupRecord,\n\t\tmatch_end);\n return true;\n}", "template <typename Types>\nstruct ChainRule\n{\n bool intersects (const hb_set_t *glyphs, ChainContextClosureLookupContext &lookup_context) const\n {\n const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n return chain_context_intersects (glyphs,\n\t\t\t\t backtrack.len, backtrack.arrayZ,\n\t\t\t\t input.lenP1, input.arrayZ,\n\t\t\t\t lookahead.len, lookahead.arrayZ,\n\t\t\t\t lookup_context);\n }", " void closure (hb_closure_context_t *c, unsigned value,\n\t\tChainContextClosureLookupContext &lookup_context) const\n {\n if (unlikely (c->lookup_limit_exceeded ())) return;", " const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n chain_context_closure_lookup (c,\n\t\t\t\t backtrack.len, backtrack.arrayZ,\n\t\t\t\t input.lenP1, input.arrayZ,\n\t\t\t\t lookahead.len, lookahead.arrayZ,\n\t\t\t\t lookup.len, lookup.arrayZ,\n\t\t\t\t value,\n\t\t\t\t lookup_context);\n }", " void closure_lookups (hb_closure_lookups_context_t *c,\n ChainContextClosureLookupContext &lookup_context) const\n {\n if (unlikely (c->lookup_limit_exceeded ())) return;\n if (!intersects (c->glyphs, lookup_context)) return;", " const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n recurse_lookups (c, lookup.len, lookup.arrayZ);\n }", " void collect_glyphs (hb_collect_glyphs_context_t *c,\n\t\t ChainContextCollectGlyphsLookupContext &lookup_context) const\n {\n const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n chain_context_collect_glyphs_lookup (c,\n\t\t\t\t\t backtrack.len, backtrack.arrayZ,\n\t\t\t\t\t input.lenP1, input.arrayZ,\n\t\t\t\t\t lookahead.len, lookahead.arrayZ,\n\t\t\t\t\t lookup.len, lookup.arrayZ,\n\t\t\t\t\t lookup_context);\n }", " bool would_apply (hb_would_apply_context_t *c,\n\t\t const ChainContextApplyLookupContext &lookup_context) const\n {\n const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n return chain_context_would_apply_lookup (c,\n\t\t\t\t\t backtrack.len, backtrack.arrayZ,\n\t\t\t\t\t input.lenP1, input.arrayZ,\n\t\t\t\t\t lookahead.len, lookahead.arrayZ, lookup.len,\n\t\t\t\t\t lookup.arrayZ, lookup_context);\n }", " bool apply (hb_ot_apply_context_t *c,\n\t const ChainContextApplyLookupContext &lookup_context) const\n {\n TRACE_APPLY (this);\n const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n return_trace (chain_context_apply_lookup (c,\n\t\t\t\t\t backtrack.len, backtrack.arrayZ,\n\t\t\t\t\t input.lenP1, input.arrayZ,\n\t\t\t\t\t lookahead.len, lookahead.arrayZ, lookup.len,\n\t\t\t\t\t lookup.arrayZ, lookup_context));\n }", " template<typename Iterator,\n\t hb_requires (hb_is_iterator (Iterator))>\n void serialize_array (hb_serialize_context_t *c,\n\t\t\tHBUINT16 len,\n\t\t\tIterator it) const\n {\n c->copy (len);\n for (const auto g : it)\n c->copy ((HBUINT16) g);\n }", " bool serialize (hb_serialize_context_t *c,\n\t\t const hb_map_t *lookup_map,\n\t\t const hb_map_t *backtrack_map,\n\t\t const hb_map_t *input_map = nullptr,\n\t\t const hb_map_t *lookahead_map = nullptr) const\n {\n TRACE_SERIALIZE (this);\n auto *out = c->start_embed (this);\n if (unlikely (!out)) return_trace (false);", " const hb_map_t *mapping = backtrack_map;\n serialize_array (c, backtrack.len, + backtrack.iter ()\n\t\t\t\t | hb_map (mapping));", " const auto &input = StructAfter<decltype (inputX)> (backtrack);\n if (input_map) mapping = input_map;\n serialize_array (c, input.lenP1, + input.iter ()\n\t\t\t\t | hb_map (mapping));", " const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n if (lookahead_map) mapping = lookahead_map;\n serialize_array (c, lookahead.len, + lookahead.iter ()\n\t\t\t\t | hb_map (mapping));", " const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);", " HBUINT16* lookupCount = c->embed (&(lookup.len));\n if (!lookupCount) return_trace (false);", " unsigned count = serialize_lookuprecord_array (c, lookup.as_array (), lookup_map);\n return_trace (c->check_assign (*lookupCount, count, HB_SERIALIZE_ERROR_INT_OVERFLOW));\n }", " bool subset (hb_subset_context_t *c,\n\t const hb_map_t *lookup_map,\n\t const hb_map_t *backtrack_map = nullptr,\n\t const hb_map_t *input_map = nullptr,\n\t const hb_map_t *lookahead_map = nullptr) const\n {\n TRACE_SUBSET (this);", " const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);", " if (!backtrack_map)\n {\n const hb_set_t &glyphset = *c->plan->glyphset_gsub ();\n if (!hb_all (backtrack, glyphset) ||\n\t !hb_all (input, glyphset) ||\n\t !hb_all (lookahead, glyphset))\n\treturn_trace (false);", " serialize (c->serializer, lookup_map, c->plan->glyph_map);\n }\n else\n {\n if (!hb_all (backtrack, backtrack_map) ||\n\t !hb_all (input, input_map) ||\n\t !hb_all (lookahead, lookahead_map))\n\treturn_trace (false);", " serialize (c->serializer, lookup_map, backtrack_map, input_map, lookahead_map);\n }", " return_trace (true);\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n if (!backtrack.sanitize (c)) return_trace (false);\n const auto &input = StructAfter<decltype (inputX)> (backtrack);\n if (!input.sanitize (c)) return_trace (false);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n if (!lookahead.sanitize (c)) return_trace (false);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n return_trace (lookup.sanitize (c));\n }", " protected:\n Array16Of<typename Types::HBUINT>\n\t\tbacktrack;\t\t/* Array of backtracking values\n\t\t\t\t\t * (to be matched before the input\n\t\t\t\t\t * sequence) */\n HeadlessArrayOf<typename Types::HBUINT>\n\t\tinputX;\t\t\t/* Array of input values (start with\n\t\t\t\t\t * second glyph) */\n Array16Of<typename Types::HBUINT>\n\t\tlookaheadX;\t\t/* Array of lookahead values's (to be\n\t\t\t\t\t * matched after the input sequence) */\n Array16Of<LookupRecord>\n\t\tlookupX;\t\t/* Array of LookupRecords--in\n\t\t\t\t\t * design order) */\n public:\n DEFINE_SIZE_MIN (8);\n};", "template <typename Types>\nstruct ChainRuleSet\n{\n using ChainRule = OT::ChainRule<Types>;", " bool intersects (const hb_set_t *glyphs, ChainContextClosureLookupContext &lookup_context) const\n {\n return\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_map ([&] (const ChainRule &_) { return _.intersects (glyphs, lookup_context); })\n | hb_any\n ;\n }\n void closure (hb_closure_context_t *c, unsigned value, ChainContextClosureLookupContext &lookup_context) const\n {\n if (unlikely (c->lookup_limit_exceeded ())) return;", " return\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const ChainRule &_) { _.closure (c, value, lookup_context); })\n ;\n }", " void closure_lookups (hb_closure_lookups_context_t *c,\n ChainContextClosureLookupContext &lookup_context) const\n {\n if (unlikely (c->lookup_limit_exceeded ())) return;", " + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const ChainRule &_) { _.closure_lookups (c, lookup_context); })\n ;\n }", " void collect_glyphs (hb_collect_glyphs_context_t *c, ChainContextCollectGlyphsLookupContext &lookup_context) const\n {\n return\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const ChainRule &_) { _.collect_glyphs (c, lookup_context); })\n ;\n }", " bool would_apply (hb_would_apply_context_t *c,\n\t\t const ChainContextApplyLookupContext &lookup_context) const\n {\n return\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_map ([&] (const ChainRule &_) { return _.would_apply (c, lookup_context); })\n | hb_any\n ;\n }", " bool apply (hb_ot_apply_context_t *c,\n\t const ChainContextApplyLookupContext &lookup_context) const\n {\n TRACE_APPLY (this);\n return_trace (\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_map ([&] (const ChainRule &_) { return _.apply (c, lookup_context); })\n | hb_any\n )\n ;\n }", " bool subset (hb_subset_context_t *c,\n\t const hb_map_t *lookup_map,\n\t const hb_map_t *backtrack_klass_map = nullptr,\n\t const hb_map_t *input_klass_map = nullptr,\n\t const hb_map_t *lookahead_klass_map = nullptr) const\n {\n TRACE_SUBSET (this);", " auto snap = c->serializer->snapshot ();\n auto *out = c->serializer->start_embed (*this);\n if (unlikely (!c->serializer->extend_min (out))) return_trace (false);", " for (const Offset16To<ChainRule>& _ : rule)\n {\n if (!_) continue;\n auto o_snap = c->serializer->snapshot ();\n auto *o = out->rule.serialize_append (c->serializer);\n if (unlikely (!o)) continue;", " if (!o->serialize_subset (c, _, this,\n\t\t\t\tlookup_map,\n\t\t\t\tbacktrack_klass_map,\n\t\t\t\tinput_klass_map,\n\t\t\t\tlookahead_klass_map))\n {\n\tout->rule.pop ();\n\tc->serializer->revert (o_snap);\n }\n }", " bool ret = bool (out->rule);\n if (!ret) c->serializer->revert (snap);", " return_trace (ret);\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (rule.sanitize (c, this));\n }", " protected:\n Array16OfOffset16To<ChainRule>\n\t\trule;\t\t\t/* Array of ChainRule tables\n\t\t\t\t\t * ordered by preference */\n public:\n DEFINE_SIZE_ARRAY (2, rule);\n};", "template <typename Types>\nstruct ChainContextFormat1_4\n{\n using ChainRuleSet = OT::ChainRuleSet<Types>;", " bool intersects (const hb_set_t *glyphs) const\n {\n struct ChainContextClosureLookupContext lookup_context = {\n {intersects_glyph, intersected_glyph},\n ContextFormat::SimpleContext,\n {nullptr, nullptr, nullptr}\n };", " return\n + hb_zip (this+coverage, ruleSet)\n | hb_filter (*glyphs, hb_first)\n | hb_map (hb_second)\n | hb_map (hb_add (this))\n | hb_map ([&] (const ChainRuleSet &_) { return _.intersects (glyphs, lookup_context); })\n | hb_any\n ;\n }", " bool may_have_non_1to1 () const\n { return true; }", " void closure (hb_closure_context_t *c) const\n {\n hb_set_t& cur_active_glyphs = c->push_cur_active_glyphs ();\n get_coverage ().intersect_set (c->previous_parent_active_glyphs (),\n cur_active_glyphs);", " struct ChainContextClosureLookupContext lookup_context = {\n {intersects_glyph, intersected_glyph},\n ContextFormat::SimpleContext,\n {nullptr, nullptr, nullptr}\n };", " + hb_zip (this+coverage, hb_range ((unsigned) ruleSet.len))\n | hb_filter ([&] (hb_codepoint_t _) {\n return c->previous_parent_active_glyphs ().has (_);\n }, hb_first)\n | hb_map ([&](const hb_pair_t<hb_codepoint_t, unsigned> _) { return hb_pair_t<unsigned, const ChainRuleSet&> (_.first, this+ruleSet[_.second]); })\n | hb_apply ([&] (const hb_pair_t<unsigned, const ChainRuleSet&>& _) { _.second.closure (c, _.first, lookup_context); })\n ;", " c->pop_cur_done_glyphs ();\n }", " void closure_lookups (hb_closure_lookups_context_t *c) const\n {\n struct ChainContextClosureLookupContext lookup_context = {\n {intersects_glyph, nullptr},\n ContextFormat::SimpleContext,\n {nullptr, nullptr, nullptr}\n };", " + hb_zip (this+coverage, ruleSet)\n | hb_filter (*c->glyphs, hb_first)\n | hb_map (hb_second)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const ChainRuleSet &_) { _.closure_lookups (c, lookup_context); })\n ;\n }", " void collect_variation_indices (hb_collect_variation_indices_context_t *c) const {}", " void collect_glyphs (hb_collect_glyphs_context_t *c) const\n {\n (this+coverage).collect_coverage (c->input);", " struct ChainContextCollectGlyphsLookupContext lookup_context = {\n {collect_glyph},\n {nullptr, nullptr, nullptr}\n };", " + hb_iter (ruleSet)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const ChainRuleSet &_) { _.collect_glyphs (c, lookup_context); })\n ;\n }", " bool would_apply (hb_would_apply_context_t *c) const\n {\n const ChainRuleSet &rule_set = this+ruleSet[(this+coverage).get_coverage (c->glyphs[0])];\n struct ChainContextApplyLookupContext lookup_context = {\n {{match_glyph, match_glyph, match_glyph}},\n {nullptr, nullptr, nullptr}\n };\n return rule_set.would_apply (c, lookup_context);\n }", " const Coverage &get_coverage () const { return this+coverage; }", " bool apply (hb_ot_apply_context_t *c) const\n {\n TRACE_APPLY (this);\n unsigned int index = (this+coverage).get_coverage (c->buffer->cur().codepoint);\n if (likely (index == NOT_COVERED)) return_trace (false);", " const ChainRuleSet &rule_set = this+ruleSet[index];\n struct ChainContextApplyLookupContext lookup_context = {\n {{match_glyph, match_glyph, match_glyph}},\n {nullptr, nullptr, nullptr}\n };\n return_trace (rule_set.apply (c, lookup_context));\n }", " bool subset (hb_subset_context_t *c) const\n {\n TRACE_SUBSET (this);\n const hb_set_t &glyphset = *c->plan->glyphset_gsub ();\n const hb_map_t &glyph_map = *c->plan->glyph_map;", " auto *out = c->serializer->start_embed (*this);\n if (unlikely (!c->serializer->extend_min (out))) return_trace (false);\n out->format = format;", " const hb_map_t *lookup_map = c->table_tag == HB_OT_TAG_GSUB ? &c->plan->gsub_lookups : &c->plan->gpos_lookups;\n hb_sorted_vector_t<hb_codepoint_t> new_coverage;\n + hb_zip (this+coverage, ruleSet)\n | hb_filter (glyphset, hb_first)\n | hb_filter (subset_offset_array (c, out->ruleSet, this, lookup_map), hb_second)\n | hb_map (hb_first)\n | hb_map (glyph_map)\n | hb_sink (new_coverage)\n ;", " out->coverage.serialize_serialize (c->serializer, new_coverage.iter ());\n return_trace (bool (new_coverage));\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (coverage.sanitize (c, this) && ruleSet.sanitize (c, this));\n }", " protected:\n HBUINT16\tformat;\t\t\t/* Format identifier--format = 1 */\n typename Types::template OffsetTo<Coverage>\n\t\tcoverage;\t\t/* Offset to Coverage table--from\n\t\t\t\t\t * beginning of table */\n Array16Of<typename Types::template OffsetTo<ChainRuleSet>>\n\t\truleSet;\t\t/* Array of ChainRuleSet tables\n\t\t\t\t\t * ordered by Coverage Index */\n public:\n DEFINE_SIZE_ARRAY (2 + 2 * Types::size, ruleSet);\n};", "template <typename Types>\nstruct ChainContextFormat2_5\n{\n using ChainRuleSet = OT::ChainRuleSet<SmallTypes>;", " bool intersects (const hb_set_t *glyphs) const\n {\n if (!(this+coverage).intersects (glyphs))\n return false;", " const ClassDef &backtrack_class_def = this+backtrackClassDef;\n const ClassDef &input_class_def = this+inputClassDef;\n const ClassDef &lookahead_class_def = this+lookaheadClassDef;", " hb_map_t caches[3] = {};\n struct ChainContextClosureLookupContext lookup_context = {\n {intersects_class, nullptr},\n ContextFormat::ClassBasedContext,\n {&backtrack_class_def,\n &input_class_def,\n &lookahead_class_def},\n {&caches[0], &caches[1], &caches[2]}\n };", " hb_set_t retained_coverage_glyphs;\n (this+coverage).intersect_set (*glyphs, retained_coverage_glyphs);", " hb_set_t coverage_glyph_classes;\n input_class_def.intersected_classes (&retained_coverage_glyphs, &coverage_glyph_classes);", " return\n + hb_iter (ruleSet)\n | hb_map (hb_add (this))\n | hb_enumerate\n | hb_map ([&] (const hb_pair_t<unsigned, const ChainRuleSet &> p)\n\t { return input_class_def.intersects_class (glyphs, p.first) &&\n\t\t coverage_glyph_classes.has (p.first) &&\n\t\t p.second.intersects (glyphs, lookup_context); })\n | hb_any\n ;\n }", " bool may_have_non_1to1 () const\n { return true; }", " void closure (hb_closure_context_t *c) const\n {\n if (!(this+coverage).intersects (c->glyphs))\n return;", " hb_set_t& cur_active_glyphs = c->push_cur_active_glyphs ();\n get_coverage ().intersect_set (c->previous_parent_active_glyphs (),\n cur_active_glyphs);", "\n const ClassDef &backtrack_class_def = this+backtrackClassDef;\n const ClassDef &input_class_def = this+inputClassDef;\n const ClassDef &lookahead_class_def = this+lookaheadClassDef;", " hb_map_t caches[3] = {};\n intersected_class_cache_t intersected_cache;\n struct ChainContextClosureLookupContext lookup_context = {\n {intersects_class, intersected_class_glyphs},\n ContextFormat::ClassBasedContext,\n {&backtrack_class_def,\n &input_class_def,\n &lookahead_class_def},\n {&caches[0], &caches[1], &caches[2]},\n &intersected_cache\n };", " + hb_enumerate (ruleSet)\n | hb_filter ([&] (unsigned _)\n { return input_class_def.intersects_class (&c->parent_active_glyphs (), _); },\n\t\t hb_first)\n | hb_apply ([&] (const hb_pair_t<unsigned, const typename Types::template OffsetTo<ChainRuleSet>&> _)\n {\n const ChainRuleSet& chainrule_set = this+_.second;\n chainrule_set.closure (c, _.first, lookup_context);\n })\n ;", " c->pop_cur_done_glyphs ();\n }", " void closure_lookups (hb_closure_lookups_context_t *c) const\n {\n if (!(this+coverage).intersects (c->glyphs))\n return;", " const ClassDef &backtrack_class_def = this+backtrackClassDef;\n const ClassDef &input_class_def = this+inputClassDef;\n const ClassDef &lookahead_class_def = this+lookaheadClassDef;", " hb_map_t caches[3] = {};\n struct ChainContextClosureLookupContext lookup_context = {\n {intersects_class, nullptr},\n ContextFormat::ClassBasedContext,\n {&backtrack_class_def,\n &input_class_def,\n &lookahead_class_def},\n {&caches[0], &caches[1], &caches[2]}\n };", " + hb_iter (ruleSet)\n | hb_map (hb_add (this))\n | hb_enumerate\n | hb_filter([&] (unsigned klass)\n { return input_class_def.intersects_class (c->glyphs, klass); }, hb_first)\n | hb_map (hb_second)\n | hb_apply ([&] (const ChainRuleSet &_)\n { _.closure_lookups (c, lookup_context); })\n ;\n }", " void collect_variation_indices (hb_collect_variation_indices_context_t *c) const {}", " void collect_glyphs (hb_collect_glyphs_context_t *c) const\n {\n (this+coverage).collect_coverage (c->input);", " const ClassDef &backtrack_class_def = this+backtrackClassDef;\n const ClassDef &input_class_def = this+inputClassDef;\n const ClassDef &lookahead_class_def = this+lookaheadClassDef;", " struct ChainContextCollectGlyphsLookupContext lookup_context = {\n {collect_class},\n {&backtrack_class_def,\n &input_class_def,\n &lookahead_class_def}\n };", " + hb_iter (ruleSet)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const ChainRuleSet &_) { _.collect_glyphs (c, lookup_context); })\n ;\n }", " bool would_apply (hb_would_apply_context_t *c) const\n {\n const ClassDef &backtrack_class_def = this+backtrackClassDef;\n const ClassDef &input_class_def = this+inputClassDef;\n const ClassDef &lookahead_class_def = this+lookaheadClassDef;", " unsigned int index = input_class_def.get_class (c->glyphs[0]);\n const ChainRuleSet &rule_set = this+ruleSet[index];\n struct ChainContextApplyLookupContext lookup_context = {\n {{match_class, match_class, match_class}},\n {&backtrack_class_def,\n &input_class_def,\n &lookahead_class_def}\n };\n return rule_set.would_apply (c, lookup_context);\n }", " const Coverage &get_coverage () const { return this+coverage; }", " unsigned cache_cost () const\n {\n unsigned c = (this+lookaheadClassDef).cost () * ruleSet.len;\n return c >= 4 ? c : 0;\n }\n bool cache_func (hb_ot_apply_context_t *c, bool enter) const\n {\n if (enter)\n {\n if (!HB_BUFFER_TRY_ALLOCATE_VAR (c->buffer, syllable))\n\treturn false;\n auto &info = c->buffer->info;\n unsigned count = c->buffer->len;\n for (unsigned i = 0; i < count; i++)\n\tinfo[i].syllable() = 255;\n c->new_syllables = 255;\n return true;\n }\n else\n {\n c->new_syllables = (unsigned) -1;\n HB_BUFFER_DEALLOCATE_VAR (c->buffer, syllable);\n return true;\n }\n }", " bool apply (hb_ot_apply_context_t *c, bool cached = false) const\n {\n TRACE_APPLY (this);\n unsigned int index = (this+coverage).get_coverage (c->buffer->cur().codepoint);\n if (likely (index == NOT_COVERED)) return_trace (false);", " const ClassDef &backtrack_class_def = this+backtrackClassDef;\n const ClassDef &input_class_def = this+inputClassDef;\n const ClassDef &lookahead_class_def = this+lookaheadClassDef;", " /* For ChainContextFormat2_5 we cache the LookaheadClassDef instead of InputClassDef.\n * The reason is that most heavy fonts want to identify a glyph in context and apply\n * a lookup to it. In this scenario, the length of the input sequence is one, whereas\n * the lookahead / backtrack are typically longer. The one glyph in input sequence is\n * looked-up below and no input glyph is looked up in individual rules, whereas the\n * lookahead and backtrack glyphs are tried. Since we match lookahead before backtrack,\n * we should cache lookahead. This decisions showed a 20% improvement in shaping of\n * the Gulzar font.\n */", " struct ChainContextApplyLookupContext lookup_context = {\n {{cached && &backtrack_class_def == &lookahead_class_def ? match_class_cached : match_class,\n cached && &input_class_def == &lookahead_class_def ? match_class_cached : match_class,\n cached ? match_class_cached : match_class}},\n {&backtrack_class_def,\n &input_class_def,\n &lookahead_class_def}\n };", " index = input_class_def.get_class (c->buffer->cur().codepoint);\n const ChainRuleSet &rule_set = this+ruleSet[index];\n return_trace (rule_set.apply (c, lookup_context));\n }", " bool subset (hb_subset_context_t *c) const\n {\n TRACE_SUBSET (this);\n auto *out = c->serializer->start_embed (*this);\n if (unlikely (!c->serializer->extend_min (out))) return_trace (false);\n out->format = format;\n out->coverage.serialize_subset (c, coverage, this);", " hb_map_t backtrack_klass_map;\n hb_map_t input_klass_map;\n hb_map_t lookahead_klass_map;", " out->backtrackClassDef.serialize_subset (c, backtrackClassDef, this, &backtrack_klass_map);\n // TODO: subset inputClassDef based on glyphs survived in Coverage subsetting\n out->inputClassDef.serialize_subset (c, inputClassDef, this, &input_klass_map);\n out->lookaheadClassDef.serialize_subset (c, lookaheadClassDef, this, &lookahead_klass_map);", " if (unlikely (!c->serializer->propagate_error (backtrack_klass_map,\n\t\t\t\t\t\t input_klass_map,\n\t\t\t\t\t\t lookahead_klass_map)))\n return_trace (false);", " const hb_set_t* glyphset = c->plan->glyphset_gsub ();\n hb_set_t retained_coverage_glyphs;\n (this+coverage).intersect_set (*glyphset, retained_coverage_glyphs);", " hb_set_t coverage_glyph_classes;\n (this+inputClassDef).intersected_classes (&retained_coverage_glyphs, &coverage_glyph_classes);", " int non_zero_index = -1, index = 0;\n bool ret = true;\n const hb_map_t *lookup_map = c->table_tag == HB_OT_TAG_GSUB ? &c->plan->gsub_lookups : &c->plan->gpos_lookups;\n auto last_non_zero = c->serializer->snapshot ();\n for (const auto& _ : + hb_enumerate (ruleSet)\n\t\t\t | hb_filter (input_klass_map, hb_first))\n {\n auto *o = out->ruleSet.serialize_append (c->serializer);\n if (unlikely (!o))\n {\n\tret = false;\n\tbreak;\n }\n if (coverage_glyph_classes.has (_.first) &&\n o->serialize_subset (c, _.second, this,\n\t\t\t lookup_map,\n\t\t\t &backtrack_klass_map,\n\t\t\t &input_klass_map,\n\t\t\t &lookahead_klass_map))\n {\n last_non_zero = c->serializer->snapshot ();\n\tnon_zero_index = index;\n }", " index++;\n }", " if (!ret || non_zero_index == -1) return_trace (false);", " // prune empty trailing ruleSets\n if (index > non_zero_index) {\n c->serializer->revert (last_non_zero);\n out->ruleSet.len = non_zero_index + 1;\n }", " return_trace (bool (out->ruleSet));\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (coverage.sanitize (c, this) &&\n\t\t backtrackClassDef.sanitize (c, this) &&\n\t\t inputClassDef.sanitize (c, this) &&\n\t\t lookaheadClassDef.sanitize (c, this) &&\n\t\t ruleSet.sanitize (c, this));\n }", " protected:\n HBUINT16\tformat;\t\t\t/* Format identifier--format = 2 */\n typename Types::template OffsetTo<Coverage>\n\t\tcoverage;\t\t/* Offset to Coverage table--from\n\t\t\t\t\t * beginning of table */\n typename Types::template OffsetTo<ClassDef>\n\t\tbacktrackClassDef;\t/* Offset to glyph ClassDef table\n\t\t\t\t\t * containing backtrack sequence\n\t\t\t\t\t * data--from beginning of table */\n typename Types::template OffsetTo<ClassDef>\n\t\tinputClassDef;\t\t/* Offset to glyph ClassDef\n\t\t\t\t\t * table containing input sequence\n\t\t\t\t\t * data--from beginning of table */\n typename Types::template OffsetTo<ClassDef>\n\t\tlookaheadClassDef;\t/* Offset to glyph ClassDef table\n\t\t\t\t\t * containing lookahead sequence\n\t\t\t\t\t * data--from beginning of table */\n Array16Of<typename Types::template OffsetTo<ChainRuleSet>>\n\t\truleSet;\t\t/* Array of ChainRuleSet tables\n\t\t\t\t\t * ordered by class */\n public:\n DEFINE_SIZE_ARRAY (4 + 4 * Types::size, ruleSet);\n};", "struct ChainContextFormat3\n{\n using RuleSet = OT::RuleSet<SmallTypes>;", " bool intersects (const hb_set_t *glyphs) const\n {\n const auto &input = StructAfter<decltype (inputX)> (backtrack);", " if (!(this+input[0]).intersects (glyphs))\n return false;", " const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n struct ChainContextClosureLookupContext lookup_context = {\n {intersects_coverage, nullptr},\n ContextFormat::CoverageBasedContext,\n {this, this, this}\n };\n return chain_context_intersects (glyphs,\n\t\t\t\t backtrack.len, (const HBUINT16 *) backtrack.arrayZ,\n\t\t\t\t input.len, (const HBUINT16 *) input.arrayZ + 1,\n\t\t\t\t lookahead.len, (const HBUINT16 *) lookahead.arrayZ,\n\t\t\t\t lookup_context);\n }", " bool may_have_non_1to1 () const\n { return true; }", " void closure (hb_closure_context_t *c) const\n {\n const auto &input = StructAfter<decltype (inputX)> (backtrack);", " if (!(this+input[0]).intersects (c->glyphs))\n return;", " hb_set_t& cur_active_glyphs = c->push_cur_active_glyphs ();\n get_coverage ().intersect_set (c->previous_parent_active_glyphs (),\n cur_active_glyphs);", "\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n struct ChainContextClosureLookupContext lookup_context = {\n {intersects_coverage, intersected_coverage_glyphs},\n ContextFormat::CoverageBasedContext,\n {this, this, this}\n };\n chain_context_closure_lookup (c,\n\t\t\t\t backtrack.len, (const HBUINT16 *) backtrack.arrayZ,\n\t\t\t\t input.len, (const HBUINT16 *) input.arrayZ + 1,\n\t\t\t\t lookahead.len, (const HBUINT16 *) lookahead.arrayZ,\n\t\t\t\t lookup.len, lookup.arrayZ,\n\t\t\t\t 0, lookup_context);", " c->pop_cur_done_glyphs ();\n }", " void closure_lookups (hb_closure_lookups_context_t *c) const\n {\n if (!intersects (c->glyphs))\n return;", " const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n recurse_lookups (c, lookup.len, lookup.arrayZ);\n }", " void collect_variation_indices (hb_collect_variation_indices_context_t *c) const {}", " void collect_glyphs (hb_collect_glyphs_context_t *c) const\n {\n const auto &input = StructAfter<decltype (inputX)> (backtrack);", " (this+input[0]).collect_coverage (c->input);", " const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);", " struct ChainContextCollectGlyphsLookupContext lookup_context = {\n {collect_coverage},\n {this, this, this}\n };\n chain_context_collect_glyphs_lookup (c,\n\t\t\t\t\t backtrack.len, (const HBUINT16 *) backtrack.arrayZ,\n\t\t\t\t\t input.len, (const HBUINT16 *) input.arrayZ + 1,\n\t\t\t\t\t lookahead.len, (const HBUINT16 *) lookahead.arrayZ,\n\t\t\t\t\t lookup.len, lookup.arrayZ,\n\t\t\t\t\t lookup_context);\n }", " bool would_apply (hb_would_apply_context_t *c) const\n {\n const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n struct ChainContextApplyLookupContext lookup_context = {\n {{match_coverage, match_coverage, match_coverage}},\n {this, this, this}\n };\n return chain_context_would_apply_lookup (c,\n\t\t\t\t\t backtrack.len, (const HBUINT16 *) backtrack.arrayZ,\n\t\t\t\t\t input.len, (const HBUINT16 *) input.arrayZ + 1,\n\t\t\t\t\t lookahead.len, (const HBUINT16 *) lookahead.arrayZ,\n\t\t\t\t\t lookup.len, lookup.arrayZ, lookup_context);\n }", " const Coverage &get_coverage () const\n {\n const auto &input = StructAfter<decltype (inputX)> (backtrack);\n return this+input[0];\n }", " bool apply (hb_ot_apply_context_t *c) const\n {\n TRACE_APPLY (this);\n const auto &input = StructAfter<decltype (inputX)> (backtrack);", " unsigned int index = (this+input[0]).get_coverage (c->buffer->cur().codepoint);\n if (likely (index == NOT_COVERED)) return_trace (false);", " const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n struct ChainContextApplyLookupContext lookup_context = {\n {{match_coverage, match_coverage, match_coverage}},\n {this, this, this}\n };\n return_trace (chain_context_apply_lookup (c,\n\t\t\t\t\t backtrack.len, (const HBUINT16 *) backtrack.arrayZ,\n\t\t\t\t\t input.len, (const HBUINT16 *) input.arrayZ + 1,\n\t\t\t\t\t lookahead.len, (const HBUINT16 *) lookahead.arrayZ,\n\t\t\t\t\t lookup.len, lookup.arrayZ, lookup_context));\n }", " template<typename Iterator,\n\t hb_requires (hb_is_iterator (Iterator))>\n bool serialize_coverage_offsets (hb_subset_context_t *c, Iterator it, const void* base) const\n {\n TRACE_SERIALIZE (this);\n auto *out = c->serializer->start_embed<Array16OfOffset16To<Coverage>> ();", " if (unlikely (!c->serializer->allocate_size<HBUINT16> (HBUINT16::static_size)))\n return_trace (false);", " for (auto& offset : it) {\n auto *o = out->serialize_append (c->serializer);\n if (unlikely (!o) || !o->serialize_subset (c, offset, base))\n return_trace (false);\n }", " return_trace (true);\n }", " bool subset (hb_subset_context_t *c) const\n {\n TRACE_SUBSET (this);", " auto *out = c->serializer->start_embed (this);\n if (unlikely (!out)) return_trace (false);\n if (unlikely (!c->serializer->embed (this->format))) return_trace (false);", " if (!serialize_coverage_offsets (c, backtrack.iter (), this))\n return_trace (false);", " const auto &input = StructAfter<decltype (inputX)> (backtrack);\n if (!serialize_coverage_offsets (c, input.iter (), this))\n return_trace (false);", " const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n if (!serialize_coverage_offsets (c, lookahead.iter (), this))\n return_trace (false);", " const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n const hb_map_t *lookup_map = c->table_tag == HB_OT_TAG_GSUB ? &c->plan->gsub_lookups : &c->plan->gpos_lookups;", " HBUINT16 *lookupCount = c->serializer->copy<HBUINT16> (lookup.len);\n if (!lookupCount) return_trace (false);", " unsigned count = serialize_lookuprecord_array (c->serializer, lookup.as_array (), lookup_map);\n return_trace (c->serializer->check_assign (*lookupCount, count, HB_SERIALIZE_ERROR_INT_OVERFLOW));\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n if (!backtrack.sanitize (c, this)) return_trace (false);\n const auto &input = StructAfter<decltype (inputX)> (backtrack);\n if (!input.sanitize (c, this)) return_trace (false);\n if (!input.len) return_trace (false); /* To be consistent with Context. */\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n if (!lookahead.sanitize (c, this)) return_trace (false);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n return_trace (lookup.sanitize (c));\n }", " protected:\n HBUINT16\tformat;\t\t\t/* Format identifier--format = 3 */\n Array16OfOffset16To<Coverage>\n\t\tbacktrack;\t\t/* Array of coverage tables\n\t\t\t\t\t * in backtracking sequence, in glyph\n\t\t\t\t\t * sequence order */\n Array16OfOffset16To<Coverage>\n\t\tinputX\t\t;\t/* Array of coverage\n\t\t\t\t\t * tables in input sequence, in glyph\n\t\t\t\t\t * sequence order */\n Array16OfOffset16To<Coverage>\n\t\tlookaheadX;\t\t/* Array of coverage tables\n\t\t\t\t\t * in lookahead sequence, in glyph\n\t\t\t\t\t * sequence order */\n Array16Of<LookupRecord>\n\t\tlookupX;\t\t/* Array of LookupRecords--in\n\t\t\t\t\t * design order) */\n public:\n DEFINE_SIZE_MIN (10);\n};", "struct ChainContext\n{\n template <typename context_t, typename ...Ts>\n typename context_t::return_t dispatch (context_t *c, Ts&&... ds) const\n {\n if (unlikely (!c->may_dispatch (this, &u.format))) return c->no_dispatch_return_value ();\n TRACE_DISPATCH (this, u.format);\n switch (u.format) {\n case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));\n case 2: return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));\n case 3: return_trace (c->dispatch (u.format3, std::forward<Ts> (ds)...));\n#ifndef HB_NO_BEYOND_64K\n case 4: return_trace (c->dispatch (u.format4, std::forward<Ts> (ds)...));\n case 5: return_trace (c->dispatch (u.format5, std::forward<Ts> (ds)...));\n#endif\n default:return_trace (c->default_return_value ());\n }\n }", " protected:\n union {\n HBUINT16\t\t\t\tformat;\t/* Format identifier */\n ChainContextFormat1_4<SmallTypes>\tformat1;\n ChainContextFormat2_5<SmallTypes>\tformat2;\n ChainContextFormat3\t\t\tformat3;\n#ifndef HB_NO_BEYOND_64K\n ChainContextFormat1_4<MediumTypes>\tformat4;\n ChainContextFormat2_5<MediumTypes>\tformat5;\n#endif\n } u;\n};", "\ntemplate <typename T>\nstruct ExtensionFormat1\n{\n unsigned int get_type () const { return extensionLookupType; }", " template <typename X>\n const X& get_subtable () const\n { return this + reinterpret_cast<const Offset32To<typename T::SubTable> &> (extensionOffset); }", " template <typename context_t, typename ...Ts>\n typename context_t::return_t dispatch (context_t *c, Ts&&... ds) const\n {\n if (unlikely (!c->may_dispatch (this, this))) return c->no_dispatch_return_value ();\n TRACE_DISPATCH (this, format);\n return_trace (get_subtable<typename T::SubTable> ().dispatch (c, get_type (), std::forward<Ts> (ds)...));\n }", " void collect_variation_indices (hb_collect_variation_indices_context_t *c) const\n { dispatch (c); }", " /* This is called from may_dispatch() above with hb_sanitize_context_t. */\n bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (c->check_struct (this) &&\n\t\t extensionLookupType != T::SubTable::Extension);\n }", " bool subset (hb_subset_context_t *c) const\n {\n TRACE_SUBSET (this);", " auto *out = c->serializer->start_embed (this);\n if (unlikely (!out || !c->serializer->extend_min (out))) return_trace (false);", " out->format = format;\n out->extensionLookupType = extensionLookupType;", " const auto& src_offset =\n reinterpret_cast<const Offset32To<typename T::SubTable> &> (extensionOffset);\n auto& dest_offset =\n reinterpret_cast<Offset32To<typename T::SubTable> &> (out->extensionOffset);", " return_trace (dest_offset.serialize_subset (c, src_offset, this, get_type ()));\n }", " protected:\n HBUINT16\tformat;\t\t\t/* Format identifier. Set to 1. */\n HBUINT16\textensionLookupType;\t/* Lookup type of subtable referenced\n\t\t\t\t\t * by ExtensionOffset (i.e. the\n\t\t\t\t\t * extension subtable). */\n Offset32\textensionOffset;\t/* Offset to the extension subtable,\n\t\t\t\t\t * of lookup type subtable. */\n public:\n DEFINE_SIZE_STATIC (8);\n};", "template <typename T>\nstruct Extension\n{\n unsigned int get_type () const\n {\n switch (u.format) {\n case 1: return u.format1.get_type ();\n default:return 0;\n }\n }\n template <typename X>\n const X& get_subtable () const\n {\n switch (u.format) {\n case 1: return u.format1.template get_subtable<typename T::SubTable> ();\n default:return Null (typename T::SubTable);\n }\n }", " // Specialization of dispatch for subset. dispatch() normally just\n // dispatches to the sub table this points too, but for subset\n // we need to run subset on this subtable too.\n template <typename ...Ts>\n typename hb_subset_context_t::return_t dispatch (hb_subset_context_t *c, Ts&&... ds) const\n {\n switch (u.format) {\n case 1: return u.format1.subset (c);\n default: return c->default_return_value ();\n }\n }", " template <typename context_t, typename ...Ts>\n typename context_t::return_t dispatch (context_t *c, Ts&&... ds) const\n {\n if (unlikely (!c->may_dispatch (this, &u.format))) return c->no_dispatch_return_value ();\n TRACE_DISPATCH (this, u.format);\n switch (u.format) {\n case 1: return_trace (u.format1.dispatch (c, std::forward<Ts> (ds)...));\n default:return_trace (c->default_return_value ());\n }\n }", " protected:\n union {\n HBUINT16\t\tformat;\t\t/* Format identifier */\n ExtensionFormat1<T>\tformat1;\n } u;\n};", "\n/*\n * GSUB/GPOS Common\n */", "struct hb_ot_layout_lookup_accelerator_t\n{\n template <typename TLookup>\n static hb_ot_layout_lookup_accelerator_t *create (const TLookup &lookup)\n {\n unsigned count = lookup.get_subtable_count ();", " unsigned size = sizeof (hb_ot_layout_lookup_accelerator_t) -\n\t\t HB_VAR_ARRAY * sizeof (hb_accelerate_subtables_context_t::hb_applicable_t) +\n\t\t count * sizeof (hb_accelerate_subtables_context_t::hb_applicable_t);", " /* The following is a calloc because when we are collecting subtables,\n * some of them might be invalid and hence not collect; as a result,\n * we might not fill in all the count entries of the subtables array.\n * Zeroing it allows the set digest to gatekeep it without having to\n * initialize it further. */\n auto *thiz = (hb_ot_layout_lookup_accelerator_t *) hb_calloc (1, size);\n if (unlikely (!thiz))\n return nullptr;", " hb_accelerate_subtables_context_t c_accelerate_subtables (thiz->subtables);\n lookup.dispatch (&c_accelerate_subtables);", " thiz->digest.init ();\n for (auto& subtable : hb_iter (thiz->subtables, count))\n thiz->digest.add (subtable.digest);", "#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n thiz->cache_user_idx = c_accelerate_subtables.cache_user_idx;\n for (unsigned i = 0; i < count; i++)\n if (i != thiz->cache_user_idx)\n\tthiz->subtables[i].apply_cached_func = thiz->subtables[i].apply_func;\n#endif", " return thiz;\n }", " bool may_have (hb_codepoint_t g) const\n { return digest.may_have (g); }", " bool apply (hb_ot_apply_context_t *c, unsigned subtables_count, bool use_cache) const\n {\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n if (use_cache)\n {\n return\n + hb_iter (hb_iter (subtables, subtables_count))\n | hb_map ([&c] (const hb_accelerate_subtables_context_t::hb_applicable_t &_) { return _.apply_cached (c); })\n | hb_any\n ;\n }\n else\n#endif\n {\n return\n + hb_iter (hb_iter (subtables, subtables_count))\n | hb_map ([&c] (const hb_accelerate_subtables_context_t::hb_applicable_t &_) { return _.apply (c); })\n | hb_any\n ;\n }\n return false;\n }", " bool cache_enter (hb_ot_apply_context_t *c) const\n {\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n return cache_user_idx != (unsigned) -1 &&\n\t subtables[cache_user_idx].cache_enter (c);\n#else\n return false;\n#endif\n }\n void cache_leave (hb_ot_apply_context_t *c) const\n {\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n subtables[cache_user_idx].cache_leave (c);\n#endif\n }", "\n hb_set_digest_t digest;\n private:\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n unsigned cache_user_idx = (unsigned) -1;\n#endif\n hb_accelerate_subtables_context_t::hb_applicable_t subtables[HB_VAR_ARRAY];\n};", "template <typename Types>\nstruct GSUBGPOSVersion1_2\n{\n friend struct GSUBGPOS;", " protected:\n FixedVersion<>version;\t/* Version of the GSUB/GPOS table--initially set\n\t\t\t\t * to 0x00010000u */\n typename Types:: template OffsetTo<ScriptList>\n\t\tscriptList;\t/* ScriptList table */\n typename Types::template OffsetTo<FeatureList>\n\t\tfeatureList;\t/* FeatureList table */\n typename Types::template OffsetTo<LookupList<Types>>\n\t\tlookupList;\t/* LookupList table */\n Offset32To<FeatureVariations>\n\t\tfeatureVars;\t/* Offset to Feature Variations\n\t\t\t\t table--from beginning of table\n\t\t\t\t * (may be NULL). Introduced\n\t\t\t\t * in version 0x00010001. */\n public:\n DEFINE_SIZE_MIN (4 + 3 * Types::size);", " unsigned int get_size () const\n {\n return min_size +\n\t (version.to_int () >= 0x00010001u ? featureVars.static_size : 0);\n }", " const typename Types::template OffsetTo<LookupList<Types>>* get_lookup_list_offset () const\n {\n return &lookupList;\n }", " template <typename TLookup>\n bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n typedef List16OfOffsetTo<TLookup, typename Types::HBUINT> TLookupList;\n if (unlikely (!(scriptList.sanitize (c, this) &&\n\t\t featureList.sanitize (c, this) &&\n\t\t reinterpret_cast<const typename Types::template OffsetTo<TLookupList> &> (lookupList).sanitize (c, this))))\n return_trace (false);", "#ifndef HB_NO_VAR\n if (unlikely (!(version.to_int () < 0x00010001u || featureVars.sanitize (c, this))))\n return_trace (false);\n#endif", " return_trace (true);\n }", " template <typename TLookup>\n bool subset (hb_subset_layout_context_t *c) const\n {\n TRACE_SUBSET (this);", " auto *out = c->subset_context->serializer->start_embed (this);\n if (unlikely (!c->subset_context->serializer->extend_min (out))) return_trace (false);", " out->version = version;", " typedef LookupOffsetList<TLookup, typename Types::HBUINT> TLookupList;\n reinterpret_cast<typename Types::template OffsetTo<TLookupList> &> (out->lookupList)\n\t.serialize_subset (c->subset_context,\n\t\t\t reinterpret_cast<const typename Types::template OffsetTo<TLookupList> &> (lookupList),\n\t\t\t this,\n\t\t\t c);", " reinterpret_cast<typename Types::template OffsetTo<RecordListOfFeature> &> (out->featureList)\n\t.serialize_subset (c->subset_context,\n\t\t\t reinterpret_cast<const typename Types::template OffsetTo<RecordListOfFeature> &> (featureList),\n\t\t\t this,\n\t\t\t c);", " out->scriptList.serialize_subset (c->subset_context,\n\t\t\t\t scriptList,\n\t\t\t\t this,\n\t\t\t\t c);", "#ifndef HB_NO_VAR\n if (version.to_int () >= 0x00010001u)\n {\n auto snapshot = c->subset_context->serializer->snapshot ();\n if (!c->subset_context->serializer->extend_min (&out->featureVars))\n return_trace (false);", " // TODO(qxliu76): the current implementation doesn't correctly handle feature variations\n // that are dropped by instancing when the associated conditions don't trigger.\n // Since partial instancing isn't yet supported this isn't an issue yet but will\n // need to be fixed for partial instancing.", "", " // if all axes are pinned all feature vars are dropped.\n bool ret = !c->subset_context->plan->all_axes_pinned\n && out->featureVars.serialize_subset (c->subset_context, featureVars, this, c);\n if (!ret && version.major == 1)\n {\n c->subset_context->serializer->revert (snapshot);\n\tout->version.major = 1;\n\tout->version.minor = 0;\n }\n }\n#endif", " return_trace (true);\n }\n};", "struct GSUBGPOS\n{\n unsigned int get_size () const\n {\n switch (u.version.major) {\n case 1: return u.version1.get_size ();\n#ifndef HB_NO_BEYOND_64K\n case 2: return u.version2.get_size ();\n#endif\n default: return u.version.static_size;\n }\n }", " template <typename TLookup>\n bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n if (unlikely (!u.version.sanitize (c))) return_trace (false);\n switch (u.version.major) {\n case 1: return_trace (u.version1.sanitize<TLookup> (c));\n#ifndef HB_NO_BEYOND_64K\n case 2: return_trace (u.version2.sanitize<TLookup> (c));\n#endif\n default: return_trace (true);\n }\n }", " template <typename TLookup>\n bool subset (hb_subset_layout_context_t *c) const\n {\n switch (u.version.major) {\n case 1: return u.version1.subset<TLookup> (c);\n#ifndef HB_NO_BEYOND_64K\n case 2: return u.version2.subset<TLookup> (c);\n#endif\n default: return false;\n }\n }", " const ScriptList &get_script_list () const\n {\n switch (u.version.major) {\n case 1: return this+u.version1.scriptList;\n#ifndef HB_NO_BEYOND_64K\n case 2: return this+u.version2.scriptList;\n#endif\n default: return Null (ScriptList);\n }\n }\n const FeatureList &get_feature_list () const\n {\n switch (u.version.major) {\n case 1: return this+u.version1.featureList;\n#ifndef HB_NO_BEYOND_64K\n case 2: return this+u.version2.featureList;\n#endif\n default: return Null (FeatureList);\n }\n }\n unsigned int get_lookup_count () const\n {\n switch (u.version.major) {\n case 1: return (this+u.version1.lookupList).len;\n#ifndef HB_NO_BEYOND_64K\n case 2: return (this+u.version2.lookupList).len;\n#endif\n default: return 0;\n }\n }\n const Lookup& get_lookup (unsigned int i) const\n {\n switch (u.version.major) {\n case 1: return (this+u.version1.lookupList)[i];\n#ifndef HB_NO_BEYOND_64K\n case 2: return (this+u.version2.lookupList)[i];\n#endif\n default: return Null (Lookup);\n }\n }\n const FeatureVariations &get_feature_variations () const\n {\n switch (u.version.major) {\n case 1: return (u.version.to_int () >= 0x00010001u ? this+u.version1.featureVars : Null (FeatureVariations));\n#ifndef HB_NO_BEYOND_64K\n case 2: return this+u.version2.featureVars;\n#endif\n default: return Null (FeatureVariations);\n }\n }", " bool has_data () const { return u.version.to_int (); }\n unsigned int get_script_count () const\n { return get_script_list ().len; }\n const Tag& get_script_tag (unsigned int i) const\n { return get_script_list ().get_tag (i); }\n unsigned int get_script_tags (unsigned int start_offset,\n\t\t\t\tunsigned int *script_count /* IN/OUT */,\n\t\t\t\thb_tag_t *script_tags /* OUT */) const\n { return get_script_list ().get_tags (start_offset, script_count, script_tags); }\n const Script& get_script (unsigned int i) const\n { return get_script_list ()[i]; }\n bool find_script_index (hb_tag_t tag, unsigned int *index) const\n { return get_script_list ().find_index (tag, index); }", " unsigned int get_feature_count () const\n { return get_feature_list ().len; }\n hb_tag_t get_feature_tag (unsigned int i) const\n { return i == Index::NOT_FOUND_INDEX ? HB_TAG_NONE : get_feature_list ().get_tag (i); }\n unsigned int get_feature_tags (unsigned int start_offset,\n\t\t\t\t unsigned int *feature_count /* IN/OUT */,\n\t\t\t\t hb_tag_t *feature_tags /* OUT */) const\n { return get_feature_list ().get_tags (start_offset, feature_count, feature_tags); }\n const Feature& get_feature (unsigned int i) const\n { return get_feature_list ()[i]; }\n bool find_feature_index (hb_tag_t tag, unsigned int *index) const\n { return get_feature_list ().find_index (tag, index); }", " bool find_variations_index (const int *coords, unsigned int num_coords,\n\t\t\t unsigned int *index) const\n {\n#ifdef HB_NO_VAR\n *index = FeatureVariations::NOT_FOUND_INDEX;\n return false;\n#endif\n return get_feature_variations ().find_index (coords, num_coords, index);\n }\n const Feature& get_feature_variation (unsigned int feature_index,\n\t\t\t\t\tunsigned int variations_index) const\n {\n#ifndef HB_NO_VAR\n if (FeatureVariations::NOT_FOUND_INDEX != variations_index &&\n\tu.version.to_int () >= 0x00010001u)\n {\n const Feature *feature = get_feature_variations ().find_substitute (variations_index,\n\t\t\t\t\t\t\t\t\t feature_index);\n if (feature)\n\treturn *feature;\n }\n#endif\n return get_feature (feature_index);\n }", " void feature_variation_collect_lookups (const hb_set_t *feature_indexes,\n\t\t\t\t\t const hb_hashmap_t<unsigned, const Feature*> *feature_substitutes_map,\n\t\t\t\t\t hb_set_t *lookup_indexes /* OUT */) const\n {\n#ifndef HB_NO_VAR\n get_feature_variations ().collect_lookups (feature_indexes, feature_substitutes_map, lookup_indexes);\n#endif\n }", "#ifndef HB_NO_VAR\n void collect_feature_substitutes_with_variations (hb_collect_feature_substitutes_with_var_context_t *c) const\n { get_feature_variations ().collect_feature_substitutes_with_variations (c); }\n#endif", " template <typename TLookup>\n void closure_lookups (hb_face_t *face,\n\t\t\tconst hb_set_t *glyphs,\n\t\t\thb_set_t *lookup_indexes /* IN/OUT */) const\n {\n hb_set_t visited_lookups, inactive_lookups;\n hb_closure_lookups_context_t c (face, glyphs, &visited_lookups, &inactive_lookups);", " c.set_recurse_func (TLookup::template dispatch_recurse_func<hb_closure_lookups_context_t>);", " for (unsigned lookup_index : *lookup_indexes)\n reinterpret_cast<const TLookup &> (get_lookup (lookup_index)).closure_lookups (&c, lookup_index);", " hb_set_union (lookup_indexes, &visited_lookups);\n hb_set_subtract (lookup_indexes, &inactive_lookups);\n }", " void prune_langsys (const hb_map_t *duplicate_feature_map,\n const hb_set_t *layout_scripts,\n hb_hashmap_t<unsigned, hb::unique_ptr<hb_set_t>> *script_langsys_map,\n hb_set_t *new_feature_indexes /* OUT */) const\n {\n hb_prune_langsys_context_t c (this, script_langsys_map, duplicate_feature_map, new_feature_indexes);", " unsigned count = get_script_count ();\n for (unsigned script_index = 0; script_index < count; script_index++)\n {\n const Tag& tag = get_script_tag (script_index);\n if (!layout_scripts->has (tag)) continue;\n const Script& s = get_script (script_index);\n s.prune_langsys (&c, script_index);\n }\n }", " void prune_features (const hb_map_t *lookup_indices, /* IN */\n\t\t const hb_hashmap_t<unsigned, hb::shared_ptr<hb_set_t>> *feature_record_cond_idx_map, /* IN */\n\t\t const hb_hashmap_t<unsigned, const Feature*> *feature_substitutes_map, /* IN */\n\t\t hb_set_t *feature_indices /* IN/OUT */) const\n {\n#ifndef HB_NO_VAR\n // This is the set of feature indices which have alternate versions defined\n // if the FeatureVariation's table and the alternate version(s) intersect the\n // set of lookup indices.\n hb_set_t alternate_feature_indices;\n get_feature_variations ().closure_features (lookup_indices, feature_record_cond_idx_map, &alternate_feature_indices);\n if (unlikely (alternate_feature_indices.in_error()))\n {\n feature_indices->err ();\n return;\n }\n#endif", " for (unsigned i : hb_iter (feature_indices))\n {\n hb_tag_t tag = get_feature_tag (i);\n if (tag == HB_TAG ('p', 'r', 'e', 'f'))\n // Note: Never ever drop feature 'pref', even if it's empty.\n // HarfBuzz chooses shaper for Khmer based on presence of this\n // feature.\tSee thread at:\n\t// http://lists.freedesktop.org/archives/harfbuzz/2012-November/002660.html\n continue;", "\n const Feature *f = &(get_feature (i));\n const Feature** p = nullptr;\n if (feature_substitutes_map->has (i, &p))\n f = *p;", " if (!f->featureParams.is_null () &&\n tag == HB_TAG ('s', 'i', 'z', 'e'))\n continue;", " if (!f->intersects_lookup_indexes (lookup_indices)\n#ifndef HB_NO_VAR\n && !alternate_feature_indices.has (i)\n#endif\n\t )\n\tfeature_indices->del (i);\n }\n }", " template <typename T>\n struct accelerator_t\n {\n accelerator_t (hb_face_t *face)\n {\n this->table = hb_sanitize_context_t ().reference_table<T> (face);\n if (unlikely (this->table->is_blocklisted (this->table.get_blob (), face)))\n {\n\thb_blob_destroy (this->table.get_blob ());\n\tthis->table = hb_blob_get_empty ();\n }", " this->lookup_count = table->get_lookup_count ();", " this->accels = (hb_atomic_ptr_t<hb_ot_layout_lookup_accelerator_t> *) hb_calloc (this->lookup_count, sizeof (*accels));\n if (unlikely (!this->accels))\n {\n\tthis->lookup_count = 0;\n\tthis->table.destroy ();\n\tthis->table = hb_blob_get_empty ();\n }\n }\n ~accelerator_t ()\n {\n for (unsigned int i = 0; i < this->lookup_count; i++)\n\thb_free (this->accels[i]);\n hb_free (this->accels);\n this->table.destroy ();\n }", " hb_ot_layout_lookup_accelerator_t *get_accel (unsigned lookup_index) const\n {\n if (unlikely (lookup_index >= lookup_count)) return nullptr;", " retry:\n auto *accel = accels[lookup_index].get_acquire ();\n if (unlikely (!accel))\n {\n\taccel = hb_ot_layout_lookup_accelerator_t::create (table->get_lookup (lookup_index));\n\tif (unlikely (!accel))\n\t return nullptr;", "\tif (unlikely (!accels[lookup_index].cmpexch (nullptr, accel)))\n\t{\n\t hb_free (accel);\n\t goto retry;\n\t}\n }", " return accel;\n }", " hb_blob_ptr_t<T> table;\n unsigned int lookup_count;\n hb_atomic_ptr_t<hb_ot_layout_lookup_accelerator_t> *accels;\n };", " protected:\n union {\n FixedVersion<>\t\t\tversion;\t/* Version identifier */\n GSUBGPOSVersion1_2<SmallTypes>\tversion1;\n#ifndef HB_NO_BEYOND_64K\n GSUBGPOSVersion1_2<MediumTypes>\tversion2;\n#endif\n } u;\n public:\n DEFINE_SIZE_MIN (4);\n};", "\n} /* namespace OT */", "\n#endif /* HB_OT_LAYOUT_GSUBGPOS_HH */" ]
[ 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [580], "buggy_code_start_loc": [580], "filenames": ["src/hb-ot-layout-gsubgpos.hh"], "fixing_code_end_loc": [588], "fixing_code_start_loc": [581], "message": "hb-ot-layout-gsubgpos.hh in HarfBuzz through 6.0.0 allows attackers to trigger O(n^2) growth via consecutive marks during the process of looking back for base glyphs when attaching marks.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:harfbuzz_project:harfbuzz:*:*:*:*:*:*:*:*", "matchCriteriaId": "85CABB33-5FC2-447E-BFD5-70AA07F97359", "versionEndExcluding": null, "versionEndIncluding": "6.0.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:36:*:*:*:*:*:*:*", "matchCriteriaId": "5C675112-476C-4D7C-BCB9-A2FB2D0BC9FD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "hb-ot-layout-gsubgpos.hh in HarfBuzz through 6.0.0 allows attackers to trigger O(n^2) growth via consecutive marks during the process of looking back for base glyphs when attaching marks."}], "evaluatorComment": null, "id": "CVE-2023-25193", "lastModified": "2023-03-14T05:15:29.457", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-02-04T20:15:08.027", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://chromium.googlesource.com/chromium/src/+/e1f324aa681af54101c1f2d173d92adb80e37088/DEPS#361"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/harfbuzz/harfbuzz/blob/2822b589bc837fae6f66233e2cf2eef0f6ce8470/src/hb-ot-layout-gsubgpos.hh"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/harfbuzz/harfbuzz/commit/85be877925ddbf34f74a1229f3ca1716bb6170dc"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/KWCHWSICWVZSAXP2YAXM65JC2GR53547/"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/YZ5M2GSAIHFPLHYJXUPQ2QDJCLWXUGO3/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-770"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/harfbuzz/harfbuzz/commit/85be877925ddbf34f74a1229f3ca1716bb6170dc"}, "type": "CWE-770"}
179
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright © 2007,2008,2009,2010 Red Hat, Inc.\n * Copyright © 2010,2012 Google, Inc.\n *\n * This is part of HarfBuzz, a text shaping library.\n *\n * Permission is hereby granted, without written agreement and without\n * license or royalty fees, to use, copy, modify, and distribute this\n * software and its documentation for any purpose, provided that the\n * above copyright notice and the following two paragraphs appear in\n * all copies of this software.\n *\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR\n * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES\n * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN\n * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\n * DAMAGE.\n *\n * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS\n * ON AN \"AS IS\" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO\n * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n *\n * Red Hat Author(s): Behdad Esfahbod\n * Google Author(s): Behdad Esfahbod\n */", "#ifndef HB_OT_LAYOUT_GSUBGPOS_HH\n#define HB_OT_LAYOUT_GSUBGPOS_HH", "#include \"hb.hh\"\n#include \"hb-buffer.hh\"\n#include \"hb-map.hh\"\n#include \"hb-set.hh\"\n#include \"hb-ot-map.hh\"\n#include \"hb-ot-layout-common.hh\"\n#include \"hb-ot-layout-gdef-table.hh\"", "\nnamespace OT {", "\nstruct hb_intersects_context_t :\n hb_dispatch_context_t<hb_intersects_context_t, bool>\n{\n template <typename T>\n return_t dispatch (const T &obj) { return obj.intersects (this->glyphs); }\n static return_t default_return_value () { return false; }\n bool stop_sublookup_iteration (return_t r) const { return r; }", " const hb_set_t *glyphs;", " hb_intersects_context_t (const hb_set_t *glyphs_) :\n glyphs (glyphs_) {}\n};", "struct hb_have_non_1to1_context_t :\n hb_dispatch_context_t<hb_have_non_1to1_context_t, bool>\n{\n template <typename T>\n return_t dispatch (const T &obj) { return obj.may_have_non_1to1 (); }\n static return_t default_return_value () { return false; }\n bool stop_sublookup_iteration (return_t r) const { return r; }\n};", "struct hb_closure_context_t :\n hb_dispatch_context_t<hb_closure_context_t>\n{\n typedef return_t (*recurse_func_t) (hb_closure_context_t *c, unsigned lookup_index, hb_set_t *covered_seq_indicies, unsigned seq_index, unsigned end_index);\n template <typename T>\n return_t dispatch (const T &obj) { obj.closure (this); return hb_empty_t (); }\n static return_t default_return_value () { return hb_empty_t (); }\n void recurse (unsigned lookup_index, hb_set_t *covered_seq_indicies, unsigned seq_index, unsigned end_index)\n {\n if (unlikely (nesting_level_left == 0 || !recurse_func))\n return;", " nesting_level_left--;\n recurse_func (this, lookup_index, covered_seq_indicies, seq_index, end_index);\n nesting_level_left++;\n }", " void reset_lookup_visit_count ()\n { lookup_count = 0; }", " bool lookup_limit_exceeded ()\n { return lookup_count > HB_MAX_LOOKUP_VISIT_COUNT; }", " bool should_visit_lookup (unsigned int lookup_index)\n {\n if (lookup_count++ > HB_MAX_LOOKUP_VISIT_COUNT)\n return false;", " if (is_lookup_done (lookup_index))\n return false;", " return true;\n }", " bool is_lookup_done (unsigned int lookup_index)\n {\n if (unlikely (done_lookups_glyph_count->in_error () ||\n\t\t done_lookups_glyph_set->in_error ()))\n return true;", " /* Have we visited this lookup with the current set of glyphs? */\n if (done_lookups_glyph_count->get (lookup_index) != glyphs->get_population ())\n {\n done_lookups_glyph_count->set (lookup_index, glyphs->get_population ());", " if (!done_lookups_glyph_set->has (lookup_index))\n {\n\tif (unlikely (!done_lookups_glyph_set->set (lookup_index, hb::unique_ptr<hb_set_t> {hb_set_create ()})))\n\t return true;\n }", " done_lookups_glyph_set->get (lookup_index)->clear ();\n }", " hb_set_t *covered_glyph_set = done_lookups_glyph_set->get (lookup_index);\n if (unlikely (covered_glyph_set->in_error ()))\n return true;\n if (parent_active_glyphs ().is_subset (*covered_glyph_set))\n return true;", " covered_glyph_set->union_ (parent_active_glyphs ());\n return false;\n }", " const hb_set_t& previous_parent_active_glyphs () {\n if (active_glyphs_stack.length <= 1)\n return *glyphs;", " return active_glyphs_stack[active_glyphs_stack.length - 2];\n }", " const hb_set_t& parent_active_glyphs ()\n {\n if (!active_glyphs_stack)\n return *glyphs;", " return active_glyphs_stack.tail ();\n }", " hb_set_t& push_cur_active_glyphs ()\n {\n return *active_glyphs_stack.push ();\n }", " bool pop_cur_done_glyphs ()\n {\n if (!active_glyphs_stack)\n return false;", " active_glyphs_stack.pop ();\n return true;\n }", " hb_face_t *face;\n hb_set_t *glyphs;\n hb_set_t output[1];\n hb_vector_t<hb_set_t> active_glyphs_stack;\n recurse_func_t recurse_func = nullptr;\n unsigned int nesting_level_left;", " hb_closure_context_t (hb_face_t *face_,\n\t\t\thb_set_t *glyphs_,\n\t\t\thb_map_t *done_lookups_glyph_count_,\n\t\t\thb_hashmap_t<unsigned, hb::unique_ptr<hb_set_t>> *done_lookups_glyph_set_,\n\t\t\tunsigned int nesting_level_left_ = HB_MAX_NESTING_LEVEL) :\n\t\t\t face (face_),\n\t\t\t glyphs (glyphs_),\n\t\t\t nesting_level_left (nesting_level_left_),\n\t\t\t done_lookups_glyph_count (done_lookups_glyph_count_),\n\t\t\t done_lookups_glyph_set (done_lookups_glyph_set_)\n {}", " ~hb_closure_context_t () { flush (); }", " void set_recurse_func (recurse_func_t func) { recurse_func = func; }", " void flush ()\n {\n output->del_range (face->get_num_glyphs (), HB_SET_VALUE_INVALID);\t/* Remove invalid glyphs. */\n glyphs->union_ (*output);\n output->clear ();\n active_glyphs_stack.pop ();\n active_glyphs_stack.reset ();\n }", " private:\n hb_map_t *done_lookups_glyph_count;\n hb_hashmap_t<unsigned, hb::unique_ptr<hb_set_t>> *done_lookups_glyph_set;\n unsigned int lookup_count = 0;\n};", "", "struct hb_closure_lookups_context_t :\n hb_dispatch_context_t<hb_closure_lookups_context_t>\n{\n typedef return_t (*recurse_func_t) (hb_closure_lookups_context_t *c, unsigned lookup_index);\n template <typename T>\n return_t dispatch (const T &obj) { obj.closure_lookups (this); return hb_empty_t (); }\n static return_t default_return_value () { return hb_empty_t (); }\n void recurse (unsigned lookup_index)\n {\n if (unlikely (nesting_level_left == 0 || !recurse_func))\n return;", " /* Return if new lookup was recursed to before. */\n if (lookup_limit_exceeded ()\n || visited_lookups->in_error ()\n || visited_lookups->has (lookup_index))\n // Don't increment lookup count here, that will be done in the call to closure_lookups()\n // made by recurse_func.\n return;", " nesting_level_left--;\n recurse_func (this, lookup_index);\n nesting_level_left++;\n }", " void set_lookup_visited (unsigned lookup_index)\n { visited_lookups->add (lookup_index); }", " void set_lookup_inactive (unsigned lookup_index)\n { inactive_lookups->add (lookup_index); }", " bool lookup_limit_exceeded ()\n {\n bool ret = lookup_count > HB_MAX_LOOKUP_VISIT_COUNT;\n if (ret)\n DEBUG_MSG (SUBSET, nullptr, \"lookup visit count limit exceeded in lookup closure!\");\n return ret; }", " bool is_lookup_visited (unsigned lookup_index)\n {\n if (unlikely (lookup_count++ > HB_MAX_LOOKUP_VISIT_COUNT))\n {\n DEBUG_MSG (SUBSET, nullptr, \"total visited lookup count %u exceeds max limit, lookup %u is dropped.\",\n lookup_count, lookup_index);\n return true;\n }", " if (unlikely (visited_lookups->in_error ()))\n return true;", " return visited_lookups->has (lookup_index);\n }", " hb_face_t *face;\n const hb_set_t *glyphs;\n recurse_func_t recurse_func;\n unsigned int nesting_level_left;", " hb_closure_lookups_context_t (hb_face_t *face_,\n\t\t\t\tconst hb_set_t *glyphs_,\n\t\t\t\thb_set_t *visited_lookups_,\n\t\t\t\thb_set_t *inactive_lookups_,\n\t\t\t\tunsigned nesting_level_left_ = HB_MAX_NESTING_LEVEL) :\n\t\t\t\tface (face_),\n\t\t\t\tglyphs (glyphs_),\n\t\t\t\trecurse_func (nullptr),\n\t\t\t\tnesting_level_left (nesting_level_left_),\n\t\t\t\tvisited_lookups (visited_lookups_),\n\t\t\t\tinactive_lookups (inactive_lookups_),\n\t\t\t\tlookup_count (0) {}", " void set_recurse_func (recurse_func_t func) { recurse_func = func; }", " private:\n hb_set_t *visited_lookups;\n hb_set_t *inactive_lookups;\n unsigned int lookup_count;\n};", "struct hb_would_apply_context_t :\n hb_dispatch_context_t<hb_would_apply_context_t, bool>\n{\n template <typename T>\n return_t dispatch (const T &obj) { return obj.would_apply (this); }\n static return_t default_return_value () { return false; }\n bool stop_sublookup_iteration (return_t r) const { return r; }", " hb_face_t *face;\n const hb_codepoint_t *glyphs;\n unsigned int len;\n bool zero_context;", " hb_would_apply_context_t (hb_face_t *face_,\n\t\t\t const hb_codepoint_t *glyphs_,\n\t\t\t unsigned int len_,\n\t\t\t bool zero_context_) :\n\t\t\t face (face_),\n\t\t\t glyphs (glyphs_),\n\t\t\t len (len_),\n\t\t\t zero_context (zero_context_) {}\n};", "struct hb_collect_glyphs_context_t :\n hb_dispatch_context_t<hb_collect_glyphs_context_t>\n{\n typedef return_t (*recurse_func_t) (hb_collect_glyphs_context_t *c, unsigned int lookup_index);\n template <typename T>\n return_t dispatch (const T &obj) { obj.collect_glyphs (this); return hb_empty_t (); }\n static return_t default_return_value () { return hb_empty_t (); }\n void recurse (unsigned int lookup_index)\n {\n if (unlikely (nesting_level_left == 0 || !recurse_func))\n return;", " /* Note that GPOS sets recurse_func to nullptr already, so it doesn't get\n * past the previous check. For GSUB, we only want to collect the output\n * glyphs in the recursion. If output is not requested, we can go home now.\n *\n * Note further, that the above is not exactly correct. A recursed lookup\n * is allowed to match input that is not matched in the context, but that's\n * not how most fonts are built. It's possible to relax that and recurse\n * with all sets here if it proves to be an issue.\n */", " if (output == hb_set_get_empty ())\n return;", " /* Return if new lookup was recursed to before. */\n if (recursed_lookups->has (lookup_index))\n return;", " hb_set_t *old_before = before;\n hb_set_t *old_input = input;\n hb_set_t *old_after = after;\n before = input = after = hb_set_get_empty ();", " nesting_level_left--;\n recurse_func (this, lookup_index);\n nesting_level_left++;", " before = old_before;\n input = old_input;\n after = old_after;", " recursed_lookups->add (lookup_index);\n }", " hb_face_t *face;\n hb_set_t *before;\n hb_set_t *input;\n hb_set_t *after;\n hb_set_t *output;\n recurse_func_t recurse_func;\n hb_set_t *recursed_lookups;\n unsigned int nesting_level_left;", " hb_collect_glyphs_context_t (hb_face_t *face_,\n\t\t\t hb_set_t *glyphs_before, /* OUT. May be NULL */\n\t\t\t hb_set_t *glyphs_input, /* OUT. May be NULL */\n\t\t\t hb_set_t *glyphs_after, /* OUT. May be NULL */\n\t\t\t hb_set_t *glyphs_output, /* OUT. May be NULL */\n\t\t\t unsigned int nesting_level_left_ = HB_MAX_NESTING_LEVEL) :\n\t\t\t face (face_),\n\t\t\t before (glyphs_before ? glyphs_before : hb_set_get_empty ()),\n\t\t\t input (glyphs_input ? glyphs_input : hb_set_get_empty ()),\n\t\t\t after (glyphs_after ? glyphs_after : hb_set_get_empty ()),\n\t\t\t output (glyphs_output ? glyphs_output : hb_set_get_empty ()),\n\t\t\t recurse_func (nullptr),\n\t\t\t recursed_lookups (hb_set_create ()),\n\t\t\t nesting_level_left (nesting_level_left_) {}\n ~hb_collect_glyphs_context_t () { hb_set_destroy (recursed_lookups); }", " void set_recurse_func (recurse_func_t func) { recurse_func = func; }\n};", "", "template <typename set_t>\nstruct hb_collect_coverage_context_t :\n hb_dispatch_context_t<hb_collect_coverage_context_t<set_t>, const Coverage &>\n{\n typedef const Coverage &return_t; // Stoopid that we have to dupe this here.\n template <typename T>\n return_t dispatch (const T &obj) { return obj.get_coverage (); }\n static return_t default_return_value () { return Null (Coverage); }\n bool stop_sublookup_iteration (return_t r) const\n {\n r.collect_coverage (set);\n return false;\n }", " hb_collect_coverage_context_t (set_t *set_) :\n\t\t\t\t set (set_) {}", " set_t *set;\n};", "struct hb_ot_apply_context_t :\n hb_dispatch_context_t<hb_ot_apply_context_t, bool, HB_DEBUG_APPLY>\n{\n struct matcher_t\n {\n matcher_t () :\n\t lookup_props (0),\n\t mask (-1),\n\t ignore_zwnj (false),\n\t ignore_zwj (false),\n\t per_syllable (false),\n\t syllable {0},\n\t match_func (nullptr),\n\t match_data (nullptr) {}", " typedef bool (*match_func_t) (hb_glyph_info_t &info, unsigned value, const void *data);", " void set_ignore_zwnj (bool ignore_zwnj_) { ignore_zwnj = ignore_zwnj_; }\n void set_ignore_zwj (bool ignore_zwj_) { ignore_zwj = ignore_zwj_; }\n void set_lookup_props (unsigned int lookup_props_) { lookup_props = lookup_props_; }\n void set_mask (hb_mask_t mask_) { mask = mask_; }\n void set_per_syllable (bool per_syllable_) { per_syllable = per_syllable_; }\n void set_syllable (uint8_t syllable_) { syllable = per_syllable ? syllable_ : 0; }\n void set_match_func (match_func_t match_func_,\n\t\t\t const void *match_data_)\n { match_func = match_func_; match_data = match_data_; }", " enum may_match_t {\n MATCH_NO,\n MATCH_YES,\n MATCH_MAYBE\n };", " may_match_t may_match (hb_glyph_info_t &info,\n\t\t\t hb_codepoint_t glyph_data) const\n {\n if (!(info.mask & mask) ||\n\t (syllable && syllable != info.syllable ()))\n\treturn MATCH_NO;", " if (match_func)\n\treturn match_func (info, glyph_data, match_data) ? MATCH_YES : MATCH_NO;", " return MATCH_MAYBE;\n }", " enum may_skip_t {\n SKIP_NO,\n SKIP_YES,\n SKIP_MAYBE\n };", " may_skip_t may_skip (const hb_ot_apply_context_t *c,\n\t\t\t const hb_glyph_info_t &info) const\n {\n if (!c->check_glyph_property (&info, lookup_props))\n\treturn SKIP_YES;", " if (unlikely (_hb_glyph_info_is_default_ignorable_and_not_hidden (&info) &&\n\t\t (ignore_zwnj || !_hb_glyph_info_is_zwnj (&info)) &&\n\t\t (ignore_zwj || !_hb_glyph_info_is_zwj (&info))))\n\treturn SKIP_MAYBE;", " return SKIP_NO;\n }", " protected:\n unsigned int lookup_props;\n hb_mask_t mask;\n bool ignore_zwnj;\n bool ignore_zwj;\n bool per_syllable;\n uint8_t syllable;\n match_func_t match_func;\n const void *match_data;\n };", " struct skipping_iterator_t\n {\n void init (hb_ot_apply_context_t *c_, bool context_match = false)\n {\n c = c_;\n match_glyph_data16 = nullptr;\n#ifndef HB_NO_BEYOND_64K\n match_glyph_data24 = nullptr;\n#endif\n matcher.set_match_func (nullptr, nullptr);\n matcher.set_lookup_props (c->lookup_props);\n /* Ignore ZWNJ if we are matching GPOS, or matching GSUB context and asked to. */\n matcher.set_ignore_zwnj (c->table_index == 1 || (context_match && c->auto_zwnj));\n /* Ignore ZWJ if we are matching context, or asked to. */\n matcher.set_ignore_zwj (context_match || c->auto_zwj);\n matcher.set_mask (context_match ? -1 : c->lookup_mask);\n matcher.set_per_syllable (c->per_syllable);\n }\n void set_lookup_props (unsigned int lookup_props)\n {\n matcher.set_lookup_props (lookup_props);\n }\n void set_match_func (matcher_t::match_func_t match_func_,\n\t\t\t const void *match_data_)\n {\n matcher.set_match_func (match_func_, match_data_);\n }\n void set_glyph_data (const HBUINT16 glyph_data[])\n {\n match_glyph_data16 = glyph_data;\n#ifndef HB_NO_BEYOND_64K\n match_glyph_data24 = nullptr;\n#endif\n }\n#ifndef HB_NO_BEYOND_64K\n void set_glyph_data (const HBUINT24 glyph_data[])\n {\n match_glyph_data16 = nullptr;\n match_glyph_data24 = glyph_data;\n }\n#endif", " void reset (unsigned int start_index_,\n\t\tunsigned int num_items_)\n {\n idx = start_index_;\n num_items = num_items_;\n end = c->buffer->len;\n matcher.set_syllable (start_index_ == c->buffer->idx ? c->buffer->cur().syllable () : 0);\n }", " void reject ()\n {\n num_items++;\n backup_glyph_data ();\n }", " matcher_t::may_skip_t\n may_skip (const hb_glyph_info_t &info) const\n { return matcher.may_skip (c, info); }", " bool next (unsigned *unsafe_to = nullptr)\n {\n assert (num_items > 0);\n /* The alternate condition below is faster at string boundaries,\n * but produces subpar \"unsafe-to-concat\" values. */\n signed stop = (signed) end - (signed) num_items;\n if (c->buffer->flags & HB_BUFFER_FLAG_PRODUCE_UNSAFE_TO_CONCAT)\n stop = (signed) end - 1;\n while ((signed) idx < stop)\n {\n\tidx++;\n\thb_glyph_info_t &info = c->buffer->info[idx];", "\tmatcher_t::may_skip_t skip = matcher.may_skip (c, info);\n\tif (unlikely (skip == matcher_t::SKIP_YES))\n\t continue;", "\tmatcher_t::may_match_t match = matcher.may_match (info, get_glyph_data ());\n\tif (match == matcher_t::MATCH_YES ||\n\t (match == matcher_t::MATCH_MAYBE &&\n\t skip == matcher_t::SKIP_NO))\n\t{\n\t num_items--;\n\t advance_glyph_data ();\n\t return true;\n\t}", "\tif (skip == matcher_t::SKIP_NO)\n\t{\n\t if (unsafe_to)\n\t *unsafe_to = idx + 1;\n\t return false;\n\t}\n }\n if (unsafe_to)\n *unsafe_to = end;\n return false;\n }\n bool prev (unsigned *unsafe_from = nullptr)\n {\n assert (num_items > 0);\n /* The alternate condition below is faster at string boundaries,\n * but produces subpar \"unsafe-to-concat\" values. */\n unsigned stop = num_items - 1;\n if (c->buffer->flags & HB_BUFFER_FLAG_PRODUCE_UNSAFE_TO_CONCAT)\n stop = 1 - 1;", "\n /* When looking back, limit how far we search; this function is mostly\n * used for looking back for base glyphs when attaching marks. If we\n * don't limit, we can get O(n^2) behavior where n is the number of\n * consecutive marks. */\n stop = (unsigned) hb_max ((int) stop, (int) idx - HB_MAX_CONTEXT_LENGTH);\n", " while (idx > stop)\n {\n\tidx--;\n\thb_glyph_info_t &info = c->buffer->out_info[idx];", "\tmatcher_t::may_skip_t skip = matcher.may_skip (c, info);\n\tif (unlikely (skip == matcher_t::SKIP_YES))\n\t continue;", "\tmatcher_t::may_match_t match = matcher.may_match (info, get_glyph_data ());\n\tif (match == matcher_t::MATCH_YES ||\n\t (match == matcher_t::MATCH_MAYBE &&\n\t skip == matcher_t::SKIP_NO))\n\t{\n\t num_items--;\n\t advance_glyph_data ();\n\t return true;\n\t}", "\tif (skip == matcher_t::SKIP_NO)\n\t{\n\t if (unsafe_from)\n\t *unsafe_from = hb_max (1u, idx) - 1u;\n\t return false;\n\t}\n }\n if (unsafe_from)\n *unsafe_from = 0;\n return false;\n }", " hb_codepoint_t\n get_glyph_data ()\n {\n if (match_glyph_data16) return *match_glyph_data16;\n#ifndef HB_NO_BEYOND_64K\n else\n if (match_glyph_data24) return *match_glyph_data24;\n#endif\n return 0;\n }\n void\n advance_glyph_data ()\n {\n if (match_glyph_data16) match_glyph_data16++;\n#ifndef HB_NO_BEYOND_64K\n else\n if (match_glyph_data24) match_glyph_data24++;\n#endif\n }\n void\n backup_glyph_data ()\n {\n if (match_glyph_data16) match_glyph_data16--;\n#ifndef HB_NO_BEYOND_64K\n else\n if (match_glyph_data24) match_glyph_data24--;\n#endif\n }", " unsigned int idx;\n protected:\n hb_ot_apply_context_t *c;\n matcher_t matcher;\n const HBUINT16 *match_glyph_data16;\n#ifndef HB_NO_BEYOND_64K\n const HBUINT24 *match_glyph_data24;\n#endif", " unsigned int num_items;\n unsigned int end;\n };", "\n const char *get_name () { return \"APPLY\"; }\n typedef return_t (*recurse_func_t) (hb_ot_apply_context_t *c, unsigned int lookup_index);\n template <typename T>\n return_t dispatch (const T &obj) { return obj.apply (this); }\n static return_t default_return_value () { return false; }\n bool stop_sublookup_iteration (return_t r) const { return r; }\n return_t recurse (unsigned int sub_lookup_index)\n {\n if (unlikely (nesting_level_left == 0 || !recurse_func || buffer->max_ops-- <= 0))\n {\n buffer->shaping_failed = true;\n return default_return_value ();\n }", " nesting_level_left--;\n bool ret = recurse_func (this, sub_lookup_index);\n nesting_level_left++;\n return ret;\n }", " skipping_iterator_t iter_input, iter_context;", " unsigned int table_index; /* GSUB/GPOS */\n hb_font_t *font;\n hb_face_t *face;\n hb_buffer_t *buffer;\n recurse_func_t recurse_func = nullptr;\n const GDEF &gdef;\n const VariationStore &var_store;\n VariationStore::cache_t *var_store_cache;\n hb_set_digest_t digest;", " hb_direction_t direction;\n hb_mask_t lookup_mask = 1;\n unsigned int lookup_index = (unsigned) -1;\n unsigned int lookup_props = 0;\n unsigned int nesting_level_left = HB_MAX_NESTING_LEVEL;", " bool has_glyph_classes;\n bool auto_zwnj = true;\n bool auto_zwj = true;\n bool per_syllable = false;\n bool random = false;\n uint32_t random_state = 1;\n unsigned new_syllables = (unsigned) -1;", " hb_ot_apply_context_t (unsigned int table_index_,\n\t\t\t hb_font_t *font_,\n\t\t\t hb_buffer_t *buffer_) :\n\t\t\ttable_index (table_index_),\n\t\t\tfont (font_), face (font->face), buffer (buffer_),\n\t\t\tgdef (\n#ifndef HB_NO_OT_LAYOUT\n\t\t\t *face->table.GDEF->table\n#else\n\t\t\t Null (GDEF)\n#endif\n\t\t\t ),\n\t\t\tvar_store (gdef.get_var_store ()),\n\t\t\tvar_store_cache (\n#ifndef HB_NO_VAR\n\t\t\t\t\t table_index == 1 && font->num_coords ? var_store.create_cache () : nullptr\n#else\n\t\t\t\t\t nullptr\n#endif\n\t\t\t\t\t),\n\t\t\tdigest (buffer_->digest ()),\n\t\t\tdirection (buffer_->props.direction),\n\t\t\thas_glyph_classes (gdef.has_glyph_classes ())\n { init_iters (); }", " ~hb_ot_apply_context_t ()\n {\n#ifndef HB_NO_VAR\n VariationStore::destroy_cache (var_store_cache);\n#endif\n }", " void init_iters ()\n {\n iter_input.init (this, false);\n iter_context.init (this, true);\n }", " void set_lookup_mask (hb_mask_t mask) { lookup_mask = mask; init_iters (); }\n void set_auto_zwj (bool auto_zwj_) { auto_zwj = auto_zwj_; init_iters (); }\n void set_auto_zwnj (bool auto_zwnj_) { auto_zwnj = auto_zwnj_; init_iters (); }\n void set_per_syllable (bool per_syllable_) { per_syllable = per_syllable_; init_iters (); }\n void set_random (bool random_) { random = random_; }\n void set_recurse_func (recurse_func_t func) { recurse_func = func; }\n void set_lookup_index (unsigned int lookup_index_) { lookup_index = lookup_index_; }\n void set_lookup_props (unsigned int lookup_props_) { lookup_props = lookup_props_; init_iters (); }", " uint32_t random_number ()\n {\n /* http://www.cplusplus.com/reference/random/minstd_rand/ */\n random_state = random_state * 48271 % 2147483647;\n return random_state;\n }", " bool match_properties_mark (hb_codepoint_t glyph,\n\t\t\t unsigned int glyph_props,\n\t\t\t unsigned int match_props) const\n {\n /* If using mark filtering sets, the high short of\n * match_props has the set index.\n */\n if (match_props & LookupFlag::UseMarkFilteringSet)\n return gdef.mark_set_covers (match_props >> 16, glyph);", " /* The second byte of match_props has the meaning\n * \"ignore marks of attachment type different than\n * the attachment type specified.\"\n */\n if (match_props & LookupFlag::MarkAttachmentType)\n return (match_props & LookupFlag::MarkAttachmentType) == (glyph_props & LookupFlag::MarkAttachmentType);", " return true;\n }", " bool check_glyph_property (const hb_glyph_info_t *info,\n\t\t\t unsigned int match_props) const\n {\n hb_codepoint_t glyph = info->codepoint;\n unsigned int glyph_props = _hb_glyph_info_get_glyph_props (info);", " /* Not covered, if, for example, glyph class is ligature and\n * match_props includes LookupFlags::IgnoreLigatures\n */\n if (glyph_props & match_props & LookupFlag::IgnoreFlags)\n return false;", " if (unlikely (glyph_props & HB_OT_LAYOUT_GLYPH_PROPS_MARK))\n return match_properties_mark (glyph, glyph_props, match_props);", " return true;\n }", " void _set_glyph_class (hb_codepoint_t glyph_index,\n\t\t\t unsigned int class_guess = 0,\n\t\t\t bool ligature = false,\n\t\t\t bool component = false)\n {\n digest.add (glyph_index);", " if (new_syllables != (unsigned) -1)\n buffer->cur().syllable() = new_syllables;", " unsigned int props = _hb_glyph_info_get_glyph_props (&buffer->cur());\n props |= HB_OT_LAYOUT_GLYPH_PROPS_SUBSTITUTED;\n if (ligature)\n {\n props |= HB_OT_LAYOUT_GLYPH_PROPS_LIGATED;\n /* In the only place that the MULTIPLIED bit is used, Uniscribe\n * seems to only care about the \"last\" transformation between\n * Ligature and Multiple substitutions. Ie. if you ligate, expand,\n * and ligate again, it forgives the multiplication and acts as\n * if only ligation happened. As such, clear MULTIPLIED bit.\n */\n props &= ~HB_OT_LAYOUT_GLYPH_PROPS_MULTIPLIED;\n }\n if (component)\n props |= HB_OT_LAYOUT_GLYPH_PROPS_MULTIPLIED;\n if (likely (has_glyph_classes))\n {\n props &= HB_OT_LAYOUT_GLYPH_PROPS_PRESERVE;\n _hb_glyph_info_set_glyph_props (&buffer->cur(), props | gdef.get_glyph_props (glyph_index));\n }\n else if (class_guess)\n {\n props &= HB_OT_LAYOUT_GLYPH_PROPS_PRESERVE;\n _hb_glyph_info_set_glyph_props (&buffer->cur(), props | class_guess);\n }\n else\n _hb_glyph_info_set_glyph_props (&buffer->cur(), props);\n }", " void replace_glyph (hb_codepoint_t glyph_index)\n {\n _set_glyph_class (glyph_index);\n (void) buffer->replace_glyph (glyph_index);\n }\n void replace_glyph_inplace (hb_codepoint_t glyph_index)\n {\n _set_glyph_class (glyph_index);\n buffer->cur().codepoint = glyph_index;\n }\n void replace_glyph_with_ligature (hb_codepoint_t glyph_index,\n\t\t\t\t unsigned int class_guess)\n {\n _set_glyph_class (glyph_index, class_guess, true);\n (void) buffer->replace_glyph (glyph_index);\n }\n void output_glyph_for_component (hb_codepoint_t glyph_index,\n\t\t\t\t unsigned int class_guess)\n {\n _set_glyph_class (glyph_index, class_guess, false, true);\n (void) buffer->output_glyph (glyph_index);\n }\n};", "\nstruct hb_accelerate_subtables_context_t :\n hb_dispatch_context_t<hb_accelerate_subtables_context_t>\n{\n template <typename Type>\n static inline bool apply_to (const void *obj, hb_ot_apply_context_t *c)\n {\n const Type *typed_obj = (const Type *) obj;\n return typed_obj->apply (c);\n }", "#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n template <typename T>\n static inline auto apply_cached_ (const T *obj, hb_ot_apply_context_t *c, hb_priority<1>) HB_RETURN (bool, obj->apply (c, true) )\n template <typename T>\n static inline auto apply_cached_ (const T *obj, hb_ot_apply_context_t *c, hb_priority<0>) HB_RETURN (bool, obj->apply (c) )\n template <typename Type>\n static inline bool apply_cached_to (const void *obj, hb_ot_apply_context_t *c)\n {\n const Type *typed_obj = (const Type *) obj;\n return apply_cached_ (typed_obj, c, hb_prioritize);\n }", " template <typename T>\n static inline auto cache_func_ (const T *obj, hb_ot_apply_context_t *c, bool enter, hb_priority<1>) HB_RETURN (bool, obj->cache_func (c, enter) )\n template <typename T>\n static inline bool cache_func_ (const T *obj, hb_ot_apply_context_t *c, bool enter, hb_priority<0>) { return false; }\n template <typename Type>\n static inline bool cache_func_to (const void *obj, hb_ot_apply_context_t *c, bool enter)\n {\n const Type *typed_obj = (const Type *) obj;\n return cache_func_ (typed_obj, c, enter, hb_prioritize);\n }\n#endif", " typedef bool (*hb_apply_func_t) (const void *obj, hb_ot_apply_context_t *c);\n typedef bool (*hb_cache_func_t) (const void *obj, hb_ot_apply_context_t *c, bool enter);", " struct hb_applicable_t\n {\n friend struct hb_accelerate_subtables_context_t;\n friend struct hb_ot_layout_lookup_accelerator_t;", " template <typename T>\n void init (const T &obj_,\n\t hb_apply_func_t apply_func_\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n\t , hb_apply_func_t apply_cached_func_\n\t , hb_cache_func_t cache_func_\n#endif\n\t\t)\n {\n obj = &obj_;\n apply_func = apply_func_;\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n apply_cached_func = apply_cached_func_;\n cache_func = cache_func_;\n#endif\n digest.init ();\n obj_.get_coverage ().collect_coverage (&digest);\n }", " bool apply (hb_ot_apply_context_t *c) const\n {\n return digest.may_have (c->buffer->cur().codepoint) && apply_func (obj, c);\n }\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n bool apply_cached (hb_ot_apply_context_t *c) const\n {\n return digest.may_have (c->buffer->cur().codepoint) && apply_cached_func (obj, c);\n }\n bool cache_enter (hb_ot_apply_context_t *c) const\n {\n return cache_func (obj, c, true);\n }\n void cache_leave (hb_ot_apply_context_t *c) const\n {\n cache_func (obj, c, false);\n }\n#endif", " private:\n const void *obj;\n hb_apply_func_t apply_func;\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n hb_apply_func_t apply_cached_func;\n hb_cache_func_t cache_func;\n#endif\n hb_set_digest_t digest;\n };", "#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n template <typename T>\n auto cache_cost (const T &obj, hb_priority<1>) HB_AUTO_RETURN ( obj.cache_cost () )\n template <typename T>\n auto cache_cost (const T &obj, hb_priority<0>) HB_AUTO_RETURN ( 0u )\n#endif", " /* Dispatch interface. */\n template <typename T>\n return_t dispatch (const T &obj)\n {\n hb_applicable_t *entry = &array[i++];", " entry->init (obj,\n\t\t apply_to<T>\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n\t\t , apply_cached_to<T>\n\t\t , cache_func_to<T>\n#endif\n\t\t );", "#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n /* Cache handling\n *\n * We allow one subtable from each lookup to use a cache. The assumption\n * being that multiple subtables of the same lookup cannot use a cache\n * because the resources they would use will collide. As such, we ask\n * each subtable to tell us how much it costs (which a cache would avoid),\n * and we allocate the cache opportunity to the costliest subtable.\n */\n unsigned cost = cache_cost (obj, hb_prioritize);\n if (cost > cache_user_cost)\n {\n cache_user_idx = i - 1;\n cache_user_cost = cost;\n }\n#endif", " return hb_empty_t ();\n }\n static return_t default_return_value () { return hb_empty_t (); }", " hb_accelerate_subtables_context_t (hb_applicable_t *array_) :\n\t\t\t\t array (array_) {}", " hb_applicable_t *array;\n unsigned i = 0;", "#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n unsigned cache_user_idx = (unsigned) -1;\n unsigned cache_user_cost = 0;\n#endif\n};", "\ntypedef bool (*intersects_func_t) (const hb_set_t *glyphs, unsigned value, const void *data, void *cache);\ntypedef void (*intersected_glyphs_func_t) (const hb_set_t *glyphs, const void *data, unsigned value, hb_set_t *intersected_glyphs, void *cache);\ntypedef void (*collect_glyphs_func_t) (hb_set_t *glyphs, unsigned value, const void *data);\ntypedef bool (*match_func_t) (hb_glyph_info_t &info, unsigned value, const void *data);", "struct ContextClosureFuncs\n{\n intersects_func_t intersects;\n intersected_glyphs_func_t intersected_glyphs;\n};\nstruct ContextCollectGlyphsFuncs\n{\n collect_glyphs_func_t collect;\n};\nstruct ContextApplyFuncs\n{\n match_func_t match;\n};\nstruct ChainContextApplyFuncs\n{\n match_func_t match[3];\n};", "\nstatic inline bool intersects_glyph (const hb_set_t *glyphs, unsigned value, const void *data HB_UNUSED, void *cache HB_UNUSED)\n{\n return glyphs->has (value);\n}\nstatic inline bool intersects_class (const hb_set_t *glyphs, unsigned value, const void *data, void *cache)\n{\n const ClassDef &class_def = *reinterpret_cast<const ClassDef *>(data);\n hb_map_t *map = (hb_map_t *) cache;", " hb_codepoint_t *cached_v;\n if (map->has (value, &cached_v))\n return *cached_v;", " bool v = class_def.intersects_class (glyphs, value);\n map->set (value, v);", " return v;\n}\nstatic inline bool intersects_coverage (const hb_set_t *glyphs, unsigned value, const void *data, void *cache HB_UNUSED)\n{\n Offset16To<Coverage> coverage;\n coverage = value;\n return (data+coverage).intersects (glyphs);\n}", "\nstatic inline void intersected_glyph (const hb_set_t *glyphs HB_UNUSED, const void *data, unsigned value, hb_set_t *intersected_glyphs, HB_UNUSED void *cache)\n{\n unsigned g = reinterpret_cast<const HBUINT16 *>(data)[value];\n intersected_glyphs->add (g);\n}", "using intersected_class_cache_t = hb_hashmap_t<unsigned, hb_set_t>;", "static inline void intersected_class_glyphs (const hb_set_t *glyphs, const void *data, unsigned value, hb_set_t *intersected_glyphs, void *cache)\n{\n const ClassDef &class_def = *reinterpret_cast<const ClassDef *>(data);", " intersected_class_cache_t *map = (intersected_class_cache_t *) cache;", " hb_set_t *cached_v;\n if (map->has (value, &cached_v))\n {\n intersected_glyphs->union_ (*cached_v);\n return;\n }", " hb_set_t v;\n class_def.intersected_class_glyphs (glyphs, value, &v);", " intersected_glyphs->union_ (v);", " map->set (value, std::move (v));\n}", "static inline void intersected_coverage_glyphs (const hb_set_t *glyphs, const void *data, unsigned value, hb_set_t *intersected_glyphs, HB_UNUSED void *cache)\n{\n Offset16To<Coverage> coverage;\n coverage = value;\n (data+coverage).intersect_set (*glyphs, *intersected_glyphs);\n}", "\ntemplate <typename HBUINT>\nstatic inline bool array_is_subset_of (const hb_set_t *glyphs,\n\t\t\t\t unsigned int count,\n\t\t\t\t const HBUINT values[],\n\t\t\t\t intersects_func_t intersects_func,\n\t\t\t\t const void *intersects_data,\n\t\t\t\t void *cache)\n{\n for (const auto &_ : + hb_iter (values, count))\n if (!intersects_func (glyphs, _, intersects_data, cache)) return false;\n return true;\n}", "\nstatic inline void collect_glyph (hb_set_t *glyphs, unsigned value, const void *data HB_UNUSED)\n{\n glyphs->add (value);\n}\nstatic inline void collect_class (hb_set_t *glyphs, unsigned value, const void *data)\n{\n const ClassDef &class_def = *reinterpret_cast<const ClassDef *>(data);\n class_def.collect_class (glyphs, value);\n}\nstatic inline void collect_coverage (hb_set_t *glyphs, unsigned value, const void *data)\n{\n Offset16To<Coverage> coverage;\n coverage = value;\n (data+coverage).collect_coverage (glyphs);\n}\ntemplate <typename HBUINT>\nstatic inline void collect_array (hb_collect_glyphs_context_t *c HB_UNUSED,\n\t\t\t\t hb_set_t *glyphs,\n\t\t\t\t unsigned int count,\n\t\t\t\t const HBUINT values[],\n\t\t\t\t collect_glyphs_func_t collect_func,\n\t\t\t\t const void *collect_data)\n{\n return\n + hb_iter (values, count)\n | hb_apply ([&] (const HBUINT &_) { collect_func (glyphs, _, collect_data); })\n ;\n}", "\nstatic inline bool match_glyph (hb_glyph_info_t &info, unsigned value, const void *data HB_UNUSED)\n{\n return info.codepoint == value;\n}\nstatic inline bool match_class (hb_glyph_info_t &info, unsigned value, const void *data)\n{\n const ClassDef &class_def = *reinterpret_cast<const ClassDef *>(data);\n return class_def.get_class (info.codepoint) == value;\n}\nstatic inline bool match_class_cached (hb_glyph_info_t &info, unsigned value, const void *data)\n{\n unsigned klass = info.syllable();\n if (klass < 255)\n return klass == value;\n const ClassDef &class_def = *reinterpret_cast<const ClassDef *>(data);\n klass = class_def.get_class (info.codepoint);\n if (likely (klass < 255))\n info.syllable() = klass;\n return klass == value;\n}\nstatic inline bool match_coverage (hb_glyph_info_t &info, unsigned value, const void *data)\n{\n Offset16To<Coverage> coverage;\n coverage = value;\n return (data+coverage).get_coverage (info.codepoint) != NOT_COVERED;\n}", "template <typename HBUINT>\nstatic inline bool would_match_input (hb_would_apply_context_t *c,\n\t\t\t\t unsigned int count, /* Including the first glyph (not matched) */\n\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t match_func_t match_func,\n\t\t\t\t const void *match_data)\n{\n if (count != c->len)\n return false;", " for (unsigned int i = 1; i < count; i++)\n {\n hb_glyph_info_t info;\n info.codepoint = c->glyphs[i];\n if (likely (!match_func (info, input[i - 1], match_data)))\n return false;\n }", " return true;\n}\ntemplate <typename HBUINT>\nstatic inline bool match_input (hb_ot_apply_context_t *c,\n\t\t\t\tunsigned int count, /* Including the first glyph (not matched) */\n\t\t\t\tconst HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\tmatch_func_t match_func,\n\t\t\t\tconst void *match_data,\n\t\t\t\tunsigned int *end_position,\n\t\t\t\tunsigned int match_positions[HB_MAX_CONTEXT_LENGTH],\n\t\t\t\tunsigned int *p_total_component_count = nullptr)\n{\n TRACE_APPLY (nullptr);", " if (unlikely (count > HB_MAX_CONTEXT_LENGTH)) return_trace (false);", " hb_buffer_t *buffer = c->buffer;", " hb_ot_apply_context_t::skipping_iterator_t &skippy_iter = c->iter_input;\n skippy_iter.reset (buffer->idx, count - 1);\n skippy_iter.set_match_func (match_func, match_data);\n skippy_iter.set_glyph_data (input);", " /*\n * This is perhaps the trickiest part of OpenType... Remarks:\n *\n * - If all components of the ligature were marks, we call this a mark ligature.\n *\n * - If there is no GDEF, and the ligature is NOT a mark ligature, we categorize\n * it as a ligature glyph.\n *\n * - Ligatures cannot be formed across glyphs attached to different components\n * of previous ligatures. Eg. the sequence is LAM,SHADDA,LAM,FATHA,HEH, and\n * LAM,LAM,HEH form a ligature, leaving SHADDA,FATHA next to eachother.\n * However, it would be wrong to ligate that SHADDA,FATHA sequence.\n * There are a couple of exceptions to this:\n *\n * o If a ligature tries ligating with marks that belong to it itself, go ahead,\n * assuming that the font designer knows what they are doing (otherwise it can\n * break Indic stuff when a matra wants to ligate with a conjunct,\n *\n * o If two marks want to ligate and they belong to different components of the\n * same ligature glyph, and said ligature glyph is to be ignored according to\n * mark-filtering rules, then allow.\n * https://github.com/harfbuzz/harfbuzz/issues/545\n */", " unsigned int total_component_count = 0;\n total_component_count += _hb_glyph_info_get_lig_num_comps (&buffer->cur());", " unsigned int first_lig_id = _hb_glyph_info_get_lig_id (&buffer->cur());\n unsigned int first_lig_comp = _hb_glyph_info_get_lig_comp (&buffer->cur());", " enum {\n LIGBASE_NOT_CHECKED,\n LIGBASE_MAY_NOT_SKIP,\n LIGBASE_MAY_SKIP\n } ligbase = LIGBASE_NOT_CHECKED;", " match_positions[0] = buffer->idx;\n for (unsigned int i = 1; i < count; i++)\n {\n unsigned unsafe_to;\n if (!skippy_iter.next (&unsafe_to))\n {\n *end_position = unsafe_to;\n return_trace (false);\n }", " match_positions[i] = skippy_iter.idx;", " unsigned int this_lig_id = _hb_glyph_info_get_lig_id (&buffer->info[skippy_iter.idx]);\n unsigned int this_lig_comp = _hb_glyph_info_get_lig_comp (&buffer->info[skippy_iter.idx]);", " if (first_lig_id && first_lig_comp)\n {\n /* If first component was attached to a previous ligature component,\n * all subsequent components should be attached to the same ligature\n * component, otherwise we shouldn't ligate them... */\n if (first_lig_id != this_lig_id || first_lig_comp != this_lig_comp)\n {\n\t/* ...unless, we are attached to a base ligature and that base\n\t * ligature is ignorable. */\n\tif (ligbase == LIGBASE_NOT_CHECKED)\n\t{\n\t bool found = false;\n\t const auto *out = buffer->out_info;\n\t unsigned int j = buffer->out_len;\n\t while (j && _hb_glyph_info_get_lig_id (&out[j - 1]) == first_lig_id)\n\t {\n\t if (_hb_glyph_info_get_lig_comp (&out[j - 1]) == 0)\n\t {\n\t j--;\n\t found = true;\n\t break;\n\t }\n\t j--;\n\t }", "\t if (found && skippy_iter.may_skip (out[j]) == hb_ot_apply_context_t::matcher_t::SKIP_YES)\n\t ligbase = LIGBASE_MAY_SKIP;\n\t else\n\t ligbase = LIGBASE_MAY_NOT_SKIP;\n\t}", "\tif (ligbase == LIGBASE_MAY_NOT_SKIP)\n\t return_trace (false);\n }\n }\n else\n {\n /* If first component was NOT attached to a previous ligature component,\n * all subsequent components should also NOT be attached to any ligature\n * component, unless they are attached to the first component itself! */\n if (this_lig_id && this_lig_comp && (this_lig_id != first_lig_id))\n\treturn_trace (false);\n }", " total_component_count += _hb_glyph_info_get_lig_num_comps (&buffer->info[skippy_iter.idx]);\n }", " *end_position = skippy_iter.idx + 1;", " if (p_total_component_count)\n *p_total_component_count = total_component_count;", " return_trace (true);\n}\nstatic inline bool ligate_input (hb_ot_apply_context_t *c,\n\t\t\t\t unsigned int count, /* Including the first glyph */\n\t\t\t\t const unsigned int match_positions[HB_MAX_CONTEXT_LENGTH], /* Including the first glyph */\n\t\t\t\t unsigned int match_end,\n\t\t\t\t hb_codepoint_t lig_glyph,\n\t\t\t\t unsigned int total_component_count)\n{\n TRACE_APPLY (nullptr);", " hb_buffer_t *buffer = c->buffer;", " buffer->merge_clusters (buffer->idx, match_end);", " /* - If a base and one or more marks ligate, consider that as a base, NOT\n * ligature, such that all following marks can still attach to it.\n * https://github.com/harfbuzz/harfbuzz/issues/1109\n *\n * - If all components of the ligature were marks, we call this a mark ligature.\n * If it *is* a mark ligature, we don't allocate a new ligature id, and leave\n * the ligature to keep its old ligature id. This will allow it to attach to\n * a base ligature in GPOS. Eg. if the sequence is: LAM,LAM,SHADDA,FATHA,HEH,\n * and LAM,LAM,HEH for a ligature, they will leave SHADDA and FATHA with a\n * ligature id and component value of 2. Then if SHADDA,FATHA form a ligature\n * later, we don't want them to lose their ligature id/component, otherwise\n * GPOS will fail to correctly position the mark ligature on top of the\n * LAM,LAM,HEH ligature. See:\n * https://bugzilla.gnome.org/show_bug.cgi?id=676343\n *\n * - If a ligature is formed of components that some of which are also ligatures\n * themselves, and those ligature components had marks attached to *their*\n * components, we have to attach the marks to the new ligature component\n * positions! Now *that*'s tricky! And these marks may be following the\n * last component of the whole sequence, so we should loop forward looking\n * for them and update them.\n *\n * Eg. the sequence is LAM,LAM,SHADDA,FATHA,HEH, and the font first forms a\n * 'calt' ligature of LAM,HEH, leaving the SHADDA and FATHA with a ligature\n * id and component == 1. Now, during 'liga', the LAM and the LAM-HEH ligature\n * form a LAM-LAM-HEH ligature. We need to reassign the SHADDA and FATHA to\n * the new ligature with a component value of 2.\n *\n * This in fact happened to a font... See:\n * https://bugzilla.gnome.org/show_bug.cgi?id=437633\n */", " bool is_base_ligature = _hb_glyph_info_is_base_glyph (&buffer->info[match_positions[0]]);\n bool is_mark_ligature = _hb_glyph_info_is_mark (&buffer->info[match_positions[0]]);\n for (unsigned int i = 1; i < count; i++)\n if (!_hb_glyph_info_is_mark (&buffer->info[match_positions[i]]))\n {\n is_base_ligature = false;\n is_mark_ligature = false;\n break;\n }\n bool is_ligature = !is_base_ligature && !is_mark_ligature;", " unsigned int klass = is_ligature ? HB_OT_LAYOUT_GLYPH_PROPS_LIGATURE : 0;\n unsigned int lig_id = is_ligature ? _hb_allocate_lig_id (buffer) : 0;\n unsigned int last_lig_id = _hb_glyph_info_get_lig_id (&buffer->cur());\n unsigned int last_num_components = _hb_glyph_info_get_lig_num_comps (&buffer->cur());\n unsigned int components_so_far = last_num_components;", " if (is_ligature)\n {\n _hb_glyph_info_set_lig_props_for_ligature (&buffer->cur(), lig_id, total_component_count);\n if (_hb_glyph_info_get_general_category (&buffer->cur()) == HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK)\n {\n _hb_glyph_info_set_general_category (&buffer->cur(), HB_UNICODE_GENERAL_CATEGORY_OTHER_LETTER);\n }\n }\n c->replace_glyph_with_ligature (lig_glyph, klass);", " for (unsigned int i = 1; i < count; i++)\n {\n while (buffer->idx < match_positions[i] && buffer->successful)\n {\n if (is_ligature)\n {\n\tunsigned int this_comp = _hb_glyph_info_get_lig_comp (&buffer->cur());\n\tif (this_comp == 0)\n\t this_comp = last_num_components;\n\tunsigned int new_lig_comp = components_so_far - last_num_components +\n\t\t\t\t hb_min (this_comp, last_num_components);\n\t _hb_glyph_info_set_lig_props_for_mark (&buffer->cur(), lig_id, new_lig_comp);\n }\n (void) buffer->next_glyph ();\n }", " last_lig_id = _hb_glyph_info_get_lig_id (&buffer->cur());\n last_num_components = _hb_glyph_info_get_lig_num_comps (&buffer->cur());\n components_so_far += last_num_components;", " /* Skip the base glyph */\n buffer->idx++;\n }", " if (!is_mark_ligature && last_lig_id)\n {\n /* Re-adjust components for any marks following. */\n for (unsigned i = buffer->idx; i < buffer->len; ++i)\n {\n if (last_lig_id != _hb_glyph_info_get_lig_id (&buffer->info[i])) break;", " unsigned this_comp = _hb_glyph_info_get_lig_comp (&buffer->info[i]);\n if (!this_comp) break;", " unsigned new_lig_comp = components_so_far - last_num_components +\n\t\t\t hb_min (this_comp, last_num_components);\n _hb_glyph_info_set_lig_props_for_mark (&buffer->info[i], lig_id, new_lig_comp);\n }\n }\n return_trace (true);\n}", "template <typename HBUINT>\nstatic inline bool match_backtrack (hb_ot_apply_context_t *c,\n\t\t\t\t unsigned int count,\n\t\t\t\t const HBUINT backtrack[],\n\t\t\t\t match_func_t match_func,\n\t\t\t\t const void *match_data,\n\t\t\t\t unsigned int *match_start)\n{\n TRACE_APPLY (nullptr);", " hb_ot_apply_context_t::skipping_iterator_t &skippy_iter = c->iter_context;\n skippy_iter.reset (c->buffer->backtrack_len (), count);\n skippy_iter.set_match_func (match_func, match_data);\n skippy_iter.set_glyph_data (backtrack);", " for (unsigned int i = 0; i < count; i++)\n {\n unsigned unsafe_from;\n if (!skippy_iter.prev (&unsafe_from))\n {\n *match_start = unsafe_from;\n return_trace (false);\n }\n }", " *match_start = skippy_iter.idx;\n return_trace (true);\n}", "template <typename HBUINT>\nstatic inline bool match_lookahead (hb_ot_apply_context_t *c,\n\t\t\t\t unsigned int count,\n\t\t\t\t const HBUINT lookahead[],\n\t\t\t\t match_func_t match_func,\n\t\t\t\t const void *match_data,\n\t\t\t\t unsigned int start_index,\n\t\t\t\t unsigned int *end_index)\n{\n TRACE_APPLY (nullptr);", " hb_ot_apply_context_t::skipping_iterator_t &skippy_iter = c->iter_context;\n skippy_iter.reset (start_index - 1, count);\n skippy_iter.set_match_func (match_func, match_data);\n skippy_iter.set_glyph_data (lookahead);", " for (unsigned int i = 0; i < count; i++)\n {\n unsigned unsafe_to;\n if (!skippy_iter.next (&unsafe_to))\n {\n *end_index = unsafe_to;\n return_trace (false);\n }\n }", " *end_index = skippy_iter.idx + 1;\n return_trace (true);\n}", "", "struct LookupRecord\n{\n bool serialize (hb_serialize_context_t *c,\n\t\t const hb_map_t *lookup_map) const\n {\n TRACE_SERIALIZE (this);\n auto *out = c->embed (*this);\n if (unlikely (!out)) return_trace (false);", " return_trace (c->check_assign (out->lookupListIndex, lookup_map->get (lookupListIndex), HB_SERIALIZE_ERROR_INT_OVERFLOW));\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (c->check_struct (this));\n }", " HBUINT16\tsequenceIndex;\t\t/* Index into current glyph\n\t\t\t\t\t * sequence--first glyph = 0 */\n HBUINT16\tlookupListIndex;\t/* Lookup to apply to that\n\t\t\t\t\t * position--zero--based */\n public:\n DEFINE_SIZE_STATIC (4);\n};", "static unsigned serialize_lookuprecord_array (hb_serialize_context_t *c,\n\t\t\t\t\t const hb_array_t<const LookupRecord> lookupRecords,\n\t\t\t\t\t const hb_map_t *lookup_map)\n{\n unsigned count = 0;\n for (const LookupRecord& r : lookupRecords)\n {\n if (!lookup_map->has (r.lookupListIndex))\n continue;", " if (!r.serialize (c, lookup_map))\n return 0;", " count++;\n }\n return count;\n}", "enum ContextFormat { SimpleContext = 1, ClassBasedContext = 2, CoverageBasedContext = 3 };", "template <typename HBUINT>\nstatic void context_closure_recurse_lookups (hb_closure_context_t *c,\n\t\t\t\t\t unsigned inputCount, const HBUINT input[],\n\t\t\t\t\t unsigned lookupCount,\n\t\t\t\t\t const LookupRecord lookupRecord[] /* Array of LookupRecords--in design order */,\n\t\t\t\t\t unsigned value,\n\t\t\t\t\t ContextFormat context_format,\n\t\t\t\t\t const void *data,\n\t\t\t\t\t intersected_glyphs_func_t intersected_glyphs_func,\n\t\t\t\t\t void *cache)\n{\n hb_set_t covered_seq_indicies;\n hb_set_t pos_glyphs;\n for (unsigned int i = 0; i < lookupCount; i++)\n {\n unsigned seqIndex = lookupRecord[i].sequenceIndex;\n if (seqIndex >= inputCount) continue;", " bool has_pos_glyphs = false;", " if (!covered_seq_indicies.has (seqIndex))\n {\n has_pos_glyphs = true;\n pos_glyphs.clear ();\n if (seqIndex == 0)\n {\n switch (context_format) {\n case ContextFormat::SimpleContext:\n pos_glyphs.add (value);\n break;\n case ContextFormat::ClassBasedContext:\n intersected_glyphs_func (&c->parent_active_glyphs (), data, value, &pos_glyphs, cache);\n break;\n case ContextFormat::CoverageBasedContext:\n pos_glyphs.set (c->parent_active_glyphs ());\n break;\n }\n }\n else\n {\n const void *input_data = input;\n unsigned input_value = seqIndex - 1;\n if (context_format != ContextFormat::SimpleContext)\n {\n input_data = data;\n input_value = input[seqIndex - 1];\n }", " intersected_glyphs_func (c->glyphs, input_data, input_value, &pos_glyphs, cache);\n }\n }", " covered_seq_indicies.add (seqIndex);\n if (has_pos_glyphs) {\n c->push_cur_active_glyphs () = std::move (pos_glyphs);\n } else {\n c->push_cur_active_glyphs ().set (*c->glyphs);\n }", " unsigned endIndex = inputCount;\n if (context_format == ContextFormat::CoverageBasedContext)\n endIndex += 1;", " c->recurse (lookupRecord[i].lookupListIndex, &covered_seq_indicies, seqIndex, endIndex);", " c->pop_cur_done_glyphs ();\n }\n}", "template <typename context_t>\nstatic inline void recurse_lookups (context_t *c,\n unsigned int lookupCount,\n const LookupRecord lookupRecord[] /* Array of LookupRecords--in design order */)\n{\n for (unsigned int i = 0; i < lookupCount; i++)\n c->recurse (lookupRecord[i].lookupListIndex);\n}", "static inline void apply_lookup (hb_ot_apply_context_t *c,\n\t\t\t\t unsigned int count, /* Including the first glyph */\n\t\t\t\t unsigned int match_positions[HB_MAX_CONTEXT_LENGTH], /* Including the first glyph */\n\t\t\t\t unsigned int lookupCount,\n\t\t\t\t const LookupRecord lookupRecord[], /* Array of LookupRecords--in design order */\n\t\t\t\t unsigned int match_end)\n{\n hb_buffer_t *buffer = c->buffer;\n int end;", " /* All positions are distance from beginning of *output* buffer.\n * Adjust. */\n {\n unsigned int bl = buffer->backtrack_len ();\n end = bl + match_end - buffer->idx;", " int delta = bl - buffer->idx;\n /* Convert positions to new indexing. */\n for (unsigned int j = 0; j < count; j++)\n match_positions[j] += delta;\n }", " for (unsigned int i = 0; i < lookupCount && buffer->successful; i++)\n {\n unsigned int idx = lookupRecord[i].sequenceIndex;\n if (idx >= count)\n continue;", " unsigned int orig_len = buffer->backtrack_len () + buffer->lookahead_len ();", " /* This can happen if earlier recursed lookups deleted many entries. */\n if (unlikely (match_positions[idx] >= orig_len))\n continue;", " if (unlikely (!buffer->move_to (match_positions[idx])))\n break;", " if (unlikely (buffer->max_ops <= 0))\n break;", " if (HB_BUFFER_MESSAGE_MORE && c->buffer->messaging ())\n {\n if (buffer->have_output)\n c->buffer->sync_so_far ();\n c->buffer->message (c->font,\n\t\t\t \"recursing to lookup %u at %u\",\n\t\t\t (unsigned) lookupRecord[i].lookupListIndex,\n\t\t\t buffer->idx);\n }", " if (!c->recurse (lookupRecord[i].lookupListIndex))\n continue;", " if (HB_BUFFER_MESSAGE_MORE && c->buffer->messaging ())\n {\n if (buffer->have_output)\n c->buffer->sync_so_far ();\n c->buffer->message (c->font,\n\t\t\t \"recursed to lookup %u\",\n\t\t\t (unsigned) lookupRecord[i].lookupListIndex);\n }", " unsigned int new_len = buffer->backtrack_len () + buffer->lookahead_len ();\n int delta = new_len - orig_len;", " if (!delta)\n continue;", " /* Recursed lookup changed buffer len. Adjust.\n *\n * TODO:\n *\n * Right now, if buffer length increased by n, we assume n new glyphs\n * were added right after the current position, and if buffer length\n * was decreased by n, we assume n match positions after the current\n * one where removed. The former (buffer length increased) case is\n * fine, but the decrease case can be improved in at least two ways,\n * both of which are significant:\n *\n * - If recursed-to lookup is MultipleSubst and buffer length\n * decreased, then it's current match position that was deleted,\n * NOT the one after it.\n *\n * - If buffer length was decreased by n, it does not necessarily\n * mean that n match positions where removed, as there recursed-to\n * lookup might had a different LookupFlag. Here's a constructed\n * case of that:\n * https://github.com/harfbuzz/harfbuzz/discussions/3538\n *\n * It should be possible to construct tests for both of these cases.\n */", " end += delta;\n if (end < int (match_positions[idx]))\n {\n /* End might end up being smaller than match_positions[idx] if the recursed\n * lookup ended up removing many items.\n * Just never rewind end beyond start of current position, since that is\n * not possible in the recursed lookup. Also adjust delta as such.\n *\n * https://bugs.chromium.org/p/chromium/issues/detail?id=659496\n * https://github.com/harfbuzz/harfbuzz/issues/1611\n */\n delta += match_positions[idx] - end;\n end = match_positions[idx];\n }", " unsigned int next = idx + 1; /* next now is the position after the recursed lookup. */", " if (delta > 0)\n {\n if (unlikely (delta + count > HB_MAX_CONTEXT_LENGTH))\n\tbreak;\n }\n else\n {\n /* NOTE: delta is non-positive. */\n delta = hb_max (delta, (int) next - (int) count);\n next -= delta;\n }", " /* Shift! */\n memmove (match_positions + next + delta, match_positions + next,\n\t (count - next) * sizeof (match_positions[0]));\n next += delta;\n count += delta;", " /* Fill in new entries. */\n for (unsigned int j = idx + 1; j < next; j++)\n match_positions[j] = match_positions[j - 1] + 1;", " /* And fixup the rest. */\n for (; next < count; next++)\n match_positions[next] += delta;\n }", " (void) buffer->move_to (end);\n}", "", "/* Contextual lookups */", "struct ContextClosureLookupContext\n{\n ContextClosureFuncs funcs;\n ContextFormat context_format;\n const void *intersects_data;\n void *intersects_cache;\n void *intersected_glyphs_cache;\n};", "struct ContextCollectGlyphsLookupContext\n{\n ContextCollectGlyphsFuncs funcs;\n const void *collect_data;\n};", "struct ContextApplyLookupContext\n{\n ContextApplyFuncs funcs;\n const void *match_data;\n};", "template <typename HBUINT>\nstatic inline bool context_intersects (const hb_set_t *glyphs,\n\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t ContextClosureLookupContext &lookup_context)\n{\n return array_is_subset_of (glyphs,\n\t\t\t inputCount ? inputCount - 1 : 0, input,\n\t\t\t lookup_context.funcs.intersects,\n\t\t\t lookup_context.intersects_data,\n\t\t\t lookup_context.intersects_cache);\n}", "template <typename HBUINT>\nstatic inline void context_closure_lookup (hb_closure_context_t *c,\n\t\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t unsigned int lookupCount,\n\t\t\t\t\t const LookupRecord lookupRecord[],\n\t\t\t\t\t unsigned value, /* Index of first glyph in Coverage or Class value in ClassDef table */\n\t\t\t\t\t ContextClosureLookupContext &lookup_context)\n{\n if (context_intersects (c->glyphs,\n\t\t\t inputCount, input,\n\t\t\t lookup_context))\n context_closure_recurse_lookups (c,\n\t\t\t\t inputCount, input,\n\t\t\t\t lookupCount, lookupRecord,\n\t\t\t\t value,\n\t\t\t\t lookup_context.context_format,\n\t\t\t\t lookup_context.intersects_data,\n\t\t\t\t lookup_context.funcs.intersected_glyphs,\n\t\t\t\t lookup_context.intersected_glyphs_cache);\n}", "template <typename HBUINT>\nstatic inline void context_collect_glyphs_lookup (hb_collect_glyphs_context_t *c,\n\t\t\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t\t unsigned int lookupCount,\n\t\t\t\t\t\t const LookupRecord lookupRecord[],\n\t\t\t\t\t\t ContextCollectGlyphsLookupContext &lookup_context)\n{\n collect_array (c, c->input,\n\t\t inputCount ? inputCount - 1 : 0, input,\n\t\t lookup_context.funcs.collect, lookup_context.collect_data);\n recurse_lookups (c,\n\t\t lookupCount, lookupRecord);\n}", "template <typename HBUINT>\nstatic inline bool context_would_apply_lookup (hb_would_apply_context_t *c,\n\t\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t unsigned int lookupCount HB_UNUSED,\n\t\t\t\t\t const LookupRecord lookupRecord[] HB_UNUSED,\n\t\t\t\t\t const ContextApplyLookupContext &lookup_context)\n{\n return would_match_input (c,\n\t\t\t inputCount, input,\n\t\t\t lookup_context.funcs.match, lookup_context.match_data);\n}", "template <typename HBUINT>\nstatic inline bool context_apply_lookup (hb_ot_apply_context_t *c,\n\t\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t unsigned int lookupCount,\n\t\t\t\t\t const LookupRecord lookupRecord[],\n\t\t\t\t\t const ContextApplyLookupContext &lookup_context)\n{\n unsigned match_end = 0;\n unsigned match_positions[HB_MAX_CONTEXT_LENGTH];\n if (match_input (c,\n\t\t inputCount, input,\n\t\t lookup_context.funcs.match, lookup_context.match_data,\n\t\t &match_end, match_positions))\n {\n c->buffer->unsafe_to_break (c->buffer->idx, match_end);\n apply_lookup (c,\n\t\t inputCount, match_positions,\n\t\t lookupCount, lookupRecord,\n\t\t match_end);\n return true;\n }\n else\n {\n c->buffer->unsafe_to_concat (c->buffer->idx, match_end);\n return false;\n }\n}", "template <typename Types>\nstruct Rule\n{\n bool intersects (const hb_set_t *glyphs, ContextClosureLookupContext &lookup_context) const\n {\n return context_intersects (glyphs,\n\t\t\t inputCount, inputZ.arrayZ,\n\t\t\t lookup_context);\n }", " void closure (hb_closure_context_t *c, unsigned value, ContextClosureLookupContext &lookup_context) const\n {\n if (unlikely (c->lookup_limit_exceeded ())) return;", " const auto &lookupRecord = StructAfter<UnsizedArrayOf<LookupRecord>>\n\t\t\t\t\t (inputZ.as_array ((inputCount ? inputCount - 1 : 0)));\n context_closure_lookup (c,\n\t\t\t inputCount, inputZ.arrayZ,\n\t\t\t lookupCount, lookupRecord.arrayZ,\n\t\t\t value, lookup_context);\n }", " void closure_lookups (hb_closure_lookups_context_t *c,\n ContextClosureLookupContext &lookup_context) const\n {\n if (unlikely (c->lookup_limit_exceeded ())) return;\n if (!intersects (c->glyphs, lookup_context)) return;", " const auto &lookupRecord = StructAfter<UnsizedArrayOf<LookupRecord>>\n\t\t\t\t\t (inputZ.as_array (inputCount ? inputCount - 1 : 0));\n recurse_lookups (c, lookupCount, lookupRecord.arrayZ);\n }", " void collect_glyphs (hb_collect_glyphs_context_t *c,\n\t\t ContextCollectGlyphsLookupContext &lookup_context) const\n {\n const auto &lookupRecord = StructAfter<UnsizedArrayOf<LookupRecord>>\n\t\t\t\t\t (inputZ.as_array (inputCount ? inputCount - 1 : 0));\n context_collect_glyphs_lookup (c,\n\t\t\t\t inputCount, inputZ.arrayZ,\n\t\t\t\t lookupCount, lookupRecord.arrayZ,\n\t\t\t\t lookup_context);\n }", " bool would_apply (hb_would_apply_context_t *c,\n\t\t const ContextApplyLookupContext &lookup_context) const\n {\n const auto &lookupRecord = StructAfter<UnsizedArrayOf<LookupRecord>>\n\t\t\t\t\t (inputZ.as_array (inputCount ? inputCount - 1 : 0));\n return context_would_apply_lookup (c,\n\t\t\t\t inputCount, inputZ.arrayZ,\n\t\t\t\t lookupCount, lookupRecord.arrayZ,\n\t\t\t\t lookup_context);\n }", " bool apply (hb_ot_apply_context_t *c,\n\t const ContextApplyLookupContext &lookup_context) const\n {\n TRACE_APPLY (this);\n const auto &lookupRecord = StructAfter<UnsizedArrayOf<LookupRecord>>\n\t\t\t\t\t (inputZ.as_array (inputCount ? inputCount - 1 : 0));\n return_trace (context_apply_lookup (c, inputCount, inputZ.arrayZ, lookupCount, lookupRecord.arrayZ, lookup_context));\n }", " bool serialize (hb_serialize_context_t *c,\n\t\t const hb_map_t *input_mapping, /* old->new glyphid or class mapping */\n\t\t const hb_map_t *lookup_map) const\n {\n TRACE_SERIALIZE (this);\n auto *out = c->start_embed (this);\n if (unlikely (!c->extend_min (out))) return_trace (false);", " out->inputCount = inputCount;\n const auto input = inputZ.as_array (inputCount - 1);\n for (const auto org : input)\n {\n HBUINT16 d;\n d = input_mapping->get (org);\n c->copy (d);\n }", " const auto &lookupRecord = StructAfter<UnsizedArrayOf<LookupRecord>>\n\t\t\t\t\t (inputZ.as_array ((inputCount ? inputCount - 1 : 0)));", " unsigned count = serialize_lookuprecord_array (c, lookupRecord.as_array (lookupCount), lookup_map);\n return_trace (c->check_assign (out->lookupCount, count, HB_SERIALIZE_ERROR_INT_OVERFLOW));\n }", " bool subset (hb_subset_context_t *c,\n\t const hb_map_t *lookup_map,\n\t const hb_map_t *klass_map = nullptr) const\n {\n TRACE_SUBSET (this);\n if (unlikely (!inputCount)) return_trace (false);\n const auto input = inputZ.as_array (inputCount - 1);", " const hb_map_t *mapping = klass_map == nullptr ? c->plan->glyph_map : klass_map;\n if (!hb_all (input, mapping)) return_trace (false);\n return_trace (serialize (c->serializer, mapping, lookup_map));\n }", " public:\n bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (inputCount.sanitize (c) &&\n\t\t lookupCount.sanitize (c) &&\n\t\t c->check_range (inputZ.arrayZ,\n\t\t\t\t inputZ.item_size * (inputCount ? inputCount - 1 : 0) +\n\t\t\t\t LookupRecord::static_size * lookupCount));\n }", " protected:\n HBUINT16\tinputCount;\t\t/* Total number of glyphs in input\n\t\t\t\t\t * glyph sequence--includes the first\n\t\t\t\t\t * glyph */\n HBUINT16\tlookupCount;\t\t/* Number of LookupRecords */\n UnsizedArrayOf<typename Types::HBUINT>\n\t\tinputZ;\t\t\t/* Array of match inputs--start with\n\t\t\t\t\t * second glyph */\n/*UnsizedArrayOf<LookupRecord>\n\t\tlookupRecordX;*/\t/* Array of LookupRecords--in\n\t\t\t\t\t * design order */\n public:\n DEFINE_SIZE_ARRAY (4, inputZ);\n};", "template <typename Types>\nstruct RuleSet\n{\n using Rule = OT::Rule<Types>;", " bool intersects (const hb_set_t *glyphs,\n\t\t ContextClosureLookupContext &lookup_context) const\n {\n return\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_map ([&] (const Rule &_) { return _.intersects (glyphs, lookup_context); })\n | hb_any\n ;\n }", " void closure (hb_closure_context_t *c, unsigned value,\n\t\tContextClosureLookupContext &lookup_context) const\n {\n if (unlikely (c->lookup_limit_exceeded ())) return;", " return\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const Rule &_) { _.closure (c, value, lookup_context); })\n ;\n }", " void closure_lookups (hb_closure_lookups_context_t *c,\n ContextClosureLookupContext &lookup_context) const\n {\n if (unlikely (c->lookup_limit_exceeded ())) return;\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const Rule &_) { _.closure_lookups (c, lookup_context); })\n ;\n }", " void collect_glyphs (hb_collect_glyphs_context_t *c,\n\t\t ContextCollectGlyphsLookupContext &lookup_context) const\n {\n return\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const Rule &_) { _.collect_glyphs (c, lookup_context); })\n ;\n }", " bool would_apply (hb_would_apply_context_t *c,\n\t\t const ContextApplyLookupContext &lookup_context) const\n {\n return\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_map ([&] (const Rule &_) { return _.would_apply (c, lookup_context); })\n | hb_any\n ;\n }", " bool apply (hb_ot_apply_context_t *c,\n\t const ContextApplyLookupContext &lookup_context) const\n {\n TRACE_APPLY (this);\n return_trace (\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_map ([&] (const Rule &_) { return _.apply (c, lookup_context); })\n | hb_any\n )\n ;\n }", " bool subset (hb_subset_context_t *c,\n\t const hb_map_t *lookup_map,\n\t const hb_map_t *klass_map = nullptr) const\n {\n TRACE_SUBSET (this);", " auto snap = c->serializer->snapshot ();\n auto *out = c->serializer->start_embed (*this);\n if (unlikely (!c->serializer->extend_min (out))) return_trace (false);", " for (const Offset16To<Rule>& _ : rule)\n {\n if (!_) continue;\n auto o_snap = c->serializer->snapshot ();\n auto *o = out->rule.serialize_append (c->serializer);\n if (unlikely (!o)) continue;", " if (!o->serialize_subset (c, _, this, lookup_map, klass_map))\n {\n\tout->rule.pop ();\n\tc->serializer->revert (o_snap);\n }\n }", " bool ret = bool (out->rule);\n if (!ret) c->serializer->revert (snap);", " return_trace (ret);\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (rule.sanitize (c, this));\n }", " protected:\n Array16OfOffset16To<Rule>\n\t\trule;\t\t\t/* Array of Rule tables\n\t\t\t\t\t * ordered by preference */\n public:\n DEFINE_SIZE_ARRAY (2, rule);\n};", "\ntemplate <typename Types>\nstruct ContextFormat1_4\n{\n using RuleSet = OT::RuleSet<Types>;", " bool intersects (const hb_set_t *glyphs) const\n {\n struct ContextClosureLookupContext lookup_context = {\n {intersects_glyph, intersected_glyph},\n ContextFormat::SimpleContext,\n nullptr\n };", " return\n + hb_zip (this+coverage, ruleSet)\n | hb_filter (*glyphs, hb_first)\n | hb_map (hb_second)\n | hb_map (hb_add (this))\n | hb_map ([&] (const RuleSet &_) { return _.intersects (glyphs, lookup_context); })\n | hb_any\n ;\n }", " bool may_have_non_1to1 () const\n { return true; }", " void closure (hb_closure_context_t *c) const\n {\n hb_set_t& cur_active_glyphs = c->push_cur_active_glyphs ();\n get_coverage ().intersect_set (c->previous_parent_active_glyphs (), cur_active_glyphs);", " struct ContextClosureLookupContext lookup_context = {\n {intersects_glyph, intersected_glyph},\n ContextFormat::SimpleContext,\n nullptr\n };", " + hb_zip (this+coverage, hb_range ((unsigned) ruleSet.len))\n | hb_filter ([&] (hb_codepoint_t _) {\n return c->previous_parent_active_glyphs ().has (_);\n }, hb_first)\n | hb_map ([&](const hb_pair_t<hb_codepoint_t, unsigned> _) { return hb_pair_t<unsigned, const RuleSet&> (_.first, this+ruleSet[_.second]); })\n | hb_apply ([&] (const hb_pair_t<unsigned, const RuleSet&>& _) { _.second.closure (c, _.first, lookup_context); })\n ;", " c->pop_cur_done_glyphs ();\n }", " void closure_lookups (hb_closure_lookups_context_t *c) const\n {\n struct ContextClosureLookupContext lookup_context = {\n {intersects_glyph, nullptr},\n ContextFormat::SimpleContext,\n nullptr\n };", " + hb_zip (this+coverage, ruleSet)\n | hb_filter (*c->glyphs, hb_first)\n | hb_map (hb_second)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const RuleSet &_) { _.closure_lookups (c, lookup_context); })\n ;\n }", " void collect_variation_indices (hb_collect_variation_indices_context_t *c) const {}", " void collect_glyphs (hb_collect_glyphs_context_t *c) const\n {\n (this+coverage).collect_coverage (c->input);", " struct ContextCollectGlyphsLookupContext lookup_context = {\n {collect_glyph},\n nullptr\n };", " + hb_iter (ruleSet)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const RuleSet &_) { _.collect_glyphs (c, lookup_context); })\n ;\n }", " bool would_apply (hb_would_apply_context_t *c) const\n {\n const RuleSet &rule_set = this+ruleSet[(this+coverage).get_coverage (c->glyphs[0])];\n struct ContextApplyLookupContext lookup_context = {\n {match_glyph},\n nullptr\n };\n return rule_set.would_apply (c, lookup_context);\n }", " const Coverage &get_coverage () const { return this+coverage; }", " bool apply (hb_ot_apply_context_t *c) const\n {\n TRACE_APPLY (this);\n unsigned int index = (this+coverage).get_coverage (c->buffer->cur().codepoint);\n if (likely (index == NOT_COVERED))\n return_trace (false);", " const RuleSet &rule_set = this+ruleSet[index];\n struct ContextApplyLookupContext lookup_context = {\n {match_glyph},\n nullptr\n };\n return_trace (rule_set.apply (c, lookup_context));\n }", " bool subset (hb_subset_context_t *c) const\n {\n TRACE_SUBSET (this);\n const hb_set_t &glyphset = *c->plan->glyphset_gsub ();\n const hb_map_t &glyph_map = *c->plan->glyph_map;", " auto *out = c->serializer->start_embed (*this);\n if (unlikely (!c->serializer->extend_min (out))) return_trace (false);\n out->format = format;", " const hb_map_t *lookup_map = c->table_tag == HB_OT_TAG_GSUB ? &c->plan->gsub_lookups : &c->plan->gpos_lookups;\n hb_sorted_vector_t<hb_codepoint_t> new_coverage;\n + hb_zip (this+coverage, ruleSet)\n | hb_filter (glyphset, hb_first)\n | hb_filter (subset_offset_array (c, out->ruleSet, this, lookup_map), hb_second)\n | hb_map (hb_first)\n | hb_map (glyph_map)\n | hb_sink (new_coverage)\n ;", " out->coverage.serialize_serialize (c->serializer, new_coverage.iter ());\n return_trace (bool (new_coverage));\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (coverage.sanitize (c, this) && ruleSet.sanitize (c, this));\n }", " protected:\n HBUINT16\tformat;\t\t\t/* Format identifier--format = 1 */\n typename Types::template OffsetTo<Coverage>\n\t\tcoverage;\t\t/* Offset to Coverage table--from\n\t\t\t\t\t * beginning of table */\n Array16Of<typename Types::template OffsetTo<RuleSet>>\n\t\truleSet;\t\t/* Array of RuleSet tables\n\t\t\t\t\t * ordered by Coverage Index */\n public:\n DEFINE_SIZE_ARRAY (2 + 2 * Types::size, ruleSet);\n};", "\ntemplate <typename Types>\nstruct ContextFormat2_5\n{\n using RuleSet = OT::RuleSet<SmallTypes>;", " bool intersects (const hb_set_t *glyphs) const\n {\n if (!(this+coverage).intersects (glyphs))\n return false;", " const ClassDef &class_def = this+classDef;", " hb_map_t cache;\n struct ContextClosureLookupContext lookup_context = {\n {intersects_class, nullptr},\n ContextFormat::ClassBasedContext,\n &class_def,\n &cache\n };", " hb_set_t retained_coverage_glyphs;\n (this+coverage).intersect_set (*glyphs, retained_coverage_glyphs);", " hb_set_t coverage_glyph_classes;\n class_def.intersected_classes (&retained_coverage_glyphs, &coverage_glyph_classes);", "\n return\n + hb_iter (ruleSet)\n | hb_map (hb_add (this))\n | hb_enumerate\n | hb_map ([&] (const hb_pair_t<unsigned, const RuleSet &> p)\n\t { return class_def.intersects_class (glyphs, p.first) &&\n\t\t coverage_glyph_classes.has (p.first) &&\n\t\t p.second.intersects (glyphs, lookup_context); })\n | hb_any\n ;\n }", " bool may_have_non_1to1 () const\n { return true; }", " void closure (hb_closure_context_t *c) const\n {\n if (!(this+coverage).intersects (c->glyphs))\n return;", " hb_set_t& cur_active_glyphs = c->push_cur_active_glyphs ();\n get_coverage ().intersect_set (c->previous_parent_active_glyphs (),\n cur_active_glyphs);", " const ClassDef &class_def = this+classDef;", " hb_map_t cache;\n intersected_class_cache_t intersected_cache;\n struct ContextClosureLookupContext lookup_context = {\n {intersects_class, intersected_class_glyphs},\n ContextFormat::ClassBasedContext,\n &class_def,\n &cache,\n &intersected_cache\n };", " + hb_enumerate (ruleSet)\n | hb_filter ([&] (unsigned _)\n { return class_def.intersects_class (&c->parent_active_glyphs (), _); },\n\t\t hb_first)\n | hb_apply ([&] (const hb_pair_t<unsigned, const typename Types::template OffsetTo<RuleSet>&> _)\n {\n const RuleSet& rule_set = this+_.second;\n rule_set.closure (c, _.first, lookup_context);\n })\n ;", " c->pop_cur_done_glyphs ();\n }", " void closure_lookups (hb_closure_lookups_context_t *c) const\n {\n if (!(this+coverage).intersects (c->glyphs))\n return;", " const ClassDef &class_def = this+classDef;", " hb_map_t cache;\n struct ContextClosureLookupContext lookup_context = {\n {intersects_class, nullptr},\n ContextFormat::ClassBasedContext,\n &class_def,\n &cache\n };", " + hb_iter (ruleSet)\n | hb_map (hb_add (this))\n | hb_enumerate\n | hb_filter ([&] (const hb_pair_t<unsigned, const RuleSet &> p)\n { return class_def.intersects_class (c->glyphs, p.first); })\n | hb_map (hb_second)\n | hb_apply ([&] (const RuleSet & _)\n { _.closure_lookups (c, lookup_context); });\n }", " void collect_variation_indices (hb_collect_variation_indices_context_t *c) const {}", " void collect_glyphs (hb_collect_glyphs_context_t *c) const\n {\n (this+coverage).collect_coverage (c->input);", " const ClassDef &class_def = this+classDef;\n struct ContextCollectGlyphsLookupContext lookup_context = {\n {collect_class},\n &class_def\n };", " + hb_iter (ruleSet)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const RuleSet &_) { _.collect_glyphs (c, lookup_context); })\n ;\n }", " bool would_apply (hb_would_apply_context_t *c) const\n {\n const ClassDef &class_def = this+classDef;\n unsigned int index = class_def.get_class (c->glyphs[0]);\n const RuleSet &rule_set = this+ruleSet[index];\n struct ContextApplyLookupContext lookup_context = {\n {match_class},\n &class_def\n };\n return rule_set.would_apply (c, lookup_context);\n }", " const Coverage &get_coverage () const { return this+coverage; }", " unsigned cache_cost () const\n {\n unsigned c = (this+classDef).cost () * ruleSet.len;\n return c >= 4 ? c : 0;\n }\n bool cache_func (hb_ot_apply_context_t *c, bool enter) const\n {\n if (enter)\n {\n if (!HB_BUFFER_TRY_ALLOCATE_VAR (c->buffer, syllable))\n\treturn false;\n auto &info = c->buffer->info;\n unsigned count = c->buffer->len;\n for (unsigned i = 0; i < count; i++)\n\tinfo[i].syllable() = 255;\n c->new_syllables = 255;\n return true;\n }\n else\n {\n c->new_syllables = (unsigned) -1;\n HB_BUFFER_DEALLOCATE_VAR (c->buffer, syllable);\n return true;\n }\n }", " bool apply (hb_ot_apply_context_t *c, bool cached = false) const\n {\n TRACE_APPLY (this);\n unsigned int index = (this+coverage).get_coverage (c->buffer->cur().codepoint);\n if (likely (index == NOT_COVERED)) return_trace (false);", " const ClassDef &class_def = this+classDef;", " struct ContextApplyLookupContext lookup_context = {\n {cached ? match_class_cached : match_class},\n &class_def\n };", " if (cached && c->buffer->cur().syllable() < 255)\n index = c->buffer->cur().syllable ();\n else\n {\n index = class_def.get_class (c->buffer->cur().codepoint);\n if (cached && index < 255)\n\tc->buffer->cur().syllable() = index;\n }\n const RuleSet &rule_set = this+ruleSet[index];\n return_trace (rule_set.apply (c, lookup_context));\n }", " bool subset (hb_subset_context_t *c) const\n {\n TRACE_SUBSET (this);\n auto *out = c->serializer->start_embed (*this);\n if (unlikely (!c->serializer->extend_min (out))) return_trace (false);\n out->format = format;\n if (unlikely (!out->coverage.serialize_subset (c, coverage, this)))\n return_trace (false);", " hb_map_t klass_map;\n out->classDef.serialize_subset (c, classDef, this, &klass_map);", " const hb_set_t* glyphset = c->plan->glyphset_gsub ();\n hb_set_t retained_coverage_glyphs;\n (this+coverage).intersect_set (*glyphset, retained_coverage_glyphs);", " hb_set_t coverage_glyph_classes;\n (this+classDef).intersected_classes (&retained_coverage_glyphs, &coverage_glyph_classes);", " const hb_map_t *lookup_map = c->table_tag == HB_OT_TAG_GSUB ? &c->plan->gsub_lookups : &c->plan->gpos_lookups;\n bool ret = true;\n int non_zero_index = -1, index = 0;\n auto snapshot = c->serializer->snapshot();\n for (const auto& _ : + hb_enumerate (ruleSet)\n\t\t\t | hb_filter (klass_map, hb_first))\n {\n auto *o = out->ruleSet.serialize_append (c->serializer);\n if (unlikely (!o))\n {\n\tret = false;\n\tbreak;\n }", " if (coverage_glyph_classes.has (_.first) &&\n\t o->serialize_subset (c, _.second, this, lookup_map, &klass_map)) {\n\tnon_zero_index = index;\n snapshot = c->serializer->snapshot();\n }", " index++;\n }", " if (!ret || non_zero_index == -1) return_trace (false);", " //prune empty trailing ruleSets\n --index;\n while (index > non_zero_index)\n {\n out->ruleSet.pop ();\n index--;\n }\n c->serializer->revert (snapshot);", " return_trace (bool (out->ruleSet));\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (coverage.sanitize (c, this) && classDef.sanitize (c, this) && ruleSet.sanitize (c, this));\n }", " protected:\n HBUINT16\tformat;\t\t\t/* Format identifier--format = 2 */\n typename Types::template OffsetTo<Coverage>\n\t\tcoverage;\t\t/* Offset to Coverage table--from\n\t\t\t\t\t * beginning of table */\n typename Types::template OffsetTo<ClassDef>\n\t\tclassDef;\t\t/* Offset to glyph ClassDef table--from\n\t\t\t\t\t * beginning of table */\n Array16Of<typename Types::template OffsetTo<RuleSet>>\n\t\truleSet;\t\t/* Array of RuleSet tables\n\t\t\t\t\t * ordered by class */\n public:\n DEFINE_SIZE_ARRAY (4 + 2 * Types::size, ruleSet);\n};", "\nstruct ContextFormat3\n{\n using RuleSet = OT::RuleSet<SmallTypes>;", " bool intersects (const hb_set_t *glyphs) const\n {\n if (!(this+coverageZ[0]).intersects (glyphs))\n return false;", " struct ContextClosureLookupContext lookup_context = {\n {intersects_coverage, nullptr},\n ContextFormat::CoverageBasedContext,\n this\n };\n return context_intersects (glyphs,\n\t\t\t glyphCount, (const HBUINT16 *) (coverageZ.arrayZ + 1),\n\t\t\t lookup_context);\n }", " bool may_have_non_1to1 () const\n { return true; }", " void closure (hb_closure_context_t *c) const\n {\n if (!(this+coverageZ[0]).intersects (c->glyphs))\n return;", " hb_set_t& cur_active_glyphs = c->push_cur_active_glyphs ();\n get_coverage ().intersect_set (c->previous_parent_active_glyphs (),\n cur_active_glyphs);", "\n const LookupRecord *lookupRecord = &StructAfter<LookupRecord> (coverageZ.as_array (glyphCount));\n struct ContextClosureLookupContext lookup_context = {\n {intersects_coverage, intersected_coverage_glyphs},\n ContextFormat::CoverageBasedContext,\n this\n };\n context_closure_lookup (c,\n\t\t\t glyphCount, (const HBUINT16 *) (coverageZ.arrayZ + 1),\n\t\t\t lookupCount, lookupRecord,\n\t\t\t 0, lookup_context);", " c->pop_cur_done_glyphs ();\n }", " void closure_lookups (hb_closure_lookups_context_t *c) const\n {\n if (!intersects (c->glyphs))\n return;\n const LookupRecord *lookupRecord = &StructAfter<LookupRecord> (coverageZ.as_array (glyphCount));\n recurse_lookups (c, lookupCount, lookupRecord);\n }", " void collect_variation_indices (hb_collect_variation_indices_context_t *c) const {}", " void collect_glyphs (hb_collect_glyphs_context_t *c) const\n {\n (this+coverageZ[0]).collect_coverage (c->input);", " const LookupRecord *lookupRecord = &StructAfter<LookupRecord> (coverageZ.as_array (glyphCount));\n struct ContextCollectGlyphsLookupContext lookup_context = {\n {collect_coverage},\n this\n };", " context_collect_glyphs_lookup (c,\n\t\t\t\t glyphCount, (const HBUINT16 *) (coverageZ.arrayZ + 1),\n\t\t\t\t lookupCount, lookupRecord,\n\t\t\t\t lookup_context);\n }", " bool would_apply (hb_would_apply_context_t *c) const\n {\n const LookupRecord *lookupRecord = &StructAfter<LookupRecord> (coverageZ.as_array (glyphCount));\n struct ContextApplyLookupContext lookup_context = {\n {match_coverage},\n this\n };\n return context_would_apply_lookup (c,\n\t\t\t\t glyphCount, (const HBUINT16 *) (coverageZ.arrayZ + 1),\n\t\t\t\t lookupCount, lookupRecord,\n\t\t\t\t lookup_context);\n }", " const Coverage &get_coverage () const { return this+coverageZ[0]; }", " bool apply (hb_ot_apply_context_t *c) const\n {\n TRACE_APPLY (this);\n unsigned int index = (this+coverageZ[0]).get_coverage (c->buffer->cur().codepoint);\n if (likely (index == NOT_COVERED)) return_trace (false);", " const LookupRecord *lookupRecord = &StructAfter<LookupRecord> (coverageZ.as_array (glyphCount));\n struct ContextApplyLookupContext lookup_context = {\n {match_coverage},\n this\n };\n return_trace (context_apply_lookup (c, glyphCount, (const HBUINT16 *) (coverageZ.arrayZ + 1), lookupCount, lookupRecord, lookup_context));\n }", " bool subset (hb_subset_context_t *c) const\n {\n TRACE_SUBSET (this);\n auto *out = c->serializer->start_embed (this);\n if (unlikely (!c->serializer->extend_min (out))) return_trace (false);", " out->format = format;\n out->glyphCount = glyphCount;", " auto coverages = coverageZ.as_array (glyphCount);", " for (const Offset16To<Coverage>& offset : coverages)\n {\n /* TODO(subset) This looks like should not be necessary to write this way. */\n auto *o = c->serializer->allocate_size<Offset16To<Coverage>> (Offset16To<Coverage>::static_size);\n if (unlikely (!o)) return_trace (false);\n if (!o->serialize_subset (c, offset, this)) return_trace (false);\n }", " const auto& lookupRecord = StructAfter<UnsizedArrayOf<LookupRecord>> (coverageZ.as_array (glyphCount));\n const hb_map_t *lookup_map = c->table_tag == HB_OT_TAG_GSUB ? &c->plan->gsub_lookups : &c->plan->gpos_lookups;", "\n unsigned count = serialize_lookuprecord_array (c->serializer, lookupRecord.as_array (lookupCount), lookup_map);\n return_trace (c->serializer->check_assign (out->lookupCount, count, HB_SERIALIZE_ERROR_INT_OVERFLOW));\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n if (!c->check_struct (this)) return_trace (false);\n unsigned int count = glyphCount;\n if (!count) return_trace (false); /* We want to access coverageZ[0] freely. */\n if (!c->check_array (coverageZ.arrayZ, count)) return_trace (false);\n for (unsigned int i = 0; i < count; i++)\n if (!coverageZ[i].sanitize (c, this)) return_trace (false);\n const LookupRecord *lookupRecord = &StructAfter<LookupRecord> (coverageZ.as_array (glyphCount));\n return_trace (c->check_array (lookupRecord, lookupCount));\n }", " protected:\n HBUINT16\tformat;\t\t\t/* Format identifier--format = 3 */\n HBUINT16\tglyphCount;\t\t/* Number of glyphs in the input glyph\n\t\t\t\t\t * sequence */\n HBUINT16\tlookupCount;\t\t/* Number of LookupRecords */\n UnsizedArrayOf<Offset16To<Coverage>>\n\t\tcoverageZ;\t\t/* Array of offsets to Coverage\n\t\t\t\t\t * table in glyph sequence order */\n/*UnsizedArrayOf<LookupRecord>\n\t\tlookupRecordX;*/\t/* Array of LookupRecords--in\n\t\t\t\t\t * design order */\n public:\n DEFINE_SIZE_ARRAY (6, coverageZ);\n};", "struct Context\n{\n template <typename context_t, typename ...Ts>\n typename context_t::return_t dispatch (context_t *c, Ts&&... ds) const\n {\n if (unlikely (!c->may_dispatch (this, &u.format))) return c->no_dispatch_return_value ();\n TRACE_DISPATCH (this, u.format);\n switch (u.format) {\n case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));\n case 2: return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));\n case 3: return_trace (c->dispatch (u.format3, std::forward<Ts> (ds)...));\n#ifndef HB_NO_BEYOND_64K\n case 4: return_trace (c->dispatch (u.format4, std::forward<Ts> (ds)...));\n case 5: return_trace (c->dispatch (u.format5, std::forward<Ts> (ds)...));\n#endif\n default:return_trace (c->default_return_value ());\n }\n }", " protected:\n union {\n HBUINT16\t\t\tformat;\t\t/* Format identifier */\n ContextFormat1_4<SmallTypes>\tformat1;\n ContextFormat2_5<SmallTypes>\tformat2;\n ContextFormat3\t\tformat3;\n#ifndef HB_NO_BEYOND_64K\n ContextFormat1_4<MediumTypes>\tformat4;\n ContextFormat2_5<MediumTypes>\tformat5;\n#endif\n } u;\n};", "\n/* Chaining Contextual lookups */", "struct ChainContextClosureLookupContext\n{\n ContextClosureFuncs funcs;\n ContextFormat context_format;\n const void *intersects_data[3];\n void *intersects_cache[3];\n void *intersected_glyphs_cache;\n};", "struct ChainContextCollectGlyphsLookupContext\n{\n ContextCollectGlyphsFuncs funcs;\n const void *collect_data[3];\n};", "struct ChainContextApplyLookupContext\n{\n ChainContextApplyFuncs funcs;\n const void *match_data[3];\n};", "template <typename HBUINT>\nstatic inline bool chain_context_intersects (const hb_set_t *glyphs,\n\t\t\t\t\t unsigned int backtrackCount,\n\t\t\t\t\t const HBUINT backtrack[],\n\t\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t unsigned int lookaheadCount,\n\t\t\t\t\t const HBUINT lookahead[],\n\t\t\t\t\t ChainContextClosureLookupContext &lookup_context)\n{\n return array_is_subset_of (glyphs,\n\t\t\t backtrackCount, backtrack,\n\t\t\t lookup_context.funcs.intersects,\n\t\t\t lookup_context.intersects_data[0],\n\t\t\t lookup_context.intersects_cache[0])\n && array_is_subset_of (glyphs,\n\t\t\t inputCount ? inputCount - 1 : 0, input,\n\t\t\t lookup_context.funcs.intersects,\n\t\t\t lookup_context.intersects_data[1],\n\t\t\t lookup_context.intersects_cache[1])\n && array_is_subset_of (glyphs,\n\t\t\t lookaheadCount, lookahead,\n\t\t\t lookup_context.funcs.intersects,\n\t\t\t lookup_context.intersects_data[2],\n\t\t\t lookup_context.intersects_cache[2]);\n}", "template <typename HBUINT>\nstatic inline void chain_context_closure_lookup (hb_closure_context_t *c,\n\t\t\t\t\t\t unsigned int backtrackCount,\n\t\t\t\t\t\t const HBUINT backtrack[],\n\t\t\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t\t unsigned int lookaheadCount,\n\t\t\t\t\t\t const HBUINT lookahead[],\n\t\t\t\t\t\t unsigned int lookupCount,\n\t\t\t\t\t\t const LookupRecord lookupRecord[],\n\t\t\t\t\t\t unsigned value,\n\t\t\t\t\t\t ChainContextClosureLookupContext &lookup_context)\n{\n if (chain_context_intersects (c->glyphs,\n\t\t\t\tbacktrackCount, backtrack,\n\t\t\t\tinputCount, input,\n\t\t\t\tlookaheadCount, lookahead,\n\t\t\t\tlookup_context))\n context_closure_recurse_lookups (c,\n\t\t inputCount, input,\n\t\t lookupCount, lookupRecord,\n\t\t value,\n\t\t lookup_context.context_format,\n\t\t lookup_context.intersects_data[1],\n\t\t lookup_context.funcs.intersected_glyphs,\n\t\t lookup_context.intersected_glyphs_cache);\n}", "template <typename HBUINT>\nstatic inline void chain_context_collect_glyphs_lookup (hb_collect_glyphs_context_t *c,\n\t\t\t\t\t\t\tunsigned int backtrackCount,\n\t\t\t\t\t\t\tconst HBUINT backtrack[],\n\t\t\t\t\t\t\tunsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t\t\tconst HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t\t\tunsigned int lookaheadCount,\n\t\t\t\t\t\t\tconst HBUINT lookahead[],\n\t\t\t\t\t\t\tunsigned int lookupCount,\n\t\t\t\t\t\t\tconst LookupRecord lookupRecord[],\n\t\t\t\t\t\t\tChainContextCollectGlyphsLookupContext &lookup_context)\n{\n collect_array (c, c->before,\n\t\t backtrackCount, backtrack,\n\t\t lookup_context.funcs.collect, lookup_context.collect_data[0]);\n collect_array (c, c->input,\n\t\t inputCount ? inputCount - 1 : 0, input,\n\t\t lookup_context.funcs.collect, lookup_context.collect_data[1]);\n collect_array (c, c->after,\n\t\t lookaheadCount, lookahead,\n\t\t lookup_context.funcs.collect, lookup_context.collect_data[2]);\n recurse_lookups (c,\n\t\t lookupCount, lookupRecord);\n}", "template <typename HBUINT>\nstatic inline bool chain_context_would_apply_lookup (hb_would_apply_context_t *c,\n\t\t\t\t\t\t unsigned int backtrackCount,\n\t\t\t\t\t\t const HBUINT backtrack[] HB_UNUSED,\n\t\t\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t\t unsigned int lookaheadCount,\n\t\t\t\t\t\t const HBUINT lookahead[] HB_UNUSED,\n\t\t\t\t\t\t unsigned int lookupCount HB_UNUSED,\n\t\t\t\t\t\t const LookupRecord lookupRecord[] HB_UNUSED,\n\t\t\t\t\t\t const ChainContextApplyLookupContext &lookup_context)\n{\n return (c->zero_context ? !backtrackCount && !lookaheadCount : true)\n && would_match_input (c,\n\t\t\t inputCount, input,\n\t\t\t lookup_context.funcs.match[1], lookup_context.match_data[1]);\n}", "template <typename HBUINT>\nstatic inline bool chain_context_apply_lookup (hb_ot_apply_context_t *c,\n\t\t\t\t\t unsigned int backtrackCount,\n\t\t\t\t\t const HBUINT backtrack[],\n\t\t\t\t\t unsigned int inputCount, /* Including the first glyph (not matched) */\n\t\t\t\t\t const HBUINT input[], /* Array of input values--start with second glyph */\n\t\t\t\t\t unsigned int lookaheadCount,\n\t\t\t\t\t const HBUINT lookahead[],\n\t\t\t\t\t unsigned int lookupCount,\n\t\t\t\t\t const LookupRecord lookupRecord[],\n\t\t\t\t\t const ChainContextApplyLookupContext &lookup_context)\n{\n unsigned end_index = c->buffer->idx;\n unsigned match_end = 0;\n unsigned match_positions[HB_MAX_CONTEXT_LENGTH];\n if (!(match_input (c,\n\t\t inputCount, input,\n\t\t lookup_context.funcs.match[1], lookup_context.match_data[1],\n\t\t &match_end, match_positions) && (end_index = match_end)\n && match_lookahead (c,\n\t\t\t lookaheadCount, lookahead,\n\t\t\t lookup_context.funcs.match[2], lookup_context.match_data[2],\n\t\t\t match_end, &end_index)))\n {\n c->buffer->unsafe_to_concat (c->buffer->idx, end_index);\n return false;\n }", " unsigned start_index = c->buffer->out_len;\n if (!match_backtrack (c,\n\t\t\tbacktrackCount, backtrack,\n\t\t\tlookup_context.funcs.match[0], lookup_context.match_data[0],\n\t\t\t&start_index))\n {\n c->buffer->unsafe_to_concat_from_outbuffer (start_index, end_index);\n return false;\n }", " c->buffer->unsafe_to_break_from_outbuffer (start_index, end_index);\n apply_lookup (c,\n\t\tinputCount, match_positions,\n\t\tlookupCount, lookupRecord,\n\t\tmatch_end);\n return true;\n}", "template <typename Types>\nstruct ChainRule\n{\n bool intersects (const hb_set_t *glyphs, ChainContextClosureLookupContext &lookup_context) const\n {\n const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n return chain_context_intersects (glyphs,\n\t\t\t\t backtrack.len, backtrack.arrayZ,\n\t\t\t\t input.lenP1, input.arrayZ,\n\t\t\t\t lookahead.len, lookahead.arrayZ,\n\t\t\t\t lookup_context);\n }", " void closure (hb_closure_context_t *c, unsigned value,\n\t\tChainContextClosureLookupContext &lookup_context) const\n {\n if (unlikely (c->lookup_limit_exceeded ())) return;", " const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n chain_context_closure_lookup (c,\n\t\t\t\t backtrack.len, backtrack.arrayZ,\n\t\t\t\t input.lenP1, input.arrayZ,\n\t\t\t\t lookahead.len, lookahead.arrayZ,\n\t\t\t\t lookup.len, lookup.arrayZ,\n\t\t\t\t value,\n\t\t\t\t lookup_context);\n }", " void closure_lookups (hb_closure_lookups_context_t *c,\n ChainContextClosureLookupContext &lookup_context) const\n {\n if (unlikely (c->lookup_limit_exceeded ())) return;\n if (!intersects (c->glyphs, lookup_context)) return;", " const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n recurse_lookups (c, lookup.len, lookup.arrayZ);\n }", " void collect_glyphs (hb_collect_glyphs_context_t *c,\n\t\t ChainContextCollectGlyphsLookupContext &lookup_context) const\n {\n const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n chain_context_collect_glyphs_lookup (c,\n\t\t\t\t\t backtrack.len, backtrack.arrayZ,\n\t\t\t\t\t input.lenP1, input.arrayZ,\n\t\t\t\t\t lookahead.len, lookahead.arrayZ,\n\t\t\t\t\t lookup.len, lookup.arrayZ,\n\t\t\t\t\t lookup_context);\n }", " bool would_apply (hb_would_apply_context_t *c,\n\t\t const ChainContextApplyLookupContext &lookup_context) const\n {\n const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n return chain_context_would_apply_lookup (c,\n\t\t\t\t\t backtrack.len, backtrack.arrayZ,\n\t\t\t\t\t input.lenP1, input.arrayZ,\n\t\t\t\t\t lookahead.len, lookahead.arrayZ, lookup.len,\n\t\t\t\t\t lookup.arrayZ, lookup_context);\n }", " bool apply (hb_ot_apply_context_t *c,\n\t const ChainContextApplyLookupContext &lookup_context) const\n {\n TRACE_APPLY (this);\n const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n return_trace (chain_context_apply_lookup (c,\n\t\t\t\t\t backtrack.len, backtrack.arrayZ,\n\t\t\t\t\t input.lenP1, input.arrayZ,\n\t\t\t\t\t lookahead.len, lookahead.arrayZ, lookup.len,\n\t\t\t\t\t lookup.arrayZ, lookup_context));\n }", " template<typename Iterator,\n\t hb_requires (hb_is_iterator (Iterator))>\n void serialize_array (hb_serialize_context_t *c,\n\t\t\tHBUINT16 len,\n\t\t\tIterator it) const\n {\n c->copy (len);\n for (const auto g : it)\n c->copy ((HBUINT16) g);\n }", " bool serialize (hb_serialize_context_t *c,\n\t\t const hb_map_t *lookup_map,\n\t\t const hb_map_t *backtrack_map,\n\t\t const hb_map_t *input_map = nullptr,\n\t\t const hb_map_t *lookahead_map = nullptr) const\n {\n TRACE_SERIALIZE (this);\n auto *out = c->start_embed (this);\n if (unlikely (!out)) return_trace (false);", " const hb_map_t *mapping = backtrack_map;\n serialize_array (c, backtrack.len, + backtrack.iter ()\n\t\t\t\t | hb_map (mapping));", " const auto &input = StructAfter<decltype (inputX)> (backtrack);\n if (input_map) mapping = input_map;\n serialize_array (c, input.lenP1, + input.iter ()\n\t\t\t\t | hb_map (mapping));", " const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n if (lookahead_map) mapping = lookahead_map;\n serialize_array (c, lookahead.len, + lookahead.iter ()\n\t\t\t\t | hb_map (mapping));", " const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);", " HBUINT16* lookupCount = c->embed (&(lookup.len));\n if (!lookupCount) return_trace (false);", " unsigned count = serialize_lookuprecord_array (c, lookup.as_array (), lookup_map);\n return_trace (c->check_assign (*lookupCount, count, HB_SERIALIZE_ERROR_INT_OVERFLOW));\n }", " bool subset (hb_subset_context_t *c,\n\t const hb_map_t *lookup_map,\n\t const hb_map_t *backtrack_map = nullptr,\n\t const hb_map_t *input_map = nullptr,\n\t const hb_map_t *lookahead_map = nullptr) const\n {\n TRACE_SUBSET (this);", " const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);", " if (!backtrack_map)\n {\n const hb_set_t &glyphset = *c->plan->glyphset_gsub ();\n if (!hb_all (backtrack, glyphset) ||\n\t !hb_all (input, glyphset) ||\n\t !hb_all (lookahead, glyphset))\n\treturn_trace (false);", " serialize (c->serializer, lookup_map, c->plan->glyph_map);\n }\n else\n {\n if (!hb_all (backtrack, backtrack_map) ||\n\t !hb_all (input, input_map) ||\n\t !hb_all (lookahead, lookahead_map))\n\treturn_trace (false);", " serialize (c->serializer, lookup_map, backtrack_map, input_map, lookahead_map);\n }", " return_trace (true);\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n if (!backtrack.sanitize (c)) return_trace (false);\n const auto &input = StructAfter<decltype (inputX)> (backtrack);\n if (!input.sanitize (c)) return_trace (false);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n if (!lookahead.sanitize (c)) return_trace (false);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n return_trace (lookup.sanitize (c));\n }", " protected:\n Array16Of<typename Types::HBUINT>\n\t\tbacktrack;\t\t/* Array of backtracking values\n\t\t\t\t\t * (to be matched before the input\n\t\t\t\t\t * sequence) */\n HeadlessArrayOf<typename Types::HBUINT>\n\t\tinputX;\t\t\t/* Array of input values (start with\n\t\t\t\t\t * second glyph) */\n Array16Of<typename Types::HBUINT>\n\t\tlookaheadX;\t\t/* Array of lookahead values's (to be\n\t\t\t\t\t * matched after the input sequence) */\n Array16Of<LookupRecord>\n\t\tlookupX;\t\t/* Array of LookupRecords--in\n\t\t\t\t\t * design order) */\n public:\n DEFINE_SIZE_MIN (8);\n};", "template <typename Types>\nstruct ChainRuleSet\n{\n using ChainRule = OT::ChainRule<Types>;", " bool intersects (const hb_set_t *glyphs, ChainContextClosureLookupContext &lookup_context) const\n {\n return\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_map ([&] (const ChainRule &_) { return _.intersects (glyphs, lookup_context); })\n | hb_any\n ;\n }\n void closure (hb_closure_context_t *c, unsigned value, ChainContextClosureLookupContext &lookup_context) const\n {\n if (unlikely (c->lookup_limit_exceeded ())) return;", " return\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const ChainRule &_) { _.closure (c, value, lookup_context); })\n ;\n }", " void closure_lookups (hb_closure_lookups_context_t *c,\n ChainContextClosureLookupContext &lookup_context) const\n {\n if (unlikely (c->lookup_limit_exceeded ())) return;", " + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const ChainRule &_) { _.closure_lookups (c, lookup_context); })\n ;\n }", " void collect_glyphs (hb_collect_glyphs_context_t *c, ChainContextCollectGlyphsLookupContext &lookup_context) const\n {\n return\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const ChainRule &_) { _.collect_glyphs (c, lookup_context); })\n ;\n }", " bool would_apply (hb_would_apply_context_t *c,\n\t\t const ChainContextApplyLookupContext &lookup_context) const\n {\n return\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_map ([&] (const ChainRule &_) { return _.would_apply (c, lookup_context); })\n | hb_any\n ;\n }", " bool apply (hb_ot_apply_context_t *c,\n\t const ChainContextApplyLookupContext &lookup_context) const\n {\n TRACE_APPLY (this);\n return_trace (\n + hb_iter (rule)\n | hb_map (hb_add (this))\n | hb_map ([&] (const ChainRule &_) { return _.apply (c, lookup_context); })\n | hb_any\n )\n ;\n }", " bool subset (hb_subset_context_t *c,\n\t const hb_map_t *lookup_map,\n\t const hb_map_t *backtrack_klass_map = nullptr,\n\t const hb_map_t *input_klass_map = nullptr,\n\t const hb_map_t *lookahead_klass_map = nullptr) const\n {\n TRACE_SUBSET (this);", " auto snap = c->serializer->snapshot ();\n auto *out = c->serializer->start_embed (*this);\n if (unlikely (!c->serializer->extend_min (out))) return_trace (false);", " for (const Offset16To<ChainRule>& _ : rule)\n {\n if (!_) continue;\n auto o_snap = c->serializer->snapshot ();\n auto *o = out->rule.serialize_append (c->serializer);\n if (unlikely (!o)) continue;", " if (!o->serialize_subset (c, _, this,\n\t\t\t\tlookup_map,\n\t\t\t\tbacktrack_klass_map,\n\t\t\t\tinput_klass_map,\n\t\t\t\tlookahead_klass_map))\n {\n\tout->rule.pop ();\n\tc->serializer->revert (o_snap);\n }\n }", " bool ret = bool (out->rule);\n if (!ret) c->serializer->revert (snap);", " return_trace (ret);\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (rule.sanitize (c, this));\n }", " protected:\n Array16OfOffset16To<ChainRule>\n\t\trule;\t\t\t/* Array of ChainRule tables\n\t\t\t\t\t * ordered by preference */\n public:\n DEFINE_SIZE_ARRAY (2, rule);\n};", "template <typename Types>\nstruct ChainContextFormat1_4\n{\n using ChainRuleSet = OT::ChainRuleSet<Types>;", " bool intersects (const hb_set_t *glyphs) const\n {\n struct ChainContextClosureLookupContext lookup_context = {\n {intersects_glyph, intersected_glyph},\n ContextFormat::SimpleContext,\n {nullptr, nullptr, nullptr}\n };", " return\n + hb_zip (this+coverage, ruleSet)\n | hb_filter (*glyphs, hb_first)\n | hb_map (hb_second)\n | hb_map (hb_add (this))\n | hb_map ([&] (const ChainRuleSet &_) { return _.intersects (glyphs, lookup_context); })\n | hb_any\n ;\n }", " bool may_have_non_1to1 () const\n { return true; }", " void closure (hb_closure_context_t *c) const\n {\n hb_set_t& cur_active_glyphs = c->push_cur_active_glyphs ();\n get_coverage ().intersect_set (c->previous_parent_active_glyphs (),\n cur_active_glyphs);", " struct ChainContextClosureLookupContext lookup_context = {\n {intersects_glyph, intersected_glyph},\n ContextFormat::SimpleContext,\n {nullptr, nullptr, nullptr}\n };", " + hb_zip (this+coverage, hb_range ((unsigned) ruleSet.len))\n | hb_filter ([&] (hb_codepoint_t _) {\n return c->previous_parent_active_glyphs ().has (_);\n }, hb_first)\n | hb_map ([&](const hb_pair_t<hb_codepoint_t, unsigned> _) { return hb_pair_t<unsigned, const ChainRuleSet&> (_.first, this+ruleSet[_.second]); })\n | hb_apply ([&] (const hb_pair_t<unsigned, const ChainRuleSet&>& _) { _.second.closure (c, _.first, lookup_context); })\n ;", " c->pop_cur_done_glyphs ();\n }", " void closure_lookups (hb_closure_lookups_context_t *c) const\n {\n struct ChainContextClosureLookupContext lookup_context = {\n {intersects_glyph, nullptr},\n ContextFormat::SimpleContext,\n {nullptr, nullptr, nullptr}\n };", " + hb_zip (this+coverage, ruleSet)\n | hb_filter (*c->glyphs, hb_first)\n | hb_map (hb_second)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const ChainRuleSet &_) { _.closure_lookups (c, lookup_context); })\n ;\n }", " void collect_variation_indices (hb_collect_variation_indices_context_t *c) const {}", " void collect_glyphs (hb_collect_glyphs_context_t *c) const\n {\n (this+coverage).collect_coverage (c->input);", " struct ChainContextCollectGlyphsLookupContext lookup_context = {\n {collect_glyph},\n {nullptr, nullptr, nullptr}\n };", " + hb_iter (ruleSet)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const ChainRuleSet &_) { _.collect_glyphs (c, lookup_context); })\n ;\n }", " bool would_apply (hb_would_apply_context_t *c) const\n {\n const ChainRuleSet &rule_set = this+ruleSet[(this+coverage).get_coverage (c->glyphs[0])];\n struct ChainContextApplyLookupContext lookup_context = {\n {{match_glyph, match_glyph, match_glyph}},\n {nullptr, nullptr, nullptr}\n };\n return rule_set.would_apply (c, lookup_context);\n }", " const Coverage &get_coverage () const { return this+coverage; }", " bool apply (hb_ot_apply_context_t *c) const\n {\n TRACE_APPLY (this);\n unsigned int index = (this+coverage).get_coverage (c->buffer->cur().codepoint);\n if (likely (index == NOT_COVERED)) return_trace (false);", " const ChainRuleSet &rule_set = this+ruleSet[index];\n struct ChainContextApplyLookupContext lookup_context = {\n {{match_glyph, match_glyph, match_glyph}},\n {nullptr, nullptr, nullptr}\n };\n return_trace (rule_set.apply (c, lookup_context));\n }", " bool subset (hb_subset_context_t *c) const\n {\n TRACE_SUBSET (this);\n const hb_set_t &glyphset = *c->plan->glyphset_gsub ();\n const hb_map_t &glyph_map = *c->plan->glyph_map;", " auto *out = c->serializer->start_embed (*this);\n if (unlikely (!c->serializer->extend_min (out))) return_trace (false);\n out->format = format;", " const hb_map_t *lookup_map = c->table_tag == HB_OT_TAG_GSUB ? &c->plan->gsub_lookups : &c->plan->gpos_lookups;\n hb_sorted_vector_t<hb_codepoint_t> new_coverage;\n + hb_zip (this+coverage, ruleSet)\n | hb_filter (glyphset, hb_first)\n | hb_filter (subset_offset_array (c, out->ruleSet, this, lookup_map), hb_second)\n | hb_map (hb_first)\n | hb_map (glyph_map)\n | hb_sink (new_coverage)\n ;", " out->coverage.serialize_serialize (c->serializer, new_coverage.iter ());\n return_trace (bool (new_coverage));\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (coverage.sanitize (c, this) && ruleSet.sanitize (c, this));\n }", " protected:\n HBUINT16\tformat;\t\t\t/* Format identifier--format = 1 */\n typename Types::template OffsetTo<Coverage>\n\t\tcoverage;\t\t/* Offset to Coverage table--from\n\t\t\t\t\t * beginning of table */\n Array16Of<typename Types::template OffsetTo<ChainRuleSet>>\n\t\truleSet;\t\t/* Array of ChainRuleSet tables\n\t\t\t\t\t * ordered by Coverage Index */\n public:\n DEFINE_SIZE_ARRAY (2 + 2 * Types::size, ruleSet);\n};", "template <typename Types>\nstruct ChainContextFormat2_5\n{\n using ChainRuleSet = OT::ChainRuleSet<SmallTypes>;", " bool intersects (const hb_set_t *glyphs) const\n {\n if (!(this+coverage).intersects (glyphs))\n return false;", " const ClassDef &backtrack_class_def = this+backtrackClassDef;\n const ClassDef &input_class_def = this+inputClassDef;\n const ClassDef &lookahead_class_def = this+lookaheadClassDef;", " hb_map_t caches[3] = {};\n struct ChainContextClosureLookupContext lookup_context = {\n {intersects_class, nullptr},\n ContextFormat::ClassBasedContext,\n {&backtrack_class_def,\n &input_class_def,\n &lookahead_class_def},\n {&caches[0], &caches[1], &caches[2]}\n };", " hb_set_t retained_coverage_glyphs;\n (this+coverage).intersect_set (*glyphs, retained_coverage_glyphs);", " hb_set_t coverage_glyph_classes;\n input_class_def.intersected_classes (&retained_coverage_glyphs, &coverage_glyph_classes);", " return\n + hb_iter (ruleSet)\n | hb_map (hb_add (this))\n | hb_enumerate\n | hb_map ([&] (const hb_pair_t<unsigned, const ChainRuleSet &> p)\n\t { return input_class_def.intersects_class (glyphs, p.first) &&\n\t\t coverage_glyph_classes.has (p.first) &&\n\t\t p.second.intersects (glyphs, lookup_context); })\n | hb_any\n ;\n }", " bool may_have_non_1to1 () const\n { return true; }", " void closure (hb_closure_context_t *c) const\n {\n if (!(this+coverage).intersects (c->glyphs))\n return;", " hb_set_t& cur_active_glyphs = c->push_cur_active_glyphs ();\n get_coverage ().intersect_set (c->previous_parent_active_glyphs (),\n cur_active_glyphs);", "\n const ClassDef &backtrack_class_def = this+backtrackClassDef;\n const ClassDef &input_class_def = this+inputClassDef;\n const ClassDef &lookahead_class_def = this+lookaheadClassDef;", " hb_map_t caches[3] = {};\n intersected_class_cache_t intersected_cache;\n struct ChainContextClosureLookupContext lookup_context = {\n {intersects_class, intersected_class_glyphs},\n ContextFormat::ClassBasedContext,\n {&backtrack_class_def,\n &input_class_def,\n &lookahead_class_def},\n {&caches[0], &caches[1], &caches[2]},\n &intersected_cache\n };", " + hb_enumerate (ruleSet)\n | hb_filter ([&] (unsigned _)\n { return input_class_def.intersects_class (&c->parent_active_glyphs (), _); },\n\t\t hb_first)\n | hb_apply ([&] (const hb_pair_t<unsigned, const typename Types::template OffsetTo<ChainRuleSet>&> _)\n {\n const ChainRuleSet& chainrule_set = this+_.second;\n chainrule_set.closure (c, _.first, lookup_context);\n })\n ;", " c->pop_cur_done_glyphs ();\n }", " void closure_lookups (hb_closure_lookups_context_t *c) const\n {\n if (!(this+coverage).intersects (c->glyphs))\n return;", " const ClassDef &backtrack_class_def = this+backtrackClassDef;\n const ClassDef &input_class_def = this+inputClassDef;\n const ClassDef &lookahead_class_def = this+lookaheadClassDef;", " hb_map_t caches[3] = {};\n struct ChainContextClosureLookupContext lookup_context = {\n {intersects_class, nullptr},\n ContextFormat::ClassBasedContext,\n {&backtrack_class_def,\n &input_class_def,\n &lookahead_class_def},\n {&caches[0], &caches[1], &caches[2]}\n };", " + hb_iter (ruleSet)\n | hb_map (hb_add (this))\n | hb_enumerate\n | hb_filter([&] (unsigned klass)\n { return input_class_def.intersects_class (c->glyphs, klass); }, hb_first)\n | hb_map (hb_second)\n | hb_apply ([&] (const ChainRuleSet &_)\n { _.closure_lookups (c, lookup_context); })\n ;\n }", " void collect_variation_indices (hb_collect_variation_indices_context_t *c) const {}", " void collect_glyphs (hb_collect_glyphs_context_t *c) const\n {\n (this+coverage).collect_coverage (c->input);", " const ClassDef &backtrack_class_def = this+backtrackClassDef;\n const ClassDef &input_class_def = this+inputClassDef;\n const ClassDef &lookahead_class_def = this+lookaheadClassDef;", " struct ChainContextCollectGlyphsLookupContext lookup_context = {\n {collect_class},\n {&backtrack_class_def,\n &input_class_def,\n &lookahead_class_def}\n };", " + hb_iter (ruleSet)\n | hb_map (hb_add (this))\n | hb_apply ([&] (const ChainRuleSet &_) { _.collect_glyphs (c, lookup_context); })\n ;\n }", " bool would_apply (hb_would_apply_context_t *c) const\n {\n const ClassDef &backtrack_class_def = this+backtrackClassDef;\n const ClassDef &input_class_def = this+inputClassDef;\n const ClassDef &lookahead_class_def = this+lookaheadClassDef;", " unsigned int index = input_class_def.get_class (c->glyphs[0]);\n const ChainRuleSet &rule_set = this+ruleSet[index];\n struct ChainContextApplyLookupContext lookup_context = {\n {{match_class, match_class, match_class}},\n {&backtrack_class_def,\n &input_class_def,\n &lookahead_class_def}\n };\n return rule_set.would_apply (c, lookup_context);\n }", " const Coverage &get_coverage () const { return this+coverage; }", " unsigned cache_cost () const\n {\n unsigned c = (this+lookaheadClassDef).cost () * ruleSet.len;\n return c >= 4 ? c : 0;\n }\n bool cache_func (hb_ot_apply_context_t *c, bool enter) const\n {\n if (enter)\n {\n if (!HB_BUFFER_TRY_ALLOCATE_VAR (c->buffer, syllable))\n\treturn false;\n auto &info = c->buffer->info;\n unsigned count = c->buffer->len;\n for (unsigned i = 0; i < count; i++)\n\tinfo[i].syllable() = 255;\n c->new_syllables = 255;\n return true;\n }\n else\n {\n c->new_syllables = (unsigned) -1;\n HB_BUFFER_DEALLOCATE_VAR (c->buffer, syllable);\n return true;\n }\n }", " bool apply (hb_ot_apply_context_t *c, bool cached = false) const\n {\n TRACE_APPLY (this);\n unsigned int index = (this+coverage).get_coverage (c->buffer->cur().codepoint);\n if (likely (index == NOT_COVERED)) return_trace (false);", " const ClassDef &backtrack_class_def = this+backtrackClassDef;\n const ClassDef &input_class_def = this+inputClassDef;\n const ClassDef &lookahead_class_def = this+lookaheadClassDef;", " /* For ChainContextFormat2_5 we cache the LookaheadClassDef instead of InputClassDef.\n * The reason is that most heavy fonts want to identify a glyph in context and apply\n * a lookup to it. In this scenario, the length of the input sequence is one, whereas\n * the lookahead / backtrack are typically longer. The one glyph in input sequence is\n * looked-up below and no input glyph is looked up in individual rules, whereas the\n * lookahead and backtrack glyphs are tried. Since we match lookahead before backtrack,\n * we should cache lookahead. This decisions showed a 20% improvement in shaping of\n * the Gulzar font.\n */", " struct ChainContextApplyLookupContext lookup_context = {\n {{cached && &backtrack_class_def == &lookahead_class_def ? match_class_cached : match_class,\n cached && &input_class_def == &lookahead_class_def ? match_class_cached : match_class,\n cached ? match_class_cached : match_class}},\n {&backtrack_class_def,\n &input_class_def,\n &lookahead_class_def}\n };", " index = input_class_def.get_class (c->buffer->cur().codepoint);\n const ChainRuleSet &rule_set = this+ruleSet[index];\n return_trace (rule_set.apply (c, lookup_context));\n }", " bool subset (hb_subset_context_t *c) const\n {\n TRACE_SUBSET (this);\n auto *out = c->serializer->start_embed (*this);\n if (unlikely (!c->serializer->extend_min (out))) return_trace (false);\n out->format = format;\n out->coverage.serialize_subset (c, coverage, this);", " hb_map_t backtrack_klass_map;\n hb_map_t input_klass_map;\n hb_map_t lookahead_klass_map;", " out->backtrackClassDef.serialize_subset (c, backtrackClassDef, this, &backtrack_klass_map);\n // TODO: subset inputClassDef based on glyphs survived in Coverage subsetting\n out->inputClassDef.serialize_subset (c, inputClassDef, this, &input_klass_map);\n out->lookaheadClassDef.serialize_subset (c, lookaheadClassDef, this, &lookahead_klass_map);", " if (unlikely (!c->serializer->propagate_error (backtrack_klass_map,\n\t\t\t\t\t\t input_klass_map,\n\t\t\t\t\t\t lookahead_klass_map)))\n return_trace (false);", " const hb_set_t* glyphset = c->plan->glyphset_gsub ();\n hb_set_t retained_coverage_glyphs;\n (this+coverage).intersect_set (*glyphset, retained_coverage_glyphs);", " hb_set_t coverage_glyph_classes;\n (this+inputClassDef).intersected_classes (&retained_coverage_glyphs, &coverage_glyph_classes);", " int non_zero_index = -1, index = 0;\n bool ret = true;\n const hb_map_t *lookup_map = c->table_tag == HB_OT_TAG_GSUB ? &c->plan->gsub_lookups : &c->plan->gpos_lookups;\n auto last_non_zero = c->serializer->snapshot ();\n for (const auto& _ : + hb_enumerate (ruleSet)\n\t\t\t | hb_filter (input_klass_map, hb_first))\n {\n auto *o = out->ruleSet.serialize_append (c->serializer);\n if (unlikely (!o))\n {\n\tret = false;\n\tbreak;\n }\n if (coverage_glyph_classes.has (_.first) &&\n o->serialize_subset (c, _.second, this,\n\t\t\t lookup_map,\n\t\t\t &backtrack_klass_map,\n\t\t\t &input_klass_map,\n\t\t\t &lookahead_klass_map))\n {\n last_non_zero = c->serializer->snapshot ();\n\tnon_zero_index = index;\n }", " index++;\n }", " if (!ret || non_zero_index == -1) return_trace (false);", " // prune empty trailing ruleSets\n if (index > non_zero_index) {\n c->serializer->revert (last_non_zero);\n out->ruleSet.len = non_zero_index + 1;\n }", " return_trace (bool (out->ruleSet));\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (coverage.sanitize (c, this) &&\n\t\t backtrackClassDef.sanitize (c, this) &&\n\t\t inputClassDef.sanitize (c, this) &&\n\t\t lookaheadClassDef.sanitize (c, this) &&\n\t\t ruleSet.sanitize (c, this));\n }", " protected:\n HBUINT16\tformat;\t\t\t/* Format identifier--format = 2 */\n typename Types::template OffsetTo<Coverage>\n\t\tcoverage;\t\t/* Offset to Coverage table--from\n\t\t\t\t\t * beginning of table */\n typename Types::template OffsetTo<ClassDef>\n\t\tbacktrackClassDef;\t/* Offset to glyph ClassDef table\n\t\t\t\t\t * containing backtrack sequence\n\t\t\t\t\t * data--from beginning of table */\n typename Types::template OffsetTo<ClassDef>\n\t\tinputClassDef;\t\t/* Offset to glyph ClassDef\n\t\t\t\t\t * table containing input sequence\n\t\t\t\t\t * data--from beginning of table */\n typename Types::template OffsetTo<ClassDef>\n\t\tlookaheadClassDef;\t/* Offset to glyph ClassDef table\n\t\t\t\t\t * containing lookahead sequence\n\t\t\t\t\t * data--from beginning of table */\n Array16Of<typename Types::template OffsetTo<ChainRuleSet>>\n\t\truleSet;\t\t/* Array of ChainRuleSet tables\n\t\t\t\t\t * ordered by class */\n public:\n DEFINE_SIZE_ARRAY (4 + 4 * Types::size, ruleSet);\n};", "struct ChainContextFormat3\n{\n using RuleSet = OT::RuleSet<SmallTypes>;", " bool intersects (const hb_set_t *glyphs) const\n {\n const auto &input = StructAfter<decltype (inputX)> (backtrack);", " if (!(this+input[0]).intersects (glyphs))\n return false;", " const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n struct ChainContextClosureLookupContext lookup_context = {\n {intersects_coverage, nullptr},\n ContextFormat::CoverageBasedContext,\n {this, this, this}\n };\n return chain_context_intersects (glyphs,\n\t\t\t\t backtrack.len, (const HBUINT16 *) backtrack.arrayZ,\n\t\t\t\t input.len, (const HBUINT16 *) input.arrayZ + 1,\n\t\t\t\t lookahead.len, (const HBUINT16 *) lookahead.arrayZ,\n\t\t\t\t lookup_context);\n }", " bool may_have_non_1to1 () const\n { return true; }", " void closure (hb_closure_context_t *c) const\n {\n const auto &input = StructAfter<decltype (inputX)> (backtrack);", " if (!(this+input[0]).intersects (c->glyphs))\n return;", " hb_set_t& cur_active_glyphs = c->push_cur_active_glyphs ();\n get_coverage ().intersect_set (c->previous_parent_active_glyphs (),\n cur_active_glyphs);", "\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n struct ChainContextClosureLookupContext lookup_context = {\n {intersects_coverage, intersected_coverage_glyphs},\n ContextFormat::CoverageBasedContext,\n {this, this, this}\n };\n chain_context_closure_lookup (c,\n\t\t\t\t backtrack.len, (const HBUINT16 *) backtrack.arrayZ,\n\t\t\t\t input.len, (const HBUINT16 *) input.arrayZ + 1,\n\t\t\t\t lookahead.len, (const HBUINT16 *) lookahead.arrayZ,\n\t\t\t\t lookup.len, lookup.arrayZ,\n\t\t\t\t 0, lookup_context);", " c->pop_cur_done_glyphs ();\n }", " void closure_lookups (hb_closure_lookups_context_t *c) const\n {\n if (!intersects (c->glyphs))\n return;", " const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n recurse_lookups (c, lookup.len, lookup.arrayZ);\n }", " void collect_variation_indices (hb_collect_variation_indices_context_t *c) const {}", " void collect_glyphs (hb_collect_glyphs_context_t *c) const\n {\n const auto &input = StructAfter<decltype (inputX)> (backtrack);", " (this+input[0]).collect_coverage (c->input);", " const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);", " struct ChainContextCollectGlyphsLookupContext lookup_context = {\n {collect_coverage},\n {this, this, this}\n };\n chain_context_collect_glyphs_lookup (c,\n\t\t\t\t\t backtrack.len, (const HBUINT16 *) backtrack.arrayZ,\n\t\t\t\t\t input.len, (const HBUINT16 *) input.arrayZ + 1,\n\t\t\t\t\t lookahead.len, (const HBUINT16 *) lookahead.arrayZ,\n\t\t\t\t\t lookup.len, lookup.arrayZ,\n\t\t\t\t\t lookup_context);\n }", " bool would_apply (hb_would_apply_context_t *c) const\n {\n const auto &input = StructAfter<decltype (inputX)> (backtrack);\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n struct ChainContextApplyLookupContext lookup_context = {\n {{match_coverage, match_coverage, match_coverage}},\n {this, this, this}\n };\n return chain_context_would_apply_lookup (c,\n\t\t\t\t\t backtrack.len, (const HBUINT16 *) backtrack.arrayZ,\n\t\t\t\t\t input.len, (const HBUINT16 *) input.arrayZ + 1,\n\t\t\t\t\t lookahead.len, (const HBUINT16 *) lookahead.arrayZ,\n\t\t\t\t\t lookup.len, lookup.arrayZ, lookup_context);\n }", " const Coverage &get_coverage () const\n {\n const auto &input = StructAfter<decltype (inputX)> (backtrack);\n return this+input[0];\n }", " bool apply (hb_ot_apply_context_t *c) const\n {\n TRACE_APPLY (this);\n const auto &input = StructAfter<decltype (inputX)> (backtrack);", " unsigned int index = (this+input[0]).get_coverage (c->buffer->cur().codepoint);\n if (likely (index == NOT_COVERED)) return_trace (false);", " const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n struct ChainContextApplyLookupContext lookup_context = {\n {{match_coverage, match_coverage, match_coverage}},\n {this, this, this}\n };\n return_trace (chain_context_apply_lookup (c,\n\t\t\t\t\t backtrack.len, (const HBUINT16 *) backtrack.arrayZ,\n\t\t\t\t\t input.len, (const HBUINT16 *) input.arrayZ + 1,\n\t\t\t\t\t lookahead.len, (const HBUINT16 *) lookahead.arrayZ,\n\t\t\t\t\t lookup.len, lookup.arrayZ, lookup_context));\n }", " template<typename Iterator,\n\t hb_requires (hb_is_iterator (Iterator))>\n bool serialize_coverage_offsets (hb_subset_context_t *c, Iterator it, const void* base) const\n {\n TRACE_SERIALIZE (this);\n auto *out = c->serializer->start_embed<Array16OfOffset16To<Coverage>> ();", " if (unlikely (!c->serializer->allocate_size<HBUINT16> (HBUINT16::static_size)))\n return_trace (false);", " for (auto& offset : it) {\n auto *o = out->serialize_append (c->serializer);\n if (unlikely (!o) || !o->serialize_subset (c, offset, base))\n return_trace (false);\n }", " return_trace (true);\n }", " bool subset (hb_subset_context_t *c) const\n {\n TRACE_SUBSET (this);", " auto *out = c->serializer->start_embed (this);\n if (unlikely (!out)) return_trace (false);\n if (unlikely (!c->serializer->embed (this->format))) return_trace (false);", " if (!serialize_coverage_offsets (c, backtrack.iter (), this))\n return_trace (false);", " const auto &input = StructAfter<decltype (inputX)> (backtrack);\n if (!serialize_coverage_offsets (c, input.iter (), this))\n return_trace (false);", " const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n if (!serialize_coverage_offsets (c, lookahead.iter (), this))\n return_trace (false);", " const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n const hb_map_t *lookup_map = c->table_tag == HB_OT_TAG_GSUB ? &c->plan->gsub_lookups : &c->plan->gpos_lookups;", " HBUINT16 *lookupCount = c->serializer->copy<HBUINT16> (lookup.len);\n if (!lookupCount) return_trace (false);", " unsigned count = serialize_lookuprecord_array (c->serializer, lookup.as_array (), lookup_map);\n return_trace (c->serializer->check_assign (*lookupCount, count, HB_SERIALIZE_ERROR_INT_OVERFLOW));\n }", " bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n if (!backtrack.sanitize (c, this)) return_trace (false);\n const auto &input = StructAfter<decltype (inputX)> (backtrack);\n if (!input.sanitize (c, this)) return_trace (false);\n if (!input.len) return_trace (false); /* To be consistent with Context. */\n const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);\n if (!lookahead.sanitize (c, this)) return_trace (false);\n const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);\n return_trace (lookup.sanitize (c));\n }", " protected:\n HBUINT16\tformat;\t\t\t/* Format identifier--format = 3 */\n Array16OfOffset16To<Coverage>\n\t\tbacktrack;\t\t/* Array of coverage tables\n\t\t\t\t\t * in backtracking sequence, in glyph\n\t\t\t\t\t * sequence order */\n Array16OfOffset16To<Coverage>\n\t\tinputX\t\t;\t/* Array of coverage\n\t\t\t\t\t * tables in input sequence, in glyph\n\t\t\t\t\t * sequence order */\n Array16OfOffset16To<Coverage>\n\t\tlookaheadX;\t\t/* Array of coverage tables\n\t\t\t\t\t * in lookahead sequence, in glyph\n\t\t\t\t\t * sequence order */\n Array16Of<LookupRecord>\n\t\tlookupX;\t\t/* Array of LookupRecords--in\n\t\t\t\t\t * design order) */\n public:\n DEFINE_SIZE_MIN (10);\n};", "struct ChainContext\n{\n template <typename context_t, typename ...Ts>\n typename context_t::return_t dispatch (context_t *c, Ts&&... ds) const\n {\n if (unlikely (!c->may_dispatch (this, &u.format))) return c->no_dispatch_return_value ();\n TRACE_DISPATCH (this, u.format);\n switch (u.format) {\n case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));\n case 2: return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));\n case 3: return_trace (c->dispatch (u.format3, std::forward<Ts> (ds)...));\n#ifndef HB_NO_BEYOND_64K\n case 4: return_trace (c->dispatch (u.format4, std::forward<Ts> (ds)...));\n case 5: return_trace (c->dispatch (u.format5, std::forward<Ts> (ds)...));\n#endif\n default:return_trace (c->default_return_value ());\n }\n }", " protected:\n union {\n HBUINT16\t\t\t\tformat;\t/* Format identifier */\n ChainContextFormat1_4<SmallTypes>\tformat1;\n ChainContextFormat2_5<SmallTypes>\tformat2;\n ChainContextFormat3\t\t\tformat3;\n#ifndef HB_NO_BEYOND_64K\n ChainContextFormat1_4<MediumTypes>\tformat4;\n ChainContextFormat2_5<MediumTypes>\tformat5;\n#endif\n } u;\n};", "\ntemplate <typename T>\nstruct ExtensionFormat1\n{\n unsigned int get_type () const { return extensionLookupType; }", " template <typename X>\n const X& get_subtable () const\n { return this + reinterpret_cast<const Offset32To<typename T::SubTable> &> (extensionOffset); }", " template <typename context_t, typename ...Ts>\n typename context_t::return_t dispatch (context_t *c, Ts&&... ds) const\n {\n if (unlikely (!c->may_dispatch (this, this))) return c->no_dispatch_return_value ();\n TRACE_DISPATCH (this, format);\n return_trace (get_subtable<typename T::SubTable> ().dispatch (c, get_type (), std::forward<Ts> (ds)...));\n }", " void collect_variation_indices (hb_collect_variation_indices_context_t *c) const\n { dispatch (c); }", " /* This is called from may_dispatch() above with hb_sanitize_context_t. */\n bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n return_trace (c->check_struct (this) &&\n\t\t extensionLookupType != T::SubTable::Extension);\n }", " bool subset (hb_subset_context_t *c) const\n {\n TRACE_SUBSET (this);", " auto *out = c->serializer->start_embed (this);\n if (unlikely (!out || !c->serializer->extend_min (out))) return_trace (false);", " out->format = format;\n out->extensionLookupType = extensionLookupType;", " const auto& src_offset =\n reinterpret_cast<const Offset32To<typename T::SubTable> &> (extensionOffset);\n auto& dest_offset =\n reinterpret_cast<Offset32To<typename T::SubTable> &> (out->extensionOffset);", " return_trace (dest_offset.serialize_subset (c, src_offset, this, get_type ()));\n }", " protected:\n HBUINT16\tformat;\t\t\t/* Format identifier. Set to 1. */\n HBUINT16\textensionLookupType;\t/* Lookup type of subtable referenced\n\t\t\t\t\t * by ExtensionOffset (i.e. the\n\t\t\t\t\t * extension subtable). */\n Offset32\textensionOffset;\t/* Offset to the extension subtable,\n\t\t\t\t\t * of lookup type subtable. */\n public:\n DEFINE_SIZE_STATIC (8);\n};", "template <typename T>\nstruct Extension\n{\n unsigned int get_type () const\n {\n switch (u.format) {\n case 1: return u.format1.get_type ();\n default:return 0;\n }\n }\n template <typename X>\n const X& get_subtable () const\n {\n switch (u.format) {\n case 1: return u.format1.template get_subtable<typename T::SubTable> ();\n default:return Null (typename T::SubTable);\n }\n }", " // Specialization of dispatch for subset. dispatch() normally just\n // dispatches to the sub table this points too, but for subset\n // we need to run subset on this subtable too.\n template <typename ...Ts>\n typename hb_subset_context_t::return_t dispatch (hb_subset_context_t *c, Ts&&... ds) const\n {\n switch (u.format) {\n case 1: return u.format1.subset (c);\n default: return c->default_return_value ();\n }\n }", " template <typename context_t, typename ...Ts>\n typename context_t::return_t dispatch (context_t *c, Ts&&... ds) const\n {\n if (unlikely (!c->may_dispatch (this, &u.format))) return c->no_dispatch_return_value ();\n TRACE_DISPATCH (this, u.format);\n switch (u.format) {\n case 1: return_trace (u.format1.dispatch (c, std::forward<Ts> (ds)...));\n default:return_trace (c->default_return_value ());\n }\n }", " protected:\n union {\n HBUINT16\t\tformat;\t\t/* Format identifier */\n ExtensionFormat1<T>\tformat1;\n } u;\n};", "\n/*\n * GSUB/GPOS Common\n */", "struct hb_ot_layout_lookup_accelerator_t\n{\n template <typename TLookup>\n static hb_ot_layout_lookup_accelerator_t *create (const TLookup &lookup)\n {\n unsigned count = lookup.get_subtable_count ();", " unsigned size = sizeof (hb_ot_layout_lookup_accelerator_t) -\n\t\t HB_VAR_ARRAY * sizeof (hb_accelerate_subtables_context_t::hb_applicable_t) +\n\t\t count * sizeof (hb_accelerate_subtables_context_t::hb_applicable_t);", " /* The following is a calloc because when we are collecting subtables,\n * some of them might be invalid and hence not collect; as a result,\n * we might not fill in all the count entries of the subtables array.\n * Zeroing it allows the set digest to gatekeep it without having to\n * initialize it further. */\n auto *thiz = (hb_ot_layout_lookup_accelerator_t *) hb_calloc (1, size);\n if (unlikely (!thiz))\n return nullptr;", " hb_accelerate_subtables_context_t c_accelerate_subtables (thiz->subtables);\n lookup.dispatch (&c_accelerate_subtables);", " thiz->digest.init ();\n for (auto& subtable : hb_iter (thiz->subtables, count))\n thiz->digest.add (subtable.digest);", "#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n thiz->cache_user_idx = c_accelerate_subtables.cache_user_idx;\n for (unsigned i = 0; i < count; i++)\n if (i != thiz->cache_user_idx)\n\tthiz->subtables[i].apply_cached_func = thiz->subtables[i].apply_func;\n#endif", " return thiz;\n }", " bool may_have (hb_codepoint_t g) const\n { return digest.may_have (g); }", " bool apply (hb_ot_apply_context_t *c, unsigned subtables_count, bool use_cache) const\n {\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n if (use_cache)\n {\n return\n + hb_iter (hb_iter (subtables, subtables_count))\n | hb_map ([&c] (const hb_accelerate_subtables_context_t::hb_applicable_t &_) { return _.apply_cached (c); })\n | hb_any\n ;\n }\n else\n#endif\n {\n return\n + hb_iter (hb_iter (subtables, subtables_count))\n | hb_map ([&c] (const hb_accelerate_subtables_context_t::hb_applicable_t &_) { return _.apply (c); })\n | hb_any\n ;\n }\n return false;\n }", " bool cache_enter (hb_ot_apply_context_t *c) const\n {\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n return cache_user_idx != (unsigned) -1 &&\n\t subtables[cache_user_idx].cache_enter (c);\n#else\n return false;\n#endif\n }\n void cache_leave (hb_ot_apply_context_t *c) const\n {\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n subtables[cache_user_idx].cache_leave (c);\n#endif\n }", "\n hb_set_digest_t digest;\n private:\n#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE\n unsigned cache_user_idx = (unsigned) -1;\n#endif\n hb_accelerate_subtables_context_t::hb_applicable_t subtables[HB_VAR_ARRAY];\n};", "template <typename Types>\nstruct GSUBGPOSVersion1_2\n{\n friend struct GSUBGPOS;", " protected:\n FixedVersion<>version;\t/* Version of the GSUB/GPOS table--initially set\n\t\t\t\t * to 0x00010000u */\n typename Types:: template OffsetTo<ScriptList>\n\t\tscriptList;\t/* ScriptList table */\n typename Types::template OffsetTo<FeatureList>\n\t\tfeatureList;\t/* FeatureList table */\n typename Types::template OffsetTo<LookupList<Types>>\n\t\tlookupList;\t/* LookupList table */\n Offset32To<FeatureVariations>\n\t\tfeatureVars;\t/* Offset to Feature Variations\n\t\t\t\t table--from beginning of table\n\t\t\t\t * (may be NULL). Introduced\n\t\t\t\t * in version 0x00010001. */\n public:\n DEFINE_SIZE_MIN (4 + 3 * Types::size);", " unsigned int get_size () const\n {\n return min_size +\n\t (version.to_int () >= 0x00010001u ? featureVars.static_size : 0);\n }", " const typename Types::template OffsetTo<LookupList<Types>>* get_lookup_list_offset () const\n {\n return &lookupList;\n }", " template <typename TLookup>\n bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n typedef List16OfOffsetTo<TLookup, typename Types::HBUINT> TLookupList;\n if (unlikely (!(scriptList.sanitize (c, this) &&\n\t\t featureList.sanitize (c, this) &&\n\t\t reinterpret_cast<const typename Types::template OffsetTo<TLookupList> &> (lookupList).sanitize (c, this))))\n return_trace (false);", "#ifndef HB_NO_VAR\n if (unlikely (!(version.to_int () < 0x00010001u || featureVars.sanitize (c, this))))\n return_trace (false);\n#endif", " return_trace (true);\n }", " template <typename TLookup>\n bool subset (hb_subset_layout_context_t *c) const\n {\n TRACE_SUBSET (this);", " auto *out = c->subset_context->serializer->start_embed (this);\n if (unlikely (!c->subset_context->serializer->extend_min (out))) return_trace (false);", " out->version = version;", " typedef LookupOffsetList<TLookup, typename Types::HBUINT> TLookupList;\n reinterpret_cast<typename Types::template OffsetTo<TLookupList> &> (out->lookupList)\n\t.serialize_subset (c->subset_context,\n\t\t\t reinterpret_cast<const typename Types::template OffsetTo<TLookupList> &> (lookupList),\n\t\t\t this,\n\t\t\t c);", " reinterpret_cast<typename Types::template OffsetTo<RecordListOfFeature> &> (out->featureList)\n\t.serialize_subset (c->subset_context,\n\t\t\t reinterpret_cast<const typename Types::template OffsetTo<RecordListOfFeature> &> (featureList),\n\t\t\t this,\n\t\t\t c);", " out->scriptList.serialize_subset (c->subset_context,\n\t\t\t\t scriptList,\n\t\t\t\t this,\n\t\t\t\t c);", "#ifndef HB_NO_VAR\n if (version.to_int () >= 0x00010001u)\n {\n auto snapshot = c->subset_context->serializer->snapshot ();\n if (!c->subset_context->serializer->extend_min (&out->featureVars))\n return_trace (false);", " // TODO(qxliu76): the current implementation doesn't correctly handle feature variations\n // that are dropped by instancing when the associated conditions don't trigger.\n // Since partial instancing isn't yet supported this isn't an issue yet but will\n // need to be fixed for partial instancing.", "", " // if all axes are pinned all feature vars are dropped.\n bool ret = !c->subset_context->plan->all_axes_pinned\n && out->featureVars.serialize_subset (c->subset_context, featureVars, this, c);\n if (!ret && version.major == 1)\n {\n c->subset_context->serializer->revert (snapshot);\n\tout->version.major = 1;\n\tout->version.minor = 0;\n }\n }\n#endif", " return_trace (true);\n }\n};", "struct GSUBGPOS\n{\n unsigned int get_size () const\n {\n switch (u.version.major) {\n case 1: return u.version1.get_size ();\n#ifndef HB_NO_BEYOND_64K\n case 2: return u.version2.get_size ();\n#endif\n default: return u.version.static_size;\n }\n }", " template <typename TLookup>\n bool sanitize (hb_sanitize_context_t *c) const\n {\n TRACE_SANITIZE (this);\n if (unlikely (!u.version.sanitize (c))) return_trace (false);\n switch (u.version.major) {\n case 1: return_trace (u.version1.sanitize<TLookup> (c));\n#ifndef HB_NO_BEYOND_64K\n case 2: return_trace (u.version2.sanitize<TLookup> (c));\n#endif\n default: return_trace (true);\n }\n }", " template <typename TLookup>\n bool subset (hb_subset_layout_context_t *c) const\n {\n switch (u.version.major) {\n case 1: return u.version1.subset<TLookup> (c);\n#ifndef HB_NO_BEYOND_64K\n case 2: return u.version2.subset<TLookup> (c);\n#endif\n default: return false;\n }\n }", " const ScriptList &get_script_list () const\n {\n switch (u.version.major) {\n case 1: return this+u.version1.scriptList;\n#ifndef HB_NO_BEYOND_64K\n case 2: return this+u.version2.scriptList;\n#endif\n default: return Null (ScriptList);\n }\n }\n const FeatureList &get_feature_list () const\n {\n switch (u.version.major) {\n case 1: return this+u.version1.featureList;\n#ifndef HB_NO_BEYOND_64K\n case 2: return this+u.version2.featureList;\n#endif\n default: return Null (FeatureList);\n }\n }\n unsigned int get_lookup_count () const\n {\n switch (u.version.major) {\n case 1: return (this+u.version1.lookupList).len;\n#ifndef HB_NO_BEYOND_64K\n case 2: return (this+u.version2.lookupList).len;\n#endif\n default: return 0;\n }\n }\n const Lookup& get_lookup (unsigned int i) const\n {\n switch (u.version.major) {\n case 1: return (this+u.version1.lookupList)[i];\n#ifndef HB_NO_BEYOND_64K\n case 2: return (this+u.version2.lookupList)[i];\n#endif\n default: return Null (Lookup);\n }\n }\n const FeatureVariations &get_feature_variations () const\n {\n switch (u.version.major) {\n case 1: return (u.version.to_int () >= 0x00010001u ? this+u.version1.featureVars : Null (FeatureVariations));\n#ifndef HB_NO_BEYOND_64K\n case 2: return this+u.version2.featureVars;\n#endif\n default: return Null (FeatureVariations);\n }\n }", " bool has_data () const { return u.version.to_int (); }\n unsigned int get_script_count () const\n { return get_script_list ().len; }\n const Tag& get_script_tag (unsigned int i) const\n { return get_script_list ().get_tag (i); }\n unsigned int get_script_tags (unsigned int start_offset,\n\t\t\t\tunsigned int *script_count /* IN/OUT */,\n\t\t\t\thb_tag_t *script_tags /* OUT */) const\n { return get_script_list ().get_tags (start_offset, script_count, script_tags); }\n const Script& get_script (unsigned int i) const\n { return get_script_list ()[i]; }\n bool find_script_index (hb_tag_t tag, unsigned int *index) const\n { return get_script_list ().find_index (tag, index); }", " unsigned int get_feature_count () const\n { return get_feature_list ().len; }\n hb_tag_t get_feature_tag (unsigned int i) const\n { return i == Index::NOT_FOUND_INDEX ? HB_TAG_NONE : get_feature_list ().get_tag (i); }\n unsigned int get_feature_tags (unsigned int start_offset,\n\t\t\t\t unsigned int *feature_count /* IN/OUT */,\n\t\t\t\t hb_tag_t *feature_tags /* OUT */) const\n { return get_feature_list ().get_tags (start_offset, feature_count, feature_tags); }\n const Feature& get_feature (unsigned int i) const\n { return get_feature_list ()[i]; }\n bool find_feature_index (hb_tag_t tag, unsigned int *index) const\n { return get_feature_list ().find_index (tag, index); }", " bool find_variations_index (const int *coords, unsigned int num_coords,\n\t\t\t unsigned int *index) const\n {\n#ifdef HB_NO_VAR\n *index = FeatureVariations::NOT_FOUND_INDEX;\n return false;\n#endif\n return get_feature_variations ().find_index (coords, num_coords, index);\n }\n const Feature& get_feature_variation (unsigned int feature_index,\n\t\t\t\t\tunsigned int variations_index) const\n {\n#ifndef HB_NO_VAR\n if (FeatureVariations::NOT_FOUND_INDEX != variations_index &&\n\tu.version.to_int () >= 0x00010001u)\n {\n const Feature *feature = get_feature_variations ().find_substitute (variations_index,\n\t\t\t\t\t\t\t\t\t feature_index);\n if (feature)\n\treturn *feature;\n }\n#endif\n return get_feature (feature_index);\n }", " void feature_variation_collect_lookups (const hb_set_t *feature_indexes,\n\t\t\t\t\t const hb_hashmap_t<unsigned, const Feature*> *feature_substitutes_map,\n\t\t\t\t\t hb_set_t *lookup_indexes /* OUT */) const\n {\n#ifndef HB_NO_VAR\n get_feature_variations ().collect_lookups (feature_indexes, feature_substitutes_map, lookup_indexes);\n#endif\n }", "#ifndef HB_NO_VAR\n void collect_feature_substitutes_with_variations (hb_collect_feature_substitutes_with_var_context_t *c) const\n { get_feature_variations ().collect_feature_substitutes_with_variations (c); }\n#endif", " template <typename TLookup>\n void closure_lookups (hb_face_t *face,\n\t\t\tconst hb_set_t *glyphs,\n\t\t\thb_set_t *lookup_indexes /* IN/OUT */) const\n {\n hb_set_t visited_lookups, inactive_lookups;\n hb_closure_lookups_context_t c (face, glyphs, &visited_lookups, &inactive_lookups);", " c.set_recurse_func (TLookup::template dispatch_recurse_func<hb_closure_lookups_context_t>);", " for (unsigned lookup_index : *lookup_indexes)\n reinterpret_cast<const TLookup &> (get_lookup (lookup_index)).closure_lookups (&c, lookup_index);", " hb_set_union (lookup_indexes, &visited_lookups);\n hb_set_subtract (lookup_indexes, &inactive_lookups);\n }", " void prune_langsys (const hb_map_t *duplicate_feature_map,\n const hb_set_t *layout_scripts,\n hb_hashmap_t<unsigned, hb::unique_ptr<hb_set_t>> *script_langsys_map,\n hb_set_t *new_feature_indexes /* OUT */) const\n {\n hb_prune_langsys_context_t c (this, script_langsys_map, duplicate_feature_map, new_feature_indexes);", " unsigned count = get_script_count ();\n for (unsigned script_index = 0; script_index < count; script_index++)\n {\n const Tag& tag = get_script_tag (script_index);\n if (!layout_scripts->has (tag)) continue;\n const Script& s = get_script (script_index);\n s.prune_langsys (&c, script_index);\n }\n }", " void prune_features (const hb_map_t *lookup_indices, /* IN */\n\t\t const hb_hashmap_t<unsigned, hb::shared_ptr<hb_set_t>> *feature_record_cond_idx_map, /* IN */\n\t\t const hb_hashmap_t<unsigned, const Feature*> *feature_substitutes_map, /* IN */\n\t\t hb_set_t *feature_indices /* IN/OUT */) const\n {\n#ifndef HB_NO_VAR\n // This is the set of feature indices which have alternate versions defined\n // if the FeatureVariation's table and the alternate version(s) intersect the\n // set of lookup indices.\n hb_set_t alternate_feature_indices;\n get_feature_variations ().closure_features (lookup_indices, feature_record_cond_idx_map, &alternate_feature_indices);\n if (unlikely (alternate_feature_indices.in_error()))\n {\n feature_indices->err ();\n return;\n }\n#endif", " for (unsigned i : hb_iter (feature_indices))\n {\n hb_tag_t tag = get_feature_tag (i);\n if (tag == HB_TAG ('p', 'r', 'e', 'f'))\n // Note: Never ever drop feature 'pref', even if it's empty.\n // HarfBuzz chooses shaper for Khmer based on presence of this\n // feature.\tSee thread at:\n\t// http://lists.freedesktop.org/archives/harfbuzz/2012-November/002660.html\n continue;", "\n const Feature *f = &(get_feature (i));\n const Feature** p = nullptr;\n if (feature_substitutes_map->has (i, &p))\n f = *p;", " if (!f->featureParams.is_null () &&\n tag == HB_TAG ('s', 'i', 'z', 'e'))\n continue;", " if (!f->intersects_lookup_indexes (lookup_indices)\n#ifndef HB_NO_VAR\n && !alternate_feature_indices.has (i)\n#endif\n\t )\n\tfeature_indices->del (i);\n }\n }", " template <typename T>\n struct accelerator_t\n {\n accelerator_t (hb_face_t *face)\n {\n this->table = hb_sanitize_context_t ().reference_table<T> (face);\n if (unlikely (this->table->is_blocklisted (this->table.get_blob (), face)))\n {\n\thb_blob_destroy (this->table.get_blob ());\n\tthis->table = hb_blob_get_empty ();\n }", " this->lookup_count = table->get_lookup_count ();", " this->accels = (hb_atomic_ptr_t<hb_ot_layout_lookup_accelerator_t> *) hb_calloc (this->lookup_count, sizeof (*accels));\n if (unlikely (!this->accels))\n {\n\tthis->lookup_count = 0;\n\tthis->table.destroy ();\n\tthis->table = hb_blob_get_empty ();\n }\n }\n ~accelerator_t ()\n {\n for (unsigned int i = 0; i < this->lookup_count; i++)\n\thb_free (this->accels[i]);\n hb_free (this->accels);\n this->table.destroy ();\n }", " hb_ot_layout_lookup_accelerator_t *get_accel (unsigned lookup_index) const\n {\n if (unlikely (lookup_index >= lookup_count)) return nullptr;", " retry:\n auto *accel = accels[lookup_index].get_acquire ();\n if (unlikely (!accel))\n {\n\taccel = hb_ot_layout_lookup_accelerator_t::create (table->get_lookup (lookup_index));\n\tif (unlikely (!accel))\n\t return nullptr;", "\tif (unlikely (!accels[lookup_index].cmpexch (nullptr, accel)))\n\t{\n\t hb_free (accel);\n\t goto retry;\n\t}\n }", " return accel;\n }", " hb_blob_ptr_t<T> table;\n unsigned int lookup_count;\n hb_atomic_ptr_t<hb_ot_layout_lookup_accelerator_t> *accels;\n };", " protected:\n union {\n FixedVersion<>\t\t\tversion;\t/* Version identifier */\n GSUBGPOSVersion1_2<SmallTypes>\tversion1;\n#ifndef HB_NO_BEYOND_64K\n GSUBGPOSVersion1_2<MediumTypes>\tversion2;\n#endif\n } u;\n public:\n DEFINE_SIZE_MIN (4);\n};", "\n} /* namespace OT */", "\n#endif /* HB_OT_LAYOUT_GSUBGPOS_HH */" ]
[ 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [580], "buggy_code_start_loc": [580], "filenames": ["src/hb-ot-layout-gsubgpos.hh"], "fixing_code_end_loc": [588], "fixing_code_start_loc": [581], "message": "hb-ot-layout-gsubgpos.hh in HarfBuzz through 6.0.0 allows attackers to trigger O(n^2) growth via consecutive marks during the process of looking back for base glyphs when attaching marks.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:harfbuzz_project:harfbuzz:*:*:*:*:*:*:*:*", "matchCriteriaId": "85CABB33-5FC2-447E-BFD5-70AA07F97359", "versionEndExcluding": null, "versionEndIncluding": "6.0.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:36:*:*:*:*:*:*:*", "matchCriteriaId": "5C675112-476C-4D7C-BCB9-A2FB2D0BC9FD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "hb-ot-layout-gsubgpos.hh in HarfBuzz through 6.0.0 allows attackers to trigger O(n^2) growth via consecutive marks during the process of looking back for base glyphs when attaching marks."}], "evaluatorComment": null, "id": "CVE-2023-25193", "lastModified": "2023-03-14T05:15:29.457", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-02-04T20:15:08.027", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://chromium.googlesource.com/chromium/src/+/e1f324aa681af54101c1f2d173d92adb80e37088/DEPS#361"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/harfbuzz/harfbuzz/blob/2822b589bc837fae6f66233e2cf2eef0f6ce8470/src/hb-ot-layout-gsubgpos.hh"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/harfbuzz/harfbuzz/commit/85be877925ddbf34f74a1229f3ca1716bb6170dc"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/KWCHWSICWVZSAXP2YAXM65JC2GR53547/"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/YZ5M2GSAIHFPLHYJXUPQ2QDJCLWXUGO3/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-770"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/harfbuzz/harfbuzz/commit/85be877925ddbf34f74a1229f3ca1716bb6170dc"}, "type": "CWE-770"}
179
Determine whether the {function_name} code is vulnerable or not.
[ "require 'action_view/helpers' if defined?(Rails)\nrequire 'action_view/context' if defined?(Rails)", "module InlineSvg\n module ActionView\n module Helpers\n def inline_svg_tag(filename, transform_params={})\n with_asset_finder(InlineSvg.configuration.asset_finder) do\n render_inline_svg(filename, transform_params)\n end\n end", " def inline_svg_pack_tag(filename, transform_params={})\n with_asset_finder(InlineSvg::WebpackAssetFinder) do\n render_inline_svg(filename, transform_params)\n end\n end", " def inline_svg(filename, transform_params={})\n ActiveSupport::Deprecation.warn(\n '`inline_svg` is deprecated and will be removed from inline_svg 2.0 (use `inline_svg_tag` or `inline_svg_pack_tag` instead)'\n )", " render_inline_svg(filename, transform_params)\n end", " private", " def render_inline_svg(filename, transform_params={})\n begin\n svg_file = read_svg(filename)\n rescue InlineSvg::AssetFile::FileNotFound => error\n raise error if InlineSvg.configuration.raise_on_file_not_found?\n return placeholder(filename) unless transform_params[:fallback].present?", " if transform_params[:fallback].present?\n begin\n svg_file = read_svg(transform_params[:fallback])\n rescue InlineSvg::AssetFile::FileNotFound\n placeholder(filename)\n end\n end\n end", " InlineSvg::TransformPipeline.generate_html_from(svg_file, transform_params).html_safe\n end", " def read_svg(filename)\n if InlineSvg::IOResource === filename\n InlineSvg::IOResource.read filename\n else\n configured_asset_file.named filename\n end\n end", " def placeholder(filename)\n css_class = InlineSvg.configuration.svg_not_found_css_class", " not_found_message = \"'#{filename}' #{extension_hint(filename)}\"", "\n if css_class.nil?\n return \"<svg><!-- SVG file not found: #{not_found_message}--></svg>\".html_safe\n else\n return \"<svg class='#{css_class}'><!-- SVG file not found: #{not_found_message}--></svg>\".html_safe\n end\n end", " def configured_asset_file\n InlineSvg.configuration.asset_file\n end", " def with_asset_finder(asset_finder)\n Thread.current[:inline_svg_asset_finder] = asset_finder\n output = yield\n Thread.current[:inline_svg_asset_finder] = nil", " output\n end", " def extension_hint(filename)\n filename.ends_with?(\".svg\") ? \"\" : \"(Try adding .svg to your filename) \"\n end\n end\n end\nend" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [59, 45], "buggy_code_start_loc": [58, 45], "filenames": ["lib/inline_svg/action_view/helpers.rb", "spec/helpers/inline_svg_spec.rb"], "fixing_code_end_loc": [59, 57], "fixing_code_start_loc": [58, 46], "message": "A vulnerability has been found in jamesmartin Inline SVG up to 1.7.1 and classified as problematic. Affected by this vulnerability is an unknown functionality of the file lib/inline_svg/action_view/helpers.rb of the component URL Parameter Handler. The manipulation of the argument filename leads to cross site scripting. The attack can be launched remotely. Upgrading to version 1.7.2 is able to address this issue. The name of the patch is f5363b351508486021f99e083c92068cf2943621. It is recommended to upgrade the affected component. The identifier VDB-217597 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:inline_svg_project:inline_svg:*:*:*:*:*:*:*:*", "matchCriteriaId": "7741CA72-12D1-4538-A079-E2EC3D4BF377", "versionEndExcluding": "1.7.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability has been found in jamesmartin Inline SVG up to 1.7.1 and classified as problematic. Affected by this vulnerability is an unknown functionality of the file lib/inline_svg/action_view/helpers.rb of the component URL Parameter Handler. The manipulation of the argument filename leads to cross site scripting. The attack can be launched remotely. Upgrading to version 1.7.2 is able to address this issue. The name of the patch is f5363b351508486021f99e083c92068cf2943621. It is recommended to upgrade the affected component. The identifier VDB-217597 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2020-36644", "lastModified": "2023-01-12T16:40:20.770", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-07T10:15:09.417", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jamesmartin/inline_svg/commit/f5363b351508486021f99e083c92068cf2943621"}, {"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jamesmartin/inline_svg/pull/117"}, {"source": "cna@vuldb.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/jamesmartin/inline_svg/releases/tag/v1.7.2"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.217597"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.217597"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/jamesmartin/inline_svg/commit/f5363b351508486021f99e083c92068cf2943621"}, "type": "CWE-79"}
180
Determine whether the {function_name} code is vulnerable or not.
[ "require 'action_view/helpers' if defined?(Rails)\nrequire 'action_view/context' if defined?(Rails)", "module InlineSvg\n module ActionView\n module Helpers\n def inline_svg_tag(filename, transform_params={})\n with_asset_finder(InlineSvg.configuration.asset_finder) do\n render_inline_svg(filename, transform_params)\n end\n end", " def inline_svg_pack_tag(filename, transform_params={})\n with_asset_finder(InlineSvg::WebpackAssetFinder) do\n render_inline_svg(filename, transform_params)\n end\n end", " def inline_svg(filename, transform_params={})\n ActiveSupport::Deprecation.warn(\n '`inline_svg` is deprecated and will be removed from inline_svg 2.0 (use `inline_svg_tag` or `inline_svg_pack_tag` instead)'\n )", " render_inline_svg(filename, transform_params)\n end", " private", " def render_inline_svg(filename, transform_params={})\n begin\n svg_file = read_svg(filename)\n rescue InlineSvg::AssetFile::FileNotFound => error\n raise error if InlineSvg.configuration.raise_on_file_not_found?\n return placeholder(filename) unless transform_params[:fallback].present?", " if transform_params[:fallback].present?\n begin\n svg_file = read_svg(transform_params[:fallback])\n rescue InlineSvg::AssetFile::FileNotFound\n placeholder(filename)\n end\n end\n end", " InlineSvg::TransformPipeline.generate_html_from(svg_file, transform_params).html_safe\n end", " def read_svg(filename)\n if InlineSvg::IOResource === filename\n InlineSvg::IOResource.read filename\n else\n configured_asset_file.named filename\n end\n end", " def placeholder(filename)\n css_class = InlineSvg.configuration.svg_not_found_css_class", " not_found_message = \"'#{ERB::Util.html_escape_once(filename)}' #{extension_hint(filename)}\"", "\n if css_class.nil?\n return \"<svg><!-- SVG file not found: #{not_found_message}--></svg>\".html_safe\n else\n return \"<svg class='#{css_class}'><!-- SVG file not found: #{not_found_message}--></svg>\".html_safe\n end\n end", " def configured_asset_file\n InlineSvg.configuration.asset_file\n end", " def with_asset_finder(asset_finder)\n Thread.current[:inline_svg_asset_finder] = asset_finder\n output = yield\n Thread.current[:inline_svg_asset_finder] = nil", " output\n end", " def extension_hint(filename)\n filename.ends_with?(\".svg\") ? \"\" : \"(Try adding .svg to your filename) \"\n end\n end\n end\nend" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [59, 45], "buggy_code_start_loc": [58, 45], "filenames": ["lib/inline_svg/action_view/helpers.rb", "spec/helpers/inline_svg_spec.rb"], "fixing_code_end_loc": [59, 57], "fixing_code_start_loc": [58, 46], "message": "A vulnerability has been found in jamesmartin Inline SVG up to 1.7.1 and classified as problematic. Affected by this vulnerability is an unknown functionality of the file lib/inline_svg/action_view/helpers.rb of the component URL Parameter Handler. The manipulation of the argument filename leads to cross site scripting. The attack can be launched remotely. Upgrading to version 1.7.2 is able to address this issue. The name of the patch is f5363b351508486021f99e083c92068cf2943621. It is recommended to upgrade the affected component. The identifier VDB-217597 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:inline_svg_project:inline_svg:*:*:*:*:*:*:*:*", "matchCriteriaId": "7741CA72-12D1-4538-A079-E2EC3D4BF377", "versionEndExcluding": "1.7.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability has been found in jamesmartin Inline SVG up to 1.7.1 and classified as problematic. Affected by this vulnerability is an unknown functionality of the file lib/inline_svg/action_view/helpers.rb of the component URL Parameter Handler. The manipulation of the argument filename leads to cross site scripting. The attack can be launched remotely. Upgrading to version 1.7.2 is able to address this issue. The name of the patch is f5363b351508486021f99e083c92068cf2943621. It is recommended to upgrade the affected component. The identifier VDB-217597 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2020-36644", "lastModified": "2023-01-12T16:40:20.770", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-07T10:15:09.417", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jamesmartin/inline_svg/commit/f5363b351508486021f99e083c92068cf2943621"}, {"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jamesmartin/inline_svg/pull/117"}, {"source": "cna@vuldb.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/jamesmartin/inline_svg/releases/tag/v1.7.2"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.217597"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.217597"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/jamesmartin/inline_svg/commit/f5363b351508486021f99e083c92068cf2943621"}, "type": "CWE-79"}
180
Determine whether the {function_name} code is vulnerable or not.
[ "require 'inline_svg'", "class WorkingCustomTransform < InlineSvg::CustomTransformation\n def transform(doc)\n doc = Nokogiri::XML::Document.parse(doc.to_html)\n svg = doc.at_css 'svg'\n svg['custom'] = value\n doc\n end\nend", "describe InlineSvg::ActionView::Helpers do", " let(:helper) { ( Class.new { include InlineSvg::ActionView::Helpers } ).new }", " shared_examples \"inline_svg helper\" do |helper_method:|", " context \"when passed the name of an SVG that does not exist\" do\n after(:each) do\n InlineSvg.reset_configuration!\n end", " context \"and configured to raise\" do\n it \"raises an exception\" do\n InlineSvg.configure do |config|\n config.raise_on_file_not_found = true\n end", " allow(InlineSvg::AssetFile).to receive(:named).\n with('some-missing-file.svg').\n and_raise(InlineSvg::AssetFile::FileNotFound.new)", " expect {\n helper.send(helper_method, 'some-missing-file.svg')\n }.to raise_error(InlineSvg::AssetFile::FileNotFound)\n end\n end", " it \"returns an empty, html safe, SVG document as a placeholder\" do\n allow(InlineSvg::AssetFile).to receive(:named).\n with('some-missing-file.svg').\n and_raise(InlineSvg::AssetFile::FileNotFound.new)", " output = helper.send(helper_method, 'some-missing-file.svg')\n expect(output).to eq \"<svg><!-- SVG file not found: 'some-missing-file.svg' --></svg>\"", "", " expect(output).to be_html_safe\n end", " it \"gives a helpful hint when no .svg extension is provided in the filename\" do\n allow(InlineSvg::AssetFile).to receive(:named).\n with('missing-file-with-no-extension').\n and_raise(InlineSvg::AssetFile::FileNotFound.new)", " output = helper.send(helper_method, 'missing-file-with-no-extension')\n expect(output).to eq \"<svg><!-- SVG file not found: 'missing-file-with-no-extension' (Try adding .svg to your filename) --></svg>\"\n end", " it \"allows the CSS class on the empty SVG document to be changed\" do\n InlineSvg.configure do |config|\n config.svg_not_found_css_class = 'missing-svg'\n end", " allow(InlineSvg::AssetFile).to receive(:named).\n with('some-other-missing-file.svg').\n and_raise(InlineSvg::AssetFile::FileNotFound.new)", " output = helper.send(helper_method, 'some-other-missing-file.svg')\n expect(output).to eq \"<svg class='missing-svg'><!-- SVG file not found: 'some-other-missing-file.svg' --></svg>\"\n expect(output).to be_html_safe\n end", " context \"and a fallback that does exist\" do\n it \"displays the fallback\" do\n allow(InlineSvg::AssetFile).to receive(:named).\n with('missing.svg').\n and_raise(InlineSvg::AssetFile::FileNotFound.new)", " fallback_file = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" xml:lang=\"en\"><!-- This is a comment --></svg>\nSVG\n allow(InlineSvg::AssetFile).to receive(:named).with('fallback.svg').and_return(fallback_file)\n expect(helper.send(helper_method, 'missing.svg', fallback: 'fallback.svg')).to eq fallback_file\n end\n end\n end", " context \"when passed an existing SVG file\" do", " context \"and no options\" do\n it \"returns a html safe version of the file's contents\" do\n example_file = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" xml:lang=\"en\"><!-- This is a comment --></svg>\nSVG\n allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(example_file)\n expect(helper.send(helper_method, 'some-file')).to eq example_file\n end\n end", " context \"and the 'title' option\" do\n it \"adds the title node to the SVG output\" do\n input_svg = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" role=\"presentation\" xml:lang=\"en\"></svg>\nSVG\n expected_output = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" role=\"presentation\" xml:lang=\"en\"><title>A title</title></svg>\nSVG\n allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(input_svg)\n expect(helper.send(helper_method, 'some-file', title: 'A title')).to eq expected_output\n end\n end", " context \"and the 'desc' option\" do\n it \"adds the description node to the SVG output\" do\n input_svg = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" role=\"presentation\" xml:lang=\"en\"></svg>\nSVG\n expected_output = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" role=\"presentation\" xml:lang=\"en\"><desc>A description</desc></svg>\nSVG\n allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(input_svg)\n expect(helper.send(helper_method, 'some-file', desc: 'A description')).to eq expected_output\n end\n end", " context \"and the 'nocomment' option\" do\n it \"strips comments and other unknown/unsafe nodes from the output\" do\n input_svg = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" xml:lang=\"en\"><!-- This is a comment --></svg>\nSVG\n expected_output = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" xml:lang=\"en\"></svg>\nSVG\n allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(input_svg)\n expect(helper.send(helper_method, 'some-file', nocomment: true)).to eq expected_output\n end\n end", " context \"and the 'aria_hidden' option\" do\n it \"sets 'aria-hidden=true' in the output\" do\n input_svg = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" xml:lang=\"en\"></svg>\nSVG\n expected_output = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" xml:lang=\"en\" aria-hidden=\"true\"></svg>\nSVG\n allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(input_svg)\n expect(helper.send(helper_method, 'some-file', aria_hidden: true)).to eq expected_output\n end\n end", " context \"and all options\" do\n it \"applies all expected transformations to the output\" do\n input_svg = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" xml:lang=\"en\"><!-- This is a comment --></svg>\nSVG\n expected_output = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" xml:lang=\"en\"><title>A title</title><desc>A description</desc></svg>\nSVG\n allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(input_svg)\n expect(helper.send(helper_method, 'some-file', title: 'A title', desc: 'A description', nocomment: true)).to eq expected_output\n end\n end", " context \"with custom transformations\" do\n before(:each) do\n InlineSvg.configure do |config|\n config.add_custom_transformation({attribute: :custom, transform: WorkingCustomTransform})\n end\n end", " after(:each) do\n InlineSvg.reset_configuration!\n end", " it \"applies custm transformations to the output\" do\n input_svg = <<-SVG\n<svg></svg>\nSVG\n expected_output = <<-SVG\n<svg custom=\"some value\"></svg>\nSVG\n allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(input_svg)\n expect(helper.send(helper_method, 'some-file', custom: 'some value')).to eq expected_output\n end\n end", " context \"with custom transformations using a default value\" do\n before(:each) do\n InlineSvg.configure do |config|\n config.add_custom_transformation({attribute: :custom, transform: WorkingCustomTransform, default_value: 'default value'})\n end\n end", " after(:each) do\n InlineSvg.reset_configuration!\n end", " context \"without passing the attribute value\" do\n it \"applies custom transformations to the output using the default value\" do\n input_svg = '<svg></svg>'", " allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(input_svg)", " expect(helper.send(helper_method, 'some-file')).to eq \"<svg custom=\\\"default value\\\"></svg>\\n\"\n end\n end", " context \"passing the attribute value\" do\n it \"applies custom transformations to the output\" do\n input_svg = '<svg></svg>'", " allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(input_svg)", " expect(helper.send(helper_method, 'some-file', custom: 'some value')).to eq \"<svg custom=\\\"some value\\\"></svg>\\n\"\n end\n end\n end", " end\n context 'argument polimorphizm' do\n let(:argument) { double('argument') }\n it 'accept IO' do\n expect(InlineSvg::IOResource).to receive(:===).with(argument).and_return(true)\n expect(InlineSvg::IOResource).to receive(:read).with(argument)\n expect(InlineSvg::AssetFile).to_not receive(:named)\n helper.send(helper_method, argument)\n end\n it 'accept filename' do\n expect(InlineSvg::IOResource).to receive(:===).with(argument).and_return(false)\n expect(InlineSvg::IOResource).to_not receive(:read)\n expect(InlineSvg::AssetFile).to receive(:named).with(argument)\n helper.send(helper_method, argument)\n end\n end\n context 'when passed IO object argument' do\n let(:io_object) { double('io_object') }\n let(:file_path) { File.expand_path('../../files/example.svg', __FILE__) }\n let(:answer) { File.read(file_path) }\n it 'return valid svg' do\n expect(InlineSvg::IOResource).to receive(:===).with(io_object).and_return(true)\n expect(InlineSvg::IOResource).to receive(:read).with(io_object).and_return(\"<svg><!-- Test IO --></svg>\")\n output = helper.send(helper_method, io_object)\n expect(output).to eq \"<svg><!-- Test IO --></svg>\\n\"\n expect(output).to be_html_safe\n end", " it 'return valid svg for file' do\n output = helper.send(helper_method, File.new(file_path))\n expect(output).to eq \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" xml:lang=\\\"en\\\" role=\\\"presentation\\\"><!-- This is a test comment --></svg>\\n\"\n expect(output).to be_html_safe\n end", " end\n end", " describe '#inline_svg' do\n it_behaves_like \"inline_svg helper\", helper_method: :inline_svg\n end", " describe '#inline_svg_tag' do\n it_behaves_like \"inline_svg helper\", helper_method: :inline_svg_tag\n end", " describe '#inline_svg_tag' do\n it_behaves_like \"inline_svg helper\", helper_method: :inline_svg_pack_tag\n end\nend" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 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 ]
PreciseBugs
{"buggy_code_end_loc": [59, 45], "buggy_code_start_loc": [58, 45], "filenames": ["lib/inline_svg/action_view/helpers.rb", "spec/helpers/inline_svg_spec.rb"], "fixing_code_end_loc": [59, 57], "fixing_code_start_loc": [58, 46], "message": "A vulnerability has been found in jamesmartin Inline SVG up to 1.7.1 and classified as problematic. Affected by this vulnerability is an unknown functionality of the file lib/inline_svg/action_view/helpers.rb of the component URL Parameter Handler. The manipulation of the argument filename leads to cross site scripting. The attack can be launched remotely. Upgrading to version 1.7.2 is able to address this issue. The name of the patch is f5363b351508486021f99e083c92068cf2943621. It is recommended to upgrade the affected component. The identifier VDB-217597 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:inline_svg_project:inline_svg:*:*:*:*:*:*:*:*", "matchCriteriaId": "7741CA72-12D1-4538-A079-E2EC3D4BF377", "versionEndExcluding": "1.7.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability has been found in jamesmartin Inline SVG up to 1.7.1 and classified as problematic. Affected by this vulnerability is an unknown functionality of the file lib/inline_svg/action_view/helpers.rb of the component URL Parameter Handler. The manipulation of the argument filename leads to cross site scripting. The attack can be launched remotely. Upgrading to version 1.7.2 is able to address this issue. The name of the patch is f5363b351508486021f99e083c92068cf2943621. It is recommended to upgrade the affected component. The identifier VDB-217597 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2020-36644", "lastModified": "2023-01-12T16:40:20.770", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-07T10:15:09.417", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jamesmartin/inline_svg/commit/f5363b351508486021f99e083c92068cf2943621"}, {"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jamesmartin/inline_svg/pull/117"}, {"source": "cna@vuldb.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/jamesmartin/inline_svg/releases/tag/v1.7.2"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.217597"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.217597"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/jamesmartin/inline_svg/commit/f5363b351508486021f99e083c92068cf2943621"}, "type": "CWE-79"}
180
Determine whether the {function_name} code is vulnerable or not.
[ "require 'inline_svg'", "class WorkingCustomTransform < InlineSvg::CustomTransformation\n def transform(doc)\n doc = Nokogiri::XML::Document.parse(doc.to_html)\n svg = doc.at_css 'svg'\n svg['custom'] = value\n doc\n end\nend", "describe InlineSvg::ActionView::Helpers do", " let(:helper) { ( Class.new { include InlineSvg::ActionView::Helpers } ).new }", " shared_examples \"inline_svg helper\" do |helper_method:|", " context \"when passed the name of an SVG that does not exist\" do\n after(:each) do\n InlineSvg.reset_configuration!\n end", " context \"and configured to raise\" do\n it \"raises an exception\" do\n InlineSvg.configure do |config|\n config.raise_on_file_not_found = true\n end", " allow(InlineSvg::AssetFile).to receive(:named).\n with('some-missing-file.svg').\n and_raise(InlineSvg::AssetFile::FileNotFound.new)", " expect {\n helper.send(helper_method, 'some-missing-file.svg')\n }.to raise_error(InlineSvg::AssetFile::FileNotFound)\n end\n end", " it \"returns an empty, html safe, SVG document as a placeholder\" do\n allow(InlineSvg::AssetFile).to receive(:named).\n with('some-missing-file.svg').\n and_raise(InlineSvg::AssetFile::FileNotFound.new)", " output = helper.send(helper_method, 'some-missing-file.svg')\n expect(output).to eq \"<svg><!-- SVG file not found: 'some-missing-file.svg' --></svg>\"", " expect(output).to be_html_safe\n end", " it \"escapes malicious input\" do\n malicious = \"--></svg><script>alert(1)</script><svg>.svg\"\n allow(InlineSvg::AssetFile).to receive(:named).\n with(malicious).\n and_raise(InlineSvg::AssetFile::FileNotFound.new)", " output = helper.send(helper_method, malicious)\n expect(output).to eq \"<svg><!-- SVG file not found: '#{ERB::Util.html_escape_once(malicious)}' --></svg>\"", " expect(output).to be_html_safe\n end", " it \"gives a helpful hint when no .svg extension is provided in the filename\" do\n allow(InlineSvg::AssetFile).to receive(:named).\n with('missing-file-with-no-extension').\n and_raise(InlineSvg::AssetFile::FileNotFound.new)", " output = helper.send(helper_method, 'missing-file-with-no-extension')\n expect(output).to eq \"<svg><!-- SVG file not found: 'missing-file-with-no-extension' (Try adding .svg to your filename) --></svg>\"\n end", " it \"allows the CSS class on the empty SVG document to be changed\" do\n InlineSvg.configure do |config|\n config.svg_not_found_css_class = 'missing-svg'\n end", " allow(InlineSvg::AssetFile).to receive(:named).\n with('some-other-missing-file.svg').\n and_raise(InlineSvg::AssetFile::FileNotFound.new)", " output = helper.send(helper_method, 'some-other-missing-file.svg')\n expect(output).to eq \"<svg class='missing-svg'><!-- SVG file not found: 'some-other-missing-file.svg' --></svg>\"\n expect(output).to be_html_safe\n end", " context \"and a fallback that does exist\" do\n it \"displays the fallback\" do\n allow(InlineSvg::AssetFile).to receive(:named).\n with('missing.svg').\n and_raise(InlineSvg::AssetFile::FileNotFound.new)", " fallback_file = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" xml:lang=\"en\"><!-- This is a comment --></svg>\nSVG\n allow(InlineSvg::AssetFile).to receive(:named).with('fallback.svg').and_return(fallback_file)\n expect(helper.send(helper_method, 'missing.svg', fallback: 'fallback.svg')).to eq fallback_file\n end\n end\n end", " context \"when passed an existing SVG file\" do", " context \"and no options\" do\n it \"returns a html safe version of the file's contents\" do\n example_file = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" xml:lang=\"en\"><!-- This is a comment --></svg>\nSVG\n allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(example_file)\n expect(helper.send(helper_method, 'some-file')).to eq example_file\n end\n end", " context \"and the 'title' option\" do\n it \"adds the title node to the SVG output\" do\n input_svg = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" role=\"presentation\" xml:lang=\"en\"></svg>\nSVG\n expected_output = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" role=\"presentation\" xml:lang=\"en\"><title>A title</title></svg>\nSVG\n allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(input_svg)\n expect(helper.send(helper_method, 'some-file', title: 'A title')).to eq expected_output\n end\n end", " context \"and the 'desc' option\" do\n it \"adds the description node to the SVG output\" do\n input_svg = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" role=\"presentation\" xml:lang=\"en\"></svg>\nSVG\n expected_output = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" role=\"presentation\" xml:lang=\"en\"><desc>A description</desc></svg>\nSVG\n allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(input_svg)\n expect(helper.send(helper_method, 'some-file', desc: 'A description')).to eq expected_output\n end\n end", " context \"and the 'nocomment' option\" do\n it \"strips comments and other unknown/unsafe nodes from the output\" do\n input_svg = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" xml:lang=\"en\"><!-- This is a comment --></svg>\nSVG\n expected_output = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" xml:lang=\"en\"></svg>\nSVG\n allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(input_svg)\n expect(helper.send(helper_method, 'some-file', nocomment: true)).to eq expected_output\n end\n end", " context \"and the 'aria_hidden' option\" do\n it \"sets 'aria-hidden=true' in the output\" do\n input_svg = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" xml:lang=\"en\"></svg>\nSVG\n expected_output = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" xml:lang=\"en\" aria-hidden=\"true\"></svg>\nSVG\n allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(input_svg)\n expect(helper.send(helper_method, 'some-file', aria_hidden: true)).to eq expected_output\n end\n end", " context \"and all options\" do\n it \"applies all expected transformations to the output\" do\n input_svg = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" xml:lang=\"en\"><!-- This is a comment --></svg>\nSVG\n expected_output = <<-SVG\n<svg xmlns=\"http://www.w3.org/2000/svg\" xml:lang=\"en\"><title>A title</title><desc>A description</desc></svg>\nSVG\n allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(input_svg)\n expect(helper.send(helper_method, 'some-file', title: 'A title', desc: 'A description', nocomment: true)).to eq expected_output\n end\n end", " context \"with custom transformations\" do\n before(:each) do\n InlineSvg.configure do |config|\n config.add_custom_transformation({attribute: :custom, transform: WorkingCustomTransform})\n end\n end", " after(:each) do\n InlineSvg.reset_configuration!\n end", " it \"applies custm transformations to the output\" do\n input_svg = <<-SVG\n<svg></svg>\nSVG\n expected_output = <<-SVG\n<svg custom=\"some value\"></svg>\nSVG\n allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(input_svg)\n expect(helper.send(helper_method, 'some-file', custom: 'some value')).to eq expected_output\n end\n end", " context \"with custom transformations using a default value\" do\n before(:each) do\n InlineSvg.configure do |config|\n config.add_custom_transformation({attribute: :custom, transform: WorkingCustomTransform, default_value: 'default value'})\n end\n end", " after(:each) do\n InlineSvg.reset_configuration!\n end", " context \"without passing the attribute value\" do\n it \"applies custom transformations to the output using the default value\" do\n input_svg = '<svg></svg>'", " allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(input_svg)", " expect(helper.send(helper_method, 'some-file')).to eq \"<svg custom=\\\"default value\\\"></svg>\\n\"\n end\n end", " context \"passing the attribute value\" do\n it \"applies custom transformations to the output\" do\n input_svg = '<svg></svg>'", " allow(InlineSvg::AssetFile).to receive(:named).with('some-file').and_return(input_svg)", " expect(helper.send(helper_method, 'some-file', custom: 'some value')).to eq \"<svg custom=\\\"some value\\\"></svg>\\n\"\n end\n end\n end", " end\n context 'argument polimorphizm' do\n let(:argument) { double('argument') }\n it 'accept IO' do\n expect(InlineSvg::IOResource).to receive(:===).with(argument).and_return(true)\n expect(InlineSvg::IOResource).to receive(:read).with(argument)\n expect(InlineSvg::AssetFile).to_not receive(:named)\n helper.send(helper_method, argument)\n end\n it 'accept filename' do\n expect(InlineSvg::IOResource).to receive(:===).with(argument).and_return(false)\n expect(InlineSvg::IOResource).to_not receive(:read)\n expect(InlineSvg::AssetFile).to receive(:named).with(argument)\n helper.send(helper_method, argument)\n end\n end\n context 'when passed IO object argument' do\n let(:io_object) { double('io_object') }\n let(:file_path) { File.expand_path('../../files/example.svg', __FILE__) }\n let(:answer) { File.read(file_path) }\n it 'return valid svg' do\n expect(InlineSvg::IOResource).to receive(:===).with(io_object).and_return(true)\n expect(InlineSvg::IOResource).to receive(:read).with(io_object).and_return(\"<svg><!-- Test IO --></svg>\")\n output = helper.send(helper_method, io_object)\n expect(output).to eq \"<svg><!-- Test IO --></svg>\\n\"\n expect(output).to be_html_safe\n end", " it 'return valid svg for file' do\n output = helper.send(helper_method, File.new(file_path))\n expect(output).to eq \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" xml:lang=\\\"en\\\" role=\\\"presentation\\\"><!-- This is a test comment --></svg>\\n\"\n expect(output).to be_html_safe\n end", " end\n end", " describe '#inline_svg' do\n it_behaves_like \"inline_svg helper\", helper_method: :inline_svg\n end", " describe '#inline_svg_tag' do\n it_behaves_like \"inline_svg helper\", helper_method: :inline_svg_tag\n end", " describe '#inline_svg_tag' do\n it_behaves_like \"inline_svg helper\", helper_method: :inline_svg_pack_tag\n end\nend" ]
[ 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 ]
PreciseBugs
{"buggy_code_end_loc": [59, 45], "buggy_code_start_loc": [58, 45], "filenames": ["lib/inline_svg/action_view/helpers.rb", "spec/helpers/inline_svg_spec.rb"], "fixing_code_end_loc": [59, 57], "fixing_code_start_loc": [58, 46], "message": "A vulnerability has been found in jamesmartin Inline SVG up to 1.7.1 and classified as problematic. Affected by this vulnerability is an unknown functionality of the file lib/inline_svg/action_view/helpers.rb of the component URL Parameter Handler. The manipulation of the argument filename leads to cross site scripting. The attack can be launched remotely. Upgrading to version 1.7.2 is able to address this issue. The name of the patch is f5363b351508486021f99e083c92068cf2943621. It is recommended to upgrade the affected component. The identifier VDB-217597 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:inline_svg_project:inline_svg:*:*:*:*:*:*:*:*", "matchCriteriaId": "7741CA72-12D1-4538-A079-E2EC3D4BF377", "versionEndExcluding": "1.7.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability has been found in jamesmartin Inline SVG up to 1.7.1 and classified as problematic. Affected by this vulnerability is an unknown functionality of the file lib/inline_svg/action_view/helpers.rb of the component URL Parameter Handler. The manipulation of the argument filename leads to cross site scripting. The attack can be launched remotely. Upgrading to version 1.7.2 is able to address this issue. The name of the patch is f5363b351508486021f99e083c92068cf2943621. It is recommended to upgrade the affected component. The identifier VDB-217597 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2020-36644", "lastModified": "2023-01-12T16:40:20.770", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-07T10:15:09.417", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jamesmartin/inline_svg/commit/f5363b351508486021f99e083c92068cf2943621"}, {"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jamesmartin/inline_svg/pull/117"}, {"source": "cna@vuldb.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/jamesmartin/inline_svg/releases/tag/v1.7.2"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.217597"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.217597"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/jamesmartin/inline_svg/commit/f5363b351508486021f99e083c92068cf2943621"}, "type": "CWE-79"}
180
Determine whether the {function_name} code is vulnerable or not.
[ "'use strict'", "const { AsyncResource } = require('async_hooks')\nconst lru = require('tiny-lru').lru", "const secureJson = require('secure-json-parse')\nconst {\n kDefaultJsonParse,\n kContentTypeParser,\n kBodyLimit,\n kRequestPayloadStream,\n kState,\n kTestInternals,\n kReplyIsError,\n kRouteContext\n} = require('./symbols')", "const {\n FST_ERR_CTP_INVALID_TYPE,\n FST_ERR_CTP_EMPTY_TYPE,\n FST_ERR_CTP_ALREADY_PRESENT,\n FST_ERR_CTP_INVALID_HANDLER,\n FST_ERR_CTP_INVALID_PARSE_TYPE,\n FST_ERR_CTP_BODY_TOO_LARGE,\n FST_ERR_CTP_INVALID_MEDIA_TYPE,\n FST_ERR_CTP_INVALID_CONTENT_LENGTH,\n FST_ERR_CTP_EMPTY_JSON_BODY\n} = require('./errors')", "function ContentTypeParser (bodyLimit, onProtoPoisoning, onConstructorPoisoning) {\n this[kDefaultJsonParse] = getDefaultJsonParser(onProtoPoisoning, onConstructorPoisoning)", " this.customParsers = {}\n this.customParsers['application/json'] = new Parser(true, false, bodyLimit, this[kDefaultJsonParse])\n this.customParsers['text/plain'] = new Parser(true, false, bodyLimit, defaultPlainTextParser)", " this.parserList = ['application/json', 'text/plain']\n this.parserRegExpList = []\n this.cache = lru(100)\n}", "ContentTypeParser.prototype.add = function (contentType, opts, parserFn) {\n const contentTypeIsString = typeof contentType === 'string'", " if (!contentTypeIsString && !(contentType instanceof RegExp)) throw new FST_ERR_CTP_INVALID_TYPE()\n if (contentTypeIsString && contentType.length === 0) throw new FST_ERR_CTP_EMPTY_TYPE()\n if (typeof parserFn !== 'function') throw new FST_ERR_CTP_INVALID_HANDLER()", " if (this.existingParser(contentType)) {\n throw new FST_ERR_CTP_ALREADY_PRESENT(contentType)\n }", " if (opts.parseAs !== undefined) {\n if (opts.parseAs !== 'string' && opts.parseAs !== 'buffer') {\n throw new FST_ERR_CTP_INVALID_PARSE_TYPE(opts.parseAs)\n }\n }", " const parser = new Parser(\n opts.parseAs === 'string',\n opts.parseAs === 'buffer',\n opts.bodyLimit,\n parserFn\n )", " if (contentTypeIsString && contentType === '*') {", " this.customParsers[''] = parser", " } else {\n if (contentTypeIsString) {\n this.parserList.unshift(contentType)\n } else {\n this.parserRegExpList.unshift(contentType)\n }", " this.customParsers[contentType] = parser", " }\n}", "ContentTypeParser.prototype.hasParser = function (contentType) {", " return contentType in this.customParsers", "}", "ContentTypeParser.prototype.existingParser = function (contentType) {", " if (contentType === 'application/json') {\n return this.customParsers['application/json'] && this.customParsers['application/json'].fn !== this[kDefaultJsonParse]\n }\n if (contentType === 'text/plain') {\n return this.customParsers['text/plain'] && this.customParsers['text/plain'].fn !== defaultPlainTextParser\n }", " return contentType in this.customParsers", "}", "ContentTypeParser.prototype.getParser = function (contentType) {", " if (contentType in this.customParsers) {\n return this.customParsers[contentType]", " }", " if (this.cache.has(contentType)) {\n return this.cache.get(contentType)\n }", " // eslint-disable-next-line no-var\n for (var i = 0; i !== this.parserList.length; ++i) {\n const parserName = this.parserList[i]\n if (contentType.indexOf(parserName) !== -1) {", " const parser = this.customParsers[parserName]", " this.cache.set(contentType, parser)\n return parser\n }\n }", " // eslint-disable-next-line no-var\n for (var j = 0; j !== this.parserRegExpList.length; ++j) {\n const parserRegExp = this.parserRegExpList[j]\n if (parserRegExp.test(contentType)) {", " const parser = this.customParsers[parserRegExp]", " this.cache.set(contentType, parser)\n return parser\n }\n }\n", " return this.customParsers['']", "}", "ContentTypeParser.prototype.removeAll = function () {", " this.customParsers = {}", " this.parserRegExpList = []\n this.parserList = []\n this.cache = lru(100)\n}", "ContentTypeParser.prototype.remove = function (contentType) {\n if (!(typeof contentType === 'string' || contentType instanceof RegExp)) throw new FST_ERR_CTP_INVALID_TYPE()\n", " delete this.customParsers[contentType]", "\n const parsers = typeof contentType === 'string' ? this.parserList : this.parserRegExpList", " const idx = parsers.findIndex(ct => ct.toString() === contentType.toString())", " if (idx > -1) {\n parsers.splice(idx, 1)\n }\n}", "ContentTypeParser.prototype.run = function (contentType, handler, request, reply) {\n const parser = this.getParser(contentType)\n const resource = new AsyncResource('content-type-parser:run', request)", " if (parser === undefined) {\n if (request.is404) {\n handler(request, reply)\n } else {\n reply.send(new FST_ERR_CTP_INVALID_MEDIA_TYPE(contentType || undefined))\n }\n } else if (parser.asString === true || parser.asBuffer === true) {\n rawBody(\n request,\n reply,\n reply[kRouteContext]._parserOptions,\n parser,\n done\n )\n } else {\n const result = parser.fn(request, request[kRequestPayloadStream], done)", " if (result && typeof result.then === 'function') {\n result.then(body => done(null, body), done)\n }\n }", " function done (error, body) {\n // We cannot use resource.bind() because it is broken in node v12 and v14\n resource.runInAsyncScope(() => {\n if (error) {\n reply[kReplyIsError] = true\n reply.send(error)\n } else {\n request.body = body\n handler(request, reply)\n }\n })\n }\n}", "function rawBody (request, reply, options, parser, done) {\n const asString = parser.asString\n const limit = options.limit === null ? parser.bodyLimit : options.limit\n const contentLength = request.headers['content-length'] === undefined\n ? NaN\n : Number(request.headers['content-length'])", " if (contentLength > limit) {\n reply.send(new FST_ERR_CTP_BODY_TOO_LARGE())\n return\n }", " let receivedLength = 0\n let body = asString === true ? '' : []", " const payload = request[kRequestPayloadStream] || request.raw", " if (asString === true) {\n payload.setEncoding('utf8')\n }", " payload.on('data', onData)\n payload.on('end', onEnd)\n payload.on('error', onEnd)\n payload.resume()", " function onData (chunk) {\n receivedLength += chunk.length", " if ((payload.receivedEncodedLength || receivedLength) > limit) {\n payload.removeListener('data', onData)\n payload.removeListener('end', onEnd)\n payload.removeListener('error', onEnd)\n reply.send(new FST_ERR_CTP_BODY_TOO_LARGE())\n return\n }", " if (asString === true) {\n body += chunk\n } else {\n body.push(chunk)\n }\n }", " function onEnd (err) {\n payload.removeListener('data', onData)\n payload.removeListener('end', onEnd)\n payload.removeListener('error', onEnd)", " if (err !== undefined) {\n err.statusCode = 400\n reply[kReplyIsError] = true\n reply.code(err.statusCode).send(err)\n return\n }", " if (asString === true) {\n receivedLength = Buffer.byteLength(body)\n }", " if (!Number.isNaN(contentLength) && (payload.receivedEncodedLength || receivedLength) !== contentLength) {\n reply.send(new FST_ERR_CTP_INVALID_CONTENT_LENGTH())\n return\n }", " if (asString === false) {\n body = Buffer.concat(body)\n }", " const result = parser.fn(request, body, done)\n if (result && typeof result.then === 'function') {\n result.then(body => done(null, body), done)\n }\n }\n}", "function getDefaultJsonParser (onProtoPoisoning, onConstructorPoisoning) {\n return defaultJsonParser", " function defaultJsonParser (req, body, done) {\n if (body === '' || body == null) {\n return done(new FST_ERR_CTP_EMPTY_JSON_BODY(), undefined)\n }\n let json\n try {\n json = secureJson.parse(body, { protoAction: onProtoPoisoning, constructorAction: onConstructorPoisoning })\n } catch (err) {\n err.statusCode = 400\n return done(err, undefined)\n }\n done(null, json)\n }\n}", "function defaultPlainTextParser (req, body, done) {\n done(null, body)\n}", "function Parser (asString, asBuffer, bodyLimit, fn) {\n this.asString = asString\n this.asBuffer = asBuffer\n this.bodyLimit = bodyLimit\n this.fn = fn\n}", "function buildContentTypeParser (c) {\n const contentTypeParser = new ContentTypeParser()\n contentTypeParser[kDefaultJsonParse] = c[kDefaultJsonParse]", " Object.assign(contentTypeParser.customParsers, c.customParsers)", " contentTypeParser.parserList = c.parserList.slice()\n return contentTypeParser\n}", "function addContentTypeParser (contentType, opts, parser) {\n if (this[kState].started) {\n throw new Error('Cannot call \"addContentTypeParser\" when fastify instance is already started!')\n }", " if (typeof opts === 'function') {\n parser = opts\n opts = {}\n }", " if (!opts) opts = {}\n if (!opts.bodyLimit) opts.bodyLimit = this[kBodyLimit]", " if (Array.isArray(contentType)) {\n contentType.forEach((type) => this[kContentTypeParser].add(type, opts, parser))\n } else {\n this[kContentTypeParser].add(contentType, opts, parser)\n }", " return this\n}", "function hasContentTypeParser (contentType) {\n return this[kContentTypeParser].hasParser(contentType)\n}", "function removeContentTypeParser (contentType) {\n if (this[kState].started) {\n throw new Error('Cannot call \"removeContentTypeParser\" when fastify instance is already started!')\n }", " if (Array.isArray(contentType)) {\n for (const type of contentType) {\n this[kContentTypeParser].remove(type)\n }\n } else {\n this[kContentTypeParser].remove(contentType)\n }\n}", "function removeAllContentTypeParsers () {\n if (this[kState].started) {\n throw new Error('Cannot call \"removeAllContentTypeParsers\" when fastify instance is already started!')\n }", " this[kContentTypeParser].removeAll()\n}", "module.exports = ContentTypeParser\nmodule.exports.helpers = {\n buildContentTypeParser,\n addContentTypeParser,\n hasContentTypeParser,\n removeContentTypeParser,\n removeAllContentTypeParsers\n}\nmodule.exports.defaultParsers = {\n getDefaultJsonParser,\n defaultTextParser: defaultPlainTextParser\n}\nmodule.exports[kTestInternals] = { rawBody }" ]
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [293, 331], "buggy_code_start_loc": [32, 199], "filenames": ["lib/contentTypeParser.js", "test/content-parser.test.js"], "fixing_code_end_loc": [294, 398], "fixing_code_start_loc": [32, 199], "message": "fastify is a fast and low overhead web framework, for Node.js. Affected versions of fastify are subject to a denial of service via malicious use of the Content-Type header. An attacker can send an invalid Content-Type header that can cause the application to crash. This issue has been addressed in commit `fbb07e8d` and will be included in release version 4.8.1. Users are advised to upgrade. Users unable to upgrade may manually filter out http content with malicious Content-Type headers.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fastify:fastify:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "807CA7E6-76C5-4960-A3FE-1D3A9340CABB", "versionEndExcluding": "4.8.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "fastify is a fast and low overhead web framework, for Node.js. Affected versions of fastify are subject to a denial of service via malicious use of the Content-Type header. An attacker can send an invalid Content-Type header that can cause the application to crash. This issue has been addressed in commit `fbb07e8d` and will be included in release version 4.8.1. Users are advised to upgrade. Users unable to upgrade may manually filter out http content with malicious Content-Type headers."}, {"lang": "es", "value": "fastify es un framework web r\u00e1pido y de baja sobrecarga, para Node.js. Las versiones afectadas de fastify est\u00e1n sujetas a una denegaci\u00f3n de servicio por medio del uso malicioso del encabezado Content-Type. Un atacante puede enviar un encabezado Content-Type no v\u00e1lida que puede causar el bloqueo de la aplicaci\u00f3n. Este problema ha sido abordado en el commit \"fbb07e8d\" y ser\u00e1 incluido en versi\u00f3n 4.8.1. Es recomendado a usuarios actualizar. Los usuarios que no puedan actualizar pueden filtrar manualmente el contenido http con encabezados Content-Type maliciosos"}], "evaluatorComment": null, "id": "CVE-2022-39288", "lastModified": "2022-10-12T18:15:46.940", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-10T21:15:11.300", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/fastify/fastify/commit/fbb07e8dfad74c69cd4cd2211aedab87194618e3"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/fastify/fastify/security/advisories/GHSA-455w-c45v-86rg"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/fastify/fastify/security/policy"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-754"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/fastify/fastify/commit/fbb07e8dfad74c69cd4cd2211aedab87194618e3"}, "type": "CWE-754"}
181
Determine whether the {function_name} code is vulnerable or not.
[ "'use strict'", "const { AsyncResource } = require('async_hooks')\nconst lru = require('tiny-lru').lru", "const secureJson = require('secure-json-parse')\nconst {\n kDefaultJsonParse,\n kContentTypeParser,\n kBodyLimit,\n kRequestPayloadStream,\n kState,\n kTestInternals,\n kReplyIsError,\n kRouteContext\n} = require('./symbols')", "const {\n FST_ERR_CTP_INVALID_TYPE,\n FST_ERR_CTP_EMPTY_TYPE,\n FST_ERR_CTP_ALREADY_PRESENT,\n FST_ERR_CTP_INVALID_HANDLER,\n FST_ERR_CTP_INVALID_PARSE_TYPE,\n FST_ERR_CTP_BODY_TOO_LARGE,\n FST_ERR_CTP_INVALID_MEDIA_TYPE,\n FST_ERR_CTP_INVALID_CONTENT_LENGTH,\n FST_ERR_CTP_EMPTY_JSON_BODY\n} = require('./errors')", "function ContentTypeParser (bodyLimit, onProtoPoisoning, onConstructorPoisoning) {\n this[kDefaultJsonParse] = getDefaultJsonParser(onProtoPoisoning, onConstructorPoisoning)", " // using a map instead of a plain object to avoid prototype hijack attacks\n this.customParsers = new Map()\n this.customParsers.set('application/json', new Parser(true, false, bodyLimit, this[kDefaultJsonParse]))\n this.customParsers.set('text/plain', new Parser(true, false, bodyLimit, defaultPlainTextParser))", " this.parserList = ['application/json', 'text/plain']\n this.parserRegExpList = []\n this.cache = lru(100)\n}", "ContentTypeParser.prototype.add = function (contentType, opts, parserFn) {\n const contentTypeIsString = typeof contentType === 'string'", " if (!contentTypeIsString && !(contentType instanceof RegExp)) throw new FST_ERR_CTP_INVALID_TYPE()\n if (contentTypeIsString && contentType.length === 0) throw new FST_ERR_CTP_EMPTY_TYPE()\n if (typeof parserFn !== 'function') throw new FST_ERR_CTP_INVALID_HANDLER()", " if (this.existingParser(contentType)) {\n throw new FST_ERR_CTP_ALREADY_PRESENT(contentType)\n }", " if (opts.parseAs !== undefined) {\n if (opts.parseAs !== 'string' && opts.parseAs !== 'buffer') {\n throw new FST_ERR_CTP_INVALID_PARSE_TYPE(opts.parseAs)\n }\n }", " const parser = new Parser(\n opts.parseAs === 'string',\n opts.parseAs === 'buffer',\n opts.bodyLimit,\n parserFn\n )", " if (contentTypeIsString && contentType === '*') {", " this.customParsers.set('', parser)", " } else {\n if (contentTypeIsString) {\n this.parserList.unshift(contentType)\n } else {\n this.parserRegExpList.unshift(contentType)\n }", " this.customParsers.set(contentType.toString(), parser)", " }\n}", "ContentTypeParser.prototype.hasParser = function (contentType) {", " return this.customParsers.has(typeof contentType === 'string' ? contentType : contentType.toString())", "}", "ContentTypeParser.prototype.existingParser = function (contentType) {", " if (contentType === 'application/json' && this.customParsers.has(contentType)) {\n return this.customParsers.get(contentType).fn !== this[kDefaultJsonParse]\n }\n if (contentType === 'text/plain' && this.customParsers.has(contentType)) {\n return this.customParsers.get(contentType).fn !== defaultPlainTextParser\n }", " return this.hasParser(contentType)", "}", "ContentTypeParser.prototype.getParser = function (contentType) {", " if (this.hasParser(contentType)) {\n return this.customParsers.get(contentType)", " }", " if (this.cache.has(contentType)) {\n return this.cache.get(contentType)\n }", " // eslint-disable-next-line no-var\n for (var i = 0; i !== this.parserList.length; ++i) {\n const parserName = this.parserList[i]\n if (contentType.indexOf(parserName) !== -1) {", " const parser = this.customParsers.get(parserName)", " this.cache.set(contentType, parser)\n return parser\n }\n }", " // eslint-disable-next-line no-var\n for (var j = 0; j !== this.parserRegExpList.length; ++j) {\n const parserRegExp = this.parserRegExpList[j]\n if (parserRegExp.test(contentType)) {", " const parser = this.customParsers.get(parserRegExp.toString())", " this.cache.set(contentType, parser)\n return parser\n }\n }\n", " return this.customParsers.get('')", "}", "ContentTypeParser.prototype.removeAll = function () {", " this.customParsers = new Map()", " this.parserRegExpList = []\n this.parserList = []\n this.cache = lru(100)\n}", "ContentTypeParser.prototype.remove = function (contentType) {\n if (!(typeof contentType === 'string' || contentType instanceof RegExp)) throw new FST_ERR_CTP_INVALID_TYPE()\n", " this.customParsers.delete(contentType.toString())", "\n const parsers = typeof contentType === 'string' ? this.parserList : this.parserRegExpList", " const idx = parsers.findIndex(ct => ct.toString() === contentType.toString())", " if (idx > -1) {\n parsers.splice(idx, 1)\n }\n}", "ContentTypeParser.prototype.run = function (contentType, handler, request, reply) {\n const parser = this.getParser(contentType)\n const resource = new AsyncResource('content-type-parser:run', request)", " if (parser === undefined) {\n if (request.is404) {\n handler(request, reply)\n } else {\n reply.send(new FST_ERR_CTP_INVALID_MEDIA_TYPE(contentType || undefined))\n }\n } else if (parser.asString === true || parser.asBuffer === true) {\n rawBody(\n request,\n reply,\n reply[kRouteContext]._parserOptions,\n parser,\n done\n )\n } else {\n const result = parser.fn(request, request[kRequestPayloadStream], done)", " if (result && typeof result.then === 'function') {\n result.then(body => done(null, body), done)\n }\n }", " function done (error, body) {\n // We cannot use resource.bind() because it is broken in node v12 and v14\n resource.runInAsyncScope(() => {\n if (error) {\n reply[kReplyIsError] = true\n reply.send(error)\n } else {\n request.body = body\n handler(request, reply)\n }\n })\n }\n}", "function rawBody (request, reply, options, parser, done) {\n const asString = parser.asString\n const limit = options.limit === null ? parser.bodyLimit : options.limit\n const contentLength = request.headers['content-length'] === undefined\n ? NaN\n : Number(request.headers['content-length'])", " if (contentLength > limit) {\n reply.send(new FST_ERR_CTP_BODY_TOO_LARGE())\n return\n }", " let receivedLength = 0\n let body = asString === true ? '' : []", " const payload = request[kRequestPayloadStream] || request.raw", " if (asString === true) {\n payload.setEncoding('utf8')\n }", " payload.on('data', onData)\n payload.on('end', onEnd)\n payload.on('error', onEnd)\n payload.resume()", " function onData (chunk) {\n receivedLength += chunk.length", " if ((payload.receivedEncodedLength || receivedLength) > limit) {\n payload.removeListener('data', onData)\n payload.removeListener('end', onEnd)\n payload.removeListener('error', onEnd)\n reply.send(new FST_ERR_CTP_BODY_TOO_LARGE())\n return\n }", " if (asString === true) {\n body += chunk\n } else {\n body.push(chunk)\n }\n }", " function onEnd (err) {\n payload.removeListener('data', onData)\n payload.removeListener('end', onEnd)\n payload.removeListener('error', onEnd)", " if (err !== undefined) {\n err.statusCode = 400\n reply[kReplyIsError] = true\n reply.code(err.statusCode).send(err)\n return\n }", " if (asString === true) {\n receivedLength = Buffer.byteLength(body)\n }", " if (!Number.isNaN(contentLength) && (payload.receivedEncodedLength || receivedLength) !== contentLength) {\n reply.send(new FST_ERR_CTP_INVALID_CONTENT_LENGTH())\n return\n }", " if (asString === false) {\n body = Buffer.concat(body)\n }", " const result = parser.fn(request, body, done)\n if (result && typeof result.then === 'function') {\n result.then(body => done(null, body), done)\n }\n }\n}", "function getDefaultJsonParser (onProtoPoisoning, onConstructorPoisoning) {\n return defaultJsonParser", " function defaultJsonParser (req, body, done) {\n if (body === '' || body == null) {\n return done(new FST_ERR_CTP_EMPTY_JSON_BODY(), undefined)\n }\n let json\n try {\n json = secureJson.parse(body, { protoAction: onProtoPoisoning, constructorAction: onConstructorPoisoning })\n } catch (err) {\n err.statusCode = 400\n return done(err, undefined)\n }\n done(null, json)\n }\n}", "function defaultPlainTextParser (req, body, done) {\n done(null, body)\n}", "function Parser (asString, asBuffer, bodyLimit, fn) {\n this.asString = asString\n this.asBuffer = asBuffer\n this.bodyLimit = bodyLimit\n this.fn = fn\n}", "function buildContentTypeParser (c) {\n const contentTypeParser = new ContentTypeParser()\n contentTypeParser[kDefaultJsonParse] = c[kDefaultJsonParse]", " contentTypeParser.customParsers = new Map(c.customParsers.entries())", " contentTypeParser.parserList = c.parserList.slice()\n return contentTypeParser\n}", "function addContentTypeParser (contentType, opts, parser) {\n if (this[kState].started) {\n throw new Error('Cannot call \"addContentTypeParser\" when fastify instance is already started!')\n }", " if (typeof opts === 'function') {\n parser = opts\n opts = {}\n }", " if (!opts) opts = {}\n if (!opts.bodyLimit) opts.bodyLimit = this[kBodyLimit]", " if (Array.isArray(contentType)) {\n contentType.forEach((type) => this[kContentTypeParser].add(type, opts, parser))\n } else {\n this[kContentTypeParser].add(contentType, opts, parser)\n }", " return this\n}", "function hasContentTypeParser (contentType) {\n return this[kContentTypeParser].hasParser(contentType)\n}", "function removeContentTypeParser (contentType) {\n if (this[kState].started) {\n throw new Error('Cannot call \"removeContentTypeParser\" when fastify instance is already started!')\n }", " if (Array.isArray(contentType)) {\n for (const type of contentType) {\n this[kContentTypeParser].remove(type)\n }\n } else {\n this[kContentTypeParser].remove(contentType)\n }\n}", "function removeAllContentTypeParsers () {\n if (this[kState].started) {\n throw new Error('Cannot call \"removeAllContentTypeParsers\" when fastify instance is already started!')\n }", " this[kContentTypeParser].removeAll()\n}", "module.exports = ContentTypeParser\nmodule.exports.helpers = {\n buildContentTypeParser,\n addContentTypeParser,\n hasContentTypeParser,\n removeContentTypeParser,\n removeAllContentTypeParsers\n}\nmodule.exports.defaultParsers = {\n getDefaultJsonParser,\n defaultTextParser: defaultPlainTextParser\n}\nmodule.exports[kTestInternals] = { rawBody }" ]
[ 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [293, 331], "buggy_code_start_loc": [32, 199], "filenames": ["lib/contentTypeParser.js", "test/content-parser.test.js"], "fixing_code_end_loc": [294, 398], "fixing_code_start_loc": [32, 199], "message": "fastify is a fast and low overhead web framework, for Node.js. Affected versions of fastify are subject to a denial of service via malicious use of the Content-Type header. An attacker can send an invalid Content-Type header that can cause the application to crash. This issue has been addressed in commit `fbb07e8d` and will be included in release version 4.8.1. Users are advised to upgrade. Users unable to upgrade may manually filter out http content with malicious Content-Type headers.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fastify:fastify:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "807CA7E6-76C5-4960-A3FE-1D3A9340CABB", "versionEndExcluding": "4.8.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "fastify is a fast and low overhead web framework, for Node.js. Affected versions of fastify are subject to a denial of service via malicious use of the Content-Type header. An attacker can send an invalid Content-Type header that can cause the application to crash. This issue has been addressed in commit `fbb07e8d` and will be included in release version 4.8.1. Users are advised to upgrade. Users unable to upgrade may manually filter out http content with malicious Content-Type headers."}, {"lang": "es", "value": "fastify es un framework web r\u00e1pido y de baja sobrecarga, para Node.js. Las versiones afectadas de fastify est\u00e1n sujetas a una denegaci\u00f3n de servicio por medio del uso malicioso del encabezado Content-Type. Un atacante puede enviar un encabezado Content-Type no v\u00e1lida que puede causar el bloqueo de la aplicaci\u00f3n. Este problema ha sido abordado en el commit \"fbb07e8d\" y ser\u00e1 incluido en versi\u00f3n 4.8.1. Es recomendado a usuarios actualizar. Los usuarios que no puedan actualizar pueden filtrar manualmente el contenido http con encabezados Content-Type maliciosos"}], "evaluatorComment": null, "id": "CVE-2022-39288", "lastModified": "2022-10-12T18:15:46.940", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-10T21:15:11.300", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/fastify/fastify/commit/fbb07e8dfad74c69cd4cd2211aedab87194618e3"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/fastify/fastify/security/advisories/GHSA-455w-c45v-86rg"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/fastify/fastify/security/policy"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-754"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/fastify/fastify/commit/fbb07e8dfad74c69cd4cd2211aedab87194618e3"}, "type": "CWE-754"}
181
Determine whether the {function_name} code is vulnerable or not.
[ "'use strict'", "const t = require('tap')\nconst test = t.test\nconst Fastify = require('..')\nconst keys = require('../lib/symbols')\nconst { FST_ERR_CTP_ALREADY_PRESENT, FST_ERR_CTP_INVALID_TYPE, FST_ERR_CTP_INVALID_MEDIA_TYPE } = require('../lib/errors')", "const first = function (req, payload, done) {}\nconst second = function (req, payload, done) {}\nconst third = function (req, payload, done) {}", "test('hasContentTypeParser', t => {\n test('should know about internal parsers', t => {\n t.plan(4)", " const fastify = Fastify()\n fastify.ready(err => {\n t.error(err)\n t.ok(fastify.hasContentTypeParser('application/json'))\n t.ok(fastify.hasContentTypeParser('text/plain'))\n t.notOk(fastify.hasContentTypeParser('application/jsoff'))\n })\n })", " test('should work with string and RegExp', t => {\n t.plan(7)", " const fastify = Fastify()\n fastify.addContentTypeParser(/^image\\/.*/, first)\n fastify.addContentTypeParser(/^application\\/.+\\+xml/, first)\n fastify.addContentTypeParser('image/gif', first)", " t.ok(fastify.hasContentTypeParser('application/json'))\n t.ok(fastify.hasContentTypeParser(/^image\\/.*/))\n t.ok(fastify.hasContentTypeParser(/^application\\/.+\\+xml/))\n t.ok(fastify.hasContentTypeParser('image/gif'))\n t.notOk(fastify.hasContentTypeParser(/^image\\/.+\\+xml/))\n t.notOk(fastify.hasContentTypeParser('image/png'))\n t.notOk(fastify.hasContentTypeParser('*'))\n })", " t.end()\n})", "test('getParser', t => {\n test('should return matching parser', t => {\n t.plan(3)", " const fastify = Fastify()", " fastify.addContentTypeParser(/^image\\/.*/, first)\n fastify.addContentTypeParser(/^application\\/.+\\+xml/, second)\n fastify.addContentTypeParser('text/html', third)", " t.equal(fastify[keys.kContentTypeParser].getParser('application/t+xml').fn, second)\n t.equal(fastify[keys.kContentTypeParser].getParser('image/png').fn, first)\n t.equal(fastify[keys.kContentTypeParser].getParser('text/html').fn, third)\n })", " test('should return matching parser with caching', t => {\n t.plan(6)", " const fastify = Fastify()", " fastify.addContentTypeParser('text/html', first)", " t.equal(fastify[keys.kContentTypeParser].getParser('text/html').fn, first)\n t.equal(fastify[keys.kContentTypeParser].cache.size, 0)\n t.equal(fastify[keys.kContentTypeParser].getParser('text/html ').fn, first)\n t.equal(fastify[keys.kContentTypeParser].cache.size, 1)\n t.equal(fastify[keys.kContentTypeParser].getParser('text/html ').fn, first)\n t.equal(fastify[keys.kContentTypeParser].cache.size, 1)\n })", " test('should prefer content type parser with string value', t => {\n t.plan(2)", " const fastify = Fastify()", " fastify.addContentTypeParser(/^image\\/.*/, first)\n fastify.addContentTypeParser('image/gif', second)", " t.equal(fastify[keys.kContentTypeParser].getParser('image/gif').fn, second)\n t.equal(fastify[keys.kContentTypeParser].getParser('image/png').fn, first)\n })", " test('should return parser that catches all if no other is set', t => {\n t.plan(3)", " const fastify = Fastify()", " fastify.addContentTypeParser('*', first)\n fastify.addContentTypeParser(/^text\\/.*/, second)", " t.equal(fastify[keys.kContentTypeParser].getParser('image/gif').fn, first)\n t.equal(fastify[keys.kContentTypeParser].getParser('text/html').fn, second)\n t.equal(fastify[keys.kContentTypeParser].getParser('text').fn, first)\n })", " test('should return undefined if no matching parser exist', t => {\n t.plan(2)", " const fastify = Fastify()", " fastify.addContentTypeParser(/^weirdType\\/.+/, first)\n fastify.addContentTypeParser('application/javascript', first)", " t.notOk(fastify[keys.kContentTypeParser].getParser('application/xml'))\n t.notOk(fastify[keys.kContentTypeParser].getParser('weirdType/'))\n })", " t.end()\n})", "test('existingParser', t => {\n test('returns always false for \"*\"', t => {\n t.plan(2)", " const fastify = Fastify()", " fastify.addContentTypeParser(/^image\\/.*/, first)\n fastify.addContentTypeParser(/^application\\/.+\\+xml/, first)\n fastify.addContentTypeParser('text/html', first)", " t.notOk(fastify[keys.kContentTypeParser].existingParser('*'))", " fastify.addContentTypeParser('*', first)", " t.notOk(fastify[keys.kContentTypeParser].existingParser('*'))\n })", " test('let you override the default parser once', t => {\n t.plan(2)", " const fastify = Fastify()", " fastify.addContentTypeParser('application/json', first)\n fastify.addContentTypeParser('text/plain', first)", " t.throws(\n () => fastify.addContentTypeParser('application/json', first),\n FST_ERR_CTP_ALREADY_PRESENT,\n \"Content type parser 'application/json' already present\"\n )\n t.throws(\n () => fastify.addContentTypeParser('text/plain', first),\n FST_ERR_CTP_ALREADY_PRESENT,\n \"Content type parser 'text/plain' already present\"\n )\n })", " const fastify = Fastify()\n const contentTypeParser = fastify[keys.kContentTypeParser]", " fastify.addContentTypeParser(/^image\\/.*/, first)\n fastify.addContentTypeParser(/^application\\/.+\\+xml/, first)\n fastify.addContentTypeParser('text/html', first)", " t.ok(contentTypeParser.existingParser(/^image\\/.*/))\n t.ok(contentTypeParser.existingParser('text/html'))\n t.ok(contentTypeParser.existingParser(/^application\\/.+\\+xml/))\n t.notOk(contentTypeParser.existingParser('application/json'))\n t.notOk(contentTypeParser.existingParser('text/plain'))\n t.notOk(contentTypeParser.existingParser('image/png'))\n t.notOk(contentTypeParser.existingParser(/^application\\/.+\\+json/))", " t.end()\n})", "test('add', t => {\n test('should only accept string and RegExp', t => {\n t.plan(4)", " const fastify = Fastify()\n const contentTypeParser = fastify[keys.kContentTypeParser]", " t.error(contentTypeParser.add('test', {}, first))\n t.error(contentTypeParser.add(/test/, {}, first))\n t.throws(\n () => contentTypeParser.add({}, {}, first),\n FST_ERR_CTP_INVALID_TYPE,\n 'The content type should be a string or a RegExp'\n )\n t.throws(\n () => contentTypeParser.add(1, {}, first),\n FST_ERR_CTP_INVALID_TYPE,\n 'The content type should be a string or a RegExp'\n )\n })", " test('should set \"*\" as parser that catches all', t => {\n t.plan(1)", " const fastify = Fastify()\n const contentTypeParser = fastify[keys.kContentTypeParser]", " contentTypeParser.add('*', {}, first)", " t.equal(contentTypeParser.customParsers[''].fn, first)", " })", " t.end()\n})", "test('non-Error thrown from content parser is properly handled', t => {\n t.plan(3)", " const fastify = Fastify()", " const throwable = 'test'\n const payload = 'error'", " fastify.addContentTypeParser('text/test', (request, payload, done) => {\n done(throwable)\n })", " fastify.post('/', (req, reply) => {\n })", " fastify.setErrorHandler((err, req, res) => {\n t.equal(err, throwable)", " res.send(payload)\n })", " fastify.inject({\n method: 'POST',\n url: '/',\n headers: { 'Content-Type': 'text/test' },\n body: 'some text'\n }, (err, res) => {\n t.error(err)\n t.equal(res.payload, payload)\n })\n})", "test('Error thrown 415 from content type is null and make post request to server', t => {\n t.plan(3)", " const fastify = Fastify()\n const errMsg = new FST_ERR_CTP_INVALID_MEDIA_TYPE(undefined).message", " fastify.post('/', (req, reply) => {\n })", " fastify.inject({\n method: 'POST',\n url: '/',\n body: 'some text'\n }, (err, res) => {\n t.error(err)\n t.equal(res.statusCode, 415)\n t.equal(JSON.parse(res.body).message, errMsg)\n })\n})", "test('remove', t => {\n test('should remove default parser', t => {\n t.plan(2)", " const fastify = Fastify()\n const contentTypeParser = fastify[keys.kContentTypeParser]", " contentTypeParser.remove('application/json')", " t.notOk(contentTypeParser.customParsers['application/json'])\n t.notOk(contentTypeParser.parserList.find(parser => parser === 'application/json'))\n })", " test('should remove RegExp parser', t => {\n t.plan(2)", " const fastify = Fastify()\n fastify.addContentTypeParser(/^text\\/*/, first)", " const contentTypeParser = fastify[keys.kContentTypeParser]", " contentTypeParser.remove(/^text\\/*/)", " t.notOk(contentTypeParser.customParsers[/^text\\/*/])\n t.notOk(contentTypeParser.parserRegExpList.find(parser => parser.toString() === /^text\\/*/.toString()))\n })", " test('should throw an error if content type is neither string nor RegExp', t => {\n t.plan(1)", " const fastify = Fastify()", " t.throws(() => fastify[keys.kContentTypeParser].remove(12), FST_ERR_CTP_INVALID_TYPE)\n })", " test('should not throw error if content type does not exist', t => {\n t.plan(1)", " const fastify = Fastify()", " t.doesNotThrow(() => fastify[keys.kContentTypeParser].remove('image/png'))\n })", " test('should not remove any content type parser if content type does not exist', t => {\n t.plan(1)", " const fastify = Fastify()", " const contentTypeParser = fastify[keys.kContentTypeParser]", " contentTypeParser.remove('image/png')\n", " t.same(Object.keys(contentTypeParser.customParsers).length, 2)", " })", " t.end()\n})", "test('remove all should remove all existing parsers and reset cache', t => {\n t.plan(4)", " const fastify = Fastify()\n fastify.addContentTypeParser('application/xml', first)\n fastify.addContentTypeParser(/^image\\/.*/, first)", " const contentTypeParser = fastify[keys.kContentTypeParser]", " contentTypeParser.getParser('application/xml') // fill cache with one entry\n contentTypeParser.removeAll()", " t.same(contentTypeParser.cache.size, 0)\n t.same(contentTypeParser.parserList.length, 0)\n t.same(contentTypeParser.parserRegExpList.length, 0)\n t.same(Object.keys(contentTypeParser.customParsers).length, 0)\n})", "" ]
[ 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, 1, 1, 0, 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, 1, 1, 1, 1, 1, 1, 0 ]
PreciseBugs
{"buggy_code_end_loc": [293, 331], "buggy_code_start_loc": [32, 199], "filenames": ["lib/contentTypeParser.js", "test/content-parser.test.js"], "fixing_code_end_loc": [294, 398], "fixing_code_start_loc": [32, 199], "message": "fastify is a fast and low overhead web framework, for Node.js. Affected versions of fastify are subject to a denial of service via malicious use of the Content-Type header. An attacker can send an invalid Content-Type header that can cause the application to crash. This issue has been addressed in commit `fbb07e8d` and will be included in release version 4.8.1. Users are advised to upgrade. Users unable to upgrade may manually filter out http content with malicious Content-Type headers.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fastify:fastify:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "807CA7E6-76C5-4960-A3FE-1D3A9340CABB", "versionEndExcluding": "4.8.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "fastify is a fast and low overhead web framework, for Node.js. Affected versions of fastify are subject to a denial of service via malicious use of the Content-Type header. An attacker can send an invalid Content-Type header that can cause the application to crash. This issue has been addressed in commit `fbb07e8d` and will be included in release version 4.8.1. Users are advised to upgrade. Users unable to upgrade may manually filter out http content with malicious Content-Type headers."}, {"lang": "es", "value": "fastify es un framework web r\u00e1pido y de baja sobrecarga, para Node.js. Las versiones afectadas de fastify est\u00e1n sujetas a una denegaci\u00f3n de servicio por medio del uso malicioso del encabezado Content-Type. Un atacante puede enviar un encabezado Content-Type no v\u00e1lida que puede causar el bloqueo de la aplicaci\u00f3n. Este problema ha sido abordado en el commit \"fbb07e8d\" y ser\u00e1 incluido en versi\u00f3n 4.8.1. Es recomendado a usuarios actualizar. Los usuarios que no puedan actualizar pueden filtrar manualmente el contenido http con encabezados Content-Type maliciosos"}], "evaluatorComment": null, "id": "CVE-2022-39288", "lastModified": "2022-10-12T18:15:46.940", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-10T21:15:11.300", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/fastify/fastify/commit/fbb07e8dfad74c69cd4cd2211aedab87194618e3"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/fastify/fastify/security/advisories/GHSA-455w-c45v-86rg"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/fastify/fastify/security/policy"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-754"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/fastify/fastify/commit/fbb07e8dfad74c69cd4cd2211aedab87194618e3"}, "type": "CWE-754"}
181
Determine whether the {function_name} code is vulnerable or not.
[ "'use strict'", "const t = require('tap')\nconst test = t.test\nconst Fastify = require('..')\nconst keys = require('../lib/symbols')\nconst { FST_ERR_CTP_ALREADY_PRESENT, FST_ERR_CTP_INVALID_TYPE, FST_ERR_CTP_INVALID_MEDIA_TYPE } = require('../lib/errors')", "const first = function (req, payload, done) {}\nconst second = function (req, payload, done) {}\nconst third = function (req, payload, done) {}", "test('hasContentTypeParser', t => {\n test('should know about internal parsers', t => {\n t.plan(4)", " const fastify = Fastify()\n fastify.ready(err => {\n t.error(err)\n t.ok(fastify.hasContentTypeParser('application/json'))\n t.ok(fastify.hasContentTypeParser('text/plain'))\n t.notOk(fastify.hasContentTypeParser('application/jsoff'))\n })\n })", " test('should work with string and RegExp', t => {\n t.plan(7)", " const fastify = Fastify()\n fastify.addContentTypeParser(/^image\\/.*/, first)\n fastify.addContentTypeParser(/^application\\/.+\\+xml/, first)\n fastify.addContentTypeParser('image/gif', first)", " t.ok(fastify.hasContentTypeParser('application/json'))\n t.ok(fastify.hasContentTypeParser(/^image\\/.*/))\n t.ok(fastify.hasContentTypeParser(/^application\\/.+\\+xml/))\n t.ok(fastify.hasContentTypeParser('image/gif'))\n t.notOk(fastify.hasContentTypeParser(/^image\\/.+\\+xml/))\n t.notOk(fastify.hasContentTypeParser('image/png'))\n t.notOk(fastify.hasContentTypeParser('*'))\n })", " t.end()\n})", "test('getParser', t => {\n test('should return matching parser', t => {\n t.plan(3)", " const fastify = Fastify()", " fastify.addContentTypeParser(/^image\\/.*/, first)\n fastify.addContentTypeParser(/^application\\/.+\\+xml/, second)\n fastify.addContentTypeParser('text/html', third)", " t.equal(fastify[keys.kContentTypeParser].getParser('application/t+xml').fn, second)\n t.equal(fastify[keys.kContentTypeParser].getParser('image/png').fn, first)\n t.equal(fastify[keys.kContentTypeParser].getParser('text/html').fn, third)\n })", " test('should return matching parser with caching', t => {\n t.plan(6)", " const fastify = Fastify()", " fastify.addContentTypeParser('text/html', first)", " t.equal(fastify[keys.kContentTypeParser].getParser('text/html').fn, first)\n t.equal(fastify[keys.kContentTypeParser].cache.size, 0)\n t.equal(fastify[keys.kContentTypeParser].getParser('text/html ').fn, first)\n t.equal(fastify[keys.kContentTypeParser].cache.size, 1)\n t.equal(fastify[keys.kContentTypeParser].getParser('text/html ').fn, first)\n t.equal(fastify[keys.kContentTypeParser].cache.size, 1)\n })", " test('should prefer content type parser with string value', t => {\n t.plan(2)", " const fastify = Fastify()", " fastify.addContentTypeParser(/^image\\/.*/, first)\n fastify.addContentTypeParser('image/gif', second)", " t.equal(fastify[keys.kContentTypeParser].getParser('image/gif').fn, second)\n t.equal(fastify[keys.kContentTypeParser].getParser('image/png').fn, first)\n })", " test('should return parser that catches all if no other is set', t => {\n t.plan(3)", " const fastify = Fastify()", " fastify.addContentTypeParser('*', first)\n fastify.addContentTypeParser(/^text\\/.*/, second)", " t.equal(fastify[keys.kContentTypeParser].getParser('image/gif').fn, first)\n t.equal(fastify[keys.kContentTypeParser].getParser('text/html').fn, second)\n t.equal(fastify[keys.kContentTypeParser].getParser('text').fn, first)\n })", " test('should return undefined if no matching parser exist', t => {\n t.plan(2)", " const fastify = Fastify()", " fastify.addContentTypeParser(/^weirdType\\/.+/, first)\n fastify.addContentTypeParser('application/javascript', first)", " t.notOk(fastify[keys.kContentTypeParser].getParser('application/xml'))\n t.notOk(fastify[keys.kContentTypeParser].getParser('weirdType/'))\n })", " t.end()\n})", "test('existingParser', t => {\n test('returns always false for \"*\"', t => {\n t.plan(2)", " const fastify = Fastify()", " fastify.addContentTypeParser(/^image\\/.*/, first)\n fastify.addContentTypeParser(/^application\\/.+\\+xml/, first)\n fastify.addContentTypeParser('text/html', first)", " t.notOk(fastify[keys.kContentTypeParser].existingParser('*'))", " fastify.addContentTypeParser('*', first)", " t.notOk(fastify[keys.kContentTypeParser].existingParser('*'))\n })", " test('let you override the default parser once', t => {\n t.plan(2)", " const fastify = Fastify()", " fastify.addContentTypeParser('application/json', first)\n fastify.addContentTypeParser('text/plain', first)", " t.throws(\n () => fastify.addContentTypeParser('application/json', first),\n FST_ERR_CTP_ALREADY_PRESENT,\n \"Content type parser 'application/json' already present\"\n )\n t.throws(\n () => fastify.addContentTypeParser('text/plain', first),\n FST_ERR_CTP_ALREADY_PRESENT,\n \"Content type parser 'text/plain' already present\"\n )\n })", " const fastify = Fastify()\n const contentTypeParser = fastify[keys.kContentTypeParser]", " fastify.addContentTypeParser(/^image\\/.*/, first)\n fastify.addContentTypeParser(/^application\\/.+\\+xml/, first)\n fastify.addContentTypeParser('text/html', first)", " t.ok(contentTypeParser.existingParser(/^image\\/.*/))\n t.ok(contentTypeParser.existingParser('text/html'))\n t.ok(contentTypeParser.existingParser(/^application\\/.+\\+xml/))\n t.notOk(contentTypeParser.existingParser('application/json'))\n t.notOk(contentTypeParser.existingParser('text/plain'))\n t.notOk(contentTypeParser.existingParser('image/png'))\n t.notOk(contentTypeParser.existingParser(/^application\\/.+\\+json/))", " t.end()\n})", "test('add', t => {\n test('should only accept string and RegExp', t => {\n t.plan(4)", " const fastify = Fastify()\n const contentTypeParser = fastify[keys.kContentTypeParser]", " t.error(contentTypeParser.add('test', {}, first))\n t.error(contentTypeParser.add(/test/, {}, first))\n t.throws(\n () => contentTypeParser.add({}, {}, first),\n FST_ERR_CTP_INVALID_TYPE,\n 'The content type should be a string or a RegExp'\n )\n t.throws(\n () => contentTypeParser.add(1, {}, first),\n FST_ERR_CTP_INVALID_TYPE,\n 'The content type should be a string or a RegExp'\n )\n })", " test('should set \"*\" as parser that catches all', t => {\n t.plan(1)", " const fastify = Fastify()\n const contentTypeParser = fastify[keys.kContentTypeParser]", " contentTypeParser.add('*', {}, first)", " t.equal(contentTypeParser.customParsers.get('').fn, first)", " })", " t.end()\n})", "test('non-Error thrown from content parser is properly handled', t => {\n t.plan(3)", " const fastify = Fastify()", " const throwable = 'test'\n const payload = 'error'", " fastify.addContentTypeParser('text/test', (request, payload, done) => {\n done(throwable)\n })", " fastify.post('/', (req, reply) => {\n })", " fastify.setErrorHandler((err, req, res) => {\n t.equal(err, throwable)", " res.send(payload)\n })", " fastify.inject({\n method: 'POST',\n url: '/',\n headers: { 'Content-Type': 'text/test' },\n body: 'some text'\n }, (err, res) => {\n t.error(err)\n t.equal(res.payload, payload)\n })\n})", "test('Error thrown 415 from content type is null and make post request to server', t => {\n t.plan(3)", " const fastify = Fastify()\n const errMsg = new FST_ERR_CTP_INVALID_MEDIA_TYPE(undefined).message", " fastify.post('/', (req, reply) => {\n })", " fastify.inject({\n method: 'POST',\n url: '/',\n body: 'some text'\n }, (err, res) => {\n t.error(err)\n t.equal(res.statusCode, 415)\n t.equal(JSON.parse(res.body).message, errMsg)\n })\n})", "test('remove', t => {\n test('should remove default parser', t => {\n t.plan(2)", " const fastify = Fastify()\n const contentTypeParser = fastify[keys.kContentTypeParser]", " contentTypeParser.remove('application/json')", " t.notOk(contentTypeParser.customParsers['application/json'])\n t.notOk(contentTypeParser.parserList.find(parser => parser === 'application/json'))\n })", " test('should remove RegExp parser', t => {\n t.plan(2)", " const fastify = Fastify()\n fastify.addContentTypeParser(/^text\\/*/, first)", " const contentTypeParser = fastify[keys.kContentTypeParser]", " contentTypeParser.remove(/^text\\/*/)", " t.notOk(contentTypeParser.customParsers[/^text\\/*/])\n t.notOk(contentTypeParser.parserRegExpList.find(parser => parser.toString() === /^text\\/*/.toString()))\n })", " test('should throw an error if content type is neither string nor RegExp', t => {\n t.plan(1)", " const fastify = Fastify()", " t.throws(() => fastify[keys.kContentTypeParser].remove(12), FST_ERR_CTP_INVALID_TYPE)\n })", " test('should not throw error if content type does not exist', t => {\n t.plan(1)", " const fastify = Fastify()", " t.doesNotThrow(() => fastify[keys.kContentTypeParser].remove('image/png'))\n })", " test('should not remove any content type parser if content type does not exist', t => {\n t.plan(1)", " const fastify = Fastify()", " const contentTypeParser = fastify[keys.kContentTypeParser]", " contentTypeParser.remove('image/png')\n", " t.same(contentTypeParser.customParsers.size, 2)", " })", " t.end()\n})", "test('remove all should remove all existing parsers and reset cache', t => {\n t.plan(4)", " const fastify = Fastify()\n fastify.addContentTypeParser('application/xml', first)\n fastify.addContentTypeParser(/^image\\/.*/, first)", " const contentTypeParser = fastify[keys.kContentTypeParser]", " contentTypeParser.getParser('application/xml') // fill cache with one entry\n contentTypeParser.removeAll()", " t.same(contentTypeParser.cache.size, 0)\n t.same(contentTypeParser.parserList.length, 0)\n t.same(contentTypeParser.parserRegExpList.length, 0)\n t.same(Object.keys(contentTypeParser.customParsers).length, 0)\n})", "\ntest('Safeguard against malicious content-type / 1', async t => {\n const badNames = Object.getOwnPropertyNames({}.__proto__) // eslint-disable-line\n t.plan(badNames.length)", " const fastify = Fastify()", " fastify.post('/', async () => {\n return 'ok'\n })", " for (const prop of badNames) {\n const response = await fastify.inject({\n method: 'POST',\n path: '/',\n headers: {\n 'content-type': prop\n },\n body: ''\n })", " t.same(response.statusCode, 415)\n }\n})", "test('Safeguard against malicious content-type / 2', async t => {\n t.plan(1)", " const fastify = Fastify()", " fastify.post('/', async () => {\n return 'ok'\n })", " const response = await fastify.inject({\n method: 'POST',\n path: '/',\n headers: {\n 'content-type': '\\\\u0063\\\\u006fnstructor'\n },\n body: ''\n })", " t.same(response.statusCode, 415)\n})", "test('Safeguard against malicious content-type / 3', async t => {\n t.plan(1)", " const fastify = Fastify()", " fastify.post('/', async () => {\n return 'ok'\n })", " const response = await fastify.inject({\n method: 'POST',\n path: '/',\n headers: {\n 'content-type': 'constructor; charset=utf-8'\n },\n body: ''\n })", " t.same(response.statusCode, 415)\n})" ]
[ 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [293, 331], "buggy_code_start_loc": [32, 199], "filenames": ["lib/contentTypeParser.js", "test/content-parser.test.js"], "fixing_code_end_loc": [294, 398], "fixing_code_start_loc": [32, 199], "message": "fastify is a fast and low overhead web framework, for Node.js. Affected versions of fastify are subject to a denial of service via malicious use of the Content-Type header. An attacker can send an invalid Content-Type header that can cause the application to crash. This issue has been addressed in commit `fbb07e8d` and will be included in release version 4.8.1. Users are advised to upgrade. Users unable to upgrade may manually filter out http content with malicious Content-Type headers.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fastify:fastify:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "807CA7E6-76C5-4960-A3FE-1D3A9340CABB", "versionEndExcluding": "4.8.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "fastify is a fast and low overhead web framework, for Node.js. Affected versions of fastify are subject to a denial of service via malicious use of the Content-Type header. An attacker can send an invalid Content-Type header that can cause the application to crash. This issue has been addressed in commit `fbb07e8d` and will be included in release version 4.8.1. Users are advised to upgrade. Users unable to upgrade may manually filter out http content with malicious Content-Type headers."}, {"lang": "es", "value": "fastify es un framework web r\u00e1pido y de baja sobrecarga, para Node.js. Las versiones afectadas de fastify est\u00e1n sujetas a una denegaci\u00f3n de servicio por medio del uso malicioso del encabezado Content-Type. Un atacante puede enviar un encabezado Content-Type no v\u00e1lida que puede causar el bloqueo de la aplicaci\u00f3n. Este problema ha sido abordado en el commit \"fbb07e8d\" y ser\u00e1 incluido en versi\u00f3n 4.8.1. Es recomendado a usuarios actualizar. Los usuarios que no puedan actualizar pueden filtrar manualmente el contenido http con encabezados Content-Type maliciosos"}], "evaluatorComment": null, "id": "CVE-2022-39288", "lastModified": "2022-10-12T18:15:46.940", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-10T21:15:11.300", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/fastify/fastify/commit/fbb07e8dfad74c69cd4cd2211aedab87194618e3"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Third Party Advisory"], "url": "https://github.com/fastify/fastify/security/advisories/GHSA-455w-c45v-86rg"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/fastify/fastify/security/policy"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-754"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/fastify/fastify/commit/fbb07e8dfad74c69cd4cd2211aedab87194618e3"}, "type": "CWE-754"}
181
Determine whether the {function_name} code is vulnerable or not.
[ "#include \"sb_pci_mp.h\"\n#include <linux/module.h>\n#include <linux/parport.h>", "extern struct parport *parport_pc_probe_port(unsigned long base_lo,\n\t\tunsigned long base_hi,\n\t\tint irq, int dma,\n\t\tstruct device *dev,\n\t\tint irqflags);", "static struct mp_device_t mp_devs[MAX_MP_DEV];\nstatic int mp_nrpcibrds = sizeof(mp_pciboards)/sizeof(mppcibrd_t);\nstatic int NR_BOARD=0;\nstatic int NR_PORTS=0;\nstatic struct mp_port multi_ports[MAX_MP_PORT];\nstatic struct irq_info irq_lists[NR_IRQS];", "static _INLINE_ unsigned int serial_in(struct mp_port *mtpt, int offset);\nstatic _INLINE_ void serial_out(struct mp_port *mtpt, int offset, int value);\nstatic _INLINE_ unsigned int read_option_register(struct mp_port *mtpt, int offset);\nstatic int sb1054_get_register(struct sb_uart_port *port, int page, int reg);\nstatic int sb1054_set_register(struct sb_uart_port *port, int page, int reg, int value);\nstatic void SendATCommand(struct mp_port *mtpt);\nstatic int set_deep_fifo(struct sb_uart_port *port, int status);\nstatic int get_deep_fifo(struct sb_uart_port *port);\nstatic int get_device_type(int arg);\nstatic int set_auto_rts(struct sb_uart_port *port, int status);\nstatic void mp_stop(struct tty_struct *tty);\nstatic void __mp_start(struct tty_struct *tty);\nstatic void mp_start(struct tty_struct *tty);\nstatic void mp_tasklet_action(unsigned long data);\nstatic inline void mp_update_mctrl(struct sb_uart_port *port, unsigned int set, unsigned int clear);\nstatic int mp_startup(struct sb_uart_state *state, int init_hw);\nstatic void mp_shutdown(struct sb_uart_state *state);\nstatic void mp_change_speed(struct sb_uart_state *state, struct MP_TERMIOS *old_termios);", "static inline int __mp_put_char(struct sb_uart_port *port, struct circ_buf *circ, unsigned char c);\nstatic int mp_put_char(struct tty_struct *tty, unsigned char ch);", "static void mp_put_chars(struct tty_struct *tty);\nstatic int mp_write(struct tty_struct *tty, const unsigned char *buf, int count);\nstatic int mp_write_room(struct tty_struct *tty);\nstatic int mp_chars_in_buffer(struct tty_struct *tty);\nstatic void mp_flush_buffer(struct tty_struct *tty);\nstatic void mp_send_xchar(struct tty_struct *tty, char ch);\nstatic void mp_throttle(struct tty_struct *tty);\nstatic void mp_unthrottle(struct tty_struct *tty);\nstatic int mp_get_info(struct sb_uart_state *state, struct serial_struct *retinfo);\nstatic int mp_set_info(struct sb_uart_state *state, struct serial_struct *newinfo);\nstatic int mp_get_lsr_info(struct sb_uart_state *state, unsigned int *value);", "static int mp_tiocmget(struct tty_struct *tty);\nstatic int mp_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear);\nstatic int mp_break_ctl(struct tty_struct *tty, int break_state);\nstatic int mp_do_autoconfig(struct sb_uart_state *state);\nstatic int mp_wait_modem_status(struct sb_uart_state *state, unsigned long arg);\nstatic int mp_get_count(struct sb_uart_state *state, struct serial_icounter_struct *icnt);\nstatic int mp_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg);\nstatic void mp_set_termios(struct tty_struct *tty, struct MP_TERMIOS *old_termios);\nstatic void mp_close(struct tty_struct *tty, struct file *filp);\nstatic void mp_wait_until_sent(struct tty_struct *tty, int timeout);\nstatic void mp_hangup(struct tty_struct *tty);\nstatic void mp_update_termios(struct sb_uart_state *state);\nstatic int mp_block_til_ready(struct file *filp, struct sb_uart_state *state);\nstatic struct sb_uart_state *uart_get(struct uart_driver *drv, int line);\nstatic int mp_open(struct tty_struct *tty, struct file *filp);\nstatic const char *mp_type(struct sb_uart_port *port);\nstatic void mp_change_pm(struct sb_uart_state *state, int pm_state);\nstatic inline void mp_report_port(struct uart_driver *drv, struct sb_uart_port *port);\nstatic void mp_configure_port(struct uart_driver *drv, struct sb_uart_state *state, struct sb_uart_port *port);\nstatic void mp_unconfigure_port(struct uart_driver *drv, struct sb_uart_state *state);\nstatic int mp_register_driver(struct uart_driver *drv);\nstatic void mp_unregister_driver(struct uart_driver *drv);\nstatic int mp_add_one_port(struct uart_driver *drv, struct sb_uart_port *port);\nstatic int mp_remove_one_port(struct uart_driver *drv, struct sb_uart_port *port);\nstatic void autoconfig(struct mp_port *mtpt, unsigned int probeflags);\nstatic void autoconfig_irq(struct mp_port *mtpt);\nstatic void multi_stop_tx(struct sb_uart_port *port);\nstatic void multi_start_tx(struct sb_uart_port *port);\nstatic void multi_stop_rx(struct sb_uart_port *port);\nstatic void multi_enable_ms(struct sb_uart_port *port);\nstatic _INLINE_ void receive_chars(struct mp_port *mtpt, int *status );\nstatic _INLINE_ void transmit_chars(struct mp_port *mtpt);\nstatic _INLINE_ void check_modem_status(struct mp_port *mtpt);\nstatic inline void multi_handle_port(struct mp_port *mtpt);\nstatic irqreturn_t multi_interrupt(int irq, void *dev_id);\nstatic void serial_do_unlink(struct irq_info *i, struct mp_port *mtpt);\nstatic int serial_link_irq_chain(struct mp_port *mtpt);\nstatic void serial_unlink_irq_chain(struct mp_port *mtpt);\nstatic void multi_timeout(unsigned long data);\nstatic unsigned int multi_tx_empty(struct sb_uart_port *port);\nstatic unsigned int multi_get_mctrl(struct sb_uart_port *port);\nstatic void multi_set_mctrl(struct sb_uart_port *port, unsigned int mctrl);\nstatic void multi_break_ctl(struct sb_uart_port *port, int break_state);\nstatic int multi_startup(struct sb_uart_port *port);\nstatic void multi_shutdown(struct sb_uart_port *port);\nstatic unsigned int multi_get_divisor(struct sb_uart_port *port, unsigned int baud);\nstatic void multi_set_termios(struct sb_uart_port *port, struct MP_TERMIOS *termios, struct MP_TERMIOS *old);\nstatic void multi_pm(struct sb_uart_port *port, unsigned int state, unsigned int oldstate);\nstatic void multi_release_std_resource(struct mp_port *mtpt);\nstatic void multi_release_port(struct sb_uart_port *port);\nstatic int multi_request_port(struct sb_uart_port *port);\nstatic void multi_config_port(struct sb_uart_port *port, int flags);\nstatic int multi_verify_port(struct sb_uart_port *port, struct serial_struct *ser);\nstatic const char *multi_type(struct sb_uart_port *port);\nstatic void __init multi_init_ports(void);\nstatic void __init multi_register_ports(struct uart_driver *drv);\nstatic int init_mp_dev(struct pci_dev *pcidev, mppcibrd_t brd);", "static int deep[256];\nstatic int deep_count;\nstatic int fcr_arr[256];\nstatic int fcr_count;\nstatic int ttr[256];\nstatic int ttr_count;\nstatic int rtr[256];\nstatic int rtr_count;", "module_param_array(deep,int,&deep_count,0);\nmodule_param_array(fcr_arr,int,&fcr_count,0);\nmodule_param_array(ttr,int,&ttr_count,0);\nmodule_param_array(rtr,int,&rtr_count,0);", "static _INLINE_ unsigned int serial_in(struct mp_port *mtpt, int offset)\n{\n\treturn inb(mtpt->port.iobase + offset);\n}", "static _INLINE_ void serial_out(struct mp_port *mtpt, int offset, int value)\n{\n\toutb(value, mtpt->port.iobase + offset);\n}", "static _INLINE_ unsigned int read_option_register(struct mp_port *mtpt, int offset)\n{\n\treturn inb(mtpt->option_base_addr + offset);\n}", "static int sb1053a_get_interface(struct mp_port *mtpt, int port_num)\n{\n\tunsigned long option_base_addr = mtpt->option_base_addr;\n\tunsigned int interface = 0;", "\tswitch (port_num)\n\t{\n\t\tcase 0:\n\t\tcase 1:\n\t\t\t/* set GPO[1:0] = 00 */\n\t\t\toutb(0x00, option_base_addr + MP_OPTR_GPODR);\n\t\t\tbreak;\n\t\tcase 2:\n\t\tcase 3:\n\t\t\t/* set GPO[1:0] = 01 */\n\t\t\toutb(0x01, option_base_addr + MP_OPTR_GPODR);\n\t\t\tbreak;\n\t\tcase 4:\n\t\tcase 5:\n\t\t\t/* set GPO[1:0] = 10 */\n\t\t\toutb(0x02, option_base_addr + MP_OPTR_GPODR);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}", "\tport_num &= 0x1;", "\t/* get interface */\n\tinterface = inb(option_base_addr + MP_OPTR_IIR0 + port_num);", "\t/* set GPO[1:0] = 11 */\n\toutb(0x03, option_base_addr + MP_OPTR_GPODR);", "\treturn (interface);\n}\n\t\t\nstatic int sb1054_get_register(struct sb_uart_port *port, int page, int reg)\n{\n\tint ret = 0;\n\tunsigned int lcr = 0;\n\tunsigned int mcr = 0;\n\tunsigned int tmp = 0;", "\tif( page <= 0)\n\t{\n\t\tprintk(\" page 0 can not use this fuction\\n\");\n\t\treturn -1;\n\t}", "\tswitch(page)\n\t{\n\t\tcase 1:\n\t\t\tlcr = SB105X_GET_LCR(port);\n\t\t\ttmp = lcr | SB105X_LCR_DLAB;\n\t\t\tSB105X_PUT_LCR(port, tmp);", "\t\t\ttmp = SB105X_GET_LCR(port);", "\t\t\tret = SB105X_GET_REG(port,reg);\n\t\t\tSB105X_PUT_LCR(port,lcr);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tmcr = SB105X_GET_MCR(port);\n\t\t\ttmp = mcr | SB105X_MCR_P2S;\n\t\t\tSB105X_PUT_MCR(port,tmp);", "\t\t\tret = SB105X_GET_REG(port,reg);", "\t\t\tSB105X_PUT_MCR(port,mcr);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tlcr = SB105X_GET_LCR(port);\n\t\t\ttmp = lcr | SB105X_LCR_BF;\n\t\t\tSB105X_PUT_LCR(port,tmp);\n\t\t\tSB105X_PUT_REG(port,SB105X_PSR,SB105X_PSR_P3KEY);", "\t\t\tret = SB105X_GET_REG(port,reg);", "\t\t\tSB105X_PUT_LCR(port,lcr);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tlcr = SB105X_GET_LCR(port);\n\t\t\ttmp = lcr | SB105X_LCR_BF;\n\t\t\tSB105X_PUT_LCR(port,tmp);\n\t\t\tSB105X_PUT_REG(port,SB105X_PSR,SB105X_PSR_P4KEY);", "\t\t\tret = SB105X_GET_REG(port,reg);", "\t\t\tSB105X_PUT_LCR(port,lcr);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tprintk(\" error invalid page number \\n\");\n\t\t\treturn -1;\n\t}", "\treturn ret;\n}", "static int sb1054_set_register(struct sb_uart_port *port, int page, int reg, int value)\n{ \n\tint lcr = 0;\n\tint mcr = 0;\n\tint ret = 0;", "\tif( page <= 0)\n\t{\n\t\tprintk(\" page 0 can not use this fuction\\n\");\n\t\treturn -1;\n\t}\n\tswitch(page)\n\t{\n\t\tcase 1:\n\t\t\tlcr = SB105X_GET_LCR(port);\n\t\t\tSB105X_PUT_LCR(port, lcr | SB105X_LCR_DLAB);", "\t\t\tSB105X_PUT_REG(port,reg,value);", "\t\t\tSB105X_PUT_LCR(port, lcr);\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tmcr = SB105X_GET_MCR(port);\n\t\t\tSB105X_PUT_MCR(port, mcr | SB105X_MCR_P2S);", "\t\t\tSB105X_PUT_REG(port,reg,value);", "\t\t\tSB105X_PUT_MCR(port, mcr);\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tlcr = SB105X_GET_LCR(port);\n\t\t\tSB105X_PUT_LCR(port, lcr | SB105X_LCR_BF);\n\t\t\tSB105X_PUT_PSR(port, SB105X_PSR_P3KEY);", "\t\t\tSB105X_PUT_REG(port,reg,value);", "\t\t\tSB105X_PUT_LCR(port, lcr);\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tlcr = SB105X_GET_LCR(port);\n\t\t\tSB105X_PUT_LCR(port, lcr | SB105X_LCR_BF);\n\t\t\tSB105X_PUT_PSR(port, SB105X_PSR_P4KEY);", "\t\t\tSB105X_PUT_REG(port,reg,value);", "\t\t\tSB105X_PUT_LCR(port, lcr);\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tprintk(\" error invalid page number \\n\");\n\t\t\treturn -1;\n\t}", "\treturn ret;\n}", "static int set_multidrop_mode(struct sb_uart_port *port, unsigned int mode)\n{\n\tint mdr = SB105XA_MDR_NPS;", "\tif (mode & MDMODE_ENABLE)\n\t{\n\t\tmdr |= SB105XA_MDR_MDE;\n\t}", "\tif (1) //(mode & MDMODE_AUTO)\n\t{\n\t\tint efr = 0;\n\t\tmdr |= SB105XA_MDR_AME;\n\t\tefr = sb1054_get_register(port, PAGE_3, SB105X_EFR);\n\t\tefr |= SB105X_EFR_SCD;\n\t\tsb1054_set_register(port, PAGE_3, SB105X_EFR, efr);\n\t}", "\tsb1054_set_register(port, PAGE_1, SB105XA_MDR, mdr);\n\tport->mdmode &= ~0x6;\n\tport->mdmode |= mode;\n\tprintk(\"[%d] multidrop init: %x\\n\", port->line, port->mdmode);", "\treturn 0;\n}", "static int get_multidrop_addr(struct sb_uart_port *port)\n{\n\treturn sb1054_get_register(port, PAGE_3, SB105X_XOFF2);\n}", "static int set_multidrop_addr(struct sb_uart_port *port, unsigned int addr)\n{\n\tsb1054_set_register(port, PAGE_3, SB105X_XOFF2, addr);", "\treturn 0;\n}", "static void SendATCommand(struct mp_port *mtpt)\n{\n\t//\t\t a t\tcr lf\n\tunsigned char ch[] = {0x61,0x74,0x0d,0x0a,0x0};\n\tunsigned char lineControl;\n\tunsigned char i=0;\n\tunsigned char Divisor = 0xc;", "\tlineControl = serial_inp(mtpt,UART_LCR);\n\tserial_outp(mtpt,UART_LCR,(lineControl | UART_LCR_DLAB));\n\tserial_outp(mtpt,UART_DLL,(Divisor & 0xff));\n\tserial_outp(mtpt,UART_DLM,(Divisor & 0xff00)>>8); //baudrate is 4800", "\n\tserial_outp(mtpt,UART_LCR,lineControl);\t\n\tserial_outp(mtpt,UART_LCR,0x03); // N-8-1\n\tserial_outp(mtpt,UART_FCR,7); \n\tserial_outp(mtpt,UART_MCR,0x3);\n\twhile(ch[i]){\n\t\twhile((serial_inp(mtpt,UART_LSR) & 0x60) !=0x60){\n\t\t\t;\n\t\t}\n\t\tserial_outp(mtpt,0,ch[i++]);\n\t}", "\n}// end of SendATCommand()", "static int set_deep_fifo(struct sb_uart_port *port, int status)\n{\n\tint afr_status = 0;\n\tafr_status = sb1054_get_register(port, PAGE_4, SB105X_AFR);", "\tif(status == ENABLE)\n\t{\n\t\tafr_status |= SB105X_AFR_AFEN;\n\t}\n\telse\n\t{\n\t\tafr_status &= ~SB105X_AFR_AFEN;\n\t}\n\t\t\n\tsb1054_set_register(port,PAGE_4,SB105X_AFR,afr_status);\n\tsb1054_set_register(port,PAGE_4,SB105X_TTR,ttr[port->line]); \n\tsb1054_set_register(port,PAGE_4,SB105X_RTR,rtr[port->line]); \n\tafr_status = sb1054_get_register(port, PAGE_4, SB105X_AFR);\n\t\t\n\treturn afr_status;\n}", "static int get_device_type(int arg)\n{\n\tint ret;\n ret = inb(mp_devs[arg].option_reg_addr+MP_OPTR_DIR0);\n ret = (ret & 0xf0) >> 4;\n switch (ret)\n {\n case DIR_UART_16C550:\n return PORT_16C55X;\n case DIR_UART_16C1050:\n return PORT_16C105X;\n case DIR_UART_16C1050A:\n /*\n if (mtpt->port.line < 2)\n {\n return PORT_16C105XA;\n }\n else\n {\n if (mtpt->device->device_id & 0x50)\n {\n return PORT_16C55X;\n }\n else\n {\n return PORT_16C105X;\n }\n }*/\n return PORT_16C105XA;\n default:\n return PORT_UNKNOWN;\n }", "}\nstatic int get_deep_fifo(struct sb_uart_port *port)\n{\n\tint afr_status = 0;\n\tafr_status = sb1054_get_register(port, PAGE_4, SB105X_AFR);\n\treturn afr_status;\n}", "static int set_auto_rts(struct sb_uart_port *port, int status)\n{\n\tint atr_status = 0;", "#if 0\n\tint efr_status = 0;", "\tefr_status = sb1054_get_register(port, PAGE_3, SB105X_EFR);\n\tif(status == ENABLE)\n\t\tefr_status |= SB105X_EFR_ARTS;\n\telse\n\t\tefr_status &= ~SB105X_EFR_ARTS;\n\tsb1054_set_register(port,PAGE_3,SB105X_EFR,efr_status);\n\tefr_status = sb1054_get_register(port, PAGE_3, SB105X_EFR);\n#endif\n\t\t\n//ATR\n\tatr_status = sb1054_get_register(port, PAGE_3, SB105X_ATR);\n\tswitch(status)\n\t{\n\t\tcase RS422PTP:\n\t\t\tatr_status = (SB105X_ATR_TPS) | (SB105X_ATR_A80);\n\t\t\tbreak;\n\t\tcase RS422MD:\n\t\t\tatr_status = (SB105X_ATR_TPS) | (SB105X_ATR_TCMS) | (SB105X_ATR_A80);\n\t\t\tbreak;\n\t\tcase RS485NE:\n\t\t\tatr_status = (SB105X_ATR_RCMS) | (SB105X_ATR_TPS) | (SB105X_ATR_TCMS) | (SB105X_ATR_A80);\n\t\t\tbreak;\n\t\tcase RS485ECHO:\n\t\t\tatr_status = (SB105X_ATR_TPS) | (SB105X_ATR_TCMS) | (SB105X_ATR_A80);\n\t\t\tbreak;\n\t}", "\tsb1054_set_register(port,PAGE_3,SB105X_ATR,atr_status);\n\tatr_status = sb1054_get_register(port, PAGE_3, SB105X_ATR);", "\treturn atr_status;\n}", "static void mp_stop(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port = state->port;\n\tunsigned long flags;", "\tspin_lock_irqsave(&port->lock, flags);\n\tport->ops->stop_tx(port);\n\tspin_unlock_irqrestore(&port->lock, flags);\n}", "static void __mp_start(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port = state->port;", "\tif (!uart_circ_empty(&state->info->xmit) && state->info->xmit.buf &&\n\t\t\t!tty->stopped && !tty->hw_stopped)\n\t\tport->ops->start_tx(port);\n}", "static void mp_start(struct tty_struct *tty)\n{\n\t__mp_start(tty);\n}", "static void mp_tasklet_action(unsigned long data)\n{\n\tstruct sb_uart_state *state = (struct sb_uart_state *)data;\n\tstruct tty_struct *tty;", "\tprintk(\"tasklet is called!\\n\");\n\ttty = state->info->tty;\n\ttty_wakeup(tty);\n}", "static inline void mp_update_mctrl(struct sb_uart_port *port, unsigned int set, unsigned int clear)\n{\n\tunsigned int old;", "\told = port->mctrl;\n\tport->mctrl = (old & ~clear) | set;\n\tif (old != port->mctrl)\n\t\tport->ops->set_mctrl(port, port->mctrl);\n}", "#define uart_set_mctrl(port,set)\tmp_update_mctrl(port,set,0)\n#define uart_clear_mctrl(port,clear)\tmp_update_mctrl(port,0,clear)", "static int mp_startup(struct sb_uart_state *state, int init_hw)\n{\n\tstruct sb_uart_info *info = state->info;\n\tstruct sb_uart_port *port = state->port;\n\tunsigned long page;\n\tint retval = 0;", "\tif (info->flags & UIF_INITIALIZED)\n\t\treturn 0;", "\tif (info->tty)\n\t\tset_bit(TTY_IO_ERROR, &info->tty->flags);", "\tif (port->type == PORT_UNKNOWN)\n\t\treturn 0;", "\tif (!info->xmit.buf) {\n\t\tpage = get_zeroed_page(GFP_KERNEL);\n\t\tif (!page)\n\t\t\treturn -ENOMEM;", "\t\tinfo->xmit.buf = (unsigned char *) page;\n\t\t\t\n\t\tuart_circ_clear(&info->xmit);\n\t}", "\tretval = port->ops->startup(port);\n\tif (retval == 0) {\n\t\tif (init_hw) {\n\t\t\tmp_change_speed(state, NULL);", "\t\t\tif (info->tty->termios.c_cflag & CBAUD)\n\t\t\t\tuart_set_mctrl(port, TIOCM_RTS | TIOCM_DTR);\n\t\t}", "\t\tinfo->flags |= UIF_INITIALIZED;", "\n\t\tclear_bit(TTY_IO_ERROR, &info->tty->flags);\n\t}", "\tif (retval && capable(CAP_SYS_ADMIN))\n\t\tretval = 0;", "\treturn retval;\n}", "static void mp_shutdown(struct sb_uart_state *state)\n{\n\tstruct sb_uart_info *info = state->info;\n\tstruct sb_uart_port *port = state->port;", "\tif (info->tty)\n\t\tset_bit(TTY_IO_ERROR, &info->tty->flags);", "\tif (info->flags & UIF_INITIALIZED) {\n\t\tinfo->flags &= ~UIF_INITIALIZED;", "\t\tif (!info->tty || (info->tty->termios.c_cflag & HUPCL))\n\t\t\tuart_clear_mctrl(port, TIOCM_DTR | TIOCM_RTS);", "\t\twake_up_interruptible(&info->delta_msr_wait);", "\t\tport->ops->shutdown(port);", "\t\tsynchronize_irq(port->irq);\n\t}\n\ttasklet_kill(&info->tlet);", "\tif (info->xmit.buf) {\n\t\tfree_page((unsigned long)info->xmit.buf);\n\t\tinfo->xmit.buf = NULL;\n\t}\n}", "static void mp_change_speed(struct sb_uart_state *state, struct MP_TERMIOS *old_termios)\n{\n\tstruct tty_struct *tty = state->info->tty;\n\tstruct sb_uart_port *port = state->port;", "\tif (!tty || port->type == PORT_UNKNOWN)\n\t\treturn;", "\tif (tty->termios.c_cflag & CRTSCTS)\n\t\tstate->info->flags |= UIF_CTS_FLOW;\n\telse\n\t\tstate->info->flags &= ~UIF_CTS_FLOW;", "\tif (tty->termios.c_cflag & CLOCAL)\n\t\tstate->info->flags &= ~UIF_CHECK_CD;\n\telse\n\t\tstate->info->flags |= UIF_CHECK_CD;", "\tport->ops->set_termios(port, &tty->termios, old_termios);\n}", "static inline int __mp_put_char(struct sb_uart_port *port, struct circ_buf *circ, unsigned char c)\n{\n\tunsigned long flags;\n\tint ret = 0;", "\tif (!circ->buf)\n\t\treturn 0;", "\tspin_lock_irqsave(&port->lock, flags);\n\tif (uart_circ_chars_free(circ) != 0) {\n\t\tcirc->buf[circ->head] = c;\n\t\tcirc->head = (circ->head + 1) & (UART_XMIT_SIZE - 1);\n\t\tret = 1;\n\t}\n\tspin_unlock_irqrestore(&port->lock, flags);\n\treturn ret;\n}", "static int mp_put_char(struct tty_struct *tty, unsigned char ch)\n{\n\tstruct sb_uart_state *state = tty->driver_data;", "\treturn __mp_put_char(state->port, &state->info->xmit, ch);\n}", "static void mp_put_chars(struct tty_struct *tty)\n{\n\tmp_start(tty);\n}", "static int mp_write(struct tty_struct *tty, const unsigned char *buf, int count)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port;\n\tstruct circ_buf *circ;\n\tint c, ret = 0;", "\tif (!state || !state->info) {\n\t\treturn -EL3HLT;\n\t}", "\tport = state->port;\n\tcirc = &state->info->xmit;", "\tif (!circ->buf)\n\t\treturn 0;\n\t\t\n\twhile (1) {\n\t\tc = CIRC_SPACE_TO_END(circ->head, circ->tail, UART_XMIT_SIZE);\n\t\tif (count < c)\n\t\t\tc = count;\n\t\tif (c <= 0)\n\t\t\tbreak;\n\tmemcpy(circ->buf + circ->head, buf, c);", "\t\tcirc->head = (circ->head + c) & (UART_XMIT_SIZE - 1);\n\t\tbuf += c;\n\t\tcount -= c;\n\t\tret += c;\n\t}\n\tmp_start(tty);\n\treturn ret;\n}", "static int mp_write_room(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;", "\treturn uart_circ_chars_free(&state->info->xmit);\n}", "static int mp_chars_in_buffer(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;", "\treturn uart_circ_chars_pending(&state->info->xmit);\n}", "static void mp_flush_buffer(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port;\n\tunsigned long flags;", "\tif (!state || !state->info) {\n\t\treturn;\n\t}", "\tport = state->port;\n\tspin_lock_irqsave(&port->lock, flags);\n\tuart_circ_clear(&state->info->xmit);\n\tspin_unlock_irqrestore(&port->lock, flags);\n\twake_up_interruptible(&tty->write_wait);\n\ttty_wakeup(tty);\n}", "static void mp_send_xchar(struct tty_struct *tty, char ch)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port = state->port;\n\tunsigned long flags;", "\tif (port->ops->send_xchar)\n\t\tport->ops->send_xchar(port, ch);\n\telse {\n\t\tport->x_char = ch;\n\t\tif (ch) {\n\t\t\tspin_lock_irqsave(&port->lock, flags);\n\t\t\tport->ops->start_tx(port);\n\t\t\tspin_unlock_irqrestore(&port->lock, flags);\n\t\t}\n\t}\n}", "static void mp_throttle(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;", "\tif (I_IXOFF(tty))\n\t\tmp_send_xchar(tty, STOP_CHAR(tty));", "\tif (tty->termios.c_cflag & CRTSCTS)\n\t\tuart_clear_mctrl(state->port, TIOCM_RTS);\n}", "static void mp_unthrottle(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port = state->port;", "\tif (I_IXOFF(tty)) {\n\t\tif (port->x_char)\n\t\t\tport->x_char = 0;\n\t\telse\n\t\t\tmp_send_xchar(tty, START_CHAR(tty));\n\t}", "\tif (tty->termios.c_cflag & CRTSCTS)\n\t\tuart_set_mctrl(port, TIOCM_RTS);\n}", "static int mp_get_info(struct sb_uart_state *state, struct serial_struct *retinfo)\n{\n\tstruct sb_uart_port *port = state->port;\n\tstruct serial_struct tmp;", "\tmemset(&tmp, 0, sizeof(tmp));\n\ttmp.type\t = port->type;\n\ttmp.line\t = port->line;\n\ttmp.port\t = port->iobase;\n\tif (HIGH_BITS_OFFSET)\n\t\ttmp.port_high = (long) port->iobase >> HIGH_BITS_OFFSET;\n\ttmp.irq\t\t = port->irq;\n\ttmp.flags\t = port->flags;\n\ttmp.xmit_fifo_size = port->fifosize;\n\ttmp.baud_base\t = port->uartclk / 16;\n\ttmp.close_delay\t = state->close_delay;\n\ttmp.closing_wait = state->closing_wait == USF_CLOSING_WAIT_NONE ?\n\t\tASYNC_CLOSING_WAIT_NONE :\n\t\tstate->closing_wait;\n\ttmp.custom_divisor = port->custom_divisor;\n\ttmp.hub6\t = port->hub6;\n\ttmp.io_type = port->iotype;\n\ttmp.iomem_reg_shift = port->regshift;\n\ttmp.iomem_base = (void *)port->mapbase;", "\tif (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))\n\t\treturn -EFAULT;\n\treturn 0;\n}", "static int mp_set_info(struct sb_uart_state *state, struct serial_struct *newinfo)\n{\n\tstruct serial_struct new_serial;\n\tstruct sb_uart_port *port = state->port;\n\tunsigned long new_port;\n\tunsigned int change_irq, change_port, closing_wait;\n\tunsigned int old_custom_divisor;\n\tunsigned int old_flags, new_flags;\n\tint retval = 0;", "\tif (copy_from_user(&new_serial, newinfo, sizeof(new_serial)))\n\t\treturn -EFAULT;", "\tnew_port = new_serial.port;\n\tif (HIGH_BITS_OFFSET)\n\t\tnew_port += (unsigned long) new_serial.port_high << HIGH_BITS_OFFSET;", "\tnew_serial.irq = irq_canonicalize(new_serial.irq);", "\tclosing_wait = new_serial.closing_wait == ASYNC_CLOSING_WAIT_NONE ?\n\t\tUSF_CLOSING_WAIT_NONE : new_serial.closing_wait;\n\tMP_STATE_LOCK(state);", "\tchange_irq = new_serial.irq != port->irq;\n\tchange_port = new_port != port->iobase ||\n\t\t(unsigned long)new_serial.iomem_base != port->mapbase ||\n\t\tnew_serial.hub6 != port->hub6 ||\n\t\tnew_serial.io_type != port->iotype ||\n\t\tnew_serial.iomem_reg_shift != port->regshift ||\n\t\tnew_serial.type != port->type;\n\told_flags = port->flags;\n\tnew_flags = new_serial.flags;\n\told_custom_divisor = port->custom_divisor;", "\tif (!capable(CAP_SYS_ADMIN)) {\n\t\tretval = -EPERM;\n\t\tif (change_irq || change_port ||\n\t\t\t\t(new_serial.baud_base != port->uartclk / 16) ||\n\t\t\t\t(new_serial.close_delay != state->close_delay) ||\n\t\t\t\t(closing_wait != state->closing_wait) ||\n\t\t\t\t(new_serial.xmit_fifo_size != port->fifosize) ||\n\t\t\t\t(((new_flags ^ old_flags) & ~UPF_USR_MASK) != 0))\n\t\t\tgoto exit;\n\t\tport->flags = ((port->flags & ~UPF_USR_MASK) |\n\t\t\t\t(new_flags & UPF_USR_MASK));\n\t\tport->custom_divisor = new_serial.custom_divisor;\n\t\tgoto check_and_exit;\n\t}", "\tif (port->ops->verify_port)\n\t\tretval = port->ops->verify_port(port, &new_serial);", "\tif ((new_serial.irq >= NR_IRQS) || (new_serial.irq < 0) ||\n\t\t\t(new_serial.baud_base < 9600))\n\t\tretval = -EINVAL;", "\tif (retval)\n\t\tgoto exit;", "\tif (change_port || change_irq) {\n\t\tretval = -EBUSY;", "\t\tif (uart_users(state) > 1)\n\t\t\tgoto exit;", "\t\tmp_shutdown(state);\n\t}", "\tif (change_port) {\n\t\tunsigned long old_iobase, old_mapbase;\n\t\tunsigned int old_type, old_iotype, old_hub6, old_shift;", "\t\told_iobase = port->iobase;\n\t\told_mapbase = port->mapbase;\n\t\told_type = port->type;\n\t\told_hub6 = port->hub6;\n\t\told_iotype = port->iotype;\n\t\told_shift = port->regshift;", "\t\tif (old_type != PORT_UNKNOWN)\n\t\t\tport->ops->release_port(port);", "\t\tport->iobase = new_port;\n\t\tport->type = new_serial.type;\n\t\tport->hub6 = new_serial.hub6;\n\t\tport->iotype = new_serial.io_type;\n\t\tport->regshift = new_serial.iomem_reg_shift;\n\t\tport->mapbase = (unsigned long)new_serial.iomem_base;", "\t\tif (port->type != PORT_UNKNOWN) {\n\t\t\tretval = port->ops->request_port(port);\n\t\t} else {\n\t\t\tretval = 0;\n\t\t}", "\t\tif (retval && old_type != PORT_UNKNOWN) {\n\t\t\tport->iobase = old_iobase;\n\t\t\tport->type = old_type;\n\t\t\tport->hub6 = old_hub6;\n\t\t\tport->iotype = old_iotype;\n\t\t\tport->regshift = old_shift;\n\t\t\tport->mapbase = old_mapbase;\n\t\t\tretval = port->ops->request_port(port);\n\t\t\tif (retval)\n\t\t\t\tport->type = PORT_UNKNOWN;", "\t\t\tretval = -EBUSY;\n\t\t}\n\t}", "\tport->irq = new_serial.irq;\n\tport->uartclk = new_serial.baud_base * 16;\n\tport->flags = (port->flags & ~UPF_CHANGE_MASK) |\n\t\t(new_flags & UPF_CHANGE_MASK);\n\tport->custom_divisor = new_serial.custom_divisor;\n\tstate->close_delay = new_serial.close_delay;\n\tstate->closing_wait = closing_wait;\n\tport->fifosize = new_serial.xmit_fifo_size;\n\tif (state->info->tty)\n\t\tstate->info->tty->low_latency =\n\t\t\t(port->flags & UPF_LOW_LATENCY) ? 1 : 0;", "check_and_exit:\n\tretval = 0;\n\tif (port->type == PORT_UNKNOWN)\n\t\tgoto exit;\n\tif (state->info->flags & UIF_INITIALIZED) {\n\t\tif (((old_flags ^ port->flags) & UPF_SPD_MASK) ||\n\t\t\t\told_custom_divisor != port->custom_divisor) {\n\t\t\tif (port->flags & UPF_SPD_MASK) {\n\t\t\t\tprintk(KERN_NOTICE\n\t\t\t\t\t\t\"%s sets custom speed on ttyMP%d. This \"\n\t\t\t\t\t\t\"is deprecated.\\n\", current->comm,\n\t\t\t\t\t\tport->line);\n\t\t\t}\n\t\t\tmp_change_speed(state, NULL);\n\t\t}\n\t} else\n\t\tretval = mp_startup(state, 1);\nexit:\n\tMP_STATE_UNLOCK(state);\n\treturn retval;\n}", "\nstatic int mp_get_lsr_info(struct sb_uart_state *state, unsigned int *value)\n{\n\tstruct sb_uart_port *port = state->port;\n\tunsigned int result;", "\tresult = port->ops->tx_empty(port);", "\tif (port->x_char ||\n\t\t\t((uart_circ_chars_pending(&state->info->xmit) > 0) &&\n\t\t\t\t!state->info->tty->stopped && !state->info->tty->hw_stopped))\n\t\tresult &= ~TIOCSER_TEMT;", "\treturn put_user(result, value);\n}", "static int mp_tiocmget(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port = state->port;\n\tint result = -EIO;", "\tMP_STATE_LOCK(state);\n\tif (!(tty->flags & (1 << TTY_IO_ERROR))) {\n\t\tresult = port->mctrl;\n\t\tspin_lock_irq(&port->lock);\n\t\tresult |= port->ops->get_mctrl(port);\n\t\tspin_unlock_irq(&port->lock);\n\t}\n\tMP_STATE_UNLOCK(state);\n\treturn result;\n}", "static int mp_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port = state->port;\n\tint ret = -EIO;", "\n\tMP_STATE_LOCK(state);\n\tif (!(tty->flags & (1 << TTY_IO_ERROR))) {\n\t\tmp_update_mctrl(port, set, clear);\n\t\tret = 0;\n\t}\n\tMP_STATE_UNLOCK(state);", "\treturn ret;\n}", "static int mp_break_ctl(struct tty_struct *tty, int break_state)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port = state->port;", "\tMP_STATE_LOCK(state);", "\tif (port->type != PORT_UNKNOWN)\n\t\tport->ops->break_ctl(port, break_state);", "\tMP_STATE_UNLOCK(state);\n\treturn 0;\n}", "static int mp_do_autoconfig(struct sb_uart_state *state)\n{\n\tstruct sb_uart_port *port = state->port;\n\tint flags, ret;", "\tif (!capable(CAP_SYS_ADMIN))\n\t\treturn -EPERM;", "\tif (mutex_lock_interruptible(&state->mutex))\n\t\treturn -ERESTARTSYS;\n\tret = -EBUSY;\n\tif (uart_users(state) == 1) {\n\t\tmp_shutdown(state);", "\t\tif (port->type != PORT_UNKNOWN)\n\t\t\tport->ops->release_port(port);", "\t\tflags = UART_CONFIG_TYPE;\n\t\tif (port->flags & UPF_AUTO_IRQ)\n\t\t\tflags |= UART_CONFIG_IRQ;", "\t\tport->ops->config_port(port, flags);", "\t\tret = mp_startup(state, 1);\n\t}\n\tMP_STATE_UNLOCK(state);\n\treturn ret;\n}", "static int mp_wait_modem_status(struct sb_uart_state *state, unsigned long arg)\n{\n\tstruct sb_uart_port *port = state->port;\n\tDECLARE_WAITQUEUE(wait, current);\n\tstruct sb_uart_icount cprev, cnow;\n\tint ret;", "\tspin_lock_irq(&port->lock);\n\tmemcpy(&cprev, &port->icount, sizeof(struct sb_uart_icount));", "\tport->ops->enable_ms(port);\n\tspin_unlock_irq(&port->lock);", "\tadd_wait_queue(&state->info->delta_msr_wait, &wait);\n\tfor (;;) {\n\t\tspin_lock_irq(&port->lock);\n\t\tmemcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount));\n\t\tspin_unlock_irq(&port->lock);", "\t\tset_current_state(TASK_INTERRUPTIBLE);", "\t\tif (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||\n\t\t\t\t((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||\n\t\t\t\t((arg & TIOCM_CD) && (cnow.dcd != cprev.dcd)) ||\n\t\t\t\t((arg & TIOCM_CTS) && (cnow.cts != cprev.cts))) {\n\t\t\tret = 0;\n\t\t\tbreak;\n\t\t}", "\t\tschedule();", "\t\tif (signal_pending(current)) {\n\t\t\tret = -ERESTARTSYS;\n\t\t\tbreak;\n\t\t}", "\t\tcprev = cnow;\n\t}", "\tcurrent->state = TASK_RUNNING;\n\tremove_wait_queue(&state->info->delta_msr_wait, &wait);", "\treturn ret;\n}", "static int mp_get_count(struct sb_uart_state *state, struct serial_icounter_struct *icnt)\n{", "\tstruct serial_icounter_struct icount;", "\tstruct sb_uart_icount cnow;\n\tstruct sb_uart_port *port = state->port;", "\tspin_lock_irq(&port->lock);\n\tmemcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount));\n\tspin_unlock_irq(&port->lock);", "\ticount.cts = cnow.cts;\n\ticount.dsr = cnow.dsr;\n\ticount.rng = cnow.rng;\n\ticount.dcd = cnow.dcd;\n\ticount.rx = cnow.rx;\n\ticount.tx = cnow.tx;\n\ticount.frame = cnow.frame;\n\ticount.overrun = cnow.overrun;\n\ticount.parity = cnow.parity;\n\ticount.brk = cnow.brk;\n\ticount.buf_overrun = cnow.buf_overrun;", "\treturn copy_to_user(icnt, &icount, sizeof(icount)) ? -EFAULT : 0;\n}", "static int mp_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct mp_port *info = (struct mp_port *)state->port;\n\tint ret = -ENOIOCTLCMD;", "\n\tswitch (cmd) {\n\t\tcase TIOCSMULTIDROP:\n\t\t\t/* set multi-drop mode enable or disable, and default operation mode is H/W mode */\n\t\t\tif (info->port.type == PORT_16C105XA)\n\t\t\t{\n\t\t\t\t//arg &= ~0x6;\n\t\t\t\t//state->port->mdmode = 0;\n\t\t\t\treturn set_multidrop_mode((struct sb_uart_port *)info, (unsigned int)arg);\n\t\t\t}\n\t\t\tret = -ENOTSUPP;\n\t\t\tbreak;\n\t\tcase GETDEEPFIFO:\n\t\t\tret = get_deep_fifo(state->port);\n\t\t\treturn ret;\n\t\tcase SETDEEPFIFO:\n\t\t\tret = set_deep_fifo(state->port,arg);\n\t\t\tdeep[state->port->line] = arg;\n\t\t\treturn ret;\n\t\tcase SETTTR:\n\t\t\tif (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){\n\t\t\t\tret = sb1054_set_register(state->port,PAGE_4,SB105X_TTR,arg);\n\t\t\t\tttr[state->port->line] = arg;\n\t\t\t}\n\t\t\treturn ret;\n\t\tcase SETRTR:\n\t\t\tif (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){\n\t\t\t\tret = sb1054_set_register(state->port,PAGE_4,SB105X_RTR,arg);\n\t\t\t\trtr[state->port->line] = arg;\n\t\t\t}\n\t\t\treturn ret;\n\t\tcase GETTTR:\n\t\t\tif (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){\n\t\t\t\tret = sb1054_get_register(state->port,PAGE_4,SB105X_TTR);\n\t\t\t}\n\t\t\treturn ret;\n\t\tcase GETRTR:\n\t\t\tif (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){\n\t\t\t\tret = sb1054_get_register(state->port,PAGE_4,SB105X_RTR);\n\t\t\t}\n\t\t\treturn ret;", "\t\tcase SETFCR:\n\t\t\tif (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){\n\t\t\t\tret = sb1054_set_register(state->port,PAGE_1,SB105X_FCR,arg);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tserial_out(info,2,arg);\n\t\t\t}", "\t\t\treturn ret;\n\t\tcase TIOCSMDADDR:\n\t\t\t/* set multi-drop address */\n\t\t\tif (info->port.type == PORT_16C105XA)\n\t\t\t{\n\t\t\t\tstate->port->mdmode |= MDMODE_ADDR;\n\t\t\t\treturn set_multidrop_addr((struct sb_uart_port *)info, (unsigned int)arg);\n\t\t\t}\n\t\t\tret = -ENOTSUPP;\n\t\t\tbreak;", "\t\tcase TIOCGMDADDR:\n\t\t\t/* set multi-drop address */\n\t\t\tif ((info->port.type == PORT_16C105XA) && (state->port->mdmode & MDMODE_ADDR))\n\t\t\t{\n\t\t\t\treturn get_multidrop_addr((struct sb_uart_port *)info);\n\t\t\t}\n\t\t\tret = -ENOTSUPP;\n\t\t\tbreak;", "\t\tcase TIOCSENDADDR:\n\t\t\t/* send address in multi-drop mode */\n\t\t\tif ((info->port.type == PORT_16C105XA) \n\t\t\t\t\t&& (state->port->mdmode & (MDMODE_ENABLE)))\n\t\t\t{\n\t\t\t\tif (mp_chars_in_buffer(tty) > 0)\n\t\t\t\t{\n\t\t\t\t\ttty_wait_until_sent(tty, 0);\n\t\t\t\t}\n\t\t\t\t//while ((serial_in(info, UART_LSR) & 0x60) != 0x60);\n\t\t\t\t//while (sb1054_get_register(state->port, PAGE_2, SB105X_TFCR) != 0);\n\t\t\t\twhile ((serial_in(info, UART_LSR) & 0x60) != 0x60);\n\t\t\t\tserial_out(info, UART_SCR, (int)arg);\n\t\t\t}\n\t\t\tbreak;", "\t\tcase TIOCGSERIAL:\n\t\t\tret = mp_get_info(state, (struct serial_struct *)arg);\n\t\t\tbreak;", "\t\tcase TIOCSSERIAL:\n\t\t\tret = mp_set_info(state, (struct serial_struct *)arg);\n\t\t\tbreak;", "\t\tcase TIOCSERCONFIG:\n\t\t\tret = mp_do_autoconfig(state);\n\t\t\tbreak;", "\t\tcase TIOCSERGWILD: /* obsolete */\n\t\tcase TIOCSERSWILD: /* obsolete */\n\t\t\tret = 0;\n\t\t\tbreak;\n\t\t\t/* for Multiport */\n\t\tcase TIOCGNUMOFPORT: /* Get number of ports */\n\t\t\treturn NR_PORTS;\n\t\tcase TIOCGGETDEVID:\n\t\t\treturn mp_devs[arg].device_id;\n\t\tcase TIOCGGETREV:\n\t\t\treturn mp_devs[arg].revision;\n\t\tcase TIOCGGETNRPORTS:\n\t\t\treturn mp_devs[arg].nr_ports;\n\t\tcase TIOCGGETBDNO:\n\t\t\treturn NR_BOARD;\n\t\tcase TIOCGGETINTERFACE:\n\t\t\tif (mp_devs[arg].revision == 0xc0)\n\t\t\t{\n\t\t\t\t/* for SB16C1053APCI */\n\t\t\t\treturn (sb1053a_get_interface(info, info->port.line));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn (inb(mp_devs[arg].option_reg_addr+MP_OPTR_IIR0+(state->port->line/8)));\n\t\t\t}\n\t\tcase TIOCGGETPORTTYPE:\n\t\t\tret = get_device_type(arg);;\n\t\t\treturn ret;\n\t\tcase TIOCSMULTIECHO: /* set to multi-drop mode(RS422) or echo mode(RS485)*/\n\t\t\toutb( ( inb(info->interface_config_addr) & ~0x03 ) | 0x01 , \n\t\t\t\t\tinfo->interface_config_addr);\n\t\t\treturn 0;\n\t\tcase TIOCSPTPNOECHO: /* set to multi-drop mode(RS422) or echo mode(RS485) */\n\t\t\toutb( ( inb(info->interface_config_addr) & ~0x03 ) , \n\t\t\t\t\tinfo->interface_config_addr);\n\t\t\treturn 0;\n\t}", "\tif (ret != -ENOIOCTLCMD)\n\t\tgoto out;", "\tif (tty->flags & (1 << TTY_IO_ERROR)) {\n\t\tret = -EIO;\n\t\tgoto out;\n\t}", "\tswitch (cmd) {\n\t\tcase TIOCMIWAIT:\n\t\t\tret = mp_wait_modem_status(state, arg);\n\t\t\tbreak;", "\t\tcase TIOCGICOUNT:\n\t\t\tret = mp_get_count(state, (struct serial_icounter_struct *)arg);\n\t\t\tbreak;\n\t}", "\tif (ret != -ENOIOCTLCMD)\n\t\tgoto out;", "\tMP_STATE_LOCK(state);\n\tswitch (cmd) {\n\t\tcase TIOCSERGETLSR: /* Get line status register */\n\t\t\tret = mp_get_lsr_info(state, (unsigned int *)arg);\n\t\t\tbreak;", "\t\tdefault: {\n\t\t\t\t\tstruct sb_uart_port *port = state->port;\n\t\t\t\t\tif (port->ops->ioctl)\n\t\t\t\t\t\tret = port->ops->ioctl(port, cmd, arg);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t}", "\tMP_STATE_UNLOCK(state);\nout:\n\treturn ret;\n}", "static void mp_set_termios(struct tty_struct *tty, struct MP_TERMIOS *old_termios)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tunsigned long flags;\n\tunsigned int cflag = tty->termios.c_cflag;", "#define RELEVANT_IFLAG(iflag)\t((iflag) & (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK))", "\tif ((cflag ^ old_termios->c_cflag) == 0 &&\n\t\t\tRELEVANT_IFLAG(tty->termios.c_iflag ^ old_termios->c_iflag) == 0)\n\t\treturn;", "\tmp_change_speed(state, old_termios);", "\tif ((old_termios->c_cflag & CBAUD) && !(cflag & CBAUD))\n\t\tuart_clear_mctrl(state->port, TIOCM_RTS | TIOCM_DTR);", "\tif (!(old_termios->c_cflag & CBAUD) && (cflag & CBAUD)) {\n\t\tunsigned int mask = TIOCM_DTR;\n\t\tif (!(cflag & CRTSCTS) ||\n\t\t\t\t!test_bit(TTY_THROTTLED, &tty->flags))\n\t\t\tmask |= TIOCM_RTS;\n\t\tuart_set_mctrl(state->port, mask);\n\t}", "\tif ((old_termios->c_cflag & CRTSCTS) && !(cflag & CRTSCTS)) {\n\t\tspin_lock_irqsave(&state->port->lock, flags);\n\t\ttty->hw_stopped = 0;\n\t\t__mp_start(tty);\n\t\tspin_unlock_irqrestore(&state->port->lock, flags);\n\t}", "\tif (!(old_termios->c_cflag & CRTSCTS) && (cflag & CRTSCTS)) {\n\t\tspin_lock_irqsave(&state->port->lock, flags);\n\t\tif (!(state->port->ops->get_mctrl(state->port) & TIOCM_CTS)) {\n\t\t\ttty->hw_stopped = 1;\n\t\t\tstate->port->ops->stop_tx(state->port);\n\t\t}\n\t\tspin_unlock_irqrestore(&state->port->lock, flags);\n\t}\n}", "static void mp_close(struct tty_struct *tty, struct file *filp)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port;", "\tprintk(\"mp_close!\\n\");\n\tif (!state || !state->port)\n\t\treturn;", "\tport = state->port;", "\tprintk(\"close1 %d\\n\", __LINE__);\n\tMP_STATE_LOCK(state);", "\tprintk(\"close2 %d\\n\", __LINE__);\n\tif (tty_hung_up_p(filp))\n\t\tgoto done;", "\tprintk(\"close3 %d\\n\", __LINE__);\n\tif ((tty->count == 1) && (state->count != 1)) {\n\t\tprintk(\"mp_close: bad serial port count; tty->count is 1, \"\n\t\t\t\t\"state->count is %d\\n\", state->count);\n\t\tstate->count = 1;\n\t}\n\tprintk(\"close4 %d\\n\", __LINE__);\n\tif (--state->count < 0) {\n\t\tprintk(\"rs_close: bad serial port count for ttyMP%d: %d\\n\",\n\t\t\t\tport->line, state->count);\n\t\tstate->count = 0;\n\t}\n\tif (state->count)\n\t\tgoto done;", "\ttty->closing = 1;", "\tprintk(\"close5 %d\\n\", __LINE__);\n\tif (state->closing_wait != USF_CLOSING_WAIT_NONE)\n\t\ttty_wait_until_sent(tty, state->closing_wait);", "\tprintk(\"close6 %d\\n\", __LINE__);\n\tif (state->info->flags & UIF_INITIALIZED) {\n\t\tunsigned long flags;\n\t\tspin_lock_irqsave(&port->lock, flags);\n\t\tport->ops->stop_rx(port);\n\t\tspin_unlock_irqrestore(&port->lock, flags);\n\t\tmp_wait_until_sent(tty, port->timeout);\n\t}\n\tprintk(\"close7 %d\\n\", __LINE__);", "\tmp_shutdown(state);\n\tprintk(\"close8 %d\\n\", __LINE__);\n\tmp_flush_buffer(tty);\n\ttty_ldisc_flush(tty);\n\ttty->closing = 0;\n\tstate->info->tty = NULL;\n\tif (state->info->blocked_open) \n\t{\n\t\tif (state->close_delay)\n\t\t{\n\t\t\tset_current_state(TASK_INTERRUPTIBLE);\n\t\t\tschedule_timeout(state->close_delay);\n\t\t}\n\t}\n\telse\n\t{\n\t\tmp_change_pm(state, 3);\n\t}\n\tprintk(\"close8 %d\\n\", __LINE__);", "\tstate->info->flags &= ~UIF_NORMAL_ACTIVE;\n\twake_up_interruptible(&state->info->open_wait);", "done:\n\tprintk(\"close done\\n\");\n\tMP_STATE_UNLOCK(state);\n\tmodule_put(THIS_MODULE);\n}", "static void mp_wait_until_sent(struct tty_struct *tty, int timeout)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port = state->port;\n\tunsigned long char_time, expire;", "\tif (port->type == PORT_UNKNOWN || port->fifosize == 0)\n\t\treturn;", "\tchar_time = (port->timeout - HZ/50) / port->fifosize;\n\tchar_time = char_time / 5;\n\tif (char_time == 0)\n\t\tchar_time = 1;\n\tif (timeout && timeout < char_time)\n\t\tchar_time = timeout;", "\tif (timeout == 0 || timeout > 2 * port->timeout)\n\t\ttimeout = 2 * port->timeout;", "\texpire = jiffies + timeout;", "\twhile (!port->ops->tx_empty(port)) {\n\t\tset_current_state(TASK_INTERRUPTIBLE);\n\t\tschedule_timeout(char_time);\n\t\tif (signal_pending(current))\n\t\t\tbreak;\n\t\tif (time_after(jiffies, expire))\n\t\t\tbreak;\n\t}\n\tset_current_state(TASK_RUNNING); /* might not be needed */\n}", "static void mp_hangup(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;", "\tMP_STATE_LOCK(state);\n\tif (state->info && state->info->flags & UIF_NORMAL_ACTIVE) {\n\t\tmp_flush_buffer(tty);\n\t\tmp_shutdown(state);\n\t\tstate->count = 0;\n\t\tstate->info->flags &= ~UIF_NORMAL_ACTIVE;\n\t\tstate->info->tty = NULL;\n\t\twake_up_interruptible(&state->info->open_wait);\n\t\twake_up_interruptible(&state->info->delta_msr_wait);\n\t}\n\tMP_STATE_UNLOCK(state);\n}", "static void mp_update_termios(struct sb_uart_state *state)\n{\n\tstruct tty_struct *tty = state->info->tty;\n\tstruct sb_uart_port *port = state->port;", "\tif (!(tty->flags & (1 << TTY_IO_ERROR))) {\n\t\tmp_change_speed(state, NULL);", "\t\tif (tty->termios.c_cflag & CBAUD)\n\t\t\tuart_set_mctrl(port, TIOCM_DTR | TIOCM_RTS);\n\t}\n}", "static int mp_block_til_ready(struct file *filp, struct sb_uart_state *state)\n{\n\tDECLARE_WAITQUEUE(wait, current);\n\tstruct sb_uart_info *info = state->info;\n\tstruct sb_uart_port *port = state->port;\n\tunsigned int mctrl;", "\tinfo->blocked_open++;\n\tstate->count--;", "\tadd_wait_queue(&info->open_wait, &wait);\n\twhile (1) {\n\t\tset_current_state(TASK_INTERRUPTIBLE);", "\t\tif (tty_hung_up_p(filp) || info->tty == NULL)\n\t\t\tbreak;", "\t\tif (!(info->flags & UIF_INITIALIZED))\n\t\t\tbreak;", "\t\tif ((filp->f_flags & O_NONBLOCK) ||\n\t\t\t\t(info->tty->termios.c_cflag & CLOCAL) ||\n\t\t\t\t(info->tty->flags & (1 << TTY_IO_ERROR))) {\n\t\t\tbreak;\n\t\t}", "\t\tif (info->tty->termios.c_cflag & CBAUD)\n\t\t\tuart_set_mctrl(port, TIOCM_DTR);", "\t\tspin_lock_irq(&port->lock);\n\t\tport->ops->enable_ms(port);\n\t\tmctrl = port->ops->get_mctrl(port);\n\t\tspin_unlock_irq(&port->lock);\n\t\tif (mctrl & TIOCM_CAR)\n\t\t\tbreak;", "\t\tMP_STATE_UNLOCK(state);\n\t\tschedule();\n\t\tMP_STATE_LOCK(state);", "\t\tif (signal_pending(current))\n\t\t\tbreak;\n\t}\n\tset_current_state(TASK_RUNNING);\n\tremove_wait_queue(&info->open_wait, &wait);", "\tstate->count++;\n\tinfo->blocked_open--;", "\tif (signal_pending(current))\n\t\treturn -ERESTARTSYS;", "\tif (!info->tty || tty_hung_up_p(filp))\n\t\treturn -EAGAIN;", "\treturn 0;\n}", "static struct sb_uart_state *uart_get(struct uart_driver *drv, int line)\n{\n\tstruct sb_uart_state *state;", "\tMP_MUTEX_LOCK(mp_mutex);\n\tstate = drv->state + line;\n\tif (mutex_lock_interruptible(&state->mutex)) {\n\t\tstate = ERR_PTR(-ERESTARTSYS);\n\t\tgoto out;\n\t}\n\tstate->count++;\n\tif (!state->port) {\n\t\tstate->count--;\n\t\tMP_STATE_UNLOCK(state);\n\t\tstate = ERR_PTR(-ENXIO);\n\t\tgoto out;\n\t}", "\tif (!state->info) {\n\t\tstate->info = kmalloc(sizeof(struct sb_uart_info), GFP_KERNEL);\n\t\tif (state->info) {\n\t\t\tmemset(state->info, 0, sizeof(struct sb_uart_info));\n\t\t\tinit_waitqueue_head(&state->info->open_wait);\n\t\t\tinit_waitqueue_head(&state->info->delta_msr_wait);", "\t\t\tstate->port->info = state->info;", "\t\t\ttasklet_init(&state->info->tlet, mp_tasklet_action,\n\t\t\t\t\t(unsigned long)state);\n\t\t} else {\n\t\t\tstate->count--;\n\t\t\tMP_STATE_UNLOCK(state);\n\t\t\tstate = ERR_PTR(-ENOMEM);\n\t\t}\n\t}", "out:\n\tMP_MUTEX_UNLOCK(mp_mutex);\n\treturn state;\n}", "static int mp_open(struct tty_struct *tty, struct file *filp)\n{\n\tstruct uart_driver *drv = (struct uart_driver *)tty->driver->driver_state;\n\tstruct sb_uart_state *state;\n\tint retval;\n\tint line = tty->index;\n\tstruct mp_port *mtpt;", "\tretval = -ENODEV;\n\tif (line >= tty->driver->num)\n\t\tgoto fail;", "\tstate = uart_get(drv, line);", "\tif (IS_ERR(state)) {\n\t\tretval = PTR_ERR(state);\n\t\tgoto fail;\n\t}", "\tmtpt = (struct mp_port *)state->port;", "\ttty->driver_data = state;\n\ttty->low_latency = (state->port->flags & UPF_LOW_LATENCY) ? 1 : 0;\n\ttty->alt_speed = 0;\n\tstate->info->tty = tty;", "\tif (tty_hung_up_p(filp)) {\n\t\tretval = -EAGAIN;\n\t\tstate->count--;\n\t\tMP_STATE_UNLOCK(state);\n\t\tgoto fail;\n\t}", "\tif (state->count == 1)\n\t\tmp_change_pm(state, 0);", "\tretval = mp_startup(state, 0);", "\tif (retval == 0)\n\t\tretval = mp_block_til_ready(filp, state);\n\tMP_STATE_UNLOCK(state);", "\tif (retval == 0 && !(state->info->flags & UIF_NORMAL_ACTIVE)) {\n\t\tstate->info->flags |= UIF_NORMAL_ACTIVE;", "\t\tmp_update_termios(state);\n\t}", "\tuart_clear_mctrl(state->port, TIOCM_RTS);\n\ttry_module_get(THIS_MODULE);\nfail:\n\treturn retval;\n}", "\nstatic const char *mp_type(struct sb_uart_port *port)\n{\n\tconst char *str = NULL;", "\tif (port->ops->type)\n\t\tstr = port->ops->type(port);", "\tif (!str)\n\t\tstr = \"unknown\";", "\treturn str;\n}", "static void mp_change_pm(struct sb_uart_state *state, int pm_state)\n{\n\tstruct sb_uart_port *port = state->port;\n\tif (port->ops->pm)\n\t\tport->ops->pm(port, pm_state, state->pm_state);\n\tstate->pm_state = pm_state;\n}", "static inline void mp_report_port(struct uart_driver *drv, struct sb_uart_port *port)\n{\n\tchar address[64];", "\tswitch (port->iotype) {\n\t\tcase UPIO_PORT:\n\t\t\tsnprintf(address, sizeof(address),\"I/O 0x%x\", port->iobase);\n\t\t\tbreak;\n\t\tcase UPIO_HUB6:\n\t\t\tsnprintf(address, sizeof(address),\"I/O 0x%x offset 0x%x\", port->iobase, port->hub6);\n\t\t\tbreak;\n\t\tcase UPIO_MEM:\n\t\t\tsnprintf(address, sizeof(address),\"MMIO 0x%lx\", port->mapbase);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tsnprintf(address, sizeof(address),\"*unknown*\" );\n\t\t\tstrlcpy(address, \"*unknown*\", sizeof(address));\n\t\t\tbreak;\n\t}", "\tprintk( \"%s%d at %s (irq = %d) is a %s\\n\",\n\t\t\tdrv->dev_name, port->line, address, port->irq, mp_type(port));", "}", "static void mp_configure_port(struct uart_driver *drv, struct sb_uart_state *state, struct sb_uart_port *port)\n{\n\tunsigned int flags;", "\n\tif (!port->iobase && !port->mapbase && !port->membase)\n\t{\n\t\tDPRINTK(\"%s error \\n\",__FUNCTION__);\n\t\treturn;\n\t}\n\tflags = UART_CONFIG_TYPE;\n\tif (port->flags & UPF_AUTO_IRQ)\n\t\tflags |= UART_CONFIG_IRQ;\n\tif (port->flags & UPF_BOOT_AUTOCONF) {\n\t\tport->type = PORT_UNKNOWN;\n\t\tport->ops->config_port(port, flags);\n\t}", "\tif (port->type != PORT_UNKNOWN) {\n\t\tunsigned long flags;", "\t\tmp_report_port(drv, port);", "\t\tspin_lock_irqsave(&port->lock, flags);\n\t\tport->ops->set_mctrl(port, 0);\n\t\tspin_unlock_irqrestore(&port->lock, flags);", "\t\tmp_change_pm(state, 3);\n\t}\n}", "static void mp_unconfigure_port(struct uart_driver *drv, struct sb_uart_state *state)\n{\n\tstruct sb_uart_port *port = state->port;\n\tstruct sb_uart_info *info = state->info;", "\tif (info && info->tty)\n\t\ttty_hangup(info->tty);", "\tMP_STATE_LOCK(state);", "\tstate->info = NULL;", "\tif (port->type != PORT_UNKNOWN)\n\t\tport->ops->release_port(port);", "\tport->type = PORT_UNKNOWN;", "\tif (info) {\n\t\ttasklet_kill(&info->tlet);\n\t\tkfree(info);\n\t}", "\tMP_STATE_UNLOCK(state);\n}\nstatic struct tty_operations mp_ops = {\n\t.open\t\t= mp_open,\n\t.close\t\t= mp_close,\n\t.write\t\t= mp_write,\n\t.put_char\t= mp_put_char,\n\t.flush_chars\t= mp_put_chars,\n\t.write_room\t= mp_write_room,\n\t.chars_in_buffer= mp_chars_in_buffer,\n\t.flush_buffer\t= mp_flush_buffer,\n\t.ioctl\t\t= mp_ioctl,\n\t.throttle\t= mp_throttle,\n\t.unthrottle\t= mp_unthrottle,\n\t.send_xchar\t= mp_send_xchar,\n\t.set_termios\t= mp_set_termios,\n\t.stop\t\t= mp_stop,\n\t.start\t\t= mp_start,\n\t.hangup\t\t= mp_hangup,\n\t.break_ctl\t= mp_break_ctl,\n\t.wait_until_sent= mp_wait_until_sent,\n#ifdef CONFIG_PROC_FS\n\t.proc_fops\t= NULL,\n#endif\n\t.tiocmget\t= mp_tiocmget,\n\t.tiocmset\t= mp_tiocmset,\n};", "static int mp_register_driver(struct uart_driver *drv)\n{\n\tstruct tty_driver *normal = NULL;\n\tint i, retval;", "\tdrv->state = kmalloc(sizeof(struct sb_uart_state) * drv->nr, GFP_KERNEL);\n\tretval = -ENOMEM;\n\tif (!drv->state)\n\t{\n\t\tprintk(\"SB PCI Error: Kernel memory allocation error!\\n\");\n\t\tgoto out;\n\t}\n\tmemset(drv->state, 0, sizeof(struct sb_uart_state) * drv->nr);", "\tnormal = alloc_tty_driver(drv->nr);\n\tif (!normal)\n\t{\n\t\tprintk(\"SB PCI Error: tty allocation error!\\n\");\n\t\tgoto out;\n\t}", "\tdrv->tty_driver = normal;", "\tnormal->owner = drv->owner;\n\tnormal->magic\t\t= TTY_DRIVER_MAGIC;\n\tnormal->driver_name = drv->driver_name;\n\tnormal->name\t\t= drv->dev_name;\n\tnormal->major\t\t= drv->major;\n\tnormal->minor_start\t= drv->minor;", "\tnormal->num\t\t= MAX_MP_PORT ; ", "\tnormal->type\t\t= TTY_DRIVER_TYPE_SERIAL;\n\tnormal->subtype\t\t= SERIAL_TYPE_NORMAL;\n\tnormal->init_termios\t= tty_std_termios;\n\tnormal->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL;\n\tnormal->flags\t\t= TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;\n\tnormal->driver_state = drv;", "\ttty_set_operations(normal, &mp_ops);", "for (i = 0; i < drv->nr; i++) {\n\tstruct sb_uart_state *state = drv->state + i;", "\tstate->close_delay = 500; \n\tstate->closing_wait = 30000; ", "\tmutex_init(&state->mutex);\n\t}", "\tretval = tty_register_driver(normal);\nout:\n\tif (retval < 0) {\n\t\tprintk(\"Register tty driver Fail!\\n\");\n\t\tput_tty_driver(normal);\n\t\tkfree(drv->state);\n\t}", "\treturn retval;\n}", "void mp_unregister_driver(struct uart_driver *drv)\n{\n struct tty_driver *normal = NULL;", " normal = drv->tty_driver;", " if (!normal)\n {\n return;\n }", " tty_unregister_driver(normal);\n put_tty_driver(normal);\n drv->tty_driver = NULL;", "\n if (drv->state)\n {\n kfree(drv->state);\n }", "}", "static int mp_add_one_port(struct uart_driver *drv, struct sb_uart_port *port)\n{\n\tstruct sb_uart_state *state;\n\tint ret = 0;", "\n\tif (port->line >= drv->nr)\n\t\treturn -EINVAL;", "\tstate = drv->state + port->line;", "\tMP_MUTEX_LOCK(mp_mutex);\n\tif (state->port) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}", "\tstate->port = port;", "\tspin_lock_init(&port->lock);\n\tport->cons = drv->cons;\n\tport->info = state->info;", "\tmp_configure_port(drv, state, port);", "\ttty_register_device(drv->tty_driver, port->line, port->dev);", "out:\n\tMP_MUTEX_UNLOCK(mp_mutex);", "\n\treturn ret;\n}", "static int mp_remove_one_port(struct uart_driver *drv, struct sb_uart_port *port)\n{\n\tstruct sb_uart_state *state = drv->state + port->line;", "\tif (state->port != port)\n\t\tprintk(KERN_ALERT \"Removing wrong port: %p != %p\\n\",\n\t\t\t\tstate->port, port);", "\tMP_MUTEX_LOCK(mp_mutex);", "\ttty_unregister_device(drv->tty_driver, port->line);", "\tmp_unconfigure_port(drv, state);\n\tstate->port = NULL;\n\tMP_MUTEX_UNLOCK(mp_mutex);", "\treturn 0;\n}", "static void autoconfig(struct mp_port *mtpt, unsigned int probeflags)\n{\n\tunsigned char status1, scratch, scratch2, scratch3;\n\tunsigned char save_lcr, save_mcr;\n\tunsigned long flags;", "\tunsigned char u_type;\n\tunsigned char b_ret = 0;", "\tif (!mtpt->port.iobase && !mtpt->port.mapbase && !mtpt->port.membase)\n\t\treturn;", "\tDEBUG_AUTOCONF(\"ttyMP%d: autoconf (0x%04x, 0x%p): \",\n\t\t\tmtpt->port.line, mtpt->port.iobase, mtpt->port.membase);", "\tspin_lock_irqsave(&mtpt->port.lock, flags);", "\tif (!(mtpt->port.flags & UPF_BUGGY_UART)) {\n\t\tscratch = serial_inp(mtpt, UART_IER);\n\t\tserial_outp(mtpt, UART_IER, 0);\n#ifdef __i386__\n\t\toutb(0xff, 0x080);\n#endif\n\t\tscratch2 = serial_inp(mtpt, UART_IER) & 0x0f;\n\t\tserial_outp(mtpt, UART_IER, 0x0F);\n#ifdef __i386__\n\t\toutb(0, 0x080);\n#endif\n\t\tscratch3 = serial_inp(mtpt, UART_IER) & 0x0F;\n\t\tserial_outp(mtpt, UART_IER, scratch);\n\t\tif (scratch2 != 0 || scratch3 != 0x0F) {\n\t\t\tDEBUG_AUTOCONF(\"IER test failed (%02x, %02x) \",\n\t\t\t\t\tscratch2, scratch3);\n\t\t\tgoto out;\n\t\t}\n\t}", "\tsave_mcr = serial_in(mtpt, UART_MCR);\n\tsave_lcr = serial_in(mtpt, UART_LCR);", "\tif (!(mtpt->port.flags & UPF_SKIP_TEST)) {\n\t\tserial_outp(mtpt, UART_MCR, UART_MCR_LOOP | 0x0A);\n\t\tstatus1 = serial_inp(mtpt, UART_MSR) & 0xF0;\n\t\tserial_outp(mtpt, UART_MCR, save_mcr);\n\t\tif (status1 != 0x90) {\n\t\t\tDEBUG_AUTOCONF(\"LOOP test failed (%02x) \",\n\t\t\t\t\tstatus1);\n\t\t\tgoto out;\n\t\t}\n\t}", "\tserial_outp(mtpt, UART_LCR, 0xBF);\n\tserial_outp(mtpt, UART_EFR, 0);\n\tserial_outp(mtpt, UART_LCR, 0);", "\tserial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO);\n\tscratch = serial_in(mtpt, UART_IIR) >> 6;", "\tDEBUG_AUTOCONF(\"iir=%d \", scratch);\n\tif(mtpt->device->nr_ports >= 8)\n\t\tb_ret = read_option_register(mtpt,(MP_OPTR_DIR0 + ((mtpt->port.line)/8)));\n\telse\t\n\t\tb_ret = read_option_register(mtpt,MP_OPTR_DIR0);\n\tu_type = (b_ret & 0xf0) >> 4;\n\tif(mtpt->port.type == PORT_UNKNOWN )\n\t{\n\t\tswitch (u_type)\n\t\t{\n\t\t\tcase DIR_UART_16C550:\n\t\t\t\tmtpt->port.type = PORT_16C55X;\n\t\t\t\tbreak;\n\t\t\tcase DIR_UART_16C1050:\n\t\t\t\tmtpt->port.type = PORT_16C105X;\n\t\t\t\tbreak;\n\t\t\tcase DIR_UART_16C1050A:\n\t\t\t\tif (mtpt->port.line < 2)\n\t\t\t\t{\n\t\t\t\t\tmtpt->port.type = PORT_16C105XA;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (mtpt->device->device_id & 0x50)\n\t\t\t\t\t{\n\t\t\t\t\t\tmtpt->port.type = PORT_16C55X;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tmtpt->port.type = PORT_16C105X;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\t\n\t\t\t\tmtpt->port.type = PORT_UNKNOWN;\n\t\t\t\tbreak;\n\t\t}\n\t}", "\tif(mtpt->port.type == PORT_UNKNOWN )\n\t{\nprintk(\"unknow2\\n\");\n\t\tswitch (scratch) {\n\t\t\tcase 0:\n\t\t\tcase 1:\n\t\t\t\tmtpt->port.type = PORT_UNKNOWN;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\tcase 3:\n\t\t\t\tmtpt->port.type = PORT_16C55X;\n\t\t\t\tbreak;\n\t\t}\n\t}", "\tserial_outp(mtpt, UART_LCR, save_lcr);", "\tmtpt->port.fifosize = uart_config[mtpt->port.type].dfl_xmit_fifo_size;\n\tmtpt->capabilities = uart_config[mtpt->port.type].flags;", "\tif (mtpt->port.type == PORT_UNKNOWN)\n\t\tgoto out;\n\tserial_outp(mtpt, UART_MCR, save_mcr);\n\tserial_outp(mtpt, UART_FCR, (UART_FCR_ENABLE_FIFO |\n\t\t\t\tUART_FCR_CLEAR_RCVR |\n\t\t\t\tUART_FCR_CLEAR_XMIT));\n\tserial_outp(mtpt, UART_FCR, 0);\n\t(void)serial_in(mtpt, UART_RX);\n\tserial_outp(mtpt, UART_IER, 0);", "out:\n\tspin_unlock_irqrestore(&mtpt->port.lock, flags);\n\tDEBUG_AUTOCONF(\"type=%s\\n\", uart_config[mtpt->port.type].name);\n}", "static void autoconfig_irq(struct mp_port *mtpt)\n{\n\tunsigned char save_mcr, save_ier;\n\tunsigned long irqs;\n\tint irq;", "\t/* forget possible initially masked and pending IRQ */\n\tprobe_irq_off(probe_irq_on());\n\tsave_mcr = serial_inp(mtpt, UART_MCR);\n\tsave_ier = serial_inp(mtpt, UART_IER);\n\tserial_outp(mtpt, UART_MCR, UART_MCR_OUT1 | UART_MCR_OUT2);", "\tirqs = probe_irq_on();\n\tserial_outp(mtpt, UART_MCR, 0);\n\tserial_outp(mtpt, UART_MCR,\n\t\tUART_MCR_DTR | UART_MCR_RTS | UART_MCR_OUT2);", "\tserial_outp(mtpt, UART_IER, 0x0f); /* enable all intrs */\n\t(void)serial_inp(mtpt, UART_LSR);\n\t(void)serial_inp(mtpt, UART_RX);\n\t(void)serial_inp(mtpt, UART_IIR);\n\t(void)serial_inp(mtpt, UART_MSR);\n\tserial_outp(mtpt, UART_TX, 0xFF);\n\tirq = probe_irq_off(irqs);", "\tserial_outp(mtpt, UART_MCR, save_mcr);\n\tserial_outp(mtpt, UART_IER, save_ier);", "\tmtpt->port.irq = (irq > 0) ? irq : 0;\n}", "static void multi_stop_tx(struct sb_uart_port *port)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;", "\tif (mtpt->ier & UART_IER_THRI) {\n\t\tmtpt->ier &= ~UART_IER_THRI;\n\t\tserial_out(mtpt, UART_IER, mtpt->ier);\n\t}", "\ttasklet_schedule(&port->info->tlet);\n}", "static void multi_start_tx(struct sb_uart_port *port)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;", "\tif (!(mtpt->ier & UART_IER_THRI)) {\n\t\tmtpt->ier |= UART_IER_THRI;\n\t\tserial_out(mtpt, UART_IER, mtpt->ier);\n\t}\n}", "static void multi_stop_rx(struct sb_uart_port *port)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;", "\tmtpt->ier &= ~UART_IER_RLSI;\n\tmtpt->port.read_status_mask &= ~UART_LSR_DR;\n\tserial_out(mtpt, UART_IER, mtpt->ier);\n}", "static void multi_enable_ms(struct sb_uart_port *port)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;", "\tmtpt->ier |= UART_IER_MSI;\n\tserial_out(mtpt, UART_IER, mtpt->ier);\n}", "\nstatic _INLINE_ void receive_chars(struct mp_port *mtpt, int *status )\n{\n\tstruct tty_struct *tty = mtpt->port.info->tty;\n\tunsigned char lsr = *status;\n\tint max_count = 256;\n\tunsigned char ch;\n\tchar flag;", "\t//lsr &= mtpt->port.read_status_mask;", "\tdo {\n\t\tif ((lsr & UART_LSR_PE) && (mtpt->port.mdmode & MDMODE_ENABLE))\n\t\t{\n\t\t\tch = serial_inp(mtpt, UART_RX);\n\t\t}\n\t\telse if (lsr & UART_LSR_SPECIAL) \n\t\t{\n\t\t\tflag = 0;\n\t\t\tch = serial_inp(mtpt, UART_RX);", "\t\t\tif (lsr & UART_LSR_BI) \n\t\t\t{", "\t\t\t\tmtpt->port.icount.brk++;\n\t\t\t\tflag = TTY_BREAK;", "\t\t\t\tif (sb_uart_handle_break(&mtpt->port))\n\t\t\t\t\tgoto ignore_char;\n\t\t\t} \n\t\t\tif (lsr & UART_LSR_PE)\n\t\t\t{\n\t\t\t\tmtpt->port.icount.parity++;\n\t\t\t\tflag = TTY_PARITY;\n\t\t\t}\n\t\t\tif (lsr & UART_LSR_FE)\n\t\t\t{\n\t\t\t\tmtpt->port.icount.frame++;\n\t\t\t\tflag = TTY_FRAME;\n\t\t\t}\n\t\t\tif (lsr & UART_LSR_OE)\n\t\t\t{\n\t\t\t\tmtpt->port.icount.overrun++;\n\t\t\t\tflag = TTY_OVERRUN;\n\t\t\t}\n\t\t\ttty_insert_flip_char(tty, ch, flag);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tch = serial_inp(mtpt, UART_RX);\n\t\t\ttty_insert_flip_char(tty, ch, 0);\n\t\t}\nignore_char:\n\t\tlsr = serial_inp(mtpt, UART_LSR);\n\t} while ((lsr & UART_LSR_DR) && (max_count-- > 0));", "\ttty_flip_buffer_push(tty);\n}", "", "\nstatic _INLINE_ void transmit_chars(struct mp_port *mtpt)\n{\n\tstruct circ_buf *xmit = &mtpt->port.info->xmit;\n\tint count;", "\tif (mtpt->port.x_char) {\n\t\tserial_outp(mtpt, UART_TX, mtpt->port.x_char);\n\t\tmtpt->port.icount.tx++;\n\t\tmtpt->port.x_char = 0;\n\t\treturn;\n\t}\n\tif (uart_circ_empty(xmit) || uart_tx_stopped(&mtpt->port)) {\n\t\tmulti_stop_tx(&mtpt->port);\n\t\treturn;\n\t}", "\tcount = uart_circ_chars_pending(xmit);", "\tif(count > mtpt->port.fifosize)\n\t{\n\t\tcount = mtpt->port.fifosize;\n\t}", "\tprintk(\"[%d] mdmode: %x\\n\", mtpt->port.line, mtpt->port.mdmode);\n\tdo {\n#if 0\n\t\t/* check multi-drop mode */\n\t\tif ((mtpt->port.mdmode & (MDMODE_ENABLE | MDMODE_ADDR)) == (MDMODE_ENABLE | MDMODE_ADDR))\n\t\t{\n\t\t\tprintk(\"send address\\n\");\n\t\t\t/* send multi-drop address */\n\t\t\tserial_out(mtpt, UART_SCR, xmit->buf[xmit->tail]);\n\t\t}\n\t\telse\n#endif\n\t\t{\n\t\t\tserial_out(mtpt, UART_TX, xmit->buf[xmit->tail]);\n\t\t}\n\t\txmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1);\n\t\tmtpt->port.icount.tx++;\n\t} while (--count > 0);\n}", "", "static _INLINE_ void check_modem_status(struct mp_port *mtpt)\n{\n\tint status;", "\tstatus = serial_in(mtpt, UART_MSR);", "\tif ((status & UART_MSR_ANY_DELTA) == 0)\n\t\treturn;", "\tif (status & UART_MSR_TERI)\n\t\tmtpt->port.icount.rng++;\n\tif (status & UART_MSR_DDSR)\n\t\tmtpt->port.icount.dsr++;\n\tif (status & UART_MSR_DDCD)\n\t\tsb_uart_handle_dcd_change(&mtpt->port, status & UART_MSR_DCD);\n\tif (status & UART_MSR_DCTS)\n\t\tsb_uart_handle_cts_change(&mtpt->port, status & UART_MSR_CTS);", "\twake_up_interruptible(&mtpt->port.info->delta_msr_wait);\n}", "static inline void multi_handle_port(struct mp_port *mtpt)\n{\n\tunsigned int status = serial_inp(mtpt, UART_LSR);", "\t//printk(\"lsr: %x\\n\", status);", "\tif ((status & UART_LSR_DR) || (status & UART_LSR_SPECIAL))\n\t\treceive_chars(mtpt, &status);\n\tcheck_modem_status(mtpt);\n\tif (status & UART_LSR_THRE)\n\t{\n\t\tif ((mtpt->port.type == PORT_16C105X)\n\t\t\t|| (mtpt->port.type == PORT_16C105XA))\n\t\t\ttransmit_chars(mtpt);\n\t\telse\n\t\t{\n\t\t\tif (mtpt->interface >= RS485NE)\n\t\t\t\tuart_set_mctrl(&mtpt->port, TIOCM_RTS);\n\t\t\t\n\t\t\ttransmit_chars(mtpt);", "\n\t\t\tif (mtpt->interface >= RS485NE)\n\t\t\t{\n\t\t\t\twhile((status=serial_in(mtpt,UART_LSR) &0x60)!=0x60);\n\t\t\t\tuart_clear_mctrl(&mtpt->port, TIOCM_RTS);\n\t\t\t}\n\t\t}\n\t}\n}", "", "static irqreturn_t multi_interrupt(int irq, void *dev_id)\n{\n\tstruct irq_info *iinfo = dev_id;\n\tstruct list_head *lhead, *end = NULL;\n\tint pass_counter = 0;", "\n\tspin_lock(&iinfo->lock);", "\tlhead = iinfo->head;\n\tdo {\n\t\tstruct mp_port *mtpt;\n\t\tunsigned int iir;", "\t\tmtpt = list_entry(lhead, struct mp_port, list);\n\t\t\n\t\tiir = serial_in(mtpt, UART_IIR);\n\t\tprintk(\"interrupt! port %d, iir 0x%x\\n\", mtpt->port.line, iir); //wlee\n\t\tif (!(iir & UART_IIR_NO_INT)) \n\t\t{\n\t\t\tprintk(\"interrupt handle\\n\");\n\t\t\tspin_lock(&mtpt->port.lock);\n\t\t\tmulti_handle_port(mtpt);\n\t\t\tspin_unlock(&mtpt->port.lock);", "\t\t\tend = NULL;\n\t\t} else if (end == NULL)\n\t\t\tend = lhead;", "\t\tlhead = lhead->next;\n\t\tif (lhead == iinfo->head && pass_counter++ > PASS_LIMIT) \n\t\t{\n\t\t\tprintk(KERN_ERR \"multi: too much work for \"\n\t\t\t\t\t\"irq%d\\n\", irq);\n\t\t\tprintk( \"multi: too much work for \"\n\t\t\t\t\t\"irq%d\\n\", irq);\n\t\t\tbreak;\n\t\t}\n\t} while (lhead != end);", "\tspin_unlock(&iinfo->lock);", "\n return IRQ_HANDLED;\n}", "static void serial_do_unlink(struct irq_info *i, struct mp_port *mtpt)\n{\n\tspin_lock_irq(&i->lock);", "\tif (!list_empty(i->head)) {\n\t\tif (i->head == &mtpt->list)\n\t\t\ti->head = i->head->next;\n\t\tlist_del(&mtpt->list);\n\t} else {\n\t\ti->head = NULL;\n\t}", "\tspin_unlock_irq(&i->lock);\n}", "static int serial_link_irq_chain(struct mp_port *mtpt)\n{\n\tstruct irq_info *i = irq_lists + mtpt->port.irq;\n\tint ret, irq_flags = mtpt->port.flags & UPF_SHARE_IRQ ? IRQF_SHARED : 0;\n\tspin_lock_irq(&i->lock);", "\tif (i->head) {\n\t\tlist_add(&mtpt->list, i->head);\n\t\tspin_unlock_irq(&i->lock);", "\t\tret = 0;\n\t} else {\n\t\tINIT_LIST_HEAD(&mtpt->list);\n\t\ti->head = &mtpt->list;\n\t\tspin_unlock_irq(&i->lock);", "\t\tret = request_irq(mtpt->port.irq, multi_interrupt,\n\t\t\t\tirq_flags, \"serial\", i);\n\t\tif (ret < 0)\n\t\t\tserial_do_unlink(i, mtpt);\n\t}", "\treturn ret;\n}", "", "\nstatic void serial_unlink_irq_chain(struct mp_port *mtpt)\n{\n\tstruct irq_info *i = irq_lists + mtpt->port.irq;", "\tif (list_empty(i->head))\n\t{\n\t\tfree_irq(mtpt->port.irq, i);\n\t}\n\tserial_do_unlink(i, mtpt);\n}", "static void multi_timeout(unsigned long data)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)data;", "\n\tspin_lock(&mtpt->port.lock);\n\tmulti_handle_port(mtpt);\n\tspin_unlock(&mtpt->port.lock);", "\tmod_timer(&mtpt->timer, jiffies+1 );\n}", "static unsigned int multi_tx_empty(struct sb_uart_port *port)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tunsigned long flags;\n\tunsigned int ret;", "\tspin_lock_irqsave(&mtpt->port.lock, flags);\n\tret = serial_in(mtpt, UART_LSR) & UART_LSR_TEMT ? TIOCSER_TEMT : 0;\n\tspin_unlock_irqrestore(&mtpt->port.lock, flags);", "\treturn ret;\n}", "\nstatic unsigned int multi_get_mctrl(struct sb_uart_port *port)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tunsigned char status;\n\tunsigned int ret;", "\tstatus = serial_in(mtpt, UART_MSR);", "\tret = 0;\n\tif (status & UART_MSR_DCD)\n\t\tret |= TIOCM_CAR;\n\tif (status & UART_MSR_RI)\n\t\tret |= TIOCM_RNG;\n\tif (status & UART_MSR_DSR)\n\t\tret |= TIOCM_DSR;\n\tif (status & UART_MSR_CTS)\n\t\tret |= TIOCM_CTS;\n\treturn ret;\n}", "static void multi_set_mctrl(struct sb_uart_port *port, unsigned int mctrl)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tunsigned char mcr = 0;", "\tmctrl &= 0xff;", "\tif (mctrl & TIOCM_RTS)\n\t\tmcr |= UART_MCR_RTS;\n\tif (mctrl & TIOCM_DTR)\n\t\tmcr |= UART_MCR_DTR;\n\tif (mctrl & TIOCM_OUT1)\n\t\tmcr |= UART_MCR_OUT1;\n\tif (mctrl & TIOCM_OUT2)\n\t\tmcr |= UART_MCR_OUT2;\n\tif (mctrl & TIOCM_LOOP)\n\t\tmcr |= UART_MCR_LOOP;", "\n\tserial_out(mtpt, UART_MCR, mcr);\n}", "\nstatic void multi_break_ctl(struct sb_uart_port *port, int break_state)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tunsigned long flags;", "\tspin_lock_irqsave(&mtpt->port.lock, flags);\n\tif (break_state == -1)\n\t\tmtpt->lcr |= UART_LCR_SBC;\n\telse\n\t\tmtpt->lcr &= ~UART_LCR_SBC;\n\tserial_out(mtpt, UART_LCR, mtpt->lcr);\n\tspin_unlock_irqrestore(&mtpt->port.lock, flags);\n}", "", "static int multi_startup(struct sb_uart_port *port)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tunsigned long flags;\n\tint retval;", "\tmtpt->capabilities = uart_config[mtpt->port.type].flags;\n\tmtpt->mcr = 0;", "\tif (mtpt->capabilities & UART_CLEAR_FIFO) {\n\t\tserial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO);\n\t\tserial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO |\n\t\t\t\tUART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT);\n\t\tserial_outp(mtpt, UART_FCR, 0);\n\t}", "\t(void) serial_inp(mtpt, UART_LSR);\n\t(void) serial_inp(mtpt, UART_RX);\n\t(void) serial_inp(mtpt, UART_IIR);\n\t(void) serial_inp(mtpt, UART_MSR);\n\t//test-wlee 9-bit disable\n\tserial_outp(mtpt, UART_MSR, 0);", "\n\tif (!(mtpt->port.flags & UPF_BUGGY_UART) &&\n\t\t\t(serial_inp(mtpt, UART_LSR) == 0xff)) {\n\t\tprintk(\"ttyS%d: LSR safety check engaged!\\n\", mtpt->port.line);\n\t\t//return -ENODEV;\n\t}", "\tif ((!is_real_interrupt(mtpt->port.irq)) || (mtpt->poll_type==TYPE_POLL)) {\n\t\tunsigned int timeout = mtpt->port.timeout;", "\t\ttimeout = timeout > 6 ? (timeout / 2 - 2) : 1;", "\t\tmtpt->timer.data = (unsigned long)mtpt;\n\t\tmod_timer(&mtpt->timer, jiffies + timeout);\n\t} \n\telse \n\t{\n\t\tretval = serial_link_irq_chain(mtpt);\n\t\tif (retval)\n\t\t\treturn retval;\n\t}", "\tserial_outp(mtpt, UART_LCR, UART_LCR_WLEN8);", "\tspin_lock_irqsave(&mtpt->port.lock, flags);\n\tif ((is_real_interrupt(mtpt->port.irq))||(mtpt->poll_type==TYPE_INTERRUPT))\n\t\tmtpt->port.mctrl |= TIOCM_OUT2;", "\tmulti_set_mctrl(&mtpt->port, mtpt->port.mctrl);\n\tspin_unlock_irqrestore(&mtpt->port.lock, flags);", "\t\n\tmtpt->ier = UART_IER_RLSI | UART_IER_RDI;\n\tserial_outp(mtpt, UART_IER, mtpt->ier);", "\t(void) serial_inp(mtpt, UART_LSR);\n\t(void) serial_inp(mtpt, UART_RX);\n\t(void) serial_inp(mtpt, UART_IIR);\n\t(void) serial_inp(mtpt, UART_MSR);", "\treturn 0;\n}", "", "static void multi_shutdown(struct sb_uart_port *port)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tunsigned long flags;", "\n\tmtpt->ier = 0;\n\tserial_outp(mtpt, UART_IER, 0);", "\tspin_lock_irqsave(&mtpt->port.lock, flags);\n\tmtpt->port.mctrl &= ~TIOCM_OUT2;", "\tmulti_set_mctrl(&mtpt->port, mtpt->port.mctrl);\n\tspin_unlock_irqrestore(&mtpt->port.lock, flags);", "\tserial_out(mtpt, UART_LCR, serial_inp(mtpt, UART_LCR) & ~UART_LCR_SBC);\n\tserial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO |\n\t\t\tUART_FCR_CLEAR_RCVR |\n\t\t\tUART_FCR_CLEAR_XMIT);\n\tserial_outp(mtpt, UART_FCR, 0);", "\n\t(void) serial_in(mtpt, UART_RX);", "\tif ((!is_real_interrupt(mtpt->port.irq))||(mtpt->poll_type==TYPE_POLL))\n\t{\n\t\tdel_timer_sync(&mtpt->timer);\n\t}\n\telse\n\t{\n\t\tserial_unlink_irq_chain(mtpt);\n\t}\n}", "", "static unsigned int multi_get_divisor(struct sb_uart_port *port, unsigned int baud)\n{\n\tunsigned int quot;", "\tif ((port->flags & UPF_MAGIC_MULTIPLIER) &&\n\t\t\tbaud == (port->uartclk/4))\n\t\tquot = 0x8001;\n\telse if ((port->flags & UPF_MAGIC_MULTIPLIER) &&\n\t\t\tbaud == (port->uartclk/8))\n\t\tquot = 0x8002;\n\telse\n\t\tquot = sb_uart_get_divisor(port, baud);", "\treturn quot;\n}", "", "\nstatic void multi_set_termios(struct sb_uart_port *port, struct MP_TERMIOS *termios, struct MP_TERMIOS *old)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tunsigned char cval, fcr = 0;\n\tunsigned long flags;\n\tunsigned int baud, quot;", "\tswitch (termios->c_cflag & CSIZE) {\n\t\tcase CS5:\n\t\t\tcval = 0x00;\n\t\t\tbreak;\n\t\tcase CS6:\n\t\t\tcval = 0x01;\n\t\t\tbreak;\n\t\tcase CS7:\n\t\t\tcval = 0x02;\n\t\t\tbreak;\n\t\tdefault:\n\t\tcase CS8:\n\t\t\tcval = 0x03;\n\t\t\tbreak;\n\t}", "\tif (termios->c_cflag & CSTOPB)\n\t\tcval |= 0x04;\n\tif (termios->c_cflag & PARENB)\n\t\tcval |= UART_LCR_PARITY;\n\tif (!(termios->c_cflag & PARODD))\n\t\tcval |= UART_LCR_EPAR;", "#ifdef CMSPAR\n\tif (termios->c_cflag & CMSPAR)\n\t\tcval |= UART_LCR_SPAR;\n#endif", "\tbaud = sb_uart_get_baud_rate(port, termios, old, 0, port->uartclk/16);\n\tquot = multi_get_divisor(port, baud);", "\tif (mtpt->capabilities & UART_USE_FIFO) {\n\t\t//if (baud < 2400)\n\t\t//\tfcr = UART_FCR_ENABLE_FIFO | UART_FCR_TRIGGER_1;\n\t\t//else\n\t\t//\tfcr = UART_FCR_ENABLE_FIFO | UART_FCR_TRIGGER_8;", "\t\t//\tfcr = UART_FCR_ENABLE_FIFO | 0x90;\n\t\t\tfcr = fcr_arr[mtpt->port.line];\n\t}", "\tspin_lock_irqsave(&mtpt->port.lock, flags);", "\tsb_uart_update_timeout(port, termios->c_cflag, baud);", "\tmtpt->port.read_status_mask = UART_LSR_OE | UART_LSR_THRE | UART_LSR_DR;\n\tif (termios->c_iflag & INPCK)\n\t\tmtpt->port.read_status_mask |= UART_LSR_FE | UART_LSR_PE;\n\tif (termios->c_iflag & (BRKINT | PARMRK))\n\t\tmtpt->port.read_status_mask |= UART_LSR_BI;", "\tmtpt->port.ignore_status_mask = 0;\n\tif (termios->c_iflag & IGNPAR)\n\t\tmtpt->port.ignore_status_mask |= UART_LSR_PE | UART_LSR_FE;\n\tif (termios->c_iflag & IGNBRK) {\n\t\tmtpt->port.ignore_status_mask |= UART_LSR_BI;\n\t\tif (termios->c_iflag & IGNPAR)\n\t\t\tmtpt->port.ignore_status_mask |= UART_LSR_OE;\n\t}", "\tif ((termios->c_cflag & CREAD) == 0)\n\t\tmtpt->port.ignore_status_mask |= UART_LSR_DR;", "\tmtpt->ier &= ~UART_IER_MSI;\n\tif (UART_ENABLE_MS(&mtpt->port, termios->c_cflag))\n\t\tmtpt->ier |= UART_IER_MSI;", "\tserial_out(mtpt, UART_IER, mtpt->ier);", "\tif (mtpt->capabilities & UART_STARTECH) {\n\t\tserial_outp(mtpt, UART_LCR, 0xBF);\n\t\tserial_outp(mtpt, UART_EFR,\n\t\t\t\ttermios->c_cflag & CRTSCTS ? UART_EFR_CTS :0);\n\t}", "\tserial_outp(mtpt, UART_LCR, cval | UART_LCR_DLAB);/* set DLAB */", "\tserial_outp(mtpt, UART_DLL, quot & 0xff); /* LS of divisor */\n\tserial_outp(mtpt, UART_DLM, quot >> 8); /* MS of divisor */", "\tserial_outp(mtpt, UART_LCR, cval); /* reset DLAB */\n\tmtpt->lcr = cval; /* Save LCR */", "\tif (fcr & UART_FCR_ENABLE_FIFO) {\n\t\t/* emulated UARTs (Lucent Venus 167x) need two steps */\n\t\tserial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO);\n\t}", "\tserial_outp(mtpt, UART_FCR, fcr); /* set fcr */", "\n\tif ((mtpt->port.type == PORT_16C105X)\n\t\t|| (mtpt->port.type == PORT_16C105XA))\n\t{\n\t\tif(deep[mtpt->port.line]!=0)\n\t\t\tset_deep_fifo(port, ENABLE);", "\t\tif (mtpt->interface != RS232)\n\t\t\tset_auto_rts(port,mtpt->interface);", "\t}\n\telse\n\t{\n\t\tif (mtpt->interface >= RS485NE)\n\t\t{\n\t\t\tuart_clear_mctrl(&mtpt->port, TIOCM_RTS);\n\t\t}\n\t}", "\tif(mtpt->device->device_id == PCI_DEVICE_ID_MP4M)\n\t{\n\t\tSendATCommand(mtpt);\n\t\tprintk(\"SendATCommand\\n\");\n\t}\t\n\tmulti_set_mctrl(&mtpt->port, mtpt->port.mctrl);\n\tspin_unlock_irqrestore(&mtpt->port.lock, flags);\n}", "static void multi_pm(struct sb_uart_port *port, unsigned int state, unsigned int oldstate)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tif (state) {\n\t\tif (mtpt->capabilities & UART_STARTECH) {\n\t\t\tserial_outp(mtpt, UART_LCR, 0xBF);\n\t\t\tserial_outp(mtpt, UART_EFR, UART_EFR_ECB);\n\t\t\tserial_outp(mtpt, UART_LCR, 0);\n\t\t\tserial_outp(mtpt, UART_IER, UART_IERX_SLEEP);\n\t\t\tserial_outp(mtpt, UART_LCR, 0xBF);\n\t\t\tserial_outp(mtpt, UART_EFR, 0);\n\t\t\tserial_outp(mtpt, UART_LCR, 0);\n\t\t}", "\t\tif (mtpt->pm)\n\t\t\tmtpt->pm(port, state, oldstate);\n\t} \n\telse \n\t{\n\t\tif (mtpt->capabilities & UART_STARTECH) {\n\t\t\tserial_outp(mtpt, UART_LCR, 0xBF);\n\t\t\tserial_outp(mtpt, UART_EFR, UART_EFR_ECB);\n\t\t\tserial_outp(mtpt, UART_LCR, 0);\n\t\t\tserial_outp(mtpt, UART_IER, 0);\n\t\t\tserial_outp(mtpt, UART_LCR, 0xBF);\n\t\t\tserial_outp(mtpt, UART_EFR, 0);\n\t\t\tserial_outp(mtpt, UART_LCR, 0);\n\t\t}", "\t\tif (mtpt->pm)\n\t\t\tmtpt->pm(port, state, oldstate);\n\t}\n}", "static void multi_release_std_resource(struct mp_port *mtpt)\n{\n\tunsigned int size = 8 << mtpt->port.regshift;", "\tswitch (mtpt->port.iotype) {\n\t\tcase UPIO_MEM:\n\t\t\tif (!mtpt->port.mapbase)\n\t\t\t\tbreak;", "\t\t\tif (mtpt->port.flags & UPF_IOREMAP) {\n\t\t\t\tiounmap(mtpt->port.membase);\n\t\t\t\tmtpt->port.membase = NULL;\n\t\t\t}", "\t\t\trelease_mem_region(mtpt->port.mapbase, size);\n\t\t\tbreak;", "\t\tcase UPIO_HUB6:\n\t\tcase UPIO_PORT:\n\t\t\trelease_region(mtpt->port.iobase,size);\n\t\t\tbreak;\n\t}\n}", "static void multi_release_port(struct sb_uart_port *port)\n{\n}", "static int multi_request_port(struct sb_uart_port *port)\n{\n\treturn 0;\n}", "static void multi_config_port(struct sb_uart_port *port, int flags)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tint probeflags = PROBE_ANY;", "\tif (flags & UART_CONFIG_TYPE)\n\t\tautoconfig(mtpt, probeflags);\n\tif (mtpt->port.type != PORT_UNKNOWN && flags & UART_CONFIG_IRQ)\n\t\tautoconfig_irq(mtpt);", "\tif (mtpt->port.type == PORT_UNKNOWN)\n\t\tmulti_release_std_resource(mtpt);\n}", "static int multi_verify_port(struct sb_uart_port *port, struct serial_struct *ser)\n{\n\tif (ser->irq >= NR_IRQS || ser->irq < 0 ||\n\t\t\tser->baud_base < 9600 || ser->type < PORT_UNKNOWN ||\n\t\t\tser->type == PORT_STARTECH)\n\t\treturn -EINVAL;\n\treturn 0;\n}", "static const char *multi_type(struct sb_uart_port *port)\n{\n\tint type = port->type;", "\tif (type >= ARRAY_SIZE(uart_config))\n\t\ttype = 0;\n\treturn uart_config[type].name;\n}", "static struct sb_uart_ops multi_pops = {\n\t.tx_empty = multi_tx_empty,\n\t.set_mctrl = multi_set_mctrl,\n\t.get_mctrl = multi_get_mctrl,\n\t.stop_tx = multi_stop_tx,\n\t.start_tx = multi_start_tx,\n\t.stop_rx = multi_stop_rx,\n\t.enable_ms = multi_enable_ms,\n\t.break_ctl = multi_break_ctl,\n\t.startup = multi_startup,\n\t.shutdown = multi_shutdown,\n\t.set_termios = multi_set_termios,\n\t.pm \t= multi_pm,\n\t.type \t= multi_type,\n\t.release_port = multi_release_port,\n\t.request_port = multi_request_port,\n\t.config_port = multi_config_port,\n\t.verify_port = multi_verify_port,\n};", "static struct uart_driver multi_reg = {\n\t.owner = THIS_MODULE,\n\t.driver_name = \"goldel_tulip\",\n\t.dev_name = \"ttyMP\",\n\t.major = SB_TTY_MP_MAJOR,\n\t.minor = 0,\n\t.nr = MAX_MP_PORT, \n\t.cons = NULL,\n};", "static void __init multi_init_ports(void)\n{\n\tstruct mp_port *mtpt;\n\tstatic int first = 1;\n\tint i,j,k;\n\tunsigned char osc;\n\tunsigned char b_ret = 0;\n\tstatic struct mp_device_t *sbdev; ", "\tif (!first)\n\t\treturn;\n\tfirst = 0;", "\tmtpt = multi_ports; ", "\tfor (k=0;k<NR_BOARD;k++)\n\t{\n\t\tsbdev = &mp_devs[k];", "\t\tfor (i = 0; i < sbdev->nr_ports; i++, mtpt++) \n\t\t{\n\t\t\tmtpt->device \t\t= sbdev;\n\t\t\tmtpt->port.iobase = sbdev->uart_access_addr + 8*i;\n\t\t\tmtpt->port.irq = sbdev->irq;\n\t\t\tif ( ((sbdev->device_id == PCI_DEVICE_ID_MP4)&&(sbdev->revision==0x91)))\n\t\t\t\tmtpt->interface_config_addr = sbdev->option_reg_addr + 0x08 + i;\n\t\t\telse if (sbdev->revision == 0xc0)\n\t\t\t\tmtpt->interface_config_addr = sbdev->option_reg_addr + 0x08 + (i & 0x1);\n\t\t\telse\n\t\t\t\tmtpt->interface_config_addr = sbdev->option_reg_addr + 0x08 + i/8;", "\t\t\tmtpt->option_base_addr = sbdev->option_reg_addr;", "\t\t\tmtpt->poll_type = sbdev->poll_type;", "\t\t\tmtpt->port.uartclk = BASE_BAUD * 16;", "\t\t\t/* get input clock information */\n\t\t\tosc = inb(sbdev->option_reg_addr + MP_OPTR_DIR0 + i/8) & 0x0F;\n\t\t\tif (osc==0x0f)\n\t\t\t\tosc = 0;\n\t\t\tfor(j=0;j<osc;j++)\n\t\t\t\tmtpt->port.uartclk *= 2;\n\t\t\tmtpt->port.flags |= STD_COM_FLAGS | UPF_SHARE_IRQ ;\n\t\t\tmtpt->port.iotype = UPIO_PORT;\n\t\t\tmtpt->port.ops = &multi_pops;", "\t\t\tif (sbdev->revision == 0xc0)\n\t\t\t{\n\t\t\t\t/* for SB16C1053APCI */\n\t\t\t\tb_ret = sb1053a_get_interface(mtpt, i);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tb_ret = read_option_register(mtpt,(MP_OPTR_IIR0 + i/8));\n\t\t\t\tprintk(\"IIR_RET = %x\\n\",b_ret);\n\t\t\t}", "\t\t\t/* default to RS232 */\n\t\t\tmtpt->interface = RS232;\n\t\t\tif (IIR_RS422 == (b_ret & IIR_TYPE_MASK))\n\t\t\t\tmtpt->interface = RS422PTP;\n\t\t\tif (IIR_RS485 == (b_ret & IIR_TYPE_MASK))\n\t\t\t\tmtpt->interface = RS485NE;\n\t\t}\n\t}\n}", "static void __init multi_register_ports(struct uart_driver *drv)\n{\n\tint i;", "\tmulti_init_ports();", "\tfor (i = 0; i < NR_PORTS; i++) {\n\t\tstruct mp_port *mtpt = &multi_ports[i];", "\t\tmtpt->port.line = i;\n\t\tmtpt->port.ops = &multi_pops;\n\t\tinit_timer(&mtpt->timer);\n\t\tmtpt->timer.function = multi_timeout;\n\t\tmp_add_one_port(drv, &mtpt->port);\n\t}\n}", "/**\n * pci_remap_base - remap BAR value of pci device\n *\n * PARAMETERS\n * pcidev - pci_dev structure address\n * offset - BAR offset PCI_BASE_ADDRESS_0 ~ PCI_BASE_ADDRESS_4\n * address - address to be changed BAR value\n * size\t- size of address space \n *\n * RETURNS\n * If this function performs successful, it returns 0. Otherwise, It returns -1.\n */\nstatic int pci_remap_base(struct pci_dev *pcidev, unsigned int offset, \n\t\tunsigned int address, unsigned int size) \n{\n#if 0\n\tstruct resource *root;\n\tunsigned index = (offset - 0x10) >> 2;\n#endif", "\tpci_write_config_dword(pcidev, offset, address);\n#if 0\n\troot = pcidev->resource[index].parent;\n\trelease_resource(&pcidev->resource[index]);\n\taddress &= ~0x1;\n\tpcidev->resource[index].start = address;\n\tpcidev->resource[index].end\t = address + size - 1;", "\tif (request_resource(root, &pcidev->resource[index]) != NULL)\n\t{\n\t\tprintk(KERN_ERR \"pci remap conflict!! 0x%x\\n\", address);\n\t\treturn (-1);\n\t}\n#endif", "\treturn (0);\n}", "static int init_mp_dev(struct pci_dev *pcidev, mppcibrd_t brd)\n{\n\tstatic struct mp_device_t *sbdev = mp_devs;\n\tunsigned long addr = 0;\n\tint j;\n\tstruct resource *ret = NULL;", "\tsbdev->device_id = brd.device_id;\n\tpci_read_config_byte(pcidev, PCI_CLASS_REVISION, &(sbdev->revision));\n\tsbdev->name = brd.name;\n\tsbdev->uart_access_addr = pcidev->resource[0].start & PCI_BASE_ADDRESS_IO_MASK;", "\t/* check revision. The SB16C1053APCI's option i/o address is BAR4 */\n\tif (sbdev->revision == 0xc0)\n\t{\n\t\t/* SB16C1053APCI */\n\t\tsbdev->option_reg_addr = pcidev->resource[4].start & PCI_BASE_ADDRESS_IO_MASK;\n\t}\n\telse\n\t{\n\t\tsbdev->option_reg_addr = pcidev->resource[1].start & PCI_BASE_ADDRESS_IO_MASK;\n\t}\n#if 1\t\n\tif (sbdev->revision == 0xc0)\n\t{\n\t\toutb(0x00, sbdev->option_reg_addr + MP_OPTR_GPOCR);\n\t\tinb(sbdev->option_reg_addr + MP_OPTR_GPOCR);\n\t\toutb(0x83, sbdev->option_reg_addr + MP_OPTR_GPOCR);\n\t}\n#endif", "\tsbdev->irq = pcidev->irq;", "\tif ((brd.device_id & 0x0800) || !(brd.device_id &0xff00))\n\t{\n\t\tsbdev->poll_type = TYPE_INTERRUPT;\n\t}\n\telse\n\t{\n\t\tsbdev->poll_type = TYPE_POLL;\n\t}", "\t/* codes which is specific to each board*/\n\tswitch(brd.device_id){\n\t\tcase PCI_DEVICE_ID_MP1 :\n\t\tcase PCIE_DEVICE_ID_MP1 :\n\t\tcase PCIE_DEVICE_ID_MP1E :\n\t\tcase PCIE_DEVICE_ID_GT_MP1 :\n\t\t\tsbdev->nr_ports = 1;\n\t\t\tbreak;\n\t\tcase PCI_DEVICE_ID_MP2 :\n\t\tcase PCIE_DEVICE_ID_MP2 :\n\t\tcase PCIE_DEVICE_ID_GT_MP2 :\n\t\tcase PCIE_DEVICE_ID_MP2B :\n\t\tcase PCIE_DEVICE_ID_MP2E :\n\t\t\tsbdev->nr_ports = 2;", "\t\t\t/* serial base address remap */\n\t\t\tif (sbdev->revision == 0xc0)\n\t\t\t{\n\t\t\t\tint prev_port_addr = 0;", "\t\t\t\tpci_read_config_dword(pcidev, PCI_BASE_ADDRESS_0, &prev_port_addr);\n\t\t\t\tpci_remap_base(pcidev, PCI_BASE_ADDRESS_1, prev_port_addr + 8, 8);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase PCI_DEVICE_ID_MP4 :\n\t\tcase PCI_DEVICE_ID_MP4A :\n\t\tcase PCIE_DEVICE_ID_MP4 :\n\t\tcase PCI_DEVICE_ID_GT_MP4 :\n\t\tcase PCI_DEVICE_ID_GT_MP4A :\n\t\tcase PCIE_DEVICE_ID_GT_MP4 :\n\t\tcase PCI_DEVICE_ID_MP4M :\n\t\tcase PCIE_DEVICE_ID_MP4B :\n\t\t\tsbdev->nr_ports = 4;", "\t\t\tif(sbdev->revision == 0x91){\n\t\t\t\tsbdev->reserved_addr[0] = pcidev->resource[0].start & PCI_BASE_ADDRESS_IO_MASK;\n\t\t\t\toutb(0x03 , sbdev->reserved_addr[0] + 0x01);\n\t\t\t\toutb(0x03 , sbdev->reserved_addr[0] + 0x02);\n\t\t\t\toutb(0x01 , sbdev->reserved_addr[0] + 0x20);\n\t\t\t\toutb(0x00 , sbdev->reserved_addr[0] + 0x21);\n\t\t\t\trequest_region(sbdev->reserved_addr[0], 32, sbdev->name);\n\t\t\t\tsbdev->uart_access_addr = pcidev->resource[1].start & PCI_BASE_ADDRESS_IO_MASK;\n\t\t\t\tsbdev->option_reg_addr = pcidev->resource[2].start & PCI_BASE_ADDRESS_IO_MASK;\n\t\t\t}", "\t\t\t/* SB16C1053APCI */\n\t\t\tif (sbdev->revision == 0xc0)\n\t\t\t{\n\t\t\t\tint prev_port_addr = 0;", "\t\t\t\tpci_read_config_dword(pcidev, PCI_BASE_ADDRESS_0, &prev_port_addr);\n\t\t\t\tpci_remap_base(pcidev, PCI_BASE_ADDRESS_1, prev_port_addr + 8, 8);\n\t\t\t\tpci_remap_base(pcidev, PCI_BASE_ADDRESS_2, prev_port_addr + 16, 8);\n\t\t\t\tpci_remap_base(pcidev, PCI_BASE_ADDRESS_3, prev_port_addr + 24, 8);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase PCI_DEVICE_ID_MP6 :\n\t\tcase PCI_DEVICE_ID_MP6A :\n\t\tcase PCI_DEVICE_ID_GT_MP6 :\n\t\tcase PCI_DEVICE_ID_GT_MP6A :\n\t\t\tsbdev->nr_ports = 6;", "\t\t\t/* SB16C1053APCI */\n\t\t\tif (sbdev->revision == 0xc0)\n\t\t\t{\n\t\t\t\tint prev_port_addr = 0;", "\t\t\t\tpci_read_config_dword(pcidev, PCI_BASE_ADDRESS_0, &prev_port_addr);\n\t\t\t\tpci_remap_base(pcidev, PCI_BASE_ADDRESS_1, prev_port_addr + 8, 8);\n\t\t\t\tpci_remap_base(pcidev, PCI_BASE_ADDRESS_2, prev_port_addr + 16, 16);\n\t\t\t\tpci_remap_base(pcidev, PCI_BASE_ADDRESS_3, prev_port_addr + 32, 16);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase PCI_DEVICE_ID_MP8 :\n\t\tcase PCIE_DEVICE_ID_MP8 :\n\t\tcase PCI_DEVICE_ID_GT_MP8 :\n\t\tcase PCIE_DEVICE_ID_GT_MP8 :\n\t\tcase PCIE_DEVICE_ID_MP8B :\n\t\t\tsbdev->nr_ports = 8;\n\t\t\tbreak;\n\t\tcase PCI_DEVICE_ID_MP32 :\n\t\tcase PCIE_DEVICE_ID_MP32 :\n\t\tcase PCI_DEVICE_ID_GT_MP32 :\n\t\tcase PCIE_DEVICE_ID_GT_MP32 :\n\t\t\t{\n\t\t\t\tint portnum_hex=0;\n\t\t\t\tportnum_hex = inb(sbdev->option_reg_addr);\n\t\t\t\tsbdev->nr_ports = ((portnum_hex/16)*10) + (portnum_hex % 16);\n\t\t\t}\n\t\t\tbreak;\n#ifdef CONFIG_PARPORT_PC\n\t\tcase PCI_DEVICE_ID_MP2S1P :\n\t\t\tsbdev->nr_ports = 2;", "\t\t\t/* SB16C1053APCI */\n\t\t\tif (sbdev->revision == 0xc0)\n\t\t\t{\n\t\t\t\tint prev_port_addr = 0;", "\t\t\t\tpci_read_config_dword(pcidev, PCI_BASE_ADDRESS_0, &prev_port_addr);\n\t\t\t\tpci_remap_base(pcidev, PCI_BASE_ADDRESS_1, prev_port_addr + 8, 8);\n\t\t\t}", "\t\t\t/* add PC compatible parallel port */\n\t\t\tparport_pc_probe_port(pcidev->resource[2].start, pcidev->resource[3].start, PARPORT_IRQ_NONE, PARPORT_DMA_NONE, &pcidev->dev, 0);\n\t\t\tbreak;\n\t\tcase PCI_DEVICE_ID_MP1P :\n\t\t\t/* add PC compatible parallel port */\n\t\t\tparport_pc_probe_port(pcidev->resource[2].start, pcidev->resource[3].start, PARPORT_IRQ_NONE, PARPORT_DMA_NONE, &pcidev->dev, 0);\n\t\t\tbreak;\n#endif\n\t}", "\tret = request_region(sbdev->uart_access_addr, (8*sbdev->nr_ports), sbdev->name);", "\tif (sbdev->revision == 0xc0)\n\t{\n\t\tret = request_region(sbdev->option_reg_addr, 0x40, sbdev->name);\n\t}\n\telse\n\t{\n\t\tret = request_region(sbdev->option_reg_addr, 0x20, sbdev->name);\n\t}", "\n\tNR_BOARD++;\n\tNR_PORTS += sbdev->nr_ports;", "\t/* Enable PCI interrupt */\n\taddr = sbdev->option_reg_addr + MP_OPTR_IMR0;\n\tfor(j=0; j < (sbdev->nr_ports/8)+1; j++)\n\t{\n\t\tif (sbdev->poll_type == TYPE_INTERRUPT)\n\t\t{\n\t\t\toutb(0xff,addr +j);\n\t\t}\n\t}\n\tsbdev++;", "\treturn 0;\n}", "static int __init multi_init(void)\n{\n\tint ret, i;\n\tstruct pci_dev *dev = NULL;", "\tif(fcr_count==0)\n\t{\n\t\tfor(i=0;i<256;i++)\n\t\t{\n\t\t\tfcr_arr[i] = 0x01;\n\t\t\t\n\t\t}\n\t}\n\tif(deep_count==0)\n\t{\n\t\tfor(i=0;i<256;i++)\n\t\t{\n\t\t\tdeep[i] = 1;\n\t\t\t\n\t\t}\n\t}\n\tif(rtr_count==0)\n {\n for(i=0;i<256;i++)\n {\n rtr[i] = 0x10;\n }\n }\n\tif(ttr_count==0)\n {\n for(i=0;i<256;i++)\n {\n ttr[i] = 0x38;\n }\n }", "\nprintk(\"MULTI INIT\\n\");\n\tfor( i=0; i< mp_nrpcibrds; i++)\n\t{", "\t\twhile( (dev = pci_get_device(mp_pciboards[i].vendor_id, mp_pciboards[i].device_id, dev) ) )", "\t\t{\nprintk(\"FOUND~~~\\n\");\n//\tCent OS bug fix\n//\t\t\tif (mp_pciboards[i].device_id & 0x0800)\n\t\t\t{\n\t\t\t\tint status;\n\t \t\tpci_disable_device(dev);\n\t \t\tstatus = pci_enable_device(dev);\n \n\t \t\t \tif (status != 0)\n \t\t\t{ \n \t\t\t\tprintk(\"Multiport Board Enable Fail !\\n\\n\");\n \t\t\t\tstatus = -ENXIO;\n \t\t\treturn status;\n \t\t\t}\n\t\t\t}", "\t\t\tinit_mp_dev(dev, mp_pciboards[i]);\t\n\t\t}\n\t}", "\tfor (i = 0; i < NR_IRQS; i++)\n\t\tspin_lock_init(&irq_lists[i].lock);", "\tret = mp_register_driver(&multi_reg);", "\tif (ret >= 0)\n\t\tmulti_register_ports(&multi_reg);", "\treturn ret;\n}", "static void __exit multi_exit(void)\n{\n\tint i;", "\tfor (i = 0; i < NR_PORTS; i++)\n\t\tmp_remove_one_port(&multi_reg, &multi_ports[i].port);", "\tmp_unregister_driver(&multi_reg);\n}", "module_init(multi_init);\nmodule_exit(multi_exit);", "MODULE_DESCRIPTION(\"SystemBase Multiport PCI/PCIe CORE\");\nMODULE_LICENSE(\"GPL\");" ]
[ 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1067], "buggy_code_start_loc": [1066], "filenames": ["drivers/staging/sb105x/sb_pci_mp.c"], "fixing_code_end_loc": [1067], "fixing_code_start_loc": [1066], "message": "The mp_get_count function in drivers/staging/sb105x/sb_pci_mp.c in the Linux kernel before 3.12 does not initialize a certain data structure, which allows local users to obtain sensitive information from kernel stack memory via a TIOCGICOUNT ioctl call.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "74676759-D357-4224-9C07-7FCAB195A0CD", "versionEndExcluding": null, "versionEndIncluding": "3.11.7", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "D30AEC07-3CBD-4F4F-9646-BEAA1D98750B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc2:*:*:*:*:*:*", "matchCriteriaId": "C2AA8E68-691B-499C-AEDD-3C0BFFE70044", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc3:*:*:*:*:*:*", "matchCriteriaId": "9440475B-5960-4066-A204-F30AAFC87846", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc4:*:*:*:*:*:*", "matchCriteriaId": "53BCFBFB-6AF0-4525-8623-7633CC5E17DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc5:*:*:*:*:*:*", "matchCriteriaId": "6ED4E86A-74F0-436A-BEB4-3F4EE93A5421", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc6:*:*:*:*:*:*", "matchCriteriaId": "BF0365B0-8E16-4F30-BD92-5DD538CC8135", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc7:*:*:*:*:*:*", "matchCriteriaId": "079505E8-2942-4C33-93D1-35ADA4C39E72", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "38989541-2360-4E0A-AE5A-3D6144AA6114", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "4E51646B-7A0E-40F3-B8C9-239C1DA81DD1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "42A8A507-F8E2-491C-A144-B2448A1DB26E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "901FC6F3-2C2A-4112-AE27-AB102BBE8DEE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "203AD334-DB9F-41B0-A4D1-A6C158EF8C40", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.6:*:*:*:*:*:*:*", "matchCriteriaId": "B3611753-E440-410F-8250-600C996A4B8E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "9739BB47-EEAF-42F1-A557-2AE2EA9526A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "5A95E3BB-0AFC-4C2E-B9BE-C975E902A266", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.9:*:*:*:*:*:*:*", "matchCriteriaId": "482A6C9A-9B8E-4D1C-917A-F16370745E7C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.10:*:*:*:*:*:*:*", "matchCriteriaId": "C6D87357-63E0-41D0-9F02-1BCBF9A77E63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.11:*:*:*:*:*:*:*", "matchCriteriaId": "3765A2D6-2D78-4FB1-989E-D5106BFA3F5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.12:*:*:*:*:*:*:*", "matchCriteriaId": "F54257DB-7023-43C4-AC4D-9590B815CD92", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.13:*:*:*:*:*:*:*", "matchCriteriaId": "61FF5FCD-A4A1-4803-AC53-320A4C838AF6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.14:*:*:*:*:*:*:*", "matchCriteriaId": "9F096553-064F-46A2-877B-F32F163A0F49", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.15:*:*:*:*:*:*:*", "matchCriteriaId": "C0D762D1-E3AD-40EA-8D39-83EEB51B5E85", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.16:*:*:*:*:*:*:*", "matchCriteriaId": "A6187D19-7148-4B87-AD7E-244FF9EE0FA6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.17:*:*:*:*:*:*:*", "matchCriteriaId": "99AC64C2-E391-485C-9CD7-BA09C8FA5E63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.18:*:*:*:*:*:*:*", "matchCriteriaId": "8CDA5E95-7805-441B-BEF7-4448EA45E964", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.19:*:*:*:*:*:*:*", "matchCriteriaId": "51561053-6C28-4F38-BC9B-3F7A7508EB72", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.20:*:*:*:*:*:*:*", "matchCriteriaId": "118F4A5B-C498-4FC3-BE28-50D18EBE4F22", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.21:*:*:*:*:*:*:*", "matchCriteriaId": "BD38EBE6-FE1A-4B55-9FB5-07952253B7A5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.22:*:*:*:*:*:*:*", "matchCriteriaId": "3A491E47-82AD-4055-9444-2EC0D6715326", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.23:*:*:*:*:*:*:*", "matchCriteriaId": "13C5FD16-23B6-467F-9438-5B554922F974", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.24:*:*:*:*:*:*:*", "matchCriteriaId": "9C67235F-5B51-4BF7-89EC-4810F720246F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.25:*:*:*:*:*:*:*", "matchCriteriaId": "08405DEF-05F4-45F0-AC95-DBF914A36D93", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.26:*:*:*:*:*:*:*", "matchCriteriaId": "1A7B9C4B-4A41-4175-9F07-191C1EE98C1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.27:*:*:*:*:*:*:*", "matchCriteriaId": "B306E0A8-4D4A-4895-8128-A500D30A7E0C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.28:*:*:*:*:*:*:*", "matchCriteriaId": "295C839A-F34E-4853-A926-55EABC639412", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.29:*:*:*:*:*:*:*", "matchCriteriaId": "2AFD5F49-7EF9-4CFE-95BD-8FD19B500B0A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.30:*:*:*:*:*:*:*", "matchCriteriaId": "00B3DDDD-B2F6-4753-BA38-65A24017857D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.31:*:*:*:*:*:*:*", "matchCriteriaId": "33FCD39E-F4BF-432D-9CF9-F195CF5844F3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.32:*:*:*:*:*:*:*", "matchCriteriaId": "C7308690-CB0D-4758-B80F-D2ADCD2A9D66", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.33:*:*:*:*:*:*:*", "matchCriteriaId": "313A470B-8A2B-478A-82B5-B27D2718331C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.34:*:*:*:*:*:*:*", "matchCriteriaId": "83FF021E-07E3-41CC-AAE8-D99D7FF24B9D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.35:*:*:*:*:*:*:*", "matchCriteriaId": "F72412E3-8DA9-4CC9-A426-B534202ADBA4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.36:*:*:*:*:*:*:*", "matchCriteriaId": "FCAA9D7A-3C3E-4C0B-9D38-EA80E68C2E46", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.37:*:*:*:*:*:*:*", "matchCriteriaId": "4A9E3AE5-3FCF-4CBB-A30B-082BCFBFB0CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.38:*:*:*:*:*:*:*", "matchCriteriaId": "CF715657-4C3A-4392-B85D-1BBF4DE45D89", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.39:*:*:*:*:*:*:*", "matchCriteriaId": "4B63C618-AC3D-4EF7-AFDF-27B9BF482B78", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.40:*:*:*:*:*:*:*", "matchCriteriaId": "C33DA5A9-5E40-4365-9602-82FB4DCD15B2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.41:*:*:*:*:*:*:*", "matchCriteriaId": "EFAFDB74-40BD-46FA-89AC-617EB2C7160B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.42:*:*:*:*:*:*:*", "matchCriteriaId": "CF5F17DA-30A7-40CF-BD7C-CEDF06D64617", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.43:*:*:*:*:*:*:*", "matchCriteriaId": "71A276F5-BD9D-4C1B-90DF-9B0C15B6F7DF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.44:*:*:*:*:*:*:*", "matchCriteriaId": "F8F6EBEC-3C29-444B-BB85-6EF239B59EC1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.45:*:*:*:*:*:*:*", "matchCriteriaId": "FDB91302-FD18-44CF-A8A8-B31483328539", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.46:*:*:*:*:*:*:*", "matchCriteriaId": "9B81DC2B-46FA-4640-AD6C-2A404D94BA0B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.47:*:*:*:*:*:*:*", "matchCriteriaId": "BA6A1663-BC4C-4FC9-B5EB-A52EDED17B26", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.48:*:*:*:*:*:*:*", "matchCriteriaId": "69C33D6C-6B9F-49F4-B505-E7B589CDEC50", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.49:*:*:*:*:*:*:*", "matchCriteriaId": "C464796B-2F31-4159-A132-82A0C74137B7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.50:*:*:*:*:*:*:*", "matchCriteriaId": "1D6C6E46-FE29-4D2D-A0EC-43DA5112BCC3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.51:*:*:*:*:*:*:*", "matchCriteriaId": "1A370E91-73A1-4D62-8E7B-696B920203F8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.52:*:*:*:*:*:*:*", "matchCriteriaId": "340197CD-9645-4B7E-B976-F3F5A7D4C5BE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.53:*:*:*:*:*:*:*", "matchCriteriaId": "96030636-0C4A-4A10-B768-525D6A0E18CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.54:*:*:*:*:*:*:*", "matchCriteriaId": "A42D8419-914F-4AD6-B0E9-C1290D514FF1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.55:*:*:*:*:*:*:*", "matchCriteriaId": "F4E2C88B-42EA-4F4F-B1F6-A9332EC6888B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.56:*:*:*:*:*:*:*", "matchCriteriaId": "2449D13B-3314-4182-832F-03F6B11AA31F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.57:*:*:*:*:*:*:*", "matchCriteriaId": "9A35B66C-F050-4462-A58E-FEE061B5582E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.58:*:*:*:*:*:*:*", "matchCriteriaId": "1B551164-0167-49BB-A3AE-4034BDA3DCB4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.59:*:*:*:*:*:*:*", "matchCriteriaId": "7244278E-49B6-4405-A14C-F3540C8F5AF8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.60:*:*:*:*:*:*:*", "matchCriteriaId": "B4C3E4B8-7274-4ABB-B7CE-6A39C183CE18", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.61:*:*:*:*:*:*:*", "matchCriteriaId": "6501EDB9-4847-47F8-90EE-B295626E4CDC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.62:*:*:*:*:*:*:*", "matchCriteriaId": "2D676D48-7521-45E2-8563-6B966FF86A35", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.63:*:*:*:*:*:*:*", "matchCriteriaId": "3B69FA17-0AB9-4986-A5A7-2A4C1DD24222", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.64:*:*:*:*:*:*:*", "matchCriteriaId": "7BC35593-96C7-41F0-B738-1568F8129121", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.65:*:*:*:*:*:*:*", "matchCriteriaId": "38D23794-0E7C-4FA5-A7A8-CF940E3FA962", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.66:*:*:*:*:*:*:*", "matchCriteriaId": "008E1E7D-4C20-4560-9288-EF532ADB0029", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.67:*:*:*:*:*:*:*", "matchCriteriaId": "3B3A7044-A92E-47A9-A7BD-35E5B575F5FD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.68:*:*:*:*:*:*:*", "matchCriteriaId": "783E2980-B6AB-489E-B157-B6A2E10A32CA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:*:*:*:*:*:*:*", "matchCriteriaId": "3DFFE5A6-6A67-4992-84A3-C0F05FACDEAD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:rc1:*:*:*:*:*:*", "matchCriteriaId": "13BBD2A3-AE10-48B9-8776-4FB1CAC37D44", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:rc2:*:*:*:*:*:*", "matchCriteriaId": "B25680CC-8918-4F27-8D7E-A6579215450B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:rc3:*:*:*:*:*:*", "matchCriteriaId": "92C48B4C-410C-4BA8-A28A-B2E928320FCC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:rc4:*:*:*:*:*:*", "matchCriteriaId": "CB447523-855B-461E-8197-95169BE86EB0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "B155BBDF-6DF6-4FF5-9C41-D8A5266DCC67", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "28476DEC-9630-4B40-9D4D-9BC151DC4CA4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "5646880A-2355-4BDD-89E7-825863A0311F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "7FF99148-267A-46F8-9927-A9082269BAF6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "A783C083-5D9C-48F9-B5A6-A97A9604FB19", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.6:*:*:*:*:*:*:*", "matchCriteriaId": "2B817A24-03AC-46CD-BEFA-505457FD2A5D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.7:*:*:*:*:*:*:*", "matchCriteriaId": "51CF1BCE-090E-4B70-BA16-ACB74411293B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.8:*:*:*:*:*:*:*", "matchCriteriaId": "187AAD67-10D7-4B57-B4C6-00443E246AF3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.9:*:*:*:*:*:*:*", "matchCriteriaId": "F341CE88-C5BC-4CDD-9CB5-B6BAD7152E63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.10:*:*:*:*:*:*:*", "matchCriteriaId": "37ACE2A6-C229-4236-8E9F-235F008F3AA0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:*:*:*:*:*:*:*", "matchCriteriaId": "D3220B70-917F-4F9F-8A3B-2BF581281E8D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:*:*:*:*:*:x86:*", "matchCriteriaId": "7D47A395-821D-4BFF-996E-E849D9A40217", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc2:*:*:*:*:*:*", "matchCriteriaId": "99372D07-C06A-41FA-9843-6D57F99AB5AF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc3:*:*:*:*:*:*", "matchCriteriaId": "2B9DC110-D260-4DB4-B8B0-EF1D160ADA07", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc4:*:*:*:*:*:*", "matchCriteriaId": "6192FE84-4D53-40D4-AF61-78CE7136141A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc5:*:*:*:*:*:*", "matchCriteriaId": "42FEF3CF-1302-45EB-89CC-3786FE4BAC1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc6:*:*:*:*:*:*", "matchCriteriaId": "AE6A6B58-2C89-4DE4-BA57-78100818095C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc7:*:*:*:*:*:*", "matchCriteriaId": "1D467F87-2F13-4D26-9A93-E0BA526FEA24", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "FE348F7B-02DE-47D5-8011-F83DA9426021", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.1:*:*:*:*:*:x86:*", "matchCriteriaId": "8A603291-33B4-4195-B52D-D2A9938089C1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "E91594EA-F0A3-41B3-A9C6-F7864FC2F229", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "9E1ECCDB-0208-48F6-B44F-16CC0ECE3503", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "FBA8B5DE-372E-47E0-A0F6-BE286D509CC3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "9A1CA083-2CF8-45AE-9E15-1AA3A8352E3B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "19D69A49-5290-4C5F-8157-719AD58D253D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "290BD969-42E7-47B0-B21B-06DE4865432C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.8:*:*:*:*:*:*:*", "matchCriteriaId": "23A9E29E-DE78-4C73-9FBD-C2410F5FC8B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.9:*:*:*:*:*:*:*", "matchCriteriaId": "018434C9-E75F-45CB-A169-DAB4B1D864D7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.10:*:*:*:*:*:*:*", "matchCriteriaId": "DC0AC68F-EC58-4C4F-8CBC-A59ECC00CCDE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.11:*:*:*:*:*:*:*", "matchCriteriaId": "C123C844-F6D7-471E-A62E-F756042FB1CD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.12:*:*:*:*:*:*:*", "matchCriteriaId": "A11C38BB-7FA2-49B0-AAC9-83DB387A06DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.13:*:*:*:*:*:*:*", "matchCriteriaId": "61F3733C-E5F6-4855-B471-DF3FB823613B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.14:*:*:*:*:*:*:*", "matchCriteriaId": "1DDCA75F-9A06-4457-9A45-38A38E7F7086", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.15:*:*:*:*:*:*:*", "matchCriteriaId": "7AEA837E-7864-4003-8DB7-111ED710A7E1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.16:*:*:*:*:*:*:*", "matchCriteriaId": "B6FE471F-2D1F-4A1D-A197-7E46B75787E1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.17:*:*:*:*:*:*:*", "matchCriteriaId": "FDA9E6AB-58DC-4EC5-A25C-11F9D0B38BF7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.18:*:*:*:*:*:*:*", "matchCriteriaId": "DC6B8DB3-B05B-41A2-B091-342D66AAE8F5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.19:*:*:*:*:*:*:*", "matchCriteriaId": "958F0FF8-33EF-4A71-A0BD-572C85211DBA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.20:*:*:*:*:*:*:*", "matchCriteriaId": "FBA39F48-B02F-4C48-B304-DA9CCA055244", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.21:*:*:*:*:*:*:*", "matchCriteriaId": "1FF841F3-48A7-41D7-9C45-A8170435A5EB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.22:*:*:*:*:*:*:*", "matchCriteriaId": "EF506916-A6DC-4B1E-90E5-959492AF55F4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.23:*:*:*:*:*:*:*", "matchCriteriaId": "B3CDAD1F-2C6A-48C0-8FAB-C2659373FA25", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.24:*:*:*:*:*:*:*", "matchCriteriaId": "4FFE4B22-C96A-43D0-B993-F51EDD9C5E0E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.25:*:*:*:*:*:*:*", "matchCriteriaId": "F571CC8B-B212-4553-B463-1DB01D616E8A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.26:*:*:*:*:*:*:*", "matchCriteriaId": "84E3E151-D437-48ED-A529-731EEFF88567", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.27:*:*:*:*:*:*:*", "matchCriteriaId": "E9E3EA3C-CCA5-4433-86E0-3D02C4757A0A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.28:*:*:*:*:*:*:*", "matchCriteriaId": "F7AC4F7D-9FA6-4CF1-B2E9-70BF7D4D177C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.29:*:*:*:*:*:*:*", "matchCriteriaId": "3CE3A80D-9648-43CC-8F99-D741ED6552BF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.30:*:*:*:*:*:*:*", "matchCriteriaId": "C8A98C03-A465-41B4-A551-A26FEC7FFD94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:*:*:*:*:*:*:*", "matchCriteriaId": "AFB76697-1C2F-48C0-9B14-517EC053D4B3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc1:*:*:*:*:*:*", "matchCriteriaId": "BED88DFD-1DC5-4505-A441-44ECDEF0252D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc2:*:*:*:*:*:*", "matchCriteriaId": "DBFD2ACD-728A-4082-BB6A-A1EF6E58E47D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc3:*:*:*:*:*:*", "matchCriteriaId": "C31B0E51-F62D-4053-B04F-FC4D5BC373D2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc4:*:*:*:*:*:*", "matchCriteriaId": "A914303E-1CB6-4AAD-9F5F-DE5433C4E814", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc5:*:*:*:*:*:*", "matchCriteriaId": "203BBA69-90B2-4C5E-8023-C14180742421", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc6:*:*:*:*:*:*", "matchCriteriaId": "0DBFAB53-B889-4028-AC0E-7E165B152A18", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc7:*:*:*:*:*:*", "matchCriteriaId": "FE409AEC-F677-4DEF-8EB7-2C35809043CE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "578EC12B-402F-4AD4-B8F8-C9B2CAB06891", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "877002ED-8097-4BB4-BB88-6FC6306C38B2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "76294CE3-D72C-41D5-9E0F-B693D0042699", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "916E97D4-1FAB-42F5-826B-653B1C0909A8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.5:*:*:*:*:*:*:*", "matchCriteriaId": "33FD2217-C5D0-48C1-AD74-3527127FEF9C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "2E92971F-B629-4E0A-9A50-8B235F9704B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.7:*:*:*:*:*:*:*", "matchCriteriaId": "EDD3A069-3829-4EE2-9D5A-29459F29D4C1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.8:*:*:*:*:*:*:*", "matchCriteriaId": "A4A0964C-CEB2-41D7-A69C-1599B05B6171", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:*:*:*:*:*:*:*", "matchCriteriaId": "0F960FA6-F904-4A4E-B483-44C70090E9A1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:*:*:*:*:*:x86:*", "matchCriteriaId": "8C3D9C66-933A-469E-9073-75015A8AD17D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc1:*:*:*:*:*:*", "matchCriteriaId": "261C1B41-C9E0-414F-8368-51C0C0B8AD38", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc1:*:*:*:*:x86:*", "matchCriteriaId": "C92F29A0-DEFF-49E4-AE86-5DBDAD51C677", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc2:*:*:*:*:*:*", "matchCriteriaId": "5CCA261D-2B97-492F-89A0-5F209A804350", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc2:*:*:*:*:x86:*", "matchCriteriaId": "5690A703-390D-4D8A-9258-2F47116DAB4F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc3:*:*:*:*:*:*", "matchCriteriaId": "1B1C0C68-9194-473F-BE5E-EC7F184899FA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc3:*:*:*:*:x86:*", "matchCriteriaId": "AB1EDDA7-15AF-4B45-A931-DFCBB1EEB701", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc4:*:*:*:*:*:*", "matchCriteriaId": "D7A6AC9E-BEA6-44B0-B3B3-F0F94E32424A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc4:*:*:*:*:x86:*", "matchCriteriaId": "952FE0DC-B2ED-4080-BF29-A2C265E83FEF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc5:*:*:*:*:*:*", "matchCriteriaId": "16038328-9399-4B85-B777-BA4757D02C9B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc5:*:*:*:*:x86:*", "matchCriteriaId": "1CE7ABDB-6572-40E8-B952-CBE52C999858", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc6:*:*:*:*:*:*", "matchCriteriaId": "16CA2757-FA8D-43D9-96E8-D3C0EB6E1DEF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc6:*:*:*:*:x86:*", "matchCriteriaId": "0F417186-D1ED-4A31-92B2-83DEDA1AF272", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc7:*:*:*:*:*:*", "matchCriteriaId": "E8CB5481-5EAE-401E-BD7E-D3095CCA9E94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc7:*:*:*:*:x86:*", "matchCriteriaId": "3D4FCFAE-918C-4886-9A17-08A5B94D35F4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.1:*:*:*:*:*:*:*", "matchCriteriaId": "A0F36FAC-141D-476D-84C5-A558C199F904", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.1:*:*:*:*:*:x86:*", "matchCriteriaId": "830D2914-C9FE-406F-AFCE-7A04BB9E2896", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.2:*:*:*:*:*:*:*", "matchCriteriaId": "51D64824-25F6-4761-BD6A-29038A143744", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.2:*:*:*:*:*:x86:*", "matchCriteriaId": "F4B791B5-2EB5-403A-90CC-B219F6277D1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.3:*:*:*:*:*:*:*", "matchCriteriaId": "E284C8A1-740F-454D-A774-99CD3A21B594", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.3:*:*:*:*:*:x86:*", "matchCriteriaId": "2BA5F34D-7490-4B2B-A7E6-8450F9C1FC31", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.4:*:*:*:*:*:*:*", "matchCriteriaId": "C70D72AE-0CBF-4324-9935-57E28EC6279C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.4:*:*:*:*:*:x86:*", "matchCriteriaId": "B803FE64-FC8D-4650-9FB9-FEEED4340416", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.5:*:*:*:*:*:*:*", "matchCriteriaId": "F674B06B-7E86-4E41-9126-8152D0DDABAE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.5:*:*:*:*:*:x86:*", "matchCriteriaId": "4C560A9A-2388-4980-9E88-118C5EB806B7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.6:*:*:*:*:*:*:*", "matchCriteriaId": "7039B3EC-8B22-413E-B582-B4BEC6181241", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.7:*:*:*:*:*:*:*", "matchCriteriaId": "35CF1DD2-80B9-4476-8963-5C3EF52B33F4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.8:*:*:*:*:*:*:*", "matchCriteriaId": "BFB0B05B-A5CE-4B9C-AE7F-83062868D35B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.9:*:*:*:*:*:*:*", "matchCriteriaId": "D166A66E-7454-47EC-BB56-861A9AFEAFE1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.10:*:*:*:*:*:*:*", "matchCriteriaId": "7DA94F50-2A62-4300-BF4D-A342AAE35629", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.11:*:*:*:*:*:*:*", "matchCriteriaId": "252D937B-50DC-444F-AE73-5FCF6203DF27", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.12:*:*:*:*:*:*:*", "matchCriteriaId": "F6D8EE51-02C1-47BC-A92C-0A8ABEFD28FF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.13:*:*:*:*:*:*:*", "matchCriteriaId": "7F20A5D7-3B38-4911-861A-04C8310D5916", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.14:*:*:*:*:*:*:*", "matchCriteriaId": "D472DE3A-71D8-4F40-9DDE-85929A2B047D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.15:*:*:*:*:*:*:*", "matchCriteriaId": "B2AED943-65A8-4FDB-BBD0-CCEF8682A48C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.16:*:*:*:*:*:*:*", "matchCriteriaId": "D4640185-F3D8-4575-A71D-4C889A93DE2C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.17:*:*:*:*:*:*:*", "matchCriteriaId": "144CCF7C-025E-4879-B2E7-ABB8E4390BE5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.18:*:*:*:*:*:*:*", "matchCriteriaId": "B6FAA052-0B2B-40CE-8C98-919B8D08A5ED", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.19:*:*:*:*:*:*:*", "matchCriteriaId": "4B5A53DE-9C83-4A6B-96F3-23C03BF445D9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.20:*:*:*:*:*:*:*", "matchCriteriaId": "063EB879-CB05-4E33-AA90-9E43516839B5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.21:*:*:*:*:*:*:*", "matchCriteriaId": "2D25764F-4B02-4C65-954E-8C7D6632DE00", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.22:*:*:*:*:*:*:*", "matchCriteriaId": "F31F5BF3-CD0A-465C-857F-273841BCD28A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.23:*:*:*:*:*:*:*", "matchCriteriaId": "FF302C8A-079B-42B9-B455-CD9083BFA067", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.24:*:*:*:*:*:*:*", "matchCriteriaId": "744999C0-33D3-4363-B3DB-E0D02CDD3918", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.25:*:*:*:*:*:*:*", "matchCriteriaId": "C2E77A76-2A60-45D8-9337-867BC22C5110", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.26:*:*:*:*:*:*:*", "matchCriteriaId": "C9F4AAE7-C870-46B7-B559-2949737BE777", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.27:*:*:*:*:*:*:*", "matchCriteriaId": "20FA2824-20B0-48B8-BB0A-4904C1D3E8AA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.28:*:*:*:*:*:*:*", "matchCriteriaId": "9F9B347E-61AC-419F-9701-B862BBFA46F2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.29:*:*:*:*:*:*:*", "matchCriteriaId": "989F351C-8B7C-4C1B-AFA2-AE9431576368", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.30:*:*:*:*:*:*:*", "matchCriteriaId": "8D22172A-9FA7-42E0-8451-165D8E47A573", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.31:*:*:*:*:*:*:*", "matchCriteriaId": "CE31624C-94F9-45D8-9B4A-D0028F10602F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.32:*:*:*:*:*:*:*", "matchCriteriaId": "70967A83-28F6-4568-9ADA-6EF232E5BBC2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.5.1:*:*:*:*:*:*:*", "matchCriteriaId": "962B0C45-AB29-4383-AC16-C6E8245D0FF7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.5.2:*:*:*:*:*:*:*", "matchCriteriaId": "A0EE126B-74B2-4F79-BFE1-3DC169F3F9B2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "392075E0-A9C7-4B4A-90F9-7F1ADFF5EFA7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.5.4:*:*:*:*:*:*:*", "matchCriteriaId": "ECC66968-06F0-4874-A95A-A292C36E45C1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.5.5:*:*:*:*:*:*:*", "matchCriteriaId": "5FE986E6-1068-4E1B-8EAB-DF1EAF32B4E3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.5.6:*:*:*:*:*:*:*", "matchCriteriaId": "543E8536-1A8E-4E76-B89F-1B1F9F26FAB8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.5.7:*:*:*:*:*:*:*", "matchCriteriaId": "EC2B45E3-31E1-4B46-85FA-3A84E75B8F84", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6:*:*:*:*:*:*:*", "matchCriteriaId": "DDB8CC75-D3EE-417C-A83D-CB6D666FE595", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.1:*:*:*:*:*:*:*", "matchCriteriaId": "09A072F1-7BEE-4236-ACBB-55DB8FEF4A03", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.2:*:*:*:*:*:*:*", "matchCriteriaId": "E19D5A58-17D6-4502-A57A-70B2F84817A4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.3:*:*:*:*:*:*:*", "matchCriteriaId": "D58BA035-1204-4DFA-98A1-12111FB6222E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.4:*:*:*:*:*:*:*", "matchCriteriaId": "A17F2E87-8EB8-476A-B5B5-9AE5CF53D9FE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.5:*:*:*:*:*:*:*", "matchCriteriaId": "A8CCC101-5852-4299-9B67-EA1B149D58C0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.6:*:*:*:*:*:*:*", "matchCriteriaId": "B8074D32-C252-4AD3-A579-1C5EDDD7014B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.7:*:*:*:*:*:*:*", "matchCriteriaId": "962AA802-8179-4606-AAC0-9363BAEABC9F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.8:*:*:*:*:*:*:*", "matchCriteriaId": "1286C858-D5A2-45F3-86D1-E50FE53FB23C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.9:*:*:*:*:*:*:*", "matchCriteriaId": "5AC4A13E-F560-4D01-98A3-E2A2B82EB25B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.10:*:*:*:*:*:*:*", "matchCriteriaId": "942C462A-5398-4BB9-A792-598682E1FEF2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.11:*:*:*:*:*:*:*", "matchCriteriaId": "B852F7E0-0282-483D-BB4D-18CB7A4F1392", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7:*:*:*:*:*:*:*", "matchCriteriaId": "53ED9A31-99CC-41C8-8B72-5B2A9B49AA6C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.1:*:*:*:*:*:*:*", "matchCriteriaId": "EFD646BC-62F7-47CF-B0BE-768F701F7D9A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.2:*:*:*:*:*:*:*", "matchCriteriaId": "F43D418E-87C1-4C83-9FF1-4F45B4F452DD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.3:*:*:*:*:*:*:*", "matchCriteriaId": "680D0E00-F29A-487C-8770-8E7EAC672B7C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.4:*:*:*:*:*:*:*", "matchCriteriaId": "2DCA96A4-A836-4E94-A39C-3AD3EA1D9611", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.5:*:*:*:*:*:*:*", "matchCriteriaId": "753C05E3-B603-4E36-B9BA-FAEDCBF62A7D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.6:*:*:*:*:*:*:*", "matchCriteriaId": "E385C2E0-B9F1-4564-8E6D-56FD9E762405", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.7:*:*:*:*:*:*:*", "matchCriteriaId": "041335D4-05E1-4004-9381-28AAD5994B47", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.8:*:*:*:*:*:*:*", "matchCriteriaId": "370F2AE5-3DBC-46B9-AC70-F052C9229C00", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.9:*:*:*:*:*:*:*", "matchCriteriaId": "7A971BE3-259D-4494-BBC5-12793D92DB57", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.10:*:*:*:*:*:*:*", "matchCriteriaId": "8E4719A6-FDEA-4714-A830-E23A52AE90BC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.0:*:*:*:*:*:*:*", "matchCriteriaId": "1A6E41FB-38CE-49F2-B796-9A5AA648E73F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.1:*:*:*:*:*:*:*", "matchCriteriaId": "93523FE1-5993-46CB-9299-7C8C1A04E873", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.2:*:*:*:*:*:*:*", "matchCriteriaId": "27ADC356-6BE9-43A3-9E0B-393DC4B1559A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.3:*:*:*:*:*:*:*", "matchCriteriaId": "4F543D23-1774-4D14-A7D1-AD49EDEA94DD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.4:*:*:*:*:*:*:*", "matchCriteriaId": "FC323F58-CA00-4C3C-BA4D-CC2C0A6E5F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.5:*:*:*:*:*:*:*", "matchCriteriaId": "FEA0B2E3-668D-40ED-9D3D-709EB6449F8D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.6:*:*:*:*:*:*:*", "matchCriteriaId": "3431B258-4EC8-4E7F-87BB-4D934880601E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.7:*:*:*:*:*:*:*", "matchCriteriaId": "1B09FA1E-8B28-4F2A-BA7E-8E1C40365970", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.8:*:*:*:*:*:*:*", "matchCriteriaId": "91917120-9D68-41C0-8B5D-85C256BC6200", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.9:*:*:*:*:*:*:*", "matchCriteriaId": "AAD268A0-096C-4C31-BEC5-D47F5149D462", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.10:*:*:*:*:*:*:*", "matchCriteriaId": "32BD2427-C47F-4660-A1D9-448E500EF5B9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.11:*:*:*:*:*:*:*", "matchCriteriaId": "02048CE5-81C7-4DFB-BC40-CE4C86B7E022", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.12:*:*:*:*:*:*:*", "matchCriteriaId": "934D2B37-0575-4A75-B00B-0028316D6DF0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.13:*:*:*:*:*:*:*", "matchCriteriaId": "06754C21-995C-4850-A4DC-F21826C0F8C5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9:rc1:*:*:*:*:*:*", "matchCriteriaId": "42633FF9-FB0C-4095-B4A1-8D623A98683B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9:rc2:*:*:*:*:*:*", "matchCriteriaId": "08C04619-89A2-4B15-82A2-48BCC662C1F1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9:rc3:*:*:*:*:*:*", "matchCriteriaId": "5B039196-7159-476C-876A-C61242CC41DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9:rc4:*:*:*:*:*:*", "matchCriteriaId": "3A9E0457-53C9-44DD-ACFB-31EE1D1E060E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9:rc5:*:*:*:*:*:*", "matchCriteriaId": "BEE406E7-87BA-44BA-BF61-673E6CC44A2F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9:rc6:*:*:*:*:*:*", "matchCriteriaId": "29FBA173-658F-45DC-8205-934CACD67166", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9:rc7:*:*:*:*:*:*", "matchCriteriaId": "139700F0-BA32-40CF-B9DF-C9C450384FDE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.0:*:*:*:*:*:*:*", "matchCriteriaId": "E578085C-3968-4543-BEBA-EE3C3CB4FA02", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.1:*:*:*:*:*:*:*", "matchCriteriaId": "4DCFA441-68FB-4559-A245-FF0B79DE43CA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.2:*:*:*:*:*:*:*", "matchCriteriaId": "8C2508D8-6571-4B81-A0D7-E494CCD039CE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.3:*:*:*:*:*:*:*", "matchCriteriaId": "8B516926-5E86-4C0A-85F3-F64E1FCDA249", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.4:*:*:*:*:*:*:*", "matchCriteriaId": "069D774D-79BE-479F-BF4E-F021AD808114", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.5:*:*:*:*:*:*:*", "matchCriteriaId": "D15B27A9-46E0-4DDF-A00C-29F8F1F18D73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.6:*:*:*:*:*:*:*", "matchCriteriaId": "A381BB4A-28B4-4672-87EE-91B3DDD6C71A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.7:*:*:*:*:*:*:*", "matchCriteriaId": "922F80CF-937D-4FA2-AFF2-6E47FFE9E1E9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.8:*:*:*:*:*:*:*", "matchCriteriaId": "A548ADF4-9E3B-407C-A5ED-05150EB3A185", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.9:*:*:*:*:*:*:*", "matchCriteriaId": "9C623230-4497-41B9-9BD2-7A6CFDD77983", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.10:*:*:*:*:*:*:*", "matchCriteriaId": "C72FA8A6-60A6-4486-A245-7BEF8B2A2711", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.11:*:*:*:*:*:*:*", "matchCriteriaId": "0A498D90-BB99-405E-9FA6-1FBFE179787E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.0:*:*:*:*:*:arm64:*", "matchCriteriaId": "C8409226-20A1-4549-9E11-6D0C3C38DCCE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.1:*:*:*:*:*:*:*", "matchCriteriaId": "D0D32776-8ADB-4E79-846A-C0C99FED19E0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.2:*:*:*:*:*:*:*", "matchCriteriaId": "B7D01673-D13F-487F-81B6-1279C187277E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.3:*:*:*:*:*:*:*", "matchCriteriaId": "ADB27A3E-78E4-40F7-9716-A1099B0D85FB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.4:*:*:*:*:*:*:*", "matchCriteriaId": "16E7136A-A8A6-4BF5-AF5D-AFB5C7A10712", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.5:*:*:*:*:*:*:*", "matchCriteriaId": "6FE127AC-E61D-427A-B998-D60DF5AABA21", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.6:*:*:*:*:*:*:*", "matchCriteriaId": "3819FF99-AEC5-4466-8542-D395419E4308", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.7:*:*:*:*:*:*:*", "matchCriteriaId": "E621FA1A-464B-4D2A-A0D6-EDA475A3709B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.8:*:*:*:*:*:*:*", "matchCriteriaId": "B760B422-EA11-43AB-B6D2-CA54E7229663", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.9:*:*:*:*:*:*:*", "matchCriteriaId": "D2CA7BBC-917C-4F31-A442-465C30444836", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.10:*:*:*:*:*:*:*", "matchCriteriaId": "AE778000-4FD5-4032-86CE-5930EF4CB7C1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.11:*:*:*:*:*:*:*", "matchCriteriaId": "B3344EEB-F037-48FE-81DC-67F6384F7D9A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.12:*:*:*:*:*:*:*", "matchCriteriaId": "0244B0CA-9C67-4F06-BFBA-1F257112AC08", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.13:*:*:*:*:*:*:*", "matchCriteriaId": "2148C13F-4BB0-4D46-A688-F7C726D12497", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.14:*:*:*:*:*:*:*", "matchCriteriaId": "9871AF57-9158-4A41-8340-596B4463289A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.15:*:*:*:*:*:*:*", "matchCriteriaId": "2A875207-DF01-4240-8895-49B62693D27B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.16:*:*:*:*:*:*:*", "matchCriteriaId": "FE04A172-6F3B-4E3B-8D4D-564740FABAAF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.17:*:*:*:*:*:*:*", "matchCriteriaId": "CFEEF8C4-7DC2-4230-B58C-337F39A4DFAF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.18:*:*:*:*:*:*:*", "matchCriteriaId": "9F74DB5C-5096-438C-8C8A-6D337A2FD06A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.11:*:*:*:*:*:*:*", "matchCriteriaId": "639E3A57-A9E7-40E6-8929-81CCC0060EFB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.11.1:*:*:*:*:*:*:*", "matchCriteriaId": "07012ADD-F521-40A8-B067-E87C2238A3D2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.11.2:*:*:*:*:*:*:*", "matchCriteriaId": "3F5FF393-3F89-4274-B82B-F671358072ED", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.11.3:*:*:*:*:*:*:*", "matchCriteriaId": "E348698F-54D1-4F5E-B701-CFAF50881E0A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.11.4:*:*:*:*:*:*:*", "matchCriteriaId": "932205D9-3514-4289-9B55-C7A169276930", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.11.5:*:*:*:*:*:*:*", "matchCriteriaId": "2ECB2D33-F517-480F-8A6F-99D9D6C49596", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.11.6:*:*:*:*:*:*:*", "matchCriteriaId": "D16F68DD-E2D4-4AA4-AB81-3796C2947E37", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The mp_get_count function in drivers/staging/sb105x/sb_pci_mp.c in the Linux kernel before 3.12 does not initialize a certain data structure, which allows local users to obtain sensitive information from kernel stack memory via a TIOCGICOUNT ioctl call."}, {"lang": "es", "value": "La funci\u00f3n mp_get_count de drivers/staging/sb105x/sb_pci_mp.c en el kernel de Linux anterior a la versi\u00f3n 3.12 no inicializa una estructura de datos determinada, lo que permite a usuarios locales obtener informaci\u00f3n sensible desde la memoria de pila del kernel a trav\u00e9s de una llamada TIOCGICOUNT ioctl."}], "evaluatorComment": null, "id": "CVE-2013-4516", "lastModified": "2023-02-13T00:28:58.263", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.9, "confidentialityImpact": "COMPLETE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:C/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2013-11-12T14:35:12.540", "references": [{"source": "secalert@redhat.com", "tags": null, "url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git%3Ba=commit%3Bh=a8b33654b1e3b0c74d4a1fed041c9aae50b3c427"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.openwall.com/lists/oss-security/2013/11/04/22"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.ubuntu.com/usn/USN-2069-1"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.ubuntu.com/usn/USN-2070-1"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.ubuntu.com/usn/USN-2073-1"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.ubuntu.com/usn/USN-2075-1"}, {"source": "secalert@redhat.com", "tags": ["Exploit", "Patch"], "url": "https://github.com/torvalds/linux/commit/a8b33654b1e3b0c74d4a1fed041c9aae50b3c427"}, {"source": "secalert@redhat.com", "tags": ["Patch"], "url": "https://www.kernel.org/pub/linux/kernel/v3.x/patch-3.12.bz2"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-200"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/a8b33654b1e3b0c74d4a1fed041c9aae50b3c427"}, "type": "CWE-200"}
182
Determine whether the {function_name} code is vulnerable or not.
[ "#include \"sb_pci_mp.h\"\n#include <linux/module.h>\n#include <linux/parport.h>", "extern struct parport *parport_pc_probe_port(unsigned long base_lo,\n\t\tunsigned long base_hi,\n\t\tint irq, int dma,\n\t\tstruct device *dev,\n\t\tint irqflags);", "static struct mp_device_t mp_devs[MAX_MP_DEV];\nstatic int mp_nrpcibrds = sizeof(mp_pciboards)/sizeof(mppcibrd_t);\nstatic int NR_BOARD=0;\nstatic int NR_PORTS=0;\nstatic struct mp_port multi_ports[MAX_MP_PORT];\nstatic struct irq_info irq_lists[NR_IRQS];", "static _INLINE_ unsigned int serial_in(struct mp_port *mtpt, int offset);\nstatic _INLINE_ void serial_out(struct mp_port *mtpt, int offset, int value);\nstatic _INLINE_ unsigned int read_option_register(struct mp_port *mtpt, int offset);\nstatic int sb1054_get_register(struct sb_uart_port *port, int page, int reg);\nstatic int sb1054_set_register(struct sb_uart_port *port, int page, int reg, int value);\nstatic void SendATCommand(struct mp_port *mtpt);\nstatic int set_deep_fifo(struct sb_uart_port *port, int status);\nstatic int get_deep_fifo(struct sb_uart_port *port);\nstatic int get_device_type(int arg);\nstatic int set_auto_rts(struct sb_uart_port *port, int status);\nstatic void mp_stop(struct tty_struct *tty);\nstatic void __mp_start(struct tty_struct *tty);\nstatic void mp_start(struct tty_struct *tty);\nstatic void mp_tasklet_action(unsigned long data);\nstatic inline void mp_update_mctrl(struct sb_uart_port *port, unsigned int set, unsigned int clear);\nstatic int mp_startup(struct sb_uart_state *state, int init_hw);\nstatic void mp_shutdown(struct sb_uart_state *state);\nstatic void mp_change_speed(struct sb_uart_state *state, struct MP_TERMIOS *old_termios);", "static inline int __mp_put_char(struct sb_uart_port *port, struct circ_buf *circ, unsigned char c);\nstatic int mp_put_char(struct tty_struct *tty, unsigned char ch);", "static void mp_put_chars(struct tty_struct *tty);\nstatic int mp_write(struct tty_struct *tty, const unsigned char *buf, int count);\nstatic int mp_write_room(struct tty_struct *tty);\nstatic int mp_chars_in_buffer(struct tty_struct *tty);\nstatic void mp_flush_buffer(struct tty_struct *tty);\nstatic void mp_send_xchar(struct tty_struct *tty, char ch);\nstatic void mp_throttle(struct tty_struct *tty);\nstatic void mp_unthrottle(struct tty_struct *tty);\nstatic int mp_get_info(struct sb_uart_state *state, struct serial_struct *retinfo);\nstatic int mp_set_info(struct sb_uart_state *state, struct serial_struct *newinfo);\nstatic int mp_get_lsr_info(struct sb_uart_state *state, unsigned int *value);", "static int mp_tiocmget(struct tty_struct *tty);\nstatic int mp_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear);\nstatic int mp_break_ctl(struct tty_struct *tty, int break_state);\nstatic int mp_do_autoconfig(struct sb_uart_state *state);\nstatic int mp_wait_modem_status(struct sb_uart_state *state, unsigned long arg);\nstatic int mp_get_count(struct sb_uart_state *state, struct serial_icounter_struct *icnt);\nstatic int mp_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg);\nstatic void mp_set_termios(struct tty_struct *tty, struct MP_TERMIOS *old_termios);\nstatic void mp_close(struct tty_struct *tty, struct file *filp);\nstatic void mp_wait_until_sent(struct tty_struct *tty, int timeout);\nstatic void mp_hangup(struct tty_struct *tty);\nstatic void mp_update_termios(struct sb_uart_state *state);\nstatic int mp_block_til_ready(struct file *filp, struct sb_uart_state *state);\nstatic struct sb_uart_state *uart_get(struct uart_driver *drv, int line);\nstatic int mp_open(struct tty_struct *tty, struct file *filp);\nstatic const char *mp_type(struct sb_uart_port *port);\nstatic void mp_change_pm(struct sb_uart_state *state, int pm_state);\nstatic inline void mp_report_port(struct uart_driver *drv, struct sb_uart_port *port);\nstatic void mp_configure_port(struct uart_driver *drv, struct sb_uart_state *state, struct sb_uart_port *port);\nstatic void mp_unconfigure_port(struct uart_driver *drv, struct sb_uart_state *state);\nstatic int mp_register_driver(struct uart_driver *drv);\nstatic void mp_unregister_driver(struct uart_driver *drv);\nstatic int mp_add_one_port(struct uart_driver *drv, struct sb_uart_port *port);\nstatic int mp_remove_one_port(struct uart_driver *drv, struct sb_uart_port *port);\nstatic void autoconfig(struct mp_port *mtpt, unsigned int probeflags);\nstatic void autoconfig_irq(struct mp_port *mtpt);\nstatic void multi_stop_tx(struct sb_uart_port *port);\nstatic void multi_start_tx(struct sb_uart_port *port);\nstatic void multi_stop_rx(struct sb_uart_port *port);\nstatic void multi_enable_ms(struct sb_uart_port *port);\nstatic _INLINE_ void receive_chars(struct mp_port *mtpt, int *status );\nstatic _INLINE_ void transmit_chars(struct mp_port *mtpt);\nstatic _INLINE_ void check_modem_status(struct mp_port *mtpt);\nstatic inline void multi_handle_port(struct mp_port *mtpt);\nstatic irqreturn_t multi_interrupt(int irq, void *dev_id);\nstatic void serial_do_unlink(struct irq_info *i, struct mp_port *mtpt);\nstatic int serial_link_irq_chain(struct mp_port *mtpt);\nstatic void serial_unlink_irq_chain(struct mp_port *mtpt);\nstatic void multi_timeout(unsigned long data);\nstatic unsigned int multi_tx_empty(struct sb_uart_port *port);\nstatic unsigned int multi_get_mctrl(struct sb_uart_port *port);\nstatic void multi_set_mctrl(struct sb_uart_port *port, unsigned int mctrl);\nstatic void multi_break_ctl(struct sb_uart_port *port, int break_state);\nstatic int multi_startup(struct sb_uart_port *port);\nstatic void multi_shutdown(struct sb_uart_port *port);\nstatic unsigned int multi_get_divisor(struct sb_uart_port *port, unsigned int baud);\nstatic void multi_set_termios(struct sb_uart_port *port, struct MP_TERMIOS *termios, struct MP_TERMIOS *old);\nstatic void multi_pm(struct sb_uart_port *port, unsigned int state, unsigned int oldstate);\nstatic void multi_release_std_resource(struct mp_port *mtpt);\nstatic void multi_release_port(struct sb_uart_port *port);\nstatic int multi_request_port(struct sb_uart_port *port);\nstatic void multi_config_port(struct sb_uart_port *port, int flags);\nstatic int multi_verify_port(struct sb_uart_port *port, struct serial_struct *ser);\nstatic const char *multi_type(struct sb_uart_port *port);\nstatic void __init multi_init_ports(void);\nstatic void __init multi_register_ports(struct uart_driver *drv);\nstatic int init_mp_dev(struct pci_dev *pcidev, mppcibrd_t brd);", "static int deep[256];\nstatic int deep_count;\nstatic int fcr_arr[256];\nstatic int fcr_count;\nstatic int ttr[256];\nstatic int ttr_count;\nstatic int rtr[256];\nstatic int rtr_count;", "module_param_array(deep,int,&deep_count,0);\nmodule_param_array(fcr_arr,int,&fcr_count,0);\nmodule_param_array(ttr,int,&ttr_count,0);\nmodule_param_array(rtr,int,&rtr_count,0);", "static _INLINE_ unsigned int serial_in(struct mp_port *mtpt, int offset)\n{\n\treturn inb(mtpt->port.iobase + offset);\n}", "static _INLINE_ void serial_out(struct mp_port *mtpt, int offset, int value)\n{\n\toutb(value, mtpt->port.iobase + offset);\n}", "static _INLINE_ unsigned int read_option_register(struct mp_port *mtpt, int offset)\n{\n\treturn inb(mtpt->option_base_addr + offset);\n}", "static int sb1053a_get_interface(struct mp_port *mtpt, int port_num)\n{\n\tunsigned long option_base_addr = mtpt->option_base_addr;\n\tunsigned int interface = 0;", "\tswitch (port_num)\n\t{\n\t\tcase 0:\n\t\tcase 1:\n\t\t\t/* set GPO[1:0] = 00 */\n\t\t\toutb(0x00, option_base_addr + MP_OPTR_GPODR);\n\t\t\tbreak;\n\t\tcase 2:\n\t\tcase 3:\n\t\t\t/* set GPO[1:0] = 01 */\n\t\t\toutb(0x01, option_base_addr + MP_OPTR_GPODR);\n\t\t\tbreak;\n\t\tcase 4:\n\t\tcase 5:\n\t\t\t/* set GPO[1:0] = 10 */\n\t\t\toutb(0x02, option_base_addr + MP_OPTR_GPODR);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}", "\tport_num &= 0x1;", "\t/* get interface */\n\tinterface = inb(option_base_addr + MP_OPTR_IIR0 + port_num);", "\t/* set GPO[1:0] = 11 */\n\toutb(0x03, option_base_addr + MP_OPTR_GPODR);", "\treturn (interface);\n}\n\t\t\nstatic int sb1054_get_register(struct sb_uart_port *port, int page, int reg)\n{\n\tint ret = 0;\n\tunsigned int lcr = 0;\n\tunsigned int mcr = 0;\n\tunsigned int tmp = 0;", "\tif( page <= 0)\n\t{\n\t\tprintk(\" page 0 can not use this fuction\\n\");\n\t\treturn -1;\n\t}", "\tswitch(page)\n\t{\n\t\tcase 1:\n\t\t\tlcr = SB105X_GET_LCR(port);\n\t\t\ttmp = lcr | SB105X_LCR_DLAB;\n\t\t\tSB105X_PUT_LCR(port, tmp);", "\t\t\ttmp = SB105X_GET_LCR(port);", "\t\t\tret = SB105X_GET_REG(port,reg);\n\t\t\tSB105X_PUT_LCR(port,lcr);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tmcr = SB105X_GET_MCR(port);\n\t\t\ttmp = mcr | SB105X_MCR_P2S;\n\t\t\tSB105X_PUT_MCR(port,tmp);", "\t\t\tret = SB105X_GET_REG(port,reg);", "\t\t\tSB105X_PUT_MCR(port,mcr);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tlcr = SB105X_GET_LCR(port);\n\t\t\ttmp = lcr | SB105X_LCR_BF;\n\t\t\tSB105X_PUT_LCR(port,tmp);\n\t\t\tSB105X_PUT_REG(port,SB105X_PSR,SB105X_PSR_P3KEY);", "\t\t\tret = SB105X_GET_REG(port,reg);", "\t\t\tSB105X_PUT_LCR(port,lcr);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tlcr = SB105X_GET_LCR(port);\n\t\t\ttmp = lcr | SB105X_LCR_BF;\n\t\t\tSB105X_PUT_LCR(port,tmp);\n\t\t\tSB105X_PUT_REG(port,SB105X_PSR,SB105X_PSR_P4KEY);", "\t\t\tret = SB105X_GET_REG(port,reg);", "\t\t\tSB105X_PUT_LCR(port,lcr);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tprintk(\" error invalid page number \\n\");\n\t\t\treturn -1;\n\t}", "\treturn ret;\n}", "static int sb1054_set_register(struct sb_uart_port *port, int page, int reg, int value)\n{ \n\tint lcr = 0;\n\tint mcr = 0;\n\tint ret = 0;", "\tif( page <= 0)\n\t{\n\t\tprintk(\" page 0 can not use this fuction\\n\");\n\t\treturn -1;\n\t}\n\tswitch(page)\n\t{\n\t\tcase 1:\n\t\t\tlcr = SB105X_GET_LCR(port);\n\t\t\tSB105X_PUT_LCR(port, lcr | SB105X_LCR_DLAB);", "\t\t\tSB105X_PUT_REG(port,reg,value);", "\t\t\tSB105X_PUT_LCR(port, lcr);\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tmcr = SB105X_GET_MCR(port);\n\t\t\tSB105X_PUT_MCR(port, mcr | SB105X_MCR_P2S);", "\t\t\tSB105X_PUT_REG(port,reg,value);", "\t\t\tSB105X_PUT_MCR(port, mcr);\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tlcr = SB105X_GET_LCR(port);\n\t\t\tSB105X_PUT_LCR(port, lcr | SB105X_LCR_BF);\n\t\t\tSB105X_PUT_PSR(port, SB105X_PSR_P3KEY);", "\t\t\tSB105X_PUT_REG(port,reg,value);", "\t\t\tSB105X_PUT_LCR(port, lcr);\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tlcr = SB105X_GET_LCR(port);\n\t\t\tSB105X_PUT_LCR(port, lcr | SB105X_LCR_BF);\n\t\t\tSB105X_PUT_PSR(port, SB105X_PSR_P4KEY);", "\t\t\tSB105X_PUT_REG(port,reg,value);", "\t\t\tSB105X_PUT_LCR(port, lcr);\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tprintk(\" error invalid page number \\n\");\n\t\t\treturn -1;\n\t}", "\treturn ret;\n}", "static int set_multidrop_mode(struct sb_uart_port *port, unsigned int mode)\n{\n\tint mdr = SB105XA_MDR_NPS;", "\tif (mode & MDMODE_ENABLE)\n\t{\n\t\tmdr |= SB105XA_MDR_MDE;\n\t}", "\tif (1) //(mode & MDMODE_AUTO)\n\t{\n\t\tint efr = 0;\n\t\tmdr |= SB105XA_MDR_AME;\n\t\tefr = sb1054_get_register(port, PAGE_3, SB105X_EFR);\n\t\tefr |= SB105X_EFR_SCD;\n\t\tsb1054_set_register(port, PAGE_3, SB105X_EFR, efr);\n\t}", "\tsb1054_set_register(port, PAGE_1, SB105XA_MDR, mdr);\n\tport->mdmode &= ~0x6;\n\tport->mdmode |= mode;\n\tprintk(\"[%d] multidrop init: %x\\n\", port->line, port->mdmode);", "\treturn 0;\n}", "static int get_multidrop_addr(struct sb_uart_port *port)\n{\n\treturn sb1054_get_register(port, PAGE_3, SB105X_XOFF2);\n}", "static int set_multidrop_addr(struct sb_uart_port *port, unsigned int addr)\n{\n\tsb1054_set_register(port, PAGE_3, SB105X_XOFF2, addr);", "\treturn 0;\n}", "static void SendATCommand(struct mp_port *mtpt)\n{\n\t//\t\t a t\tcr lf\n\tunsigned char ch[] = {0x61,0x74,0x0d,0x0a,0x0};\n\tunsigned char lineControl;\n\tunsigned char i=0;\n\tunsigned char Divisor = 0xc;", "\tlineControl = serial_inp(mtpt,UART_LCR);\n\tserial_outp(mtpt,UART_LCR,(lineControl | UART_LCR_DLAB));\n\tserial_outp(mtpt,UART_DLL,(Divisor & 0xff));\n\tserial_outp(mtpt,UART_DLM,(Divisor & 0xff00)>>8); //baudrate is 4800", "\n\tserial_outp(mtpt,UART_LCR,lineControl);\t\n\tserial_outp(mtpt,UART_LCR,0x03); // N-8-1\n\tserial_outp(mtpt,UART_FCR,7); \n\tserial_outp(mtpt,UART_MCR,0x3);\n\twhile(ch[i]){\n\t\twhile((serial_inp(mtpt,UART_LSR) & 0x60) !=0x60){\n\t\t\t;\n\t\t}\n\t\tserial_outp(mtpt,0,ch[i++]);\n\t}", "\n}// end of SendATCommand()", "static int set_deep_fifo(struct sb_uart_port *port, int status)\n{\n\tint afr_status = 0;\n\tafr_status = sb1054_get_register(port, PAGE_4, SB105X_AFR);", "\tif(status == ENABLE)\n\t{\n\t\tafr_status |= SB105X_AFR_AFEN;\n\t}\n\telse\n\t{\n\t\tafr_status &= ~SB105X_AFR_AFEN;\n\t}\n\t\t\n\tsb1054_set_register(port,PAGE_4,SB105X_AFR,afr_status);\n\tsb1054_set_register(port,PAGE_4,SB105X_TTR,ttr[port->line]); \n\tsb1054_set_register(port,PAGE_4,SB105X_RTR,rtr[port->line]); \n\tafr_status = sb1054_get_register(port, PAGE_4, SB105X_AFR);\n\t\t\n\treturn afr_status;\n}", "static int get_device_type(int arg)\n{\n\tint ret;\n ret = inb(mp_devs[arg].option_reg_addr+MP_OPTR_DIR0);\n ret = (ret & 0xf0) >> 4;\n switch (ret)\n {\n case DIR_UART_16C550:\n return PORT_16C55X;\n case DIR_UART_16C1050:\n return PORT_16C105X;\n case DIR_UART_16C1050A:\n /*\n if (mtpt->port.line < 2)\n {\n return PORT_16C105XA;\n }\n else\n {\n if (mtpt->device->device_id & 0x50)\n {\n return PORT_16C55X;\n }\n else\n {\n return PORT_16C105X;\n }\n }*/\n return PORT_16C105XA;\n default:\n return PORT_UNKNOWN;\n }", "}\nstatic int get_deep_fifo(struct sb_uart_port *port)\n{\n\tint afr_status = 0;\n\tafr_status = sb1054_get_register(port, PAGE_4, SB105X_AFR);\n\treturn afr_status;\n}", "static int set_auto_rts(struct sb_uart_port *port, int status)\n{\n\tint atr_status = 0;", "#if 0\n\tint efr_status = 0;", "\tefr_status = sb1054_get_register(port, PAGE_3, SB105X_EFR);\n\tif(status == ENABLE)\n\t\tefr_status |= SB105X_EFR_ARTS;\n\telse\n\t\tefr_status &= ~SB105X_EFR_ARTS;\n\tsb1054_set_register(port,PAGE_3,SB105X_EFR,efr_status);\n\tefr_status = sb1054_get_register(port, PAGE_3, SB105X_EFR);\n#endif\n\t\t\n//ATR\n\tatr_status = sb1054_get_register(port, PAGE_3, SB105X_ATR);\n\tswitch(status)\n\t{\n\t\tcase RS422PTP:\n\t\t\tatr_status = (SB105X_ATR_TPS) | (SB105X_ATR_A80);\n\t\t\tbreak;\n\t\tcase RS422MD:\n\t\t\tatr_status = (SB105X_ATR_TPS) | (SB105X_ATR_TCMS) | (SB105X_ATR_A80);\n\t\t\tbreak;\n\t\tcase RS485NE:\n\t\t\tatr_status = (SB105X_ATR_RCMS) | (SB105X_ATR_TPS) | (SB105X_ATR_TCMS) | (SB105X_ATR_A80);\n\t\t\tbreak;\n\t\tcase RS485ECHO:\n\t\t\tatr_status = (SB105X_ATR_TPS) | (SB105X_ATR_TCMS) | (SB105X_ATR_A80);\n\t\t\tbreak;\n\t}", "\tsb1054_set_register(port,PAGE_3,SB105X_ATR,atr_status);\n\tatr_status = sb1054_get_register(port, PAGE_3, SB105X_ATR);", "\treturn atr_status;\n}", "static void mp_stop(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port = state->port;\n\tunsigned long flags;", "\tspin_lock_irqsave(&port->lock, flags);\n\tport->ops->stop_tx(port);\n\tspin_unlock_irqrestore(&port->lock, flags);\n}", "static void __mp_start(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port = state->port;", "\tif (!uart_circ_empty(&state->info->xmit) && state->info->xmit.buf &&\n\t\t\t!tty->stopped && !tty->hw_stopped)\n\t\tport->ops->start_tx(port);\n}", "static void mp_start(struct tty_struct *tty)\n{\n\t__mp_start(tty);\n}", "static void mp_tasklet_action(unsigned long data)\n{\n\tstruct sb_uart_state *state = (struct sb_uart_state *)data;\n\tstruct tty_struct *tty;", "\tprintk(\"tasklet is called!\\n\");\n\ttty = state->info->tty;\n\ttty_wakeup(tty);\n}", "static inline void mp_update_mctrl(struct sb_uart_port *port, unsigned int set, unsigned int clear)\n{\n\tunsigned int old;", "\told = port->mctrl;\n\tport->mctrl = (old & ~clear) | set;\n\tif (old != port->mctrl)\n\t\tport->ops->set_mctrl(port, port->mctrl);\n}", "#define uart_set_mctrl(port,set)\tmp_update_mctrl(port,set,0)\n#define uart_clear_mctrl(port,clear)\tmp_update_mctrl(port,0,clear)", "static int mp_startup(struct sb_uart_state *state, int init_hw)\n{\n\tstruct sb_uart_info *info = state->info;\n\tstruct sb_uart_port *port = state->port;\n\tunsigned long page;\n\tint retval = 0;", "\tif (info->flags & UIF_INITIALIZED)\n\t\treturn 0;", "\tif (info->tty)\n\t\tset_bit(TTY_IO_ERROR, &info->tty->flags);", "\tif (port->type == PORT_UNKNOWN)\n\t\treturn 0;", "\tif (!info->xmit.buf) {\n\t\tpage = get_zeroed_page(GFP_KERNEL);\n\t\tif (!page)\n\t\t\treturn -ENOMEM;", "\t\tinfo->xmit.buf = (unsigned char *) page;\n\t\t\t\n\t\tuart_circ_clear(&info->xmit);\n\t}", "\tretval = port->ops->startup(port);\n\tif (retval == 0) {\n\t\tif (init_hw) {\n\t\t\tmp_change_speed(state, NULL);", "\t\t\tif (info->tty->termios.c_cflag & CBAUD)\n\t\t\t\tuart_set_mctrl(port, TIOCM_RTS | TIOCM_DTR);\n\t\t}", "\t\tinfo->flags |= UIF_INITIALIZED;", "\n\t\tclear_bit(TTY_IO_ERROR, &info->tty->flags);\n\t}", "\tif (retval && capable(CAP_SYS_ADMIN))\n\t\tretval = 0;", "\treturn retval;\n}", "static void mp_shutdown(struct sb_uart_state *state)\n{\n\tstruct sb_uart_info *info = state->info;\n\tstruct sb_uart_port *port = state->port;", "\tif (info->tty)\n\t\tset_bit(TTY_IO_ERROR, &info->tty->flags);", "\tif (info->flags & UIF_INITIALIZED) {\n\t\tinfo->flags &= ~UIF_INITIALIZED;", "\t\tif (!info->tty || (info->tty->termios.c_cflag & HUPCL))\n\t\t\tuart_clear_mctrl(port, TIOCM_DTR | TIOCM_RTS);", "\t\twake_up_interruptible(&info->delta_msr_wait);", "\t\tport->ops->shutdown(port);", "\t\tsynchronize_irq(port->irq);\n\t}\n\ttasklet_kill(&info->tlet);", "\tif (info->xmit.buf) {\n\t\tfree_page((unsigned long)info->xmit.buf);\n\t\tinfo->xmit.buf = NULL;\n\t}\n}", "static void mp_change_speed(struct sb_uart_state *state, struct MP_TERMIOS *old_termios)\n{\n\tstruct tty_struct *tty = state->info->tty;\n\tstruct sb_uart_port *port = state->port;", "\tif (!tty || port->type == PORT_UNKNOWN)\n\t\treturn;", "\tif (tty->termios.c_cflag & CRTSCTS)\n\t\tstate->info->flags |= UIF_CTS_FLOW;\n\telse\n\t\tstate->info->flags &= ~UIF_CTS_FLOW;", "\tif (tty->termios.c_cflag & CLOCAL)\n\t\tstate->info->flags &= ~UIF_CHECK_CD;\n\telse\n\t\tstate->info->flags |= UIF_CHECK_CD;", "\tport->ops->set_termios(port, &tty->termios, old_termios);\n}", "static inline int __mp_put_char(struct sb_uart_port *port, struct circ_buf *circ, unsigned char c)\n{\n\tunsigned long flags;\n\tint ret = 0;", "\tif (!circ->buf)\n\t\treturn 0;", "\tspin_lock_irqsave(&port->lock, flags);\n\tif (uart_circ_chars_free(circ) != 0) {\n\t\tcirc->buf[circ->head] = c;\n\t\tcirc->head = (circ->head + 1) & (UART_XMIT_SIZE - 1);\n\t\tret = 1;\n\t}\n\tspin_unlock_irqrestore(&port->lock, flags);\n\treturn ret;\n}", "static int mp_put_char(struct tty_struct *tty, unsigned char ch)\n{\n\tstruct sb_uart_state *state = tty->driver_data;", "\treturn __mp_put_char(state->port, &state->info->xmit, ch);\n}", "static void mp_put_chars(struct tty_struct *tty)\n{\n\tmp_start(tty);\n}", "static int mp_write(struct tty_struct *tty, const unsigned char *buf, int count)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port;\n\tstruct circ_buf *circ;\n\tint c, ret = 0;", "\tif (!state || !state->info) {\n\t\treturn -EL3HLT;\n\t}", "\tport = state->port;\n\tcirc = &state->info->xmit;", "\tif (!circ->buf)\n\t\treturn 0;\n\t\t\n\twhile (1) {\n\t\tc = CIRC_SPACE_TO_END(circ->head, circ->tail, UART_XMIT_SIZE);\n\t\tif (count < c)\n\t\t\tc = count;\n\t\tif (c <= 0)\n\t\t\tbreak;\n\tmemcpy(circ->buf + circ->head, buf, c);", "\t\tcirc->head = (circ->head + c) & (UART_XMIT_SIZE - 1);\n\t\tbuf += c;\n\t\tcount -= c;\n\t\tret += c;\n\t}\n\tmp_start(tty);\n\treturn ret;\n}", "static int mp_write_room(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;", "\treturn uart_circ_chars_free(&state->info->xmit);\n}", "static int mp_chars_in_buffer(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;", "\treturn uart_circ_chars_pending(&state->info->xmit);\n}", "static void mp_flush_buffer(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port;\n\tunsigned long flags;", "\tif (!state || !state->info) {\n\t\treturn;\n\t}", "\tport = state->port;\n\tspin_lock_irqsave(&port->lock, flags);\n\tuart_circ_clear(&state->info->xmit);\n\tspin_unlock_irqrestore(&port->lock, flags);\n\twake_up_interruptible(&tty->write_wait);\n\ttty_wakeup(tty);\n}", "static void mp_send_xchar(struct tty_struct *tty, char ch)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port = state->port;\n\tunsigned long flags;", "\tif (port->ops->send_xchar)\n\t\tport->ops->send_xchar(port, ch);\n\telse {\n\t\tport->x_char = ch;\n\t\tif (ch) {\n\t\t\tspin_lock_irqsave(&port->lock, flags);\n\t\t\tport->ops->start_tx(port);\n\t\t\tspin_unlock_irqrestore(&port->lock, flags);\n\t\t}\n\t}\n}", "static void mp_throttle(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;", "\tif (I_IXOFF(tty))\n\t\tmp_send_xchar(tty, STOP_CHAR(tty));", "\tif (tty->termios.c_cflag & CRTSCTS)\n\t\tuart_clear_mctrl(state->port, TIOCM_RTS);\n}", "static void mp_unthrottle(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port = state->port;", "\tif (I_IXOFF(tty)) {\n\t\tif (port->x_char)\n\t\t\tport->x_char = 0;\n\t\telse\n\t\t\tmp_send_xchar(tty, START_CHAR(tty));\n\t}", "\tif (tty->termios.c_cflag & CRTSCTS)\n\t\tuart_set_mctrl(port, TIOCM_RTS);\n}", "static int mp_get_info(struct sb_uart_state *state, struct serial_struct *retinfo)\n{\n\tstruct sb_uart_port *port = state->port;\n\tstruct serial_struct tmp;", "\tmemset(&tmp, 0, sizeof(tmp));\n\ttmp.type\t = port->type;\n\ttmp.line\t = port->line;\n\ttmp.port\t = port->iobase;\n\tif (HIGH_BITS_OFFSET)\n\t\ttmp.port_high = (long) port->iobase >> HIGH_BITS_OFFSET;\n\ttmp.irq\t\t = port->irq;\n\ttmp.flags\t = port->flags;\n\ttmp.xmit_fifo_size = port->fifosize;\n\ttmp.baud_base\t = port->uartclk / 16;\n\ttmp.close_delay\t = state->close_delay;\n\ttmp.closing_wait = state->closing_wait == USF_CLOSING_WAIT_NONE ?\n\t\tASYNC_CLOSING_WAIT_NONE :\n\t\tstate->closing_wait;\n\ttmp.custom_divisor = port->custom_divisor;\n\ttmp.hub6\t = port->hub6;\n\ttmp.io_type = port->iotype;\n\ttmp.iomem_reg_shift = port->regshift;\n\ttmp.iomem_base = (void *)port->mapbase;", "\tif (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))\n\t\treturn -EFAULT;\n\treturn 0;\n}", "static int mp_set_info(struct sb_uart_state *state, struct serial_struct *newinfo)\n{\n\tstruct serial_struct new_serial;\n\tstruct sb_uart_port *port = state->port;\n\tunsigned long new_port;\n\tunsigned int change_irq, change_port, closing_wait;\n\tunsigned int old_custom_divisor;\n\tunsigned int old_flags, new_flags;\n\tint retval = 0;", "\tif (copy_from_user(&new_serial, newinfo, sizeof(new_serial)))\n\t\treturn -EFAULT;", "\tnew_port = new_serial.port;\n\tif (HIGH_BITS_OFFSET)\n\t\tnew_port += (unsigned long) new_serial.port_high << HIGH_BITS_OFFSET;", "\tnew_serial.irq = irq_canonicalize(new_serial.irq);", "\tclosing_wait = new_serial.closing_wait == ASYNC_CLOSING_WAIT_NONE ?\n\t\tUSF_CLOSING_WAIT_NONE : new_serial.closing_wait;\n\tMP_STATE_LOCK(state);", "\tchange_irq = new_serial.irq != port->irq;\n\tchange_port = new_port != port->iobase ||\n\t\t(unsigned long)new_serial.iomem_base != port->mapbase ||\n\t\tnew_serial.hub6 != port->hub6 ||\n\t\tnew_serial.io_type != port->iotype ||\n\t\tnew_serial.iomem_reg_shift != port->regshift ||\n\t\tnew_serial.type != port->type;\n\told_flags = port->flags;\n\tnew_flags = new_serial.flags;\n\told_custom_divisor = port->custom_divisor;", "\tif (!capable(CAP_SYS_ADMIN)) {\n\t\tretval = -EPERM;\n\t\tif (change_irq || change_port ||\n\t\t\t\t(new_serial.baud_base != port->uartclk / 16) ||\n\t\t\t\t(new_serial.close_delay != state->close_delay) ||\n\t\t\t\t(closing_wait != state->closing_wait) ||\n\t\t\t\t(new_serial.xmit_fifo_size != port->fifosize) ||\n\t\t\t\t(((new_flags ^ old_flags) & ~UPF_USR_MASK) != 0))\n\t\t\tgoto exit;\n\t\tport->flags = ((port->flags & ~UPF_USR_MASK) |\n\t\t\t\t(new_flags & UPF_USR_MASK));\n\t\tport->custom_divisor = new_serial.custom_divisor;\n\t\tgoto check_and_exit;\n\t}", "\tif (port->ops->verify_port)\n\t\tretval = port->ops->verify_port(port, &new_serial);", "\tif ((new_serial.irq >= NR_IRQS) || (new_serial.irq < 0) ||\n\t\t\t(new_serial.baud_base < 9600))\n\t\tretval = -EINVAL;", "\tif (retval)\n\t\tgoto exit;", "\tif (change_port || change_irq) {\n\t\tretval = -EBUSY;", "\t\tif (uart_users(state) > 1)\n\t\t\tgoto exit;", "\t\tmp_shutdown(state);\n\t}", "\tif (change_port) {\n\t\tunsigned long old_iobase, old_mapbase;\n\t\tunsigned int old_type, old_iotype, old_hub6, old_shift;", "\t\told_iobase = port->iobase;\n\t\told_mapbase = port->mapbase;\n\t\told_type = port->type;\n\t\told_hub6 = port->hub6;\n\t\told_iotype = port->iotype;\n\t\told_shift = port->regshift;", "\t\tif (old_type != PORT_UNKNOWN)\n\t\t\tport->ops->release_port(port);", "\t\tport->iobase = new_port;\n\t\tport->type = new_serial.type;\n\t\tport->hub6 = new_serial.hub6;\n\t\tport->iotype = new_serial.io_type;\n\t\tport->regshift = new_serial.iomem_reg_shift;\n\t\tport->mapbase = (unsigned long)new_serial.iomem_base;", "\t\tif (port->type != PORT_UNKNOWN) {\n\t\t\tretval = port->ops->request_port(port);\n\t\t} else {\n\t\t\tretval = 0;\n\t\t}", "\t\tif (retval && old_type != PORT_UNKNOWN) {\n\t\t\tport->iobase = old_iobase;\n\t\t\tport->type = old_type;\n\t\t\tport->hub6 = old_hub6;\n\t\t\tport->iotype = old_iotype;\n\t\t\tport->regshift = old_shift;\n\t\t\tport->mapbase = old_mapbase;\n\t\t\tretval = port->ops->request_port(port);\n\t\t\tif (retval)\n\t\t\t\tport->type = PORT_UNKNOWN;", "\t\t\tretval = -EBUSY;\n\t\t}\n\t}", "\tport->irq = new_serial.irq;\n\tport->uartclk = new_serial.baud_base * 16;\n\tport->flags = (port->flags & ~UPF_CHANGE_MASK) |\n\t\t(new_flags & UPF_CHANGE_MASK);\n\tport->custom_divisor = new_serial.custom_divisor;\n\tstate->close_delay = new_serial.close_delay;\n\tstate->closing_wait = closing_wait;\n\tport->fifosize = new_serial.xmit_fifo_size;\n\tif (state->info->tty)\n\t\tstate->info->tty->low_latency =\n\t\t\t(port->flags & UPF_LOW_LATENCY) ? 1 : 0;", "check_and_exit:\n\tretval = 0;\n\tif (port->type == PORT_UNKNOWN)\n\t\tgoto exit;\n\tif (state->info->flags & UIF_INITIALIZED) {\n\t\tif (((old_flags ^ port->flags) & UPF_SPD_MASK) ||\n\t\t\t\told_custom_divisor != port->custom_divisor) {\n\t\t\tif (port->flags & UPF_SPD_MASK) {\n\t\t\t\tprintk(KERN_NOTICE\n\t\t\t\t\t\t\"%s sets custom speed on ttyMP%d. This \"\n\t\t\t\t\t\t\"is deprecated.\\n\", current->comm,\n\t\t\t\t\t\tport->line);\n\t\t\t}\n\t\t\tmp_change_speed(state, NULL);\n\t\t}\n\t} else\n\t\tretval = mp_startup(state, 1);\nexit:\n\tMP_STATE_UNLOCK(state);\n\treturn retval;\n}", "\nstatic int mp_get_lsr_info(struct sb_uart_state *state, unsigned int *value)\n{\n\tstruct sb_uart_port *port = state->port;\n\tunsigned int result;", "\tresult = port->ops->tx_empty(port);", "\tif (port->x_char ||\n\t\t\t((uart_circ_chars_pending(&state->info->xmit) > 0) &&\n\t\t\t\t!state->info->tty->stopped && !state->info->tty->hw_stopped))\n\t\tresult &= ~TIOCSER_TEMT;", "\treturn put_user(result, value);\n}", "static int mp_tiocmget(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port = state->port;\n\tint result = -EIO;", "\tMP_STATE_LOCK(state);\n\tif (!(tty->flags & (1 << TTY_IO_ERROR))) {\n\t\tresult = port->mctrl;\n\t\tspin_lock_irq(&port->lock);\n\t\tresult |= port->ops->get_mctrl(port);\n\t\tspin_unlock_irq(&port->lock);\n\t}\n\tMP_STATE_UNLOCK(state);\n\treturn result;\n}", "static int mp_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port = state->port;\n\tint ret = -EIO;", "\n\tMP_STATE_LOCK(state);\n\tif (!(tty->flags & (1 << TTY_IO_ERROR))) {\n\t\tmp_update_mctrl(port, set, clear);\n\t\tret = 0;\n\t}\n\tMP_STATE_UNLOCK(state);", "\treturn ret;\n}", "static int mp_break_ctl(struct tty_struct *tty, int break_state)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port = state->port;", "\tMP_STATE_LOCK(state);", "\tif (port->type != PORT_UNKNOWN)\n\t\tport->ops->break_ctl(port, break_state);", "\tMP_STATE_UNLOCK(state);\n\treturn 0;\n}", "static int mp_do_autoconfig(struct sb_uart_state *state)\n{\n\tstruct sb_uart_port *port = state->port;\n\tint flags, ret;", "\tif (!capable(CAP_SYS_ADMIN))\n\t\treturn -EPERM;", "\tif (mutex_lock_interruptible(&state->mutex))\n\t\treturn -ERESTARTSYS;\n\tret = -EBUSY;\n\tif (uart_users(state) == 1) {\n\t\tmp_shutdown(state);", "\t\tif (port->type != PORT_UNKNOWN)\n\t\t\tport->ops->release_port(port);", "\t\tflags = UART_CONFIG_TYPE;\n\t\tif (port->flags & UPF_AUTO_IRQ)\n\t\t\tflags |= UART_CONFIG_IRQ;", "\t\tport->ops->config_port(port, flags);", "\t\tret = mp_startup(state, 1);\n\t}\n\tMP_STATE_UNLOCK(state);\n\treturn ret;\n}", "static int mp_wait_modem_status(struct sb_uart_state *state, unsigned long arg)\n{\n\tstruct sb_uart_port *port = state->port;\n\tDECLARE_WAITQUEUE(wait, current);\n\tstruct sb_uart_icount cprev, cnow;\n\tint ret;", "\tspin_lock_irq(&port->lock);\n\tmemcpy(&cprev, &port->icount, sizeof(struct sb_uart_icount));", "\tport->ops->enable_ms(port);\n\tspin_unlock_irq(&port->lock);", "\tadd_wait_queue(&state->info->delta_msr_wait, &wait);\n\tfor (;;) {\n\t\tspin_lock_irq(&port->lock);\n\t\tmemcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount));\n\t\tspin_unlock_irq(&port->lock);", "\t\tset_current_state(TASK_INTERRUPTIBLE);", "\t\tif (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||\n\t\t\t\t((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||\n\t\t\t\t((arg & TIOCM_CD) && (cnow.dcd != cprev.dcd)) ||\n\t\t\t\t((arg & TIOCM_CTS) && (cnow.cts != cprev.cts))) {\n\t\t\tret = 0;\n\t\t\tbreak;\n\t\t}", "\t\tschedule();", "\t\tif (signal_pending(current)) {\n\t\t\tret = -ERESTARTSYS;\n\t\t\tbreak;\n\t\t}", "\t\tcprev = cnow;\n\t}", "\tcurrent->state = TASK_RUNNING;\n\tremove_wait_queue(&state->info->delta_msr_wait, &wait);", "\treturn ret;\n}", "static int mp_get_count(struct sb_uart_state *state, struct serial_icounter_struct *icnt)\n{", "\tstruct serial_icounter_struct icount = {};", "\tstruct sb_uart_icount cnow;\n\tstruct sb_uart_port *port = state->port;", "\tspin_lock_irq(&port->lock);\n\tmemcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount));\n\tspin_unlock_irq(&port->lock);", "\ticount.cts = cnow.cts;\n\ticount.dsr = cnow.dsr;\n\ticount.rng = cnow.rng;\n\ticount.dcd = cnow.dcd;\n\ticount.rx = cnow.rx;\n\ticount.tx = cnow.tx;\n\ticount.frame = cnow.frame;\n\ticount.overrun = cnow.overrun;\n\ticount.parity = cnow.parity;\n\ticount.brk = cnow.brk;\n\ticount.buf_overrun = cnow.buf_overrun;", "\treturn copy_to_user(icnt, &icount, sizeof(icount)) ? -EFAULT : 0;\n}", "static int mp_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct mp_port *info = (struct mp_port *)state->port;\n\tint ret = -ENOIOCTLCMD;", "\n\tswitch (cmd) {\n\t\tcase TIOCSMULTIDROP:\n\t\t\t/* set multi-drop mode enable or disable, and default operation mode is H/W mode */\n\t\t\tif (info->port.type == PORT_16C105XA)\n\t\t\t{\n\t\t\t\t//arg &= ~0x6;\n\t\t\t\t//state->port->mdmode = 0;\n\t\t\t\treturn set_multidrop_mode((struct sb_uart_port *)info, (unsigned int)arg);\n\t\t\t}\n\t\t\tret = -ENOTSUPP;\n\t\t\tbreak;\n\t\tcase GETDEEPFIFO:\n\t\t\tret = get_deep_fifo(state->port);\n\t\t\treturn ret;\n\t\tcase SETDEEPFIFO:\n\t\t\tret = set_deep_fifo(state->port,arg);\n\t\t\tdeep[state->port->line] = arg;\n\t\t\treturn ret;\n\t\tcase SETTTR:\n\t\t\tif (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){\n\t\t\t\tret = sb1054_set_register(state->port,PAGE_4,SB105X_TTR,arg);\n\t\t\t\tttr[state->port->line] = arg;\n\t\t\t}\n\t\t\treturn ret;\n\t\tcase SETRTR:\n\t\t\tif (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){\n\t\t\t\tret = sb1054_set_register(state->port,PAGE_4,SB105X_RTR,arg);\n\t\t\t\trtr[state->port->line] = arg;\n\t\t\t}\n\t\t\treturn ret;\n\t\tcase GETTTR:\n\t\t\tif (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){\n\t\t\t\tret = sb1054_get_register(state->port,PAGE_4,SB105X_TTR);\n\t\t\t}\n\t\t\treturn ret;\n\t\tcase GETRTR:\n\t\t\tif (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){\n\t\t\t\tret = sb1054_get_register(state->port,PAGE_4,SB105X_RTR);\n\t\t\t}\n\t\t\treturn ret;", "\t\tcase SETFCR:\n\t\t\tif (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){\n\t\t\t\tret = sb1054_set_register(state->port,PAGE_1,SB105X_FCR,arg);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tserial_out(info,2,arg);\n\t\t\t}", "\t\t\treturn ret;\n\t\tcase TIOCSMDADDR:\n\t\t\t/* set multi-drop address */\n\t\t\tif (info->port.type == PORT_16C105XA)\n\t\t\t{\n\t\t\t\tstate->port->mdmode |= MDMODE_ADDR;\n\t\t\t\treturn set_multidrop_addr((struct sb_uart_port *)info, (unsigned int)arg);\n\t\t\t}\n\t\t\tret = -ENOTSUPP;\n\t\t\tbreak;", "\t\tcase TIOCGMDADDR:\n\t\t\t/* set multi-drop address */\n\t\t\tif ((info->port.type == PORT_16C105XA) && (state->port->mdmode & MDMODE_ADDR))\n\t\t\t{\n\t\t\t\treturn get_multidrop_addr((struct sb_uart_port *)info);\n\t\t\t}\n\t\t\tret = -ENOTSUPP;\n\t\t\tbreak;", "\t\tcase TIOCSENDADDR:\n\t\t\t/* send address in multi-drop mode */\n\t\t\tif ((info->port.type == PORT_16C105XA) \n\t\t\t\t\t&& (state->port->mdmode & (MDMODE_ENABLE)))\n\t\t\t{\n\t\t\t\tif (mp_chars_in_buffer(tty) > 0)\n\t\t\t\t{\n\t\t\t\t\ttty_wait_until_sent(tty, 0);\n\t\t\t\t}\n\t\t\t\t//while ((serial_in(info, UART_LSR) & 0x60) != 0x60);\n\t\t\t\t//while (sb1054_get_register(state->port, PAGE_2, SB105X_TFCR) != 0);\n\t\t\t\twhile ((serial_in(info, UART_LSR) & 0x60) != 0x60);\n\t\t\t\tserial_out(info, UART_SCR, (int)arg);\n\t\t\t}\n\t\t\tbreak;", "\t\tcase TIOCGSERIAL:\n\t\t\tret = mp_get_info(state, (struct serial_struct *)arg);\n\t\t\tbreak;", "\t\tcase TIOCSSERIAL:\n\t\t\tret = mp_set_info(state, (struct serial_struct *)arg);\n\t\t\tbreak;", "\t\tcase TIOCSERCONFIG:\n\t\t\tret = mp_do_autoconfig(state);\n\t\t\tbreak;", "\t\tcase TIOCSERGWILD: /* obsolete */\n\t\tcase TIOCSERSWILD: /* obsolete */\n\t\t\tret = 0;\n\t\t\tbreak;\n\t\t\t/* for Multiport */\n\t\tcase TIOCGNUMOFPORT: /* Get number of ports */\n\t\t\treturn NR_PORTS;\n\t\tcase TIOCGGETDEVID:\n\t\t\treturn mp_devs[arg].device_id;\n\t\tcase TIOCGGETREV:\n\t\t\treturn mp_devs[arg].revision;\n\t\tcase TIOCGGETNRPORTS:\n\t\t\treturn mp_devs[arg].nr_ports;\n\t\tcase TIOCGGETBDNO:\n\t\t\treturn NR_BOARD;\n\t\tcase TIOCGGETINTERFACE:\n\t\t\tif (mp_devs[arg].revision == 0xc0)\n\t\t\t{\n\t\t\t\t/* for SB16C1053APCI */\n\t\t\t\treturn (sb1053a_get_interface(info, info->port.line));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn (inb(mp_devs[arg].option_reg_addr+MP_OPTR_IIR0+(state->port->line/8)));\n\t\t\t}\n\t\tcase TIOCGGETPORTTYPE:\n\t\t\tret = get_device_type(arg);;\n\t\t\treturn ret;\n\t\tcase TIOCSMULTIECHO: /* set to multi-drop mode(RS422) or echo mode(RS485)*/\n\t\t\toutb( ( inb(info->interface_config_addr) & ~0x03 ) | 0x01 , \n\t\t\t\t\tinfo->interface_config_addr);\n\t\t\treturn 0;\n\t\tcase TIOCSPTPNOECHO: /* set to multi-drop mode(RS422) or echo mode(RS485) */\n\t\t\toutb( ( inb(info->interface_config_addr) & ~0x03 ) , \n\t\t\t\t\tinfo->interface_config_addr);\n\t\t\treturn 0;\n\t}", "\tif (ret != -ENOIOCTLCMD)\n\t\tgoto out;", "\tif (tty->flags & (1 << TTY_IO_ERROR)) {\n\t\tret = -EIO;\n\t\tgoto out;\n\t}", "\tswitch (cmd) {\n\t\tcase TIOCMIWAIT:\n\t\t\tret = mp_wait_modem_status(state, arg);\n\t\t\tbreak;", "\t\tcase TIOCGICOUNT:\n\t\t\tret = mp_get_count(state, (struct serial_icounter_struct *)arg);\n\t\t\tbreak;\n\t}", "\tif (ret != -ENOIOCTLCMD)\n\t\tgoto out;", "\tMP_STATE_LOCK(state);\n\tswitch (cmd) {\n\t\tcase TIOCSERGETLSR: /* Get line status register */\n\t\t\tret = mp_get_lsr_info(state, (unsigned int *)arg);\n\t\t\tbreak;", "\t\tdefault: {\n\t\t\t\t\tstruct sb_uart_port *port = state->port;\n\t\t\t\t\tif (port->ops->ioctl)\n\t\t\t\t\t\tret = port->ops->ioctl(port, cmd, arg);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t}", "\tMP_STATE_UNLOCK(state);\nout:\n\treturn ret;\n}", "static void mp_set_termios(struct tty_struct *tty, struct MP_TERMIOS *old_termios)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tunsigned long flags;\n\tunsigned int cflag = tty->termios.c_cflag;", "#define RELEVANT_IFLAG(iflag)\t((iflag) & (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK))", "\tif ((cflag ^ old_termios->c_cflag) == 0 &&\n\t\t\tRELEVANT_IFLAG(tty->termios.c_iflag ^ old_termios->c_iflag) == 0)\n\t\treturn;", "\tmp_change_speed(state, old_termios);", "\tif ((old_termios->c_cflag & CBAUD) && !(cflag & CBAUD))\n\t\tuart_clear_mctrl(state->port, TIOCM_RTS | TIOCM_DTR);", "\tif (!(old_termios->c_cflag & CBAUD) && (cflag & CBAUD)) {\n\t\tunsigned int mask = TIOCM_DTR;\n\t\tif (!(cflag & CRTSCTS) ||\n\t\t\t\t!test_bit(TTY_THROTTLED, &tty->flags))\n\t\t\tmask |= TIOCM_RTS;\n\t\tuart_set_mctrl(state->port, mask);\n\t}", "\tif ((old_termios->c_cflag & CRTSCTS) && !(cflag & CRTSCTS)) {\n\t\tspin_lock_irqsave(&state->port->lock, flags);\n\t\ttty->hw_stopped = 0;\n\t\t__mp_start(tty);\n\t\tspin_unlock_irqrestore(&state->port->lock, flags);\n\t}", "\tif (!(old_termios->c_cflag & CRTSCTS) && (cflag & CRTSCTS)) {\n\t\tspin_lock_irqsave(&state->port->lock, flags);\n\t\tif (!(state->port->ops->get_mctrl(state->port) & TIOCM_CTS)) {\n\t\t\ttty->hw_stopped = 1;\n\t\t\tstate->port->ops->stop_tx(state->port);\n\t\t}\n\t\tspin_unlock_irqrestore(&state->port->lock, flags);\n\t}\n}", "static void mp_close(struct tty_struct *tty, struct file *filp)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port;", "\tprintk(\"mp_close!\\n\");\n\tif (!state || !state->port)\n\t\treturn;", "\tport = state->port;", "\tprintk(\"close1 %d\\n\", __LINE__);\n\tMP_STATE_LOCK(state);", "\tprintk(\"close2 %d\\n\", __LINE__);\n\tif (tty_hung_up_p(filp))\n\t\tgoto done;", "\tprintk(\"close3 %d\\n\", __LINE__);\n\tif ((tty->count == 1) && (state->count != 1)) {\n\t\tprintk(\"mp_close: bad serial port count; tty->count is 1, \"\n\t\t\t\t\"state->count is %d\\n\", state->count);\n\t\tstate->count = 1;\n\t}\n\tprintk(\"close4 %d\\n\", __LINE__);\n\tif (--state->count < 0) {\n\t\tprintk(\"rs_close: bad serial port count for ttyMP%d: %d\\n\",\n\t\t\t\tport->line, state->count);\n\t\tstate->count = 0;\n\t}\n\tif (state->count)\n\t\tgoto done;", "\ttty->closing = 1;", "\tprintk(\"close5 %d\\n\", __LINE__);\n\tif (state->closing_wait != USF_CLOSING_WAIT_NONE)\n\t\ttty_wait_until_sent(tty, state->closing_wait);", "\tprintk(\"close6 %d\\n\", __LINE__);\n\tif (state->info->flags & UIF_INITIALIZED) {\n\t\tunsigned long flags;\n\t\tspin_lock_irqsave(&port->lock, flags);\n\t\tport->ops->stop_rx(port);\n\t\tspin_unlock_irqrestore(&port->lock, flags);\n\t\tmp_wait_until_sent(tty, port->timeout);\n\t}\n\tprintk(\"close7 %d\\n\", __LINE__);", "\tmp_shutdown(state);\n\tprintk(\"close8 %d\\n\", __LINE__);\n\tmp_flush_buffer(tty);\n\ttty_ldisc_flush(tty);\n\ttty->closing = 0;\n\tstate->info->tty = NULL;\n\tif (state->info->blocked_open) \n\t{\n\t\tif (state->close_delay)\n\t\t{\n\t\t\tset_current_state(TASK_INTERRUPTIBLE);\n\t\t\tschedule_timeout(state->close_delay);\n\t\t}\n\t}\n\telse\n\t{\n\t\tmp_change_pm(state, 3);\n\t}\n\tprintk(\"close8 %d\\n\", __LINE__);", "\tstate->info->flags &= ~UIF_NORMAL_ACTIVE;\n\twake_up_interruptible(&state->info->open_wait);", "done:\n\tprintk(\"close done\\n\");\n\tMP_STATE_UNLOCK(state);\n\tmodule_put(THIS_MODULE);\n}", "static void mp_wait_until_sent(struct tty_struct *tty, int timeout)\n{\n\tstruct sb_uart_state *state = tty->driver_data;\n\tstruct sb_uart_port *port = state->port;\n\tunsigned long char_time, expire;", "\tif (port->type == PORT_UNKNOWN || port->fifosize == 0)\n\t\treturn;", "\tchar_time = (port->timeout - HZ/50) / port->fifosize;\n\tchar_time = char_time / 5;\n\tif (char_time == 0)\n\t\tchar_time = 1;\n\tif (timeout && timeout < char_time)\n\t\tchar_time = timeout;", "\tif (timeout == 0 || timeout > 2 * port->timeout)\n\t\ttimeout = 2 * port->timeout;", "\texpire = jiffies + timeout;", "\twhile (!port->ops->tx_empty(port)) {\n\t\tset_current_state(TASK_INTERRUPTIBLE);\n\t\tschedule_timeout(char_time);\n\t\tif (signal_pending(current))\n\t\t\tbreak;\n\t\tif (time_after(jiffies, expire))\n\t\t\tbreak;\n\t}\n\tset_current_state(TASK_RUNNING); /* might not be needed */\n}", "static void mp_hangup(struct tty_struct *tty)\n{\n\tstruct sb_uart_state *state = tty->driver_data;", "\tMP_STATE_LOCK(state);\n\tif (state->info && state->info->flags & UIF_NORMAL_ACTIVE) {\n\t\tmp_flush_buffer(tty);\n\t\tmp_shutdown(state);\n\t\tstate->count = 0;\n\t\tstate->info->flags &= ~UIF_NORMAL_ACTIVE;\n\t\tstate->info->tty = NULL;\n\t\twake_up_interruptible(&state->info->open_wait);\n\t\twake_up_interruptible(&state->info->delta_msr_wait);\n\t}\n\tMP_STATE_UNLOCK(state);\n}", "static void mp_update_termios(struct sb_uart_state *state)\n{\n\tstruct tty_struct *tty = state->info->tty;\n\tstruct sb_uart_port *port = state->port;", "\tif (!(tty->flags & (1 << TTY_IO_ERROR))) {\n\t\tmp_change_speed(state, NULL);", "\t\tif (tty->termios.c_cflag & CBAUD)\n\t\t\tuart_set_mctrl(port, TIOCM_DTR | TIOCM_RTS);\n\t}\n}", "static int mp_block_til_ready(struct file *filp, struct sb_uart_state *state)\n{\n\tDECLARE_WAITQUEUE(wait, current);\n\tstruct sb_uart_info *info = state->info;\n\tstruct sb_uart_port *port = state->port;\n\tunsigned int mctrl;", "\tinfo->blocked_open++;\n\tstate->count--;", "\tadd_wait_queue(&info->open_wait, &wait);\n\twhile (1) {\n\t\tset_current_state(TASK_INTERRUPTIBLE);", "\t\tif (tty_hung_up_p(filp) || info->tty == NULL)\n\t\t\tbreak;", "\t\tif (!(info->flags & UIF_INITIALIZED))\n\t\t\tbreak;", "\t\tif ((filp->f_flags & O_NONBLOCK) ||\n\t\t\t\t(info->tty->termios.c_cflag & CLOCAL) ||\n\t\t\t\t(info->tty->flags & (1 << TTY_IO_ERROR))) {\n\t\t\tbreak;\n\t\t}", "\t\tif (info->tty->termios.c_cflag & CBAUD)\n\t\t\tuart_set_mctrl(port, TIOCM_DTR);", "\t\tspin_lock_irq(&port->lock);\n\t\tport->ops->enable_ms(port);\n\t\tmctrl = port->ops->get_mctrl(port);\n\t\tspin_unlock_irq(&port->lock);\n\t\tif (mctrl & TIOCM_CAR)\n\t\t\tbreak;", "\t\tMP_STATE_UNLOCK(state);\n\t\tschedule();\n\t\tMP_STATE_LOCK(state);", "\t\tif (signal_pending(current))\n\t\t\tbreak;\n\t}\n\tset_current_state(TASK_RUNNING);\n\tremove_wait_queue(&info->open_wait, &wait);", "\tstate->count++;\n\tinfo->blocked_open--;", "\tif (signal_pending(current))\n\t\treturn -ERESTARTSYS;", "\tif (!info->tty || tty_hung_up_p(filp))\n\t\treturn -EAGAIN;", "\treturn 0;\n}", "static struct sb_uart_state *uart_get(struct uart_driver *drv, int line)\n{\n\tstruct sb_uart_state *state;", "\tMP_MUTEX_LOCK(mp_mutex);\n\tstate = drv->state + line;\n\tif (mutex_lock_interruptible(&state->mutex)) {\n\t\tstate = ERR_PTR(-ERESTARTSYS);\n\t\tgoto out;\n\t}\n\tstate->count++;\n\tif (!state->port) {\n\t\tstate->count--;\n\t\tMP_STATE_UNLOCK(state);\n\t\tstate = ERR_PTR(-ENXIO);\n\t\tgoto out;\n\t}", "\tif (!state->info) {\n\t\tstate->info = kmalloc(sizeof(struct sb_uart_info), GFP_KERNEL);\n\t\tif (state->info) {\n\t\t\tmemset(state->info, 0, sizeof(struct sb_uart_info));\n\t\t\tinit_waitqueue_head(&state->info->open_wait);\n\t\t\tinit_waitqueue_head(&state->info->delta_msr_wait);", "\t\t\tstate->port->info = state->info;", "\t\t\ttasklet_init(&state->info->tlet, mp_tasklet_action,\n\t\t\t\t\t(unsigned long)state);\n\t\t} else {\n\t\t\tstate->count--;\n\t\t\tMP_STATE_UNLOCK(state);\n\t\t\tstate = ERR_PTR(-ENOMEM);\n\t\t}\n\t}", "out:\n\tMP_MUTEX_UNLOCK(mp_mutex);\n\treturn state;\n}", "static int mp_open(struct tty_struct *tty, struct file *filp)\n{\n\tstruct uart_driver *drv = (struct uart_driver *)tty->driver->driver_state;\n\tstruct sb_uart_state *state;\n\tint retval;\n\tint line = tty->index;\n\tstruct mp_port *mtpt;", "\tretval = -ENODEV;\n\tif (line >= tty->driver->num)\n\t\tgoto fail;", "\tstate = uart_get(drv, line);", "\tif (IS_ERR(state)) {\n\t\tretval = PTR_ERR(state);\n\t\tgoto fail;\n\t}", "\tmtpt = (struct mp_port *)state->port;", "\ttty->driver_data = state;\n\ttty->low_latency = (state->port->flags & UPF_LOW_LATENCY) ? 1 : 0;\n\ttty->alt_speed = 0;\n\tstate->info->tty = tty;", "\tif (tty_hung_up_p(filp)) {\n\t\tretval = -EAGAIN;\n\t\tstate->count--;\n\t\tMP_STATE_UNLOCK(state);\n\t\tgoto fail;\n\t}", "\tif (state->count == 1)\n\t\tmp_change_pm(state, 0);", "\tretval = mp_startup(state, 0);", "\tif (retval == 0)\n\t\tretval = mp_block_til_ready(filp, state);\n\tMP_STATE_UNLOCK(state);", "\tif (retval == 0 && !(state->info->flags & UIF_NORMAL_ACTIVE)) {\n\t\tstate->info->flags |= UIF_NORMAL_ACTIVE;", "\t\tmp_update_termios(state);\n\t}", "\tuart_clear_mctrl(state->port, TIOCM_RTS);\n\ttry_module_get(THIS_MODULE);\nfail:\n\treturn retval;\n}", "\nstatic const char *mp_type(struct sb_uart_port *port)\n{\n\tconst char *str = NULL;", "\tif (port->ops->type)\n\t\tstr = port->ops->type(port);", "\tif (!str)\n\t\tstr = \"unknown\";", "\treturn str;\n}", "static void mp_change_pm(struct sb_uart_state *state, int pm_state)\n{\n\tstruct sb_uart_port *port = state->port;\n\tif (port->ops->pm)\n\t\tport->ops->pm(port, pm_state, state->pm_state);\n\tstate->pm_state = pm_state;\n}", "static inline void mp_report_port(struct uart_driver *drv, struct sb_uart_port *port)\n{\n\tchar address[64];", "\tswitch (port->iotype) {\n\t\tcase UPIO_PORT:\n\t\t\tsnprintf(address, sizeof(address),\"I/O 0x%x\", port->iobase);\n\t\t\tbreak;\n\t\tcase UPIO_HUB6:\n\t\t\tsnprintf(address, sizeof(address),\"I/O 0x%x offset 0x%x\", port->iobase, port->hub6);\n\t\t\tbreak;\n\t\tcase UPIO_MEM:\n\t\t\tsnprintf(address, sizeof(address),\"MMIO 0x%lx\", port->mapbase);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tsnprintf(address, sizeof(address),\"*unknown*\" );\n\t\t\tstrlcpy(address, \"*unknown*\", sizeof(address));\n\t\t\tbreak;\n\t}", "\tprintk( \"%s%d at %s (irq = %d) is a %s\\n\",\n\t\t\tdrv->dev_name, port->line, address, port->irq, mp_type(port));", "}", "static void mp_configure_port(struct uart_driver *drv, struct sb_uart_state *state, struct sb_uart_port *port)\n{\n\tunsigned int flags;", "\n\tif (!port->iobase && !port->mapbase && !port->membase)\n\t{\n\t\tDPRINTK(\"%s error \\n\",__FUNCTION__);\n\t\treturn;\n\t}\n\tflags = UART_CONFIG_TYPE;\n\tif (port->flags & UPF_AUTO_IRQ)\n\t\tflags |= UART_CONFIG_IRQ;\n\tif (port->flags & UPF_BOOT_AUTOCONF) {\n\t\tport->type = PORT_UNKNOWN;\n\t\tport->ops->config_port(port, flags);\n\t}", "\tif (port->type != PORT_UNKNOWN) {\n\t\tunsigned long flags;", "\t\tmp_report_port(drv, port);", "\t\tspin_lock_irqsave(&port->lock, flags);\n\t\tport->ops->set_mctrl(port, 0);\n\t\tspin_unlock_irqrestore(&port->lock, flags);", "\t\tmp_change_pm(state, 3);\n\t}\n}", "static void mp_unconfigure_port(struct uart_driver *drv, struct sb_uart_state *state)\n{\n\tstruct sb_uart_port *port = state->port;\n\tstruct sb_uart_info *info = state->info;", "\tif (info && info->tty)\n\t\ttty_hangup(info->tty);", "\tMP_STATE_LOCK(state);", "\tstate->info = NULL;", "\tif (port->type != PORT_UNKNOWN)\n\t\tport->ops->release_port(port);", "\tport->type = PORT_UNKNOWN;", "\tif (info) {\n\t\ttasklet_kill(&info->tlet);\n\t\tkfree(info);\n\t}", "\tMP_STATE_UNLOCK(state);\n}\nstatic struct tty_operations mp_ops = {\n\t.open\t\t= mp_open,\n\t.close\t\t= mp_close,\n\t.write\t\t= mp_write,\n\t.put_char\t= mp_put_char,\n\t.flush_chars\t= mp_put_chars,\n\t.write_room\t= mp_write_room,\n\t.chars_in_buffer= mp_chars_in_buffer,\n\t.flush_buffer\t= mp_flush_buffer,\n\t.ioctl\t\t= mp_ioctl,\n\t.throttle\t= mp_throttle,\n\t.unthrottle\t= mp_unthrottle,\n\t.send_xchar\t= mp_send_xchar,\n\t.set_termios\t= mp_set_termios,\n\t.stop\t\t= mp_stop,\n\t.start\t\t= mp_start,\n\t.hangup\t\t= mp_hangup,\n\t.break_ctl\t= mp_break_ctl,\n\t.wait_until_sent= mp_wait_until_sent,\n#ifdef CONFIG_PROC_FS\n\t.proc_fops\t= NULL,\n#endif\n\t.tiocmget\t= mp_tiocmget,\n\t.tiocmset\t= mp_tiocmset,\n};", "static int mp_register_driver(struct uart_driver *drv)\n{\n\tstruct tty_driver *normal = NULL;\n\tint i, retval;", "\tdrv->state = kmalloc(sizeof(struct sb_uart_state) * drv->nr, GFP_KERNEL);\n\tretval = -ENOMEM;\n\tif (!drv->state)\n\t{\n\t\tprintk(\"SB PCI Error: Kernel memory allocation error!\\n\");\n\t\tgoto out;\n\t}\n\tmemset(drv->state, 0, sizeof(struct sb_uart_state) * drv->nr);", "\tnormal = alloc_tty_driver(drv->nr);\n\tif (!normal)\n\t{\n\t\tprintk(\"SB PCI Error: tty allocation error!\\n\");\n\t\tgoto out;\n\t}", "\tdrv->tty_driver = normal;", "\tnormal->owner = drv->owner;\n\tnormal->magic\t\t= TTY_DRIVER_MAGIC;\n\tnormal->driver_name = drv->driver_name;\n\tnormal->name\t\t= drv->dev_name;\n\tnormal->major\t\t= drv->major;\n\tnormal->minor_start\t= drv->minor;", "\tnormal->num\t\t= MAX_MP_PORT ; ", "\tnormal->type\t\t= TTY_DRIVER_TYPE_SERIAL;\n\tnormal->subtype\t\t= SERIAL_TYPE_NORMAL;\n\tnormal->init_termios\t= tty_std_termios;\n\tnormal->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL;\n\tnormal->flags\t\t= TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;\n\tnormal->driver_state = drv;", "\ttty_set_operations(normal, &mp_ops);", "for (i = 0; i < drv->nr; i++) {\n\tstruct sb_uart_state *state = drv->state + i;", "\tstate->close_delay = 500; \n\tstate->closing_wait = 30000; ", "\tmutex_init(&state->mutex);\n\t}", "\tretval = tty_register_driver(normal);\nout:\n\tif (retval < 0) {\n\t\tprintk(\"Register tty driver Fail!\\n\");\n\t\tput_tty_driver(normal);\n\t\tkfree(drv->state);\n\t}", "\treturn retval;\n}", "void mp_unregister_driver(struct uart_driver *drv)\n{\n struct tty_driver *normal = NULL;", " normal = drv->tty_driver;", " if (!normal)\n {\n return;\n }", " tty_unregister_driver(normal);\n put_tty_driver(normal);\n drv->tty_driver = NULL;", "\n if (drv->state)\n {\n kfree(drv->state);\n }", "}", "static int mp_add_one_port(struct uart_driver *drv, struct sb_uart_port *port)\n{\n\tstruct sb_uart_state *state;\n\tint ret = 0;", "\n\tif (port->line >= drv->nr)\n\t\treturn -EINVAL;", "\tstate = drv->state + port->line;", "\tMP_MUTEX_LOCK(mp_mutex);\n\tif (state->port) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}", "\tstate->port = port;", "\tspin_lock_init(&port->lock);\n\tport->cons = drv->cons;\n\tport->info = state->info;", "\tmp_configure_port(drv, state, port);", "\ttty_register_device(drv->tty_driver, port->line, port->dev);", "out:\n\tMP_MUTEX_UNLOCK(mp_mutex);", "\n\treturn ret;\n}", "static int mp_remove_one_port(struct uart_driver *drv, struct sb_uart_port *port)\n{\n\tstruct sb_uart_state *state = drv->state + port->line;", "\tif (state->port != port)\n\t\tprintk(KERN_ALERT \"Removing wrong port: %p != %p\\n\",\n\t\t\t\tstate->port, port);", "\tMP_MUTEX_LOCK(mp_mutex);", "\ttty_unregister_device(drv->tty_driver, port->line);", "\tmp_unconfigure_port(drv, state);\n\tstate->port = NULL;\n\tMP_MUTEX_UNLOCK(mp_mutex);", "\treturn 0;\n}", "static void autoconfig(struct mp_port *mtpt, unsigned int probeflags)\n{\n\tunsigned char status1, scratch, scratch2, scratch3;\n\tunsigned char save_lcr, save_mcr;\n\tunsigned long flags;", "\tunsigned char u_type;\n\tunsigned char b_ret = 0;", "\tif (!mtpt->port.iobase && !mtpt->port.mapbase && !mtpt->port.membase)\n\t\treturn;", "\tDEBUG_AUTOCONF(\"ttyMP%d: autoconf (0x%04x, 0x%p): \",\n\t\t\tmtpt->port.line, mtpt->port.iobase, mtpt->port.membase);", "\tspin_lock_irqsave(&mtpt->port.lock, flags);", "\tif (!(mtpt->port.flags & UPF_BUGGY_UART)) {\n\t\tscratch = serial_inp(mtpt, UART_IER);\n\t\tserial_outp(mtpt, UART_IER, 0);\n#ifdef __i386__\n\t\toutb(0xff, 0x080);\n#endif\n\t\tscratch2 = serial_inp(mtpt, UART_IER) & 0x0f;\n\t\tserial_outp(mtpt, UART_IER, 0x0F);\n#ifdef __i386__\n\t\toutb(0, 0x080);\n#endif\n\t\tscratch3 = serial_inp(mtpt, UART_IER) & 0x0F;\n\t\tserial_outp(mtpt, UART_IER, scratch);\n\t\tif (scratch2 != 0 || scratch3 != 0x0F) {\n\t\t\tDEBUG_AUTOCONF(\"IER test failed (%02x, %02x) \",\n\t\t\t\t\tscratch2, scratch3);\n\t\t\tgoto out;\n\t\t}\n\t}", "\tsave_mcr = serial_in(mtpt, UART_MCR);\n\tsave_lcr = serial_in(mtpt, UART_LCR);", "\tif (!(mtpt->port.flags & UPF_SKIP_TEST)) {\n\t\tserial_outp(mtpt, UART_MCR, UART_MCR_LOOP | 0x0A);\n\t\tstatus1 = serial_inp(mtpt, UART_MSR) & 0xF0;\n\t\tserial_outp(mtpt, UART_MCR, save_mcr);\n\t\tif (status1 != 0x90) {\n\t\t\tDEBUG_AUTOCONF(\"LOOP test failed (%02x) \",\n\t\t\t\t\tstatus1);\n\t\t\tgoto out;\n\t\t}\n\t}", "\tserial_outp(mtpt, UART_LCR, 0xBF);\n\tserial_outp(mtpt, UART_EFR, 0);\n\tserial_outp(mtpt, UART_LCR, 0);", "\tserial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO);\n\tscratch = serial_in(mtpt, UART_IIR) >> 6;", "\tDEBUG_AUTOCONF(\"iir=%d \", scratch);\n\tif(mtpt->device->nr_ports >= 8)\n\t\tb_ret = read_option_register(mtpt,(MP_OPTR_DIR0 + ((mtpt->port.line)/8)));\n\telse\t\n\t\tb_ret = read_option_register(mtpt,MP_OPTR_DIR0);\n\tu_type = (b_ret & 0xf0) >> 4;\n\tif(mtpt->port.type == PORT_UNKNOWN )\n\t{\n\t\tswitch (u_type)\n\t\t{\n\t\t\tcase DIR_UART_16C550:\n\t\t\t\tmtpt->port.type = PORT_16C55X;\n\t\t\t\tbreak;\n\t\t\tcase DIR_UART_16C1050:\n\t\t\t\tmtpt->port.type = PORT_16C105X;\n\t\t\t\tbreak;\n\t\t\tcase DIR_UART_16C1050A:\n\t\t\t\tif (mtpt->port.line < 2)\n\t\t\t\t{\n\t\t\t\t\tmtpt->port.type = PORT_16C105XA;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (mtpt->device->device_id & 0x50)\n\t\t\t\t\t{\n\t\t\t\t\t\tmtpt->port.type = PORT_16C55X;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tmtpt->port.type = PORT_16C105X;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\t\n\t\t\t\tmtpt->port.type = PORT_UNKNOWN;\n\t\t\t\tbreak;\n\t\t}\n\t}", "\tif(mtpt->port.type == PORT_UNKNOWN )\n\t{\nprintk(\"unknow2\\n\");\n\t\tswitch (scratch) {\n\t\t\tcase 0:\n\t\t\tcase 1:\n\t\t\t\tmtpt->port.type = PORT_UNKNOWN;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\tcase 3:\n\t\t\t\tmtpt->port.type = PORT_16C55X;\n\t\t\t\tbreak;\n\t\t}\n\t}", "\tserial_outp(mtpt, UART_LCR, save_lcr);", "\tmtpt->port.fifosize = uart_config[mtpt->port.type].dfl_xmit_fifo_size;\n\tmtpt->capabilities = uart_config[mtpt->port.type].flags;", "\tif (mtpt->port.type == PORT_UNKNOWN)\n\t\tgoto out;\n\tserial_outp(mtpt, UART_MCR, save_mcr);\n\tserial_outp(mtpt, UART_FCR, (UART_FCR_ENABLE_FIFO |\n\t\t\t\tUART_FCR_CLEAR_RCVR |\n\t\t\t\tUART_FCR_CLEAR_XMIT));\n\tserial_outp(mtpt, UART_FCR, 0);\n\t(void)serial_in(mtpt, UART_RX);\n\tserial_outp(mtpt, UART_IER, 0);", "out:\n\tspin_unlock_irqrestore(&mtpt->port.lock, flags);\n\tDEBUG_AUTOCONF(\"type=%s\\n\", uart_config[mtpt->port.type].name);\n}", "static void autoconfig_irq(struct mp_port *mtpt)\n{\n\tunsigned char save_mcr, save_ier;\n\tunsigned long irqs;\n\tint irq;", "\t/* forget possible initially masked and pending IRQ */\n\tprobe_irq_off(probe_irq_on());\n\tsave_mcr = serial_inp(mtpt, UART_MCR);\n\tsave_ier = serial_inp(mtpt, UART_IER);\n\tserial_outp(mtpt, UART_MCR, UART_MCR_OUT1 | UART_MCR_OUT2);", "\tirqs = probe_irq_on();\n\tserial_outp(mtpt, UART_MCR, 0);\n\tserial_outp(mtpt, UART_MCR,\n\t\tUART_MCR_DTR | UART_MCR_RTS | UART_MCR_OUT2);", "\tserial_outp(mtpt, UART_IER, 0x0f); /* enable all intrs */\n\t(void)serial_inp(mtpt, UART_LSR);\n\t(void)serial_inp(mtpt, UART_RX);\n\t(void)serial_inp(mtpt, UART_IIR);\n\t(void)serial_inp(mtpt, UART_MSR);\n\tserial_outp(mtpt, UART_TX, 0xFF);\n\tirq = probe_irq_off(irqs);", "\tserial_outp(mtpt, UART_MCR, save_mcr);\n\tserial_outp(mtpt, UART_IER, save_ier);", "\tmtpt->port.irq = (irq > 0) ? irq : 0;\n}", "static void multi_stop_tx(struct sb_uart_port *port)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;", "\tif (mtpt->ier & UART_IER_THRI) {\n\t\tmtpt->ier &= ~UART_IER_THRI;\n\t\tserial_out(mtpt, UART_IER, mtpt->ier);\n\t}", "\ttasklet_schedule(&port->info->tlet);\n}", "static void multi_start_tx(struct sb_uart_port *port)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;", "\tif (!(mtpt->ier & UART_IER_THRI)) {\n\t\tmtpt->ier |= UART_IER_THRI;\n\t\tserial_out(mtpt, UART_IER, mtpt->ier);\n\t}\n}", "static void multi_stop_rx(struct sb_uart_port *port)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;", "\tmtpt->ier &= ~UART_IER_RLSI;\n\tmtpt->port.read_status_mask &= ~UART_LSR_DR;\n\tserial_out(mtpt, UART_IER, mtpt->ier);\n}", "static void multi_enable_ms(struct sb_uart_port *port)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;", "\tmtpt->ier |= UART_IER_MSI;\n\tserial_out(mtpt, UART_IER, mtpt->ier);\n}", "\nstatic _INLINE_ void receive_chars(struct mp_port *mtpt, int *status )\n{\n\tstruct tty_struct *tty = mtpt->port.info->tty;\n\tunsigned char lsr = *status;\n\tint max_count = 256;\n\tunsigned char ch;\n\tchar flag;", "\t//lsr &= mtpt->port.read_status_mask;", "\tdo {\n\t\tif ((lsr & UART_LSR_PE) && (mtpt->port.mdmode & MDMODE_ENABLE))\n\t\t{\n\t\t\tch = serial_inp(mtpt, UART_RX);\n\t\t}\n\t\telse if (lsr & UART_LSR_SPECIAL) \n\t\t{\n\t\t\tflag = 0;\n\t\t\tch = serial_inp(mtpt, UART_RX);", "\t\t\tif (lsr & UART_LSR_BI) \n\t\t\t{", "\t\t\t\tmtpt->port.icount.brk++;\n\t\t\t\tflag = TTY_BREAK;", "\t\t\t\tif (sb_uart_handle_break(&mtpt->port))\n\t\t\t\t\tgoto ignore_char;\n\t\t\t} \n\t\t\tif (lsr & UART_LSR_PE)\n\t\t\t{\n\t\t\t\tmtpt->port.icount.parity++;\n\t\t\t\tflag = TTY_PARITY;\n\t\t\t}\n\t\t\tif (lsr & UART_LSR_FE)\n\t\t\t{\n\t\t\t\tmtpt->port.icount.frame++;\n\t\t\t\tflag = TTY_FRAME;\n\t\t\t}\n\t\t\tif (lsr & UART_LSR_OE)\n\t\t\t{\n\t\t\t\tmtpt->port.icount.overrun++;\n\t\t\t\tflag = TTY_OVERRUN;\n\t\t\t}\n\t\t\ttty_insert_flip_char(tty, ch, flag);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tch = serial_inp(mtpt, UART_RX);\n\t\t\ttty_insert_flip_char(tty, ch, 0);\n\t\t}\nignore_char:\n\t\tlsr = serial_inp(mtpt, UART_LSR);\n\t} while ((lsr & UART_LSR_DR) && (max_count-- > 0));", "\ttty_flip_buffer_push(tty);\n}", "", "\nstatic _INLINE_ void transmit_chars(struct mp_port *mtpt)\n{\n\tstruct circ_buf *xmit = &mtpt->port.info->xmit;\n\tint count;", "\tif (mtpt->port.x_char) {\n\t\tserial_outp(mtpt, UART_TX, mtpt->port.x_char);\n\t\tmtpt->port.icount.tx++;\n\t\tmtpt->port.x_char = 0;\n\t\treturn;\n\t}\n\tif (uart_circ_empty(xmit) || uart_tx_stopped(&mtpt->port)) {\n\t\tmulti_stop_tx(&mtpt->port);\n\t\treturn;\n\t}", "\tcount = uart_circ_chars_pending(xmit);", "\tif(count > mtpt->port.fifosize)\n\t{\n\t\tcount = mtpt->port.fifosize;\n\t}", "\tprintk(\"[%d] mdmode: %x\\n\", mtpt->port.line, mtpt->port.mdmode);\n\tdo {\n#if 0\n\t\t/* check multi-drop mode */\n\t\tif ((mtpt->port.mdmode & (MDMODE_ENABLE | MDMODE_ADDR)) == (MDMODE_ENABLE | MDMODE_ADDR))\n\t\t{\n\t\t\tprintk(\"send address\\n\");\n\t\t\t/* send multi-drop address */\n\t\t\tserial_out(mtpt, UART_SCR, xmit->buf[xmit->tail]);\n\t\t}\n\t\telse\n#endif\n\t\t{\n\t\t\tserial_out(mtpt, UART_TX, xmit->buf[xmit->tail]);\n\t\t}\n\t\txmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1);\n\t\tmtpt->port.icount.tx++;\n\t} while (--count > 0);\n}", "", "static _INLINE_ void check_modem_status(struct mp_port *mtpt)\n{\n\tint status;", "\tstatus = serial_in(mtpt, UART_MSR);", "\tif ((status & UART_MSR_ANY_DELTA) == 0)\n\t\treturn;", "\tif (status & UART_MSR_TERI)\n\t\tmtpt->port.icount.rng++;\n\tif (status & UART_MSR_DDSR)\n\t\tmtpt->port.icount.dsr++;\n\tif (status & UART_MSR_DDCD)\n\t\tsb_uart_handle_dcd_change(&mtpt->port, status & UART_MSR_DCD);\n\tif (status & UART_MSR_DCTS)\n\t\tsb_uart_handle_cts_change(&mtpt->port, status & UART_MSR_CTS);", "\twake_up_interruptible(&mtpt->port.info->delta_msr_wait);\n}", "static inline void multi_handle_port(struct mp_port *mtpt)\n{\n\tunsigned int status = serial_inp(mtpt, UART_LSR);", "\t//printk(\"lsr: %x\\n\", status);", "\tif ((status & UART_LSR_DR) || (status & UART_LSR_SPECIAL))\n\t\treceive_chars(mtpt, &status);\n\tcheck_modem_status(mtpt);\n\tif (status & UART_LSR_THRE)\n\t{\n\t\tif ((mtpt->port.type == PORT_16C105X)\n\t\t\t|| (mtpt->port.type == PORT_16C105XA))\n\t\t\ttransmit_chars(mtpt);\n\t\telse\n\t\t{\n\t\t\tif (mtpt->interface >= RS485NE)\n\t\t\t\tuart_set_mctrl(&mtpt->port, TIOCM_RTS);\n\t\t\t\n\t\t\ttransmit_chars(mtpt);", "\n\t\t\tif (mtpt->interface >= RS485NE)\n\t\t\t{\n\t\t\t\twhile((status=serial_in(mtpt,UART_LSR) &0x60)!=0x60);\n\t\t\t\tuart_clear_mctrl(&mtpt->port, TIOCM_RTS);\n\t\t\t}\n\t\t}\n\t}\n}", "", "static irqreturn_t multi_interrupt(int irq, void *dev_id)\n{\n\tstruct irq_info *iinfo = dev_id;\n\tstruct list_head *lhead, *end = NULL;\n\tint pass_counter = 0;", "\n\tspin_lock(&iinfo->lock);", "\tlhead = iinfo->head;\n\tdo {\n\t\tstruct mp_port *mtpt;\n\t\tunsigned int iir;", "\t\tmtpt = list_entry(lhead, struct mp_port, list);\n\t\t\n\t\tiir = serial_in(mtpt, UART_IIR);\n\t\tprintk(\"interrupt! port %d, iir 0x%x\\n\", mtpt->port.line, iir); //wlee\n\t\tif (!(iir & UART_IIR_NO_INT)) \n\t\t{\n\t\t\tprintk(\"interrupt handle\\n\");\n\t\t\tspin_lock(&mtpt->port.lock);\n\t\t\tmulti_handle_port(mtpt);\n\t\t\tspin_unlock(&mtpt->port.lock);", "\t\t\tend = NULL;\n\t\t} else if (end == NULL)\n\t\t\tend = lhead;", "\t\tlhead = lhead->next;\n\t\tif (lhead == iinfo->head && pass_counter++ > PASS_LIMIT) \n\t\t{\n\t\t\tprintk(KERN_ERR \"multi: too much work for \"\n\t\t\t\t\t\"irq%d\\n\", irq);\n\t\t\tprintk( \"multi: too much work for \"\n\t\t\t\t\t\"irq%d\\n\", irq);\n\t\t\tbreak;\n\t\t}\n\t} while (lhead != end);", "\tspin_unlock(&iinfo->lock);", "\n return IRQ_HANDLED;\n}", "static void serial_do_unlink(struct irq_info *i, struct mp_port *mtpt)\n{\n\tspin_lock_irq(&i->lock);", "\tif (!list_empty(i->head)) {\n\t\tif (i->head == &mtpt->list)\n\t\t\ti->head = i->head->next;\n\t\tlist_del(&mtpt->list);\n\t} else {\n\t\ti->head = NULL;\n\t}", "\tspin_unlock_irq(&i->lock);\n}", "static int serial_link_irq_chain(struct mp_port *mtpt)\n{\n\tstruct irq_info *i = irq_lists + mtpt->port.irq;\n\tint ret, irq_flags = mtpt->port.flags & UPF_SHARE_IRQ ? IRQF_SHARED : 0;\n\tspin_lock_irq(&i->lock);", "\tif (i->head) {\n\t\tlist_add(&mtpt->list, i->head);\n\t\tspin_unlock_irq(&i->lock);", "\t\tret = 0;\n\t} else {\n\t\tINIT_LIST_HEAD(&mtpt->list);\n\t\ti->head = &mtpt->list;\n\t\tspin_unlock_irq(&i->lock);", "\t\tret = request_irq(mtpt->port.irq, multi_interrupt,\n\t\t\t\tirq_flags, \"serial\", i);\n\t\tif (ret < 0)\n\t\t\tserial_do_unlink(i, mtpt);\n\t}", "\treturn ret;\n}", "", "\nstatic void serial_unlink_irq_chain(struct mp_port *mtpt)\n{\n\tstruct irq_info *i = irq_lists + mtpt->port.irq;", "\tif (list_empty(i->head))\n\t{\n\t\tfree_irq(mtpt->port.irq, i);\n\t}\n\tserial_do_unlink(i, mtpt);\n}", "static void multi_timeout(unsigned long data)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)data;", "\n\tspin_lock(&mtpt->port.lock);\n\tmulti_handle_port(mtpt);\n\tspin_unlock(&mtpt->port.lock);", "\tmod_timer(&mtpt->timer, jiffies+1 );\n}", "static unsigned int multi_tx_empty(struct sb_uart_port *port)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tunsigned long flags;\n\tunsigned int ret;", "\tspin_lock_irqsave(&mtpt->port.lock, flags);\n\tret = serial_in(mtpt, UART_LSR) & UART_LSR_TEMT ? TIOCSER_TEMT : 0;\n\tspin_unlock_irqrestore(&mtpt->port.lock, flags);", "\treturn ret;\n}", "\nstatic unsigned int multi_get_mctrl(struct sb_uart_port *port)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tunsigned char status;\n\tunsigned int ret;", "\tstatus = serial_in(mtpt, UART_MSR);", "\tret = 0;\n\tif (status & UART_MSR_DCD)\n\t\tret |= TIOCM_CAR;\n\tif (status & UART_MSR_RI)\n\t\tret |= TIOCM_RNG;\n\tif (status & UART_MSR_DSR)\n\t\tret |= TIOCM_DSR;\n\tif (status & UART_MSR_CTS)\n\t\tret |= TIOCM_CTS;\n\treturn ret;\n}", "static void multi_set_mctrl(struct sb_uart_port *port, unsigned int mctrl)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tunsigned char mcr = 0;", "\tmctrl &= 0xff;", "\tif (mctrl & TIOCM_RTS)\n\t\tmcr |= UART_MCR_RTS;\n\tif (mctrl & TIOCM_DTR)\n\t\tmcr |= UART_MCR_DTR;\n\tif (mctrl & TIOCM_OUT1)\n\t\tmcr |= UART_MCR_OUT1;\n\tif (mctrl & TIOCM_OUT2)\n\t\tmcr |= UART_MCR_OUT2;\n\tif (mctrl & TIOCM_LOOP)\n\t\tmcr |= UART_MCR_LOOP;", "\n\tserial_out(mtpt, UART_MCR, mcr);\n}", "\nstatic void multi_break_ctl(struct sb_uart_port *port, int break_state)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tunsigned long flags;", "\tspin_lock_irqsave(&mtpt->port.lock, flags);\n\tif (break_state == -1)\n\t\tmtpt->lcr |= UART_LCR_SBC;\n\telse\n\t\tmtpt->lcr &= ~UART_LCR_SBC;\n\tserial_out(mtpt, UART_LCR, mtpt->lcr);\n\tspin_unlock_irqrestore(&mtpt->port.lock, flags);\n}", "", "static int multi_startup(struct sb_uart_port *port)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tunsigned long flags;\n\tint retval;", "\tmtpt->capabilities = uart_config[mtpt->port.type].flags;\n\tmtpt->mcr = 0;", "\tif (mtpt->capabilities & UART_CLEAR_FIFO) {\n\t\tserial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO);\n\t\tserial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO |\n\t\t\t\tUART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT);\n\t\tserial_outp(mtpt, UART_FCR, 0);\n\t}", "\t(void) serial_inp(mtpt, UART_LSR);\n\t(void) serial_inp(mtpt, UART_RX);\n\t(void) serial_inp(mtpt, UART_IIR);\n\t(void) serial_inp(mtpt, UART_MSR);\n\t//test-wlee 9-bit disable\n\tserial_outp(mtpt, UART_MSR, 0);", "\n\tif (!(mtpt->port.flags & UPF_BUGGY_UART) &&\n\t\t\t(serial_inp(mtpt, UART_LSR) == 0xff)) {\n\t\tprintk(\"ttyS%d: LSR safety check engaged!\\n\", mtpt->port.line);\n\t\t//return -ENODEV;\n\t}", "\tif ((!is_real_interrupt(mtpt->port.irq)) || (mtpt->poll_type==TYPE_POLL)) {\n\t\tunsigned int timeout = mtpt->port.timeout;", "\t\ttimeout = timeout > 6 ? (timeout / 2 - 2) : 1;", "\t\tmtpt->timer.data = (unsigned long)mtpt;\n\t\tmod_timer(&mtpt->timer, jiffies + timeout);\n\t} \n\telse \n\t{\n\t\tretval = serial_link_irq_chain(mtpt);\n\t\tif (retval)\n\t\t\treturn retval;\n\t}", "\tserial_outp(mtpt, UART_LCR, UART_LCR_WLEN8);", "\tspin_lock_irqsave(&mtpt->port.lock, flags);\n\tif ((is_real_interrupt(mtpt->port.irq))||(mtpt->poll_type==TYPE_INTERRUPT))\n\t\tmtpt->port.mctrl |= TIOCM_OUT2;", "\tmulti_set_mctrl(&mtpt->port, mtpt->port.mctrl);\n\tspin_unlock_irqrestore(&mtpt->port.lock, flags);", "\t\n\tmtpt->ier = UART_IER_RLSI | UART_IER_RDI;\n\tserial_outp(mtpt, UART_IER, mtpt->ier);", "\t(void) serial_inp(mtpt, UART_LSR);\n\t(void) serial_inp(mtpt, UART_RX);\n\t(void) serial_inp(mtpt, UART_IIR);\n\t(void) serial_inp(mtpt, UART_MSR);", "\treturn 0;\n}", "", "static void multi_shutdown(struct sb_uart_port *port)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tunsigned long flags;", "\n\tmtpt->ier = 0;\n\tserial_outp(mtpt, UART_IER, 0);", "\tspin_lock_irqsave(&mtpt->port.lock, flags);\n\tmtpt->port.mctrl &= ~TIOCM_OUT2;", "\tmulti_set_mctrl(&mtpt->port, mtpt->port.mctrl);\n\tspin_unlock_irqrestore(&mtpt->port.lock, flags);", "\tserial_out(mtpt, UART_LCR, serial_inp(mtpt, UART_LCR) & ~UART_LCR_SBC);\n\tserial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO |\n\t\t\tUART_FCR_CLEAR_RCVR |\n\t\t\tUART_FCR_CLEAR_XMIT);\n\tserial_outp(mtpt, UART_FCR, 0);", "\n\t(void) serial_in(mtpt, UART_RX);", "\tif ((!is_real_interrupt(mtpt->port.irq))||(mtpt->poll_type==TYPE_POLL))\n\t{\n\t\tdel_timer_sync(&mtpt->timer);\n\t}\n\telse\n\t{\n\t\tserial_unlink_irq_chain(mtpt);\n\t}\n}", "", "static unsigned int multi_get_divisor(struct sb_uart_port *port, unsigned int baud)\n{\n\tunsigned int quot;", "\tif ((port->flags & UPF_MAGIC_MULTIPLIER) &&\n\t\t\tbaud == (port->uartclk/4))\n\t\tquot = 0x8001;\n\telse if ((port->flags & UPF_MAGIC_MULTIPLIER) &&\n\t\t\tbaud == (port->uartclk/8))\n\t\tquot = 0x8002;\n\telse\n\t\tquot = sb_uart_get_divisor(port, baud);", "\treturn quot;\n}", "", "\nstatic void multi_set_termios(struct sb_uart_port *port, struct MP_TERMIOS *termios, struct MP_TERMIOS *old)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tunsigned char cval, fcr = 0;\n\tunsigned long flags;\n\tunsigned int baud, quot;", "\tswitch (termios->c_cflag & CSIZE) {\n\t\tcase CS5:\n\t\t\tcval = 0x00;\n\t\t\tbreak;\n\t\tcase CS6:\n\t\t\tcval = 0x01;\n\t\t\tbreak;\n\t\tcase CS7:\n\t\t\tcval = 0x02;\n\t\t\tbreak;\n\t\tdefault:\n\t\tcase CS8:\n\t\t\tcval = 0x03;\n\t\t\tbreak;\n\t}", "\tif (termios->c_cflag & CSTOPB)\n\t\tcval |= 0x04;\n\tif (termios->c_cflag & PARENB)\n\t\tcval |= UART_LCR_PARITY;\n\tif (!(termios->c_cflag & PARODD))\n\t\tcval |= UART_LCR_EPAR;", "#ifdef CMSPAR\n\tif (termios->c_cflag & CMSPAR)\n\t\tcval |= UART_LCR_SPAR;\n#endif", "\tbaud = sb_uart_get_baud_rate(port, termios, old, 0, port->uartclk/16);\n\tquot = multi_get_divisor(port, baud);", "\tif (mtpt->capabilities & UART_USE_FIFO) {\n\t\t//if (baud < 2400)\n\t\t//\tfcr = UART_FCR_ENABLE_FIFO | UART_FCR_TRIGGER_1;\n\t\t//else\n\t\t//\tfcr = UART_FCR_ENABLE_FIFO | UART_FCR_TRIGGER_8;", "\t\t//\tfcr = UART_FCR_ENABLE_FIFO | 0x90;\n\t\t\tfcr = fcr_arr[mtpt->port.line];\n\t}", "\tspin_lock_irqsave(&mtpt->port.lock, flags);", "\tsb_uart_update_timeout(port, termios->c_cflag, baud);", "\tmtpt->port.read_status_mask = UART_LSR_OE | UART_LSR_THRE | UART_LSR_DR;\n\tif (termios->c_iflag & INPCK)\n\t\tmtpt->port.read_status_mask |= UART_LSR_FE | UART_LSR_PE;\n\tif (termios->c_iflag & (BRKINT | PARMRK))\n\t\tmtpt->port.read_status_mask |= UART_LSR_BI;", "\tmtpt->port.ignore_status_mask = 0;\n\tif (termios->c_iflag & IGNPAR)\n\t\tmtpt->port.ignore_status_mask |= UART_LSR_PE | UART_LSR_FE;\n\tif (termios->c_iflag & IGNBRK) {\n\t\tmtpt->port.ignore_status_mask |= UART_LSR_BI;\n\t\tif (termios->c_iflag & IGNPAR)\n\t\t\tmtpt->port.ignore_status_mask |= UART_LSR_OE;\n\t}", "\tif ((termios->c_cflag & CREAD) == 0)\n\t\tmtpt->port.ignore_status_mask |= UART_LSR_DR;", "\tmtpt->ier &= ~UART_IER_MSI;\n\tif (UART_ENABLE_MS(&mtpt->port, termios->c_cflag))\n\t\tmtpt->ier |= UART_IER_MSI;", "\tserial_out(mtpt, UART_IER, mtpt->ier);", "\tif (mtpt->capabilities & UART_STARTECH) {\n\t\tserial_outp(mtpt, UART_LCR, 0xBF);\n\t\tserial_outp(mtpt, UART_EFR,\n\t\t\t\ttermios->c_cflag & CRTSCTS ? UART_EFR_CTS :0);\n\t}", "\tserial_outp(mtpt, UART_LCR, cval | UART_LCR_DLAB);/* set DLAB */", "\tserial_outp(mtpt, UART_DLL, quot & 0xff); /* LS of divisor */\n\tserial_outp(mtpt, UART_DLM, quot >> 8); /* MS of divisor */", "\tserial_outp(mtpt, UART_LCR, cval); /* reset DLAB */\n\tmtpt->lcr = cval; /* Save LCR */", "\tif (fcr & UART_FCR_ENABLE_FIFO) {\n\t\t/* emulated UARTs (Lucent Venus 167x) need two steps */\n\t\tserial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO);\n\t}", "\tserial_outp(mtpt, UART_FCR, fcr); /* set fcr */", "\n\tif ((mtpt->port.type == PORT_16C105X)\n\t\t|| (mtpt->port.type == PORT_16C105XA))\n\t{\n\t\tif(deep[mtpt->port.line]!=0)\n\t\t\tset_deep_fifo(port, ENABLE);", "\t\tif (mtpt->interface != RS232)\n\t\t\tset_auto_rts(port,mtpt->interface);", "\t}\n\telse\n\t{\n\t\tif (mtpt->interface >= RS485NE)\n\t\t{\n\t\t\tuart_clear_mctrl(&mtpt->port, TIOCM_RTS);\n\t\t}\n\t}", "\tif(mtpt->device->device_id == PCI_DEVICE_ID_MP4M)\n\t{\n\t\tSendATCommand(mtpt);\n\t\tprintk(\"SendATCommand\\n\");\n\t}\t\n\tmulti_set_mctrl(&mtpt->port, mtpt->port.mctrl);\n\tspin_unlock_irqrestore(&mtpt->port.lock, flags);\n}", "static void multi_pm(struct sb_uart_port *port, unsigned int state, unsigned int oldstate)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tif (state) {\n\t\tif (mtpt->capabilities & UART_STARTECH) {\n\t\t\tserial_outp(mtpt, UART_LCR, 0xBF);\n\t\t\tserial_outp(mtpt, UART_EFR, UART_EFR_ECB);\n\t\t\tserial_outp(mtpt, UART_LCR, 0);\n\t\t\tserial_outp(mtpt, UART_IER, UART_IERX_SLEEP);\n\t\t\tserial_outp(mtpt, UART_LCR, 0xBF);\n\t\t\tserial_outp(mtpt, UART_EFR, 0);\n\t\t\tserial_outp(mtpt, UART_LCR, 0);\n\t\t}", "\t\tif (mtpt->pm)\n\t\t\tmtpt->pm(port, state, oldstate);\n\t} \n\telse \n\t{\n\t\tif (mtpt->capabilities & UART_STARTECH) {\n\t\t\tserial_outp(mtpt, UART_LCR, 0xBF);\n\t\t\tserial_outp(mtpt, UART_EFR, UART_EFR_ECB);\n\t\t\tserial_outp(mtpt, UART_LCR, 0);\n\t\t\tserial_outp(mtpt, UART_IER, 0);\n\t\t\tserial_outp(mtpt, UART_LCR, 0xBF);\n\t\t\tserial_outp(mtpt, UART_EFR, 0);\n\t\t\tserial_outp(mtpt, UART_LCR, 0);\n\t\t}", "\t\tif (mtpt->pm)\n\t\t\tmtpt->pm(port, state, oldstate);\n\t}\n}", "static void multi_release_std_resource(struct mp_port *mtpt)\n{\n\tunsigned int size = 8 << mtpt->port.regshift;", "\tswitch (mtpt->port.iotype) {\n\t\tcase UPIO_MEM:\n\t\t\tif (!mtpt->port.mapbase)\n\t\t\t\tbreak;", "\t\t\tif (mtpt->port.flags & UPF_IOREMAP) {\n\t\t\t\tiounmap(mtpt->port.membase);\n\t\t\t\tmtpt->port.membase = NULL;\n\t\t\t}", "\t\t\trelease_mem_region(mtpt->port.mapbase, size);\n\t\t\tbreak;", "\t\tcase UPIO_HUB6:\n\t\tcase UPIO_PORT:\n\t\t\trelease_region(mtpt->port.iobase,size);\n\t\t\tbreak;\n\t}\n}", "static void multi_release_port(struct sb_uart_port *port)\n{\n}", "static int multi_request_port(struct sb_uart_port *port)\n{\n\treturn 0;\n}", "static void multi_config_port(struct sb_uart_port *port, int flags)\n{\n\tstruct mp_port *mtpt = (struct mp_port *)port;\n\tint probeflags = PROBE_ANY;", "\tif (flags & UART_CONFIG_TYPE)\n\t\tautoconfig(mtpt, probeflags);\n\tif (mtpt->port.type != PORT_UNKNOWN && flags & UART_CONFIG_IRQ)\n\t\tautoconfig_irq(mtpt);", "\tif (mtpt->port.type == PORT_UNKNOWN)\n\t\tmulti_release_std_resource(mtpt);\n}", "static int multi_verify_port(struct sb_uart_port *port, struct serial_struct *ser)\n{\n\tif (ser->irq >= NR_IRQS || ser->irq < 0 ||\n\t\t\tser->baud_base < 9600 || ser->type < PORT_UNKNOWN ||\n\t\t\tser->type == PORT_STARTECH)\n\t\treturn -EINVAL;\n\treturn 0;\n}", "static const char *multi_type(struct sb_uart_port *port)\n{\n\tint type = port->type;", "\tif (type >= ARRAY_SIZE(uart_config))\n\t\ttype = 0;\n\treturn uart_config[type].name;\n}", "static struct sb_uart_ops multi_pops = {\n\t.tx_empty = multi_tx_empty,\n\t.set_mctrl = multi_set_mctrl,\n\t.get_mctrl = multi_get_mctrl,\n\t.stop_tx = multi_stop_tx,\n\t.start_tx = multi_start_tx,\n\t.stop_rx = multi_stop_rx,\n\t.enable_ms = multi_enable_ms,\n\t.break_ctl = multi_break_ctl,\n\t.startup = multi_startup,\n\t.shutdown = multi_shutdown,\n\t.set_termios = multi_set_termios,\n\t.pm \t= multi_pm,\n\t.type \t= multi_type,\n\t.release_port = multi_release_port,\n\t.request_port = multi_request_port,\n\t.config_port = multi_config_port,\n\t.verify_port = multi_verify_port,\n};", "static struct uart_driver multi_reg = {\n\t.owner = THIS_MODULE,\n\t.driver_name = \"goldel_tulip\",\n\t.dev_name = \"ttyMP\",\n\t.major = SB_TTY_MP_MAJOR,\n\t.minor = 0,\n\t.nr = MAX_MP_PORT, \n\t.cons = NULL,\n};", "static void __init multi_init_ports(void)\n{\n\tstruct mp_port *mtpt;\n\tstatic int first = 1;\n\tint i,j,k;\n\tunsigned char osc;\n\tunsigned char b_ret = 0;\n\tstatic struct mp_device_t *sbdev; ", "\tif (!first)\n\t\treturn;\n\tfirst = 0;", "\tmtpt = multi_ports; ", "\tfor (k=0;k<NR_BOARD;k++)\n\t{\n\t\tsbdev = &mp_devs[k];", "\t\tfor (i = 0; i < sbdev->nr_ports; i++, mtpt++) \n\t\t{\n\t\t\tmtpt->device \t\t= sbdev;\n\t\t\tmtpt->port.iobase = sbdev->uart_access_addr + 8*i;\n\t\t\tmtpt->port.irq = sbdev->irq;\n\t\t\tif ( ((sbdev->device_id == PCI_DEVICE_ID_MP4)&&(sbdev->revision==0x91)))\n\t\t\t\tmtpt->interface_config_addr = sbdev->option_reg_addr + 0x08 + i;\n\t\t\telse if (sbdev->revision == 0xc0)\n\t\t\t\tmtpt->interface_config_addr = sbdev->option_reg_addr + 0x08 + (i & 0x1);\n\t\t\telse\n\t\t\t\tmtpt->interface_config_addr = sbdev->option_reg_addr + 0x08 + i/8;", "\t\t\tmtpt->option_base_addr = sbdev->option_reg_addr;", "\t\t\tmtpt->poll_type = sbdev->poll_type;", "\t\t\tmtpt->port.uartclk = BASE_BAUD * 16;", "\t\t\t/* get input clock information */\n\t\t\tosc = inb(sbdev->option_reg_addr + MP_OPTR_DIR0 + i/8) & 0x0F;\n\t\t\tif (osc==0x0f)\n\t\t\t\tosc = 0;\n\t\t\tfor(j=0;j<osc;j++)\n\t\t\t\tmtpt->port.uartclk *= 2;\n\t\t\tmtpt->port.flags |= STD_COM_FLAGS | UPF_SHARE_IRQ ;\n\t\t\tmtpt->port.iotype = UPIO_PORT;\n\t\t\tmtpt->port.ops = &multi_pops;", "\t\t\tif (sbdev->revision == 0xc0)\n\t\t\t{\n\t\t\t\t/* for SB16C1053APCI */\n\t\t\t\tb_ret = sb1053a_get_interface(mtpt, i);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tb_ret = read_option_register(mtpt,(MP_OPTR_IIR0 + i/8));\n\t\t\t\tprintk(\"IIR_RET = %x\\n\",b_ret);\n\t\t\t}", "\t\t\t/* default to RS232 */\n\t\t\tmtpt->interface = RS232;\n\t\t\tif (IIR_RS422 == (b_ret & IIR_TYPE_MASK))\n\t\t\t\tmtpt->interface = RS422PTP;\n\t\t\tif (IIR_RS485 == (b_ret & IIR_TYPE_MASK))\n\t\t\t\tmtpt->interface = RS485NE;\n\t\t}\n\t}\n}", "static void __init multi_register_ports(struct uart_driver *drv)\n{\n\tint i;", "\tmulti_init_ports();", "\tfor (i = 0; i < NR_PORTS; i++) {\n\t\tstruct mp_port *mtpt = &multi_ports[i];", "\t\tmtpt->port.line = i;\n\t\tmtpt->port.ops = &multi_pops;\n\t\tinit_timer(&mtpt->timer);\n\t\tmtpt->timer.function = multi_timeout;\n\t\tmp_add_one_port(drv, &mtpt->port);\n\t}\n}", "/**\n * pci_remap_base - remap BAR value of pci device\n *\n * PARAMETERS\n * pcidev - pci_dev structure address\n * offset - BAR offset PCI_BASE_ADDRESS_0 ~ PCI_BASE_ADDRESS_4\n * address - address to be changed BAR value\n * size\t- size of address space \n *\n * RETURNS\n * If this function performs successful, it returns 0. Otherwise, It returns -1.\n */\nstatic int pci_remap_base(struct pci_dev *pcidev, unsigned int offset, \n\t\tunsigned int address, unsigned int size) \n{\n#if 0\n\tstruct resource *root;\n\tunsigned index = (offset - 0x10) >> 2;\n#endif", "\tpci_write_config_dword(pcidev, offset, address);\n#if 0\n\troot = pcidev->resource[index].parent;\n\trelease_resource(&pcidev->resource[index]);\n\taddress &= ~0x1;\n\tpcidev->resource[index].start = address;\n\tpcidev->resource[index].end\t = address + size - 1;", "\tif (request_resource(root, &pcidev->resource[index]) != NULL)\n\t{\n\t\tprintk(KERN_ERR \"pci remap conflict!! 0x%x\\n\", address);\n\t\treturn (-1);\n\t}\n#endif", "\treturn (0);\n}", "static int init_mp_dev(struct pci_dev *pcidev, mppcibrd_t brd)\n{\n\tstatic struct mp_device_t *sbdev = mp_devs;\n\tunsigned long addr = 0;\n\tint j;\n\tstruct resource *ret = NULL;", "\tsbdev->device_id = brd.device_id;\n\tpci_read_config_byte(pcidev, PCI_CLASS_REVISION, &(sbdev->revision));\n\tsbdev->name = brd.name;\n\tsbdev->uart_access_addr = pcidev->resource[0].start & PCI_BASE_ADDRESS_IO_MASK;", "\t/* check revision. The SB16C1053APCI's option i/o address is BAR4 */\n\tif (sbdev->revision == 0xc0)\n\t{\n\t\t/* SB16C1053APCI */\n\t\tsbdev->option_reg_addr = pcidev->resource[4].start & PCI_BASE_ADDRESS_IO_MASK;\n\t}\n\telse\n\t{\n\t\tsbdev->option_reg_addr = pcidev->resource[1].start & PCI_BASE_ADDRESS_IO_MASK;\n\t}\n#if 1\t\n\tif (sbdev->revision == 0xc0)\n\t{\n\t\toutb(0x00, sbdev->option_reg_addr + MP_OPTR_GPOCR);\n\t\tinb(sbdev->option_reg_addr + MP_OPTR_GPOCR);\n\t\toutb(0x83, sbdev->option_reg_addr + MP_OPTR_GPOCR);\n\t}\n#endif", "\tsbdev->irq = pcidev->irq;", "\tif ((brd.device_id & 0x0800) || !(brd.device_id &0xff00))\n\t{\n\t\tsbdev->poll_type = TYPE_INTERRUPT;\n\t}\n\telse\n\t{\n\t\tsbdev->poll_type = TYPE_POLL;\n\t}", "\t/* codes which is specific to each board*/\n\tswitch(brd.device_id){\n\t\tcase PCI_DEVICE_ID_MP1 :\n\t\tcase PCIE_DEVICE_ID_MP1 :\n\t\tcase PCIE_DEVICE_ID_MP1E :\n\t\tcase PCIE_DEVICE_ID_GT_MP1 :\n\t\t\tsbdev->nr_ports = 1;\n\t\t\tbreak;\n\t\tcase PCI_DEVICE_ID_MP2 :\n\t\tcase PCIE_DEVICE_ID_MP2 :\n\t\tcase PCIE_DEVICE_ID_GT_MP2 :\n\t\tcase PCIE_DEVICE_ID_MP2B :\n\t\tcase PCIE_DEVICE_ID_MP2E :\n\t\t\tsbdev->nr_ports = 2;", "\t\t\t/* serial base address remap */\n\t\t\tif (sbdev->revision == 0xc0)\n\t\t\t{\n\t\t\t\tint prev_port_addr = 0;", "\t\t\t\tpci_read_config_dword(pcidev, PCI_BASE_ADDRESS_0, &prev_port_addr);\n\t\t\t\tpci_remap_base(pcidev, PCI_BASE_ADDRESS_1, prev_port_addr + 8, 8);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase PCI_DEVICE_ID_MP4 :\n\t\tcase PCI_DEVICE_ID_MP4A :\n\t\tcase PCIE_DEVICE_ID_MP4 :\n\t\tcase PCI_DEVICE_ID_GT_MP4 :\n\t\tcase PCI_DEVICE_ID_GT_MP4A :\n\t\tcase PCIE_DEVICE_ID_GT_MP4 :\n\t\tcase PCI_DEVICE_ID_MP4M :\n\t\tcase PCIE_DEVICE_ID_MP4B :\n\t\t\tsbdev->nr_ports = 4;", "\t\t\tif(sbdev->revision == 0x91){\n\t\t\t\tsbdev->reserved_addr[0] = pcidev->resource[0].start & PCI_BASE_ADDRESS_IO_MASK;\n\t\t\t\toutb(0x03 , sbdev->reserved_addr[0] + 0x01);\n\t\t\t\toutb(0x03 , sbdev->reserved_addr[0] + 0x02);\n\t\t\t\toutb(0x01 , sbdev->reserved_addr[0] + 0x20);\n\t\t\t\toutb(0x00 , sbdev->reserved_addr[0] + 0x21);\n\t\t\t\trequest_region(sbdev->reserved_addr[0], 32, sbdev->name);\n\t\t\t\tsbdev->uart_access_addr = pcidev->resource[1].start & PCI_BASE_ADDRESS_IO_MASK;\n\t\t\t\tsbdev->option_reg_addr = pcidev->resource[2].start & PCI_BASE_ADDRESS_IO_MASK;\n\t\t\t}", "\t\t\t/* SB16C1053APCI */\n\t\t\tif (sbdev->revision == 0xc0)\n\t\t\t{\n\t\t\t\tint prev_port_addr = 0;", "\t\t\t\tpci_read_config_dword(pcidev, PCI_BASE_ADDRESS_0, &prev_port_addr);\n\t\t\t\tpci_remap_base(pcidev, PCI_BASE_ADDRESS_1, prev_port_addr + 8, 8);\n\t\t\t\tpci_remap_base(pcidev, PCI_BASE_ADDRESS_2, prev_port_addr + 16, 8);\n\t\t\t\tpci_remap_base(pcidev, PCI_BASE_ADDRESS_3, prev_port_addr + 24, 8);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase PCI_DEVICE_ID_MP6 :\n\t\tcase PCI_DEVICE_ID_MP6A :\n\t\tcase PCI_DEVICE_ID_GT_MP6 :\n\t\tcase PCI_DEVICE_ID_GT_MP6A :\n\t\t\tsbdev->nr_ports = 6;", "\t\t\t/* SB16C1053APCI */\n\t\t\tif (sbdev->revision == 0xc0)\n\t\t\t{\n\t\t\t\tint prev_port_addr = 0;", "\t\t\t\tpci_read_config_dword(pcidev, PCI_BASE_ADDRESS_0, &prev_port_addr);\n\t\t\t\tpci_remap_base(pcidev, PCI_BASE_ADDRESS_1, prev_port_addr + 8, 8);\n\t\t\t\tpci_remap_base(pcidev, PCI_BASE_ADDRESS_2, prev_port_addr + 16, 16);\n\t\t\t\tpci_remap_base(pcidev, PCI_BASE_ADDRESS_3, prev_port_addr + 32, 16);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase PCI_DEVICE_ID_MP8 :\n\t\tcase PCIE_DEVICE_ID_MP8 :\n\t\tcase PCI_DEVICE_ID_GT_MP8 :\n\t\tcase PCIE_DEVICE_ID_GT_MP8 :\n\t\tcase PCIE_DEVICE_ID_MP8B :\n\t\t\tsbdev->nr_ports = 8;\n\t\t\tbreak;\n\t\tcase PCI_DEVICE_ID_MP32 :\n\t\tcase PCIE_DEVICE_ID_MP32 :\n\t\tcase PCI_DEVICE_ID_GT_MP32 :\n\t\tcase PCIE_DEVICE_ID_GT_MP32 :\n\t\t\t{\n\t\t\t\tint portnum_hex=0;\n\t\t\t\tportnum_hex = inb(sbdev->option_reg_addr);\n\t\t\t\tsbdev->nr_ports = ((portnum_hex/16)*10) + (portnum_hex % 16);\n\t\t\t}\n\t\t\tbreak;\n#ifdef CONFIG_PARPORT_PC\n\t\tcase PCI_DEVICE_ID_MP2S1P :\n\t\t\tsbdev->nr_ports = 2;", "\t\t\t/* SB16C1053APCI */\n\t\t\tif (sbdev->revision == 0xc0)\n\t\t\t{\n\t\t\t\tint prev_port_addr = 0;", "\t\t\t\tpci_read_config_dword(pcidev, PCI_BASE_ADDRESS_0, &prev_port_addr);\n\t\t\t\tpci_remap_base(pcidev, PCI_BASE_ADDRESS_1, prev_port_addr + 8, 8);\n\t\t\t}", "\t\t\t/* add PC compatible parallel port */\n\t\t\tparport_pc_probe_port(pcidev->resource[2].start, pcidev->resource[3].start, PARPORT_IRQ_NONE, PARPORT_DMA_NONE, &pcidev->dev, 0);\n\t\t\tbreak;\n\t\tcase PCI_DEVICE_ID_MP1P :\n\t\t\t/* add PC compatible parallel port */\n\t\t\tparport_pc_probe_port(pcidev->resource[2].start, pcidev->resource[3].start, PARPORT_IRQ_NONE, PARPORT_DMA_NONE, &pcidev->dev, 0);\n\t\t\tbreak;\n#endif\n\t}", "\tret = request_region(sbdev->uart_access_addr, (8*sbdev->nr_ports), sbdev->name);", "\tif (sbdev->revision == 0xc0)\n\t{\n\t\tret = request_region(sbdev->option_reg_addr, 0x40, sbdev->name);\n\t}\n\telse\n\t{\n\t\tret = request_region(sbdev->option_reg_addr, 0x20, sbdev->name);\n\t}", "\n\tNR_BOARD++;\n\tNR_PORTS += sbdev->nr_ports;", "\t/* Enable PCI interrupt */\n\taddr = sbdev->option_reg_addr + MP_OPTR_IMR0;\n\tfor(j=0; j < (sbdev->nr_ports/8)+1; j++)\n\t{\n\t\tif (sbdev->poll_type == TYPE_INTERRUPT)\n\t\t{\n\t\t\toutb(0xff,addr +j);\n\t\t}\n\t}\n\tsbdev++;", "\treturn 0;\n}", "static int __init multi_init(void)\n{\n\tint ret, i;\n\tstruct pci_dev *dev = NULL;", "\tif(fcr_count==0)\n\t{\n\t\tfor(i=0;i<256;i++)\n\t\t{\n\t\t\tfcr_arr[i] = 0x01;\n\t\t\t\n\t\t}\n\t}\n\tif(deep_count==0)\n\t{\n\t\tfor(i=0;i<256;i++)\n\t\t{\n\t\t\tdeep[i] = 1;\n\t\t\t\n\t\t}\n\t}\n\tif(rtr_count==0)\n {\n for(i=0;i<256;i++)\n {\n rtr[i] = 0x10;\n }\n }\n\tif(ttr_count==0)\n {\n for(i=0;i<256;i++)\n {\n ttr[i] = 0x38;\n }\n }", "\nprintk(\"MULTI INIT\\n\");\n\tfor( i=0; i< mp_nrpcibrds; i++)\n\t{", "\t\twhile( (dev = pci_get_device(mp_pciboards[i].vendor_id, mp_pciboards[i].device_id, dev) ) )", "\t\t{\nprintk(\"FOUND~~~\\n\");\n//\tCent OS bug fix\n//\t\t\tif (mp_pciboards[i].device_id & 0x0800)\n\t\t\t{\n\t\t\t\tint status;\n\t \t\tpci_disable_device(dev);\n\t \t\tstatus = pci_enable_device(dev);\n \n\t \t\t \tif (status != 0)\n \t\t\t{ \n \t\t\t\tprintk(\"Multiport Board Enable Fail !\\n\\n\");\n \t\t\t\tstatus = -ENXIO;\n \t\t\treturn status;\n \t\t\t}\n\t\t\t}", "\t\t\tinit_mp_dev(dev, mp_pciboards[i]);\t\n\t\t}\n\t}", "\tfor (i = 0; i < NR_IRQS; i++)\n\t\tspin_lock_init(&irq_lists[i].lock);", "\tret = mp_register_driver(&multi_reg);", "\tif (ret >= 0)\n\t\tmulti_register_ports(&multi_reg);", "\treturn ret;\n}", "static void __exit multi_exit(void)\n{\n\tint i;", "\tfor (i = 0; i < NR_PORTS; i++)\n\t\tmp_remove_one_port(&multi_reg, &multi_ports[i].port);", "\tmp_unregister_driver(&multi_reg);\n}", "module_init(multi_init);\nmodule_exit(multi_exit);", "MODULE_DESCRIPTION(\"SystemBase Multiport PCI/PCIe CORE\");\nMODULE_LICENSE(\"GPL\");" ]
[ 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1067], "buggy_code_start_loc": [1066], "filenames": ["drivers/staging/sb105x/sb_pci_mp.c"], "fixing_code_end_loc": [1067], "fixing_code_start_loc": [1066], "message": "The mp_get_count function in drivers/staging/sb105x/sb_pci_mp.c in the Linux kernel before 3.12 does not initialize a certain data structure, which allows local users to obtain sensitive information from kernel stack memory via a TIOCGICOUNT ioctl call.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "74676759-D357-4224-9C07-7FCAB195A0CD", "versionEndExcluding": null, "versionEndIncluding": "3.11.7", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "D30AEC07-3CBD-4F4F-9646-BEAA1D98750B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc2:*:*:*:*:*:*", "matchCriteriaId": "C2AA8E68-691B-499C-AEDD-3C0BFFE70044", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc3:*:*:*:*:*:*", "matchCriteriaId": "9440475B-5960-4066-A204-F30AAFC87846", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc4:*:*:*:*:*:*", "matchCriteriaId": "53BCFBFB-6AF0-4525-8623-7633CC5E17DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc5:*:*:*:*:*:*", "matchCriteriaId": "6ED4E86A-74F0-436A-BEB4-3F4EE93A5421", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc6:*:*:*:*:*:*", "matchCriteriaId": "BF0365B0-8E16-4F30-BD92-5DD538CC8135", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc7:*:*:*:*:*:*", "matchCriteriaId": "079505E8-2942-4C33-93D1-35ADA4C39E72", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "38989541-2360-4E0A-AE5A-3D6144AA6114", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "4E51646B-7A0E-40F3-B8C9-239C1DA81DD1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "42A8A507-F8E2-491C-A144-B2448A1DB26E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "901FC6F3-2C2A-4112-AE27-AB102BBE8DEE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "203AD334-DB9F-41B0-A4D1-A6C158EF8C40", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.6:*:*:*:*:*:*:*", "matchCriteriaId": "B3611753-E440-410F-8250-600C996A4B8E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "9739BB47-EEAF-42F1-A557-2AE2EA9526A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "5A95E3BB-0AFC-4C2E-B9BE-C975E902A266", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.9:*:*:*:*:*:*:*", "matchCriteriaId": "482A6C9A-9B8E-4D1C-917A-F16370745E7C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.10:*:*:*:*:*:*:*", "matchCriteriaId": "C6D87357-63E0-41D0-9F02-1BCBF9A77E63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.11:*:*:*:*:*:*:*", "matchCriteriaId": "3765A2D6-2D78-4FB1-989E-D5106BFA3F5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.12:*:*:*:*:*:*:*", "matchCriteriaId": "F54257DB-7023-43C4-AC4D-9590B815CD92", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.13:*:*:*:*:*:*:*", "matchCriteriaId": "61FF5FCD-A4A1-4803-AC53-320A4C838AF6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.14:*:*:*:*:*:*:*", "matchCriteriaId": "9F096553-064F-46A2-877B-F32F163A0F49", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.15:*:*:*:*:*:*:*", "matchCriteriaId": "C0D762D1-E3AD-40EA-8D39-83EEB51B5E85", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.16:*:*:*:*:*:*:*", "matchCriteriaId": "A6187D19-7148-4B87-AD7E-244FF9EE0FA6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.17:*:*:*:*:*:*:*", "matchCriteriaId": "99AC64C2-E391-485C-9CD7-BA09C8FA5E63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.18:*:*:*:*:*:*:*", "matchCriteriaId": "8CDA5E95-7805-441B-BEF7-4448EA45E964", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.19:*:*:*:*:*:*:*", "matchCriteriaId": "51561053-6C28-4F38-BC9B-3F7A7508EB72", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.20:*:*:*:*:*:*:*", "matchCriteriaId": "118F4A5B-C498-4FC3-BE28-50D18EBE4F22", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.21:*:*:*:*:*:*:*", "matchCriteriaId": "BD38EBE6-FE1A-4B55-9FB5-07952253B7A5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.22:*:*:*:*:*:*:*", "matchCriteriaId": "3A491E47-82AD-4055-9444-2EC0D6715326", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.23:*:*:*:*:*:*:*", "matchCriteriaId": "13C5FD16-23B6-467F-9438-5B554922F974", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.24:*:*:*:*:*:*:*", "matchCriteriaId": "9C67235F-5B51-4BF7-89EC-4810F720246F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.25:*:*:*:*:*:*:*", "matchCriteriaId": "08405DEF-05F4-45F0-AC95-DBF914A36D93", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.26:*:*:*:*:*:*:*", "matchCriteriaId": "1A7B9C4B-4A41-4175-9F07-191C1EE98C1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.27:*:*:*:*:*:*:*", "matchCriteriaId": "B306E0A8-4D4A-4895-8128-A500D30A7E0C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.28:*:*:*:*:*:*:*", "matchCriteriaId": "295C839A-F34E-4853-A926-55EABC639412", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.29:*:*:*:*:*:*:*", "matchCriteriaId": "2AFD5F49-7EF9-4CFE-95BD-8FD19B500B0A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.30:*:*:*:*:*:*:*", "matchCriteriaId": "00B3DDDD-B2F6-4753-BA38-65A24017857D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.31:*:*:*:*:*:*:*", "matchCriteriaId": "33FCD39E-F4BF-432D-9CF9-F195CF5844F3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.32:*:*:*:*:*:*:*", "matchCriteriaId": "C7308690-CB0D-4758-B80F-D2ADCD2A9D66", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.33:*:*:*:*:*:*:*", "matchCriteriaId": "313A470B-8A2B-478A-82B5-B27D2718331C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.34:*:*:*:*:*:*:*", "matchCriteriaId": "83FF021E-07E3-41CC-AAE8-D99D7FF24B9D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.35:*:*:*:*:*:*:*", "matchCriteriaId": "F72412E3-8DA9-4CC9-A426-B534202ADBA4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.36:*:*:*:*:*:*:*", "matchCriteriaId": "FCAA9D7A-3C3E-4C0B-9D38-EA80E68C2E46", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.37:*:*:*:*:*:*:*", "matchCriteriaId": "4A9E3AE5-3FCF-4CBB-A30B-082BCFBFB0CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.38:*:*:*:*:*:*:*", "matchCriteriaId": "CF715657-4C3A-4392-B85D-1BBF4DE45D89", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.39:*:*:*:*:*:*:*", "matchCriteriaId": "4B63C618-AC3D-4EF7-AFDF-27B9BF482B78", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.40:*:*:*:*:*:*:*", "matchCriteriaId": "C33DA5A9-5E40-4365-9602-82FB4DCD15B2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.41:*:*:*:*:*:*:*", "matchCriteriaId": "EFAFDB74-40BD-46FA-89AC-617EB2C7160B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.42:*:*:*:*:*:*:*", "matchCriteriaId": "CF5F17DA-30A7-40CF-BD7C-CEDF06D64617", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.43:*:*:*:*:*:*:*", "matchCriteriaId": "71A276F5-BD9D-4C1B-90DF-9B0C15B6F7DF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.44:*:*:*:*:*:*:*", "matchCriteriaId": "F8F6EBEC-3C29-444B-BB85-6EF239B59EC1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.45:*:*:*:*:*:*:*", "matchCriteriaId": "FDB91302-FD18-44CF-A8A8-B31483328539", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.46:*:*:*:*:*:*:*", "matchCriteriaId": "9B81DC2B-46FA-4640-AD6C-2A404D94BA0B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.47:*:*:*:*:*:*:*", "matchCriteriaId": "BA6A1663-BC4C-4FC9-B5EB-A52EDED17B26", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.48:*:*:*:*:*:*:*", "matchCriteriaId": "69C33D6C-6B9F-49F4-B505-E7B589CDEC50", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.49:*:*:*:*:*:*:*", "matchCriteriaId": "C464796B-2F31-4159-A132-82A0C74137B7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.50:*:*:*:*:*:*:*", "matchCriteriaId": "1D6C6E46-FE29-4D2D-A0EC-43DA5112BCC3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.51:*:*:*:*:*:*:*", "matchCriteriaId": "1A370E91-73A1-4D62-8E7B-696B920203F8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.52:*:*:*:*:*:*:*", "matchCriteriaId": "340197CD-9645-4B7E-B976-F3F5A7D4C5BE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.53:*:*:*:*:*:*:*", "matchCriteriaId": "96030636-0C4A-4A10-B768-525D6A0E18CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.54:*:*:*:*:*:*:*", "matchCriteriaId": "A42D8419-914F-4AD6-B0E9-C1290D514FF1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.55:*:*:*:*:*:*:*", "matchCriteriaId": "F4E2C88B-42EA-4F4F-B1F6-A9332EC6888B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.56:*:*:*:*:*:*:*", "matchCriteriaId": "2449D13B-3314-4182-832F-03F6B11AA31F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.57:*:*:*:*:*:*:*", "matchCriteriaId": "9A35B66C-F050-4462-A58E-FEE061B5582E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.58:*:*:*:*:*:*:*", "matchCriteriaId": "1B551164-0167-49BB-A3AE-4034BDA3DCB4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.59:*:*:*:*:*:*:*", "matchCriteriaId": "7244278E-49B6-4405-A14C-F3540C8F5AF8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.60:*:*:*:*:*:*:*", "matchCriteriaId": "B4C3E4B8-7274-4ABB-B7CE-6A39C183CE18", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.61:*:*:*:*:*:*:*", "matchCriteriaId": "6501EDB9-4847-47F8-90EE-B295626E4CDC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.62:*:*:*:*:*:*:*", "matchCriteriaId": "2D676D48-7521-45E2-8563-6B966FF86A35", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.63:*:*:*:*:*:*:*", "matchCriteriaId": "3B69FA17-0AB9-4986-A5A7-2A4C1DD24222", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.64:*:*:*:*:*:*:*", "matchCriteriaId": "7BC35593-96C7-41F0-B738-1568F8129121", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.65:*:*:*:*:*:*:*", "matchCriteriaId": "38D23794-0E7C-4FA5-A7A8-CF940E3FA962", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.66:*:*:*:*:*:*:*", "matchCriteriaId": "008E1E7D-4C20-4560-9288-EF532ADB0029", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.67:*:*:*:*:*:*:*", "matchCriteriaId": "3B3A7044-A92E-47A9-A7BD-35E5B575F5FD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.68:*:*:*:*:*:*:*", "matchCriteriaId": "783E2980-B6AB-489E-B157-B6A2E10A32CA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:*:*:*:*:*:*:*", "matchCriteriaId": "3DFFE5A6-6A67-4992-84A3-C0F05FACDEAD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:rc1:*:*:*:*:*:*", "matchCriteriaId": "13BBD2A3-AE10-48B9-8776-4FB1CAC37D44", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:rc2:*:*:*:*:*:*", "matchCriteriaId": "B25680CC-8918-4F27-8D7E-A6579215450B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:rc3:*:*:*:*:*:*", "matchCriteriaId": "92C48B4C-410C-4BA8-A28A-B2E928320FCC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:rc4:*:*:*:*:*:*", "matchCriteriaId": "CB447523-855B-461E-8197-95169BE86EB0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "B155BBDF-6DF6-4FF5-9C41-D8A5266DCC67", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "28476DEC-9630-4B40-9D4D-9BC151DC4CA4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "5646880A-2355-4BDD-89E7-825863A0311F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "7FF99148-267A-46F8-9927-A9082269BAF6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "A783C083-5D9C-48F9-B5A6-A97A9604FB19", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.6:*:*:*:*:*:*:*", "matchCriteriaId": "2B817A24-03AC-46CD-BEFA-505457FD2A5D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.7:*:*:*:*:*:*:*", "matchCriteriaId": "51CF1BCE-090E-4B70-BA16-ACB74411293B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.8:*:*:*:*:*:*:*", "matchCriteriaId": "187AAD67-10D7-4B57-B4C6-00443E246AF3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.9:*:*:*:*:*:*:*", "matchCriteriaId": "F341CE88-C5BC-4CDD-9CB5-B6BAD7152E63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.10:*:*:*:*:*:*:*", "matchCriteriaId": "37ACE2A6-C229-4236-8E9F-235F008F3AA0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:*:*:*:*:*:*:*", "matchCriteriaId": "D3220B70-917F-4F9F-8A3B-2BF581281E8D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:*:*:*:*:*:x86:*", "matchCriteriaId": "7D47A395-821D-4BFF-996E-E849D9A40217", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc2:*:*:*:*:*:*", "matchCriteriaId": "99372D07-C06A-41FA-9843-6D57F99AB5AF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc3:*:*:*:*:*:*", "matchCriteriaId": "2B9DC110-D260-4DB4-B8B0-EF1D160ADA07", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc4:*:*:*:*:*:*", "matchCriteriaId": "6192FE84-4D53-40D4-AF61-78CE7136141A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc5:*:*:*:*:*:*", "matchCriteriaId": "42FEF3CF-1302-45EB-89CC-3786FE4BAC1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc6:*:*:*:*:*:*", "matchCriteriaId": "AE6A6B58-2C89-4DE4-BA57-78100818095C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc7:*:*:*:*:*:*", "matchCriteriaId": "1D467F87-2F13-4D26-9A93-E0BA526FEA24", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "FE348F7B-02DE-47D5-8011-F83DA9426021", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.1:*:*:*:*:*:x86:*", "matchCriteriaId": "8A603291-33B4-4195-B52D-D2A9938089C1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "E91594EA-F0A3-41B3-A9C6-F7864FC2F229", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "9E1ECCDB-0208-48F6-B44F-16CC0ECE3503", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "FBA8B5DE-372E-47E0-A0F6-BE286D509CC3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "9A1CA083-2CF8-45AE-9E15-1AA3A8352E3B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "19D69A49-5290-4C5F-8157-719AD58D253D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "290BD969-42E7-47B0-B21B-06DE4865432C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.8:*:*:*:*:*:*:*", "matchCriteriaId": "23A9E29E-DE78-4C73-9FBD-C2410F5FC8B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.9:*:*:*:*:*:*:*", "matchCriteriaId": "018434C9-E75F-45CB-A169-DAB4B1D864D7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.10:*:*:*:*:*:*:*", "matchCriteriaId": "DC0AC68F-EC58-4C4F-8CBC-A59ECC00CCDE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.11:*:*:*:*:*:*:*", "matchCriteriaId": "C123C844-F6D7-471E-A62E-F756042FB1CD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.12:*:*:*:*:*:*:*", "matchCriteriaId": "A11C38BB-7FA2-49B0-AAC9-83DB387A06DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.13:*:*:*:*:*:*:*", "matchCriteriaId": "61F3733C-E5F6-4855-B471-DF3FB823613B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.14:*:*:*:*:*:*:*", "matchCriteriaId": "1DDCA75F-9A06-4457-9A45-38A38E7F7086", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.15:*:*:*:*:*:*:*", "matchCriteriaId": "7AEA837E-7864-4003-8DB7-111ED710A7E1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.16:*:*:*:*:*:*:*", "matchCriteriaId": "B6FE471F-2D1F-4A1D-A197-7E46B75787E1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.17:*:*:*:*:*:*:*", "matchCriteriaId": "FDA9E6AB-58DC-4EC5-A25C-11F9D0B38BF7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.18:*:*:*:*:*:*:*", "matchCriteriaId": "DC6B8DB3-B05B-41A2-B091-342D66AAE8F5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.19:*:*:*:*:*:*:*", "matchCriteriaId": "958F0FF8-33EF-4A71-A0BD-572C85211DBA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.20:*:*:*:*:*:*:*", "matchCriteriaId": "FBA39F48-B02F-4C48-B304-DA9CCA055244", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.21:*:*:*:*:*:*:*", "matchCriteriaId": "1FF841F3-48A7-41D7-9C45-A8170435A5EB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.22:*:*:*:*:*:*:*", "matchCriteriaId": "EF506916-A6DC-4B1E-90E5-959492AF55F4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.23:*:*:*:*:*:*:*", "matchCriteriaId": "B3CDAD1F-2C6A-48C0-8FAB-C2659373FA25", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.24:*:*:*:*:*:*:*", "matchCriteriaId": "4FFE4B22-C96A-43D0-B993-F51EDD9C5E0E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.25:*:*:*:*:*:*:*", "matchCriteriaId": "F571CC8B-B212-4553-B463-1DB01D616E8A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.26:*:*:*:*:*:*:*", "matchCriteriaId": "84E3E151-D437-48ED-A529-731EEFF88567", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.27:*:*:*:*:*:*:*", "matchCriteriaId": "E9E3EA3C-CCA5-4433-86E0-3D02C4757A0A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.28:*:*:*:*:*:*:*", "matchCriteriaId": "F7AC4F7D-9FA6-4CF1-B2E9-70BF7D4D177C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.29:*:*:*:*:*:*:*", "matchCriteriaId": "3CE3A80D-9648-43CC-8F99-D741ED6552BF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.30:*:*:*:*:*:*:*", "matchCriteriaId": "C8A98C03-A465-41B4-A551-A26FEC7FFD94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:*:*:*:*:*:*:*", "matchCriteriaId": "AFB76697-1C2F-48C0-9B14-517EC053D4B3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc1:*:*:*:*:*:*", "matchCriteriaId": "BED88DFD-1DC5-4505-A441-44ECDEF0252D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc2:*:*:*:*:*:*", "matchCriteriaId": "DBFD2ACD-728A-4082-BB6A-A1EF6E58E47D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc3:*:*:*:*:*:*", "matchCriteriaId": "C31B0E51-F62D-4053-B04F-FC4D5BC373D2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc4:*:*:*:*:*:*", "matchCriteriaId": "A914303E-1CB6-4AAD-9F5F-DE5433C4E814", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc5:*:*:*:*:*:*", "matchCriteriaId": "203BBA69-90B2-4C5E-8023-C14180742421", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc6:*:*:*:*:*:*", "matchCriteriaId": "0DBFAB53-B889-4028-AC0E-7E165B152A18", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc7:*:*:*:*:*:*", "matchCriteriaId": "FE409AEC-F677-4DEF-8EB7-2C35809043CE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "578EC12B-402F-4AD4-B8F8-C9B2CAB06891", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "877002ED-8097-4BB4-BB88-6FC6306C38B2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "76294CE3-D72C-41D5-9E0F-B693D0042699", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "916E97D4-1FAB-42F5-826B-653B1C0909A8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.5:*:*:*:*:*:*:*", "matchCriteriaId": "33FD2217-C5D0-48C1-AD74-3527127FEF9C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "2E92971F-B629-4E0A-9A50-8B235F9704B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.7:*:*:*:*:*:*:*", "matchCriteriaId": "EDD3A069-3829-4EE2-9D5A-29459F29D4C1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.8:*:*:*:*:*:*:*", "matchCriteriaId": "A4A0964C-CEB2-41D7-A69C-1599B05B6171", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:*:*:*:*:*:*:*", "matchCriteriaId": "0F960FA6-F904-4A4E-B483-44C70090E9A1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:*:*:*:*:*:x86:*", "matchCriteriaId": "8C3D9C66-933A-469E-9073-75015A8AD17D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc1:*:*:*:*:*:*", "matchCriteriaId": "261C1B41-C9E0-414F-8368-51C0C0B8AD38", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc1:*:*:*:*:x86:*", "matchCriteriaId": "C92F29A0-DEFF-49E4-AE86-5DBDAD51C677", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc2:*:*:*:*:*:*", "matchCriteriaId": "5CCA261D-2B97-492F-89A0-5F209A804350", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc2:*:*:*:*:x86:*", "matchCriteriaId": "5690A703-390D-4D8A-9258-2F47116DAB4F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc3:*:*:*:*:*:*", "matchCriteriaId": "1B1C0C68-9194-473F-BE5E-EC7F184899FA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc3:*:*:*:*:x86:*", "matchCriteriaId": "AB1EDDA7-15AF-4B45-A931-DFCBB1EEB701", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc4:*:*:*:*:*:*", "matchCriteriaId": "D7A6AC9E-BEA6-44B0-B3B3-F0F94E32424A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc4:*:*:*:*:x86:*", "matchCriteriaId": "952FE0DC-B2ED-4080-BF29-A2C265E83FEF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc5:*:*:*:*:*:*", "matchCriteriaId": "16038328-9399-4B85-B777-BA4757D02C9B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc5:*:*:*:*:x86:*", "matchCriteriaId": "1CE7ABDB-6572-40E8-B952-CBE52C999858", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc6:*:*:*:*:*:*", "matchCriteriaId": "16CA2757-FA8D-43D9-96E8-D3C0EB6E1DEF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc6:*:*:*:*:x86:*", "matchCriteriaId": "0F417186-D1ED-4A31-92B2-83DEDA1AF272", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc7:*:*:*:*:*:*", "matchCriteriaId": "E8CB5481-5EAE-401E-BD7E-D3095CCA9E94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc7:*:*:*:*:x86:*", "matchCriteriaId": "3D4FCFAE-918C-4886-9A17-08A5B94D35F4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.1:*:*:*:*:*:*:*", "matchCriteriaId": "A0F36FAC-141D-476D-84C5-A558C199F904", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.1:*:*:*:*:*:x86:*", "matchCriteriaId": "830D2914-C9FE-406F-AFCE-7A04BB9E2896", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.2:*:*:*:*:*:*:*", "matchCriteriaId": "51D64824-25F6-4761-BD6A-29038A143744", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.2:*:*:*:*:*:x86:*", "matchCriteriaId": "F4B791B5-2EB5-403A-90CC-B219F6277D1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.3:*:*:*:*:*:*:*", "matchCriteriaId": "E284C8A1-740F-454D-A774-99CD3A21B594", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.3:*:*:*:*:*:x86:*", "matchCriteriaId": "2BA5F34D-7490-4B2B-A7E6-8450F9C1FC31", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.4:*:*:*:*:*:*:*", "matchCriteriaId": "C70D72AE-0CBF-4324-9935-57E28EC6279C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.4:*:*:*:*:*:x86:*", "matchCriteriaId": "B803FE64-FC8D-4650-9FB9-FEEED4340416", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.5:*:*:*:*:*:*:*", "matchCriteriaId": "F674B06B-7E86-4E41-9126-8152D0DDABAE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.5:*:*:*:*:*:x86:*", "matchCriteriaId": "4C560A9A-2388-4980-9E88-118C5EB806B7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.6:*:*:*:*:*:*:*", "matchCriteriaId": "7039B3EC-8B22-413E-B582-B4BEC6181241", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.7:*:*:*:*:*:*:*", "matchCriteriaId": "35CF1DD2-80B9-4476-8963-5C3EF52B33F4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.8:*:*:*:*:*:*:*", "matchCriteriaId": "BFB0B05B-A5CE-4B9C-AE7F-83062868D35B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.9:*:*:*:*:*:*:*", "matchCriteriaId": "D166A66E-7454-47EC-BB56-861A9AFEAFE1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.10:*:*:*:*:*:*:*", "matchCriteriaId": "7DA94F50-2A62-4300-BF4D-A342AAE35629", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.11:*:*:*:*:*:*:*", "matchCriteriaId": "252D937B-50DC-444F-AE73-5FCF6203DF27", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.12:*:*:*:*:*:*:*", "matchCriteriaId": "F6D8EE51-02C1-47BC-A92C-0A8ABEFD28FF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.13:*:*:*:*:*:*:*", "matchCriteriaId": "7F20A5D7-3B38-4911-861A-04C8310D5916", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.14:*:*:*:*:*:*:*", "matchCriteriaId": "D472DE3A-71D8-4F40-9DDE-85929A2B047D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.15:*:*:*:*:*:*:*", "matchCriteriaId": "B2AED943-65A8-4FDB-BBD0-CCEF8682A48C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.16:*:*:*:*:*:*:*", "matchCriteriaId": "D4640185-F3D8-4575-A71D-4C889A93DE2C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.17:*:*:*:*:*:*:*", "matchCriteriaId": "144CCF7C-025E-4879-B2E7-ABB8E4390BE5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.18:*:*:*:*:*:*:*", "matchCriteriaId": "B6FAA052-0B2B-40CE-8C98-919B8D08A5ED", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.19:*:*:*:*:*:*:*", "matchCriteriaId": "4B5A53DE-9C83-4A6B-96F3-23C03BF445D9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.20:*:*:*:*:*:*:*", "matchCriteriaId": "063EB879-CB05-4E33-AA90-9E43516839B5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.21:*:*:*:*:*:*:*", "matchCriteriaId": "2D25764F-4B02-4C65-954E-8C7D6632DE00", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.22:*:*:*:*:*:*:*", "matchCriteriaId": "F31F5BF3-CD0A-465C-857F-273841BCD28A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.23:*:*:*:*:*:*:*", "matchCriteriaId": "FF302C8A-079B-42B9-B455-CD9083BFA067", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.24:*:*:*:*:*:*:*", "matchCriteriaId": "744999C0-33D3-4363-B3DB-E0D02CDD3918", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.25:*:*:*:*:*:*:*", "matchCriteriaId": "C2E77A76-2A60-45D8-9337-867BC22C5110", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.26:*:*:*:*:*:*:*", "matchCriteriaId": "C9F4AAE7-C870-46B7-B559-2949737BE777", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.27:*:*:*:*:*:*:*", "matchCriteriaId": "20FA2824-20B0-48B8-BB0A-4904C1D3E8AA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.28:*:*:*:*:*:*:*", "matchCriteriaId": "9F9B347E-61AC-419F-9701-B862BBFA46F2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.29:*:*:*:*:*:*:*", "matchCriteriaId": "989F351C-8B7C-4C1B-AFA2-AE9431576368", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.30:*:*:*:*:*:*:*", "matchCriteriaId": "8D22172A-9FA7-42E0-8451-165D8E47A573", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.31:*:*:*:*:*:*:*", "matchCriteriaId": "CE31624C-94F9-45D8-9B4A-D0028F10602F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.32:*:*:*:*:*:*:*", "matchCriteriaId": "70967A83-28F6-4568-9ADA-6EF232E5BBC2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.5.1:*:*:*:*:*:*:*", "matchCriteriaId": "962B0C45-AB29-4383-AC16-C6E8245D0FF7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.5.2:*:*:*:*:*:*:*", "matchCriteriaId": "A0EE126B-74B2-4F79-BFE1-3DC169F3F9B2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "392075E0-A9C7-4B4A-90F9-7F1ADFF5EFA7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.5.4:*:*:*:*:*:*:*", "matchCriteriaId": "ECC66968-06F0-4874-A95A-A292C36E45C1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.5.5:*:*:*:*:*:*:*", "matchCriteriaId": "5FE986E6-1068-4E1B-8EAB-DF1EAF32B4E3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.5.6:*:*:*:*:*:*:*", "matchCriteriaId": "543E8536-1A8E-4E76-B89F-1B1F9F26FAB8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.5.7:*:*:*:*:*:*:*", "matchCriteriaId": "EC2B45E3-31E1-4B46-85FA-3A84E75B8F84", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6:*:*:*:*:*:*:*", "matchCriteriaId": "DDB8CC75-D3EE-417C-A83D-CB6D666FE595", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.1:*:*:*:*:*:*:*", "matchCriteriaId": "09A072F1-7BEE-4236-ACBB-55DB8FEF4A03", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.2:*:*:*:*:*:*:*", "matchCriteriaId": "E19D5A58-17D6-4502-A57A-70B2F84817A4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.3:*:*:*:*:*:*:*", "matchCriteriaId": "D58BA035-1204-4DFA-98A1-12111FB6222E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.4:*:*:*:*:*:*:*", "matchCriteriaId": "A17F2E87-8EB8-476A-B5B5-9AE5CF53D9FE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.5:*:*:*:*:*:*:*", "matchCriteriaId": "A8CCC101-5852-4299-9B67-EA1B149D58C0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.6:*:*:*:*:*:*:*", "matchCriteriaId": "B8074D32-C252-4AD3-A579-1C5EDDD7014B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.7:*:*:*:*:*:*:*", "matchCriteriaId": "962AA802-8179-4606-AAC0-9363BAEABC9F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.8:*:*:*:*:*:*:*", "matchCriteriaId": "1286C858-D5A2-45F3-86D1-E50FE53FB23C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.9:*:*:*:*:*:*:*", "matchCriteriaId": "5AC4A13E-F560-4D01-98A3-E2A2B82EB25B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.10:*:*:*:*:*:*:*", "matchCriteriaId": "942C462A-5398-4BB9-A792-598682E1FEF2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.6.11:*:*:*:*:*:*:*", "matchCriteriaId": "B852F7E0-0282-483D-BB4D-18CB7A4F1392", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7:*:*:*:*:*:*:*", "matchCriteriaId": "53ED9A31-99CC-41C8-8B72-5B2A9B49AA6C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.1:*:*:*:*:*:*:*", "matchCriteriaId": "EFD646BC-62F7-47CF-B0BE-768F701F7D9A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.2:*:*:*:*:*:*:*", "matchCriteriaId": "F43D418E-87C1-4C83-9FF1-4F45B4F452DD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.3:*:*:*:*:*:*:*", "matchCriteriaId": "680D0E00-F29A-487C-8770-8E7EAC672B7C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.4:*:*:*:*:*:*:*", "matchCriteriaId": "2DCA96A4-A836-4E94-A39C-3AD3EA1D9611", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.5:*:*:*:*:*:*:*", "matchCriteriaId": "753C05E3-B603-4E36-B9BA-FAEDCBF62A7D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.6:*:*:*:*:*:*:*", "matchCriteriaId": "E385C2E0-B9F1-4564-8E6D-56FD9E762405", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.7:*:*:*:*:*:*:*", "matchCriteriaId": "041335D4-05E1-4004-9381-28AAD5994B47", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.8:*:*:*:*:*:*:*", "matchCriteriaId": "370F2AE5-3DBC-46B9-AC70-F052C9229C00", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.9:*:*:*:*:*:*:*", "matchCriteriaId": "7A971BE3-259D-4494-BBC5-12793D92DB57", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.7.10:*:*:*:*:*:*:*", "matchCriteriaId": "8E4719A6-FDEA-4714-A830-E23A52AE90BC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.0:*:*:*:*:*:*:*", "matchCriteriaId": "1A6E41FB-38CE-49F2-B796-9A5AA648E73F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.1:*:*:*:*:*:*:*", "matchCriteriaId": "93523FE1-5993-46CB-9299-7C8C1A04E873", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.2:*:*:*:*:*:*:*", "matchCriteriaId": "27ADC356-6BE9-43A3-9E0B-393DC4B1559A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.3:*:*:*:*:*:*:*", "matchCriteriaId": "4F543D23-1774-4D14-A7D1-AD49EDEA94DD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.4:*:*:*:*:*:*:*", "matchCriteriaId": "FC323F58-CA00-4C3C-BA4D-CC2C0A6E5F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.5:*:*:*:*:*:*:*", "matchCriteriaId": "FEA0B2E3-668D-40ED-9D3D-709EB6449F8D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.6:*:*:*:*:*:*:*", "matchCriteriaId": "3431B258-4EC8-4E7F-87BB-4D934880601E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.7:*:*:*:*:*:*:*", "matchCriteriaId": "1B09FA1E-8B28-4F2A-BA7E-8E1C40365970", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.8:*:*:*:*:*:*:*", "matchCriteriaId": "91917120-9D68-41C0-8B5D-85C256BC6200", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.9:*:*:*:*:*:*:*", "matchCriteriaId": "AAD268A0-096C-4C31-BEC5-D47F5149D462", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.10:*:*:*:*:*:*:*", "matchCriteriaId": "32BD2427-C47F-4660-A1D9-448E500EF5B9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.11:*:*:*:*:*:*:*", "matchCriteriaId": "02048CE5-81C7-4DFB-BC40-CE4C86B7E022", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.12:*:*:*:*:*:*:*", "matchCriteriaId": "934D2B37-0575-4A75-B00B-0028316D6DF0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.8.13:*:*:*:*:*:*:*", "matchCriteriaId": "06754C21-995C-4850-A4DC-F21826C0F8C5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9:rc1:*:*:*:*:*:*", "matchCriteriaId": "42633FF9-FB0C-4095-B4A1-8D623A98683B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9:rc2:*:*:*:*:*:*", "matchCriteriaId": "08C04619-89A2-4B15-82A2-48BCC662C1F1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9:rc3:*:*:*:*:*:*", "matchCriteriaId": "5B039196-7159-476C-876A-C61242CC41DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9:rc4:*:*:*:*:*:*", "matchCriteriaId": "3A9E0457-53C9-44DD-ACFB-31EE1D1E060E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9:rc5:*:*:*:*:*:*", "matchCriteriaId": "BEE406E7-87BA-44BA-BF61-673E6CC44A2F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9:rc6:*:*:*:*:*:*", "matchCriteriaId": "29FBA173-658F-45DC-8205-934CACD67166", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9:rc7:*:*:*:*:*:*", "matchCriteriaId": "139700F0-BA32-40CF-B9DF-C9C450384FDE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.0:*:*:*:*:*:*:*", "matchCriteriaId": "E578085C-3968-4543-BEBA-EE3C3CB4FA02", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.1:*:*:*:*:*:*:*", "matchCriteriaId": "4DCFA441-68FB-4559-A245-FF0B79DE43CA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.2:*:*:*:*:*:*:*", "matchCriteriaId": "8C2508D8-6571-4B81-A0D7-E494CCD039CE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.3:*:*:*:*:*:*:*", "matchCriteriaId": "8B516926-5E86-4C0A-85F3-F64E1FCDA249", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.4:*:*:*:*:*:*:*", "matchCriteriaId": "069D774D-79BE-479F-BF4E-F021AD808114", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.5:*:*:*:*:*:*:*", "matchCriteriaId": "D15B27A9-46E0-4DDF-A00C-29F8F1F18D73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.6:*:*:*:*:*:*:*", "matchCriteriaId": "A381BB4A-28B4-4672-87EE-91B3DDD6C71A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.7:*:*:*:*:*:*:*", "matchCriteriaId": "922F80CF-937D-4FA2-AFF2-6E47FFE9E1E9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.8:*:*:*:*:*:*:*", "matchCriteriaId": "A548ADF4-9E3B-407C-A5ED-05150EB3A185", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.9:*:*:*:*:*:*:*", "matchCriteriaId": "9C623230-4497-41B9-9BD2-7A6CFDD77983", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.10:*:*:*:*:*:*:*", "matchCriteriaId": "C72FA8A6-60A6-4486-A245-7BEF8B2A2711", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.9.11:*:*:*:*:*:*:*", "matchCriteriaId": "0A498D90-BB99-405E-9FA6-1FBFE179787E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.0:*:*:*:*:*:arm64:*", "matchCriteriaId": "C8409226-20A1-4549-9E11-6D0C3C38DCCE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.1:*:*:*:*:*:*:*", "matchCriteriaId": "D0D32776-8ADB-4E79-846A-C0C99FED19E0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.2:*:*:*:*:*:*:*", "matchCriteriaId": "B7D01673-D13F-487F-81B6-1279C187277E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.3:*:*:*:*:*:*:*", "matchCriteriaId": "ADB27A3E-78E4-40F7-9716-A1099B0D85FB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.4:*:*:*:*:*:*:*", "matchCriteriaId": "16E7136A-A8A6-4BF5-AF5D-AFB5C7A10712", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.5:*:*:*:*:*:*:*", "matchCriteriaId": "6FE127AC-E61D-427A-B998-D60DF5AABA21", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.6:*:*:*:*:*:*:*", "matchCriteriaId": "3819FF99-AEC5-4466-8542-D395419E4308", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.7:*:*:*:*:*:*:*", "matchCriteriaId": "E621FA1A-464B-4D2A-A0D6-EDA475A3709B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.8:*:*:*:*:*:*:*", "matchCriteriaId": "B760B422-EA11-43AB-B6D2-CA54E7229663", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.9:*:*:*:*:*:*:*", "matchCriteriaId": "D2CA7BBC-917C-4F31-A442-465C30444836", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.10:*:*:*:*:*:*:*", "matchCriteriaId": "AE778000-4FD5-4032-86CE-5930EF4CB7C1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.11:*:*:*:*:*:*:*", "matchCriteriaId": "B3344EEB-F037-48FE-81DC-67F6384F7D9A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.12:*:*:*:*:*:*:*", "matchCriteriaId": "0244B0CA-9C67-4F06-BFBA-1F257112AC08", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.13:*:*:*:*:*:*:*", "matchCriteriaId": "2148C13F-4BB0-4D46-A688-F7C726D12497", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.14:*:*:*:*:*:*:*", "matchCriteriaId": "9871AF57-9158-4A41-8340-596B4463289A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.15:*:*:*:*:*:*:*", "matchCriteriaId": "2A875207-DF01-4240-8895-49B62693D27B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.16:*:*:*:*:*:*:*", "matchCriteriaId": "FE04A172-6F3B-4E3B-8D4D-564740FABAAF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.17:*:*:*:*:*:*:*", "matchCriteriaId": "CFEEF8C4-7DC2-4230-B58C-337F39A4DFAF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.10.18:*:*:*:*:*:*:*", "matchCriteriaId": "9F74DB5C-5096-438C-8C8A-6D337A2FD06A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.11:*:*:*:*:*:*:*", "matchCriteriaId": "639E3A57-A9E7-40E6-8929-81CCC0060EFB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.11.1:*:*:*:*:*:*:*", "matchCriteriaId": "07012ADD-F521-40A8-B067-E87C2238A3D2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.11.2:*:*:*:*:*:*:*", "matchCriteriaId": "3F5FF393-3F89-4274-B82B-F671358072ED", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.11.3:*:*:*:*:*:*:*", "matchCriteriaId": "E348698F-54D1-4F5E-B701-CFAF50881E0A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.11.4:*:*:*:*:*:*:*", "matchCriteriaId": "932205D9-3514-4289-9B55-C7A169276930", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.11.5:*:*:*:*:*:*:*", "matchCriteriaId": "2ECB2D33-F517-480F-8A6F-99D9D6C49596", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.11.6:*:*:*:*:*:*:*", "matchCriteriaId": "D16F68DD-E2D4-4AA4-AB81-3796C2947E37", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The mp_get_count function in drivers/staging/sb105x/sb_pci_mp.c in the Linux kernel before 3.12 does not initialize a certain data structure, which allows local users to obtain sensitive information from kernel stack memory via a TIOCGICOUNT ioctl call."}, {"lang": "es", "value": "La funci\u00f3n mp_get_count de drivers/staging/sb105x/sb_pci_mp.c en el kernel de Linux anterior a la versi\u00f3n 3.12 no inicializa una estructura de datos determinada, lo que permite a usuarios locales obtener informaci\u00f3n sensible desde la memoria de pila del kernel a trav\u00e9s de una llamada TIOCGICOUNT ioctl."}], "evaluatorComment": null, "id": "CVE-2013-4516", "lastModified": "2023-02-13T00:28:58.263", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.9, "confidentialityImpact": "COMPLETE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:C/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2013-11-12T14:35:12.540", "references": [{"source": "secalert@redhat.com", "tags": null, "url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git%3Ba=commit%3Bh=a8b33654b1e3b0c74d4a1fed041c9aae50b3c427"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.openwall.com/lists/oss-security/2013/11/04/22"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.ubuntu.com/usn/USN-2069-1"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.ubuntu.com/usn/USN-2070-1"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.ubuntu.com/usn/USN-2073-1"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.ubuntu.com/usn/USN-2075-1"}, {"source": "secalert@redhat.com", "tags": ["Exploit", "Patch"], "url": "https://github.com/torvalds/linux/commit/a8b33654b1e3b0c74d4a1fed041c9aae50b3c427"}, {"source": "secalert@redhat.com", "tags": ["Patch"], "url": "https://www.kernel.org/pub/linux/kernel/v3.x/patch-3.12.bz2"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-200"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/a8b33654b1e3b0c74d4a1fed041c9aae50b3c427"}, "type": "CWE-200"}
182
Determine whether the {function_name} code is vulnerable or not.
[ "/* Copyright (c) 2008-2015, Avian Contributors", " Permission to use, copy, modify, and/or distribute this software\n for any purpose with or without fee is hereby granted, provided\n that the above copyright notice and this permission notice appear\n in all copies.", " There is NO WARRANTY for this software. See license.txt for\n details. */", "package java.io;", "public class FileOutputStream extends OutputStream {\n // static {\n // System.loadLibrary(\"natives\");\n // }", " private int fd;", " public FileOutputStream(FileDescriptor fd) {\n this.fd = fd.value;\n }", " public FileOutputStream(String path) throws IOException {\n this(path, false);\n }", " public FileOutputStream(String path, boolean append) throws IOException {\n fd = open(path, append);\n }\n ", " public FileOutputStream(File file) throws IOException {\n this(file.getPath());\n }", " private static native int open(String path, boolean append) throws IOException;", " private static native void write(int fd, int c) throws IOException;", " private static native void write(int fd, byte[] b, int offset, int length)\n throws IOException;", " private static native void close(int fd) throws IOException;", " public void write(int c) throws IOException {\n write(fd, c);\n }", " public void write(byte[] b, int offset, int length) throws IOException {\n if (b == null) {\n throw new NullPointerException();\n }\n", " if (offset < 0 || offset + length > b.length) {", " throw new ArrayIndexOutOfBoundsException();\n }", " write(fd, b, offset, length);\n }", " public void close() throws IOException {\n if (fd != -1) {\n close(fd);\n fd = -1;\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [56], "buggy_code_start_loc": [55], "filenames": ["classpath/java/io/FileOutputStream.java"], "fixing_code_end_loc": [56], "fixing_code_start_loc": [55], "message": "** UNSUPPORTED WHEN ASSIGNED ** An issue was discovered in ReadyTalk Avian 1.2.0 before 2020-10-27. The FileOutputStream.write() method in FileOutputStream.java has a boundary check to prevent out-of-bounds memory read/write operations. However, an integer overflow leads to bypassing this check and achieving the out-of-bounds access. NOTE: This vulnerability only affects products that are no longer supported by the maintainer.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:readytalk:avian:1.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "E0BC8EBC-CAAD-47D3-81D6-5B0AD9A6F0A6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "** UNSUPPORTED WHEN ASSIGNED ** An issue was discovered in ReadyTalk Avian 1.2.0 before 2020-10-27. The FileOutputStream.write() method in FileOutputStream.java has a boundary check to prevent out-of-bounds memory read/write operations. However, an integer overflow leads to bypassing this check and achieving the out-of-bounds access. NOTE: This vulnerability only affects products that are no longer supported by the maintainer."}, {"lang": "es", "value": "** NO COMPATIBLE CUANDO SE ASIGN\u00d3 ** Se detect\u00f3 un problema en ReadyTalk Avian versi\u00f3n 1.2.0 antes del 27-10-2020.&#xa0;El m\u00e9todo FileOutputStream.write() en el archivo FileOutputStream.java presenta una verificaci\u00f3n de l\u00edmites para evitar operaciones de lectura/escritura de memoria fuera de l\u00edmites.&#xa0;Sin embargo, un desbordamiento de enteros conduce a omitir esta verificaci\u00f3n y lograr el acceso fuera de l\u00edmites.&#xa0;NOTA: Esta vulnerabilidad solo afecta a los productos que ya no son compatibles con el mantenedor"}], "evaluatorComment": null, "id": "CVE-2020-28371", "lastModified": "2021-07-21T11:39:23.747", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-11-09T22:15:13.333", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ReadyTalk/avian/commit/0871979b298add320ca63f65060acb7532c8a0dd"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ReadyTalk/avian/pull/572"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-190"}, {"lang": "en", "value": "CWE-787"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/ReadyTalk/avian/commit/0871979b298add320ca63f65060acb7532c8a0dd"}, "type": "CWE-190"}
183
Determine whether the {function_name} code is vulnerable or not.
[ "/* Copyright (c) 2008-2015, Avian Contributors", " Permission to use, copy, modify, and/or distribute this software\n for any purpose with or without fee is hereby granted, provided\n that the above copyright notice and this permission notice appear\n in all copies.", " There is NO WARRANTY for this software. See license.txt for\n details. */", "package java.io;", "public class FileOutputStream extends OutputStream {\n // static {\n // System.loadLibrary(\"natives\");\n // }", " private int fd;", " public FileOutputStream(FileDescriptor fd) {\n this.fd = fd.value;\n }", " public FileOutputStream(String path) throws IOException {\n this(path, false);\n }", " public FileOutputStream(String path, boolean append) throws IOException {\n fd = open(path, append);\n }\n ", " public FileOutputStream(File file) throws IOException {\n this(file.getPath());\n }", " private static native int open(String path, boolean append) throws IOException;", " private static native void write(int fd, int c) throws IOException;", " private static native void write(int fd, byte[] b, int offset, int length)\n throws IOException;", " private static native void close(int fd) throws IOException;", " public void write(int c) throws IOException {\n write(fd, c);\n }", " public void write(byte[] b, int offset, int length) throws IOException {\n if (b == null) {\n throw new NullPointerException();\n }\n", " if (offset < 0 || length < 0 || length > b.length || offset > b.length - length) {", " throw new ArrayIndexOutOfBoundsException();\n }", " write(fd, b, offset, length);\n }", " public void close() throws IOException {\n if (fd != -1) {\n close(fd);\n fd = -1;\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [56], "buggy_code_start_loc": [55], "filenames": ["classpath/java/io/FileOutputStream.java"], "fixing_code_end_loc": [56], "fixing_code_start_loc": [55], "message": "** UNSUPPORTED WHEN ASSIGNED ** An issue was discovered in ReadyTalk Avian 1.2.0 before 2020-10-27. The FileOutputStream.write() method in FileOutputStream.java has a boundary check to prevent out-of-bounds memory read/write operations. However, an integer overflow leads to bypassing this check and achieving the out-of-bounds access. NOTE: This vulnerability only affects products that are no longer supported by the maintainer.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:readytalk:avian:1.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "E0BC8EBC-CAAD-47D3-81D6-5B0AD9A6F0A6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "** UNSUPPORTED WHEN ASSIGNED ** An issue was discovered in ReadyTalk Avian 1.2.0 before 2020-10-27. The FileOutputStream.write() method in FileOutputStream.java has a boundary check to prevent out-of-bounds memory read/write operations. However, an integer overflow leads to bypassing this check and achieving the out-of-bounds access. NOTE: This vulnerability only affects products that are no longer supported by the maintainer."}, {"lang": "es", "value": "** NO COMPATIBLE CUANDO SE ASIGN\u00d3 ** Se detect\u00f3 un problema en ReadyTalk Avian versi\u00f3n 1.2.0 antes del 27-10-2020.&#xa0;El m\u00e9todo FileOutputStream.write() en el archivo FileOutputStream.java presenta una verificaci\u00f3n de l\u00edmites para evitar operaciones de lectura/escritura de memoria fuera de l\u00edmites.&#xa0;Sin embargo, un desbordamiento de enteros conduce a omitir esta verificaci\u00f3n y lograr el acceso fuera de l\u00edmites.&#xa0;NOTA: Esta vulnerabilidad solo afecta a los productos que ya no son compatibles con el mantenedor"}], "evaluatorComment": null, "id": "CVE-2020-28371", "lastModified": "2021-07-21T11:39:23.747", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-11-09T22:15:13.333", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ReadyTalk/avian/commit/0871979b298add320ca63f65060acb7532c8a0dd"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ReadyTalk/avian/pull/572"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-190"}, {"lang": "en", "value": "CWE-787"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/ReadyTalk/avian/commit/0871979b298add320ca63f65060acb7532c8a0dd"}, "type": "CWE-190"}
183
Determine whether the {function_name} code is vulnerable or not.
[ "CHANGELOG Roundcube Webmail\n===========================", "- Security: Fix potential XSS issue in HTML editor of the identity signature input (#7507)\n- Managesieve: Fix too-small input field in Elastic when using custom headers (#7498)\n- Fix support for an error as a string in message_before_send hook (#7475)\n- Elastic: Fix redundant scrollbar in plain text editor on mail reply (#7500)\n- Elastic: Fix deleted and replied+forwarded icons on messages list (#7503)\n- Managesieve: Allow angle brackets in out-of-office message body (#7518)\n- Fix bug in conversion of email addresses to mailto links in plain text messages (#7526)\n- Fix format=flowed formatting on plain text part derived from the HTML content (#7504)\n- Fix incorrect rewriting of internal links in HTML content (#7512)\n- Fix handling links without defined protocol (#7454)\n- Fix paging of search results on IMAP servers with no SORT capability (#7462)\n- Fix detecting special folders on servers with both SPECIAL-USE and LIST-STATUS (#7525)", "", "\nRELEASE 1.4.7\n-------------\n- Fix bug where subfolders of special folders could have been duplicated on folder list\n- Increase maximum size of contact jobtitle and department fields to 128 characters\n- Fix missing newline after the logged line when writing to stdout (#7418)\n- Elastic: Fix context menu (paste) on the recipient input (#7431)\n- Fix problem with forwarding inline images attached to messages with no HTML part (#7414)\n- Fix problem with handling attached images with same name when using database_attachments/redundant_attachments (#7455)\n- Security: Fix cross-site scripting (XSS) via HTML messages with malicious svg/namespace", "RELEASE 1.4.6\n-------------\n- Installer: Fix regression in SMTP test section (#7417)", "RELEASE 1.4.5\n-------------\n- Fix bug in extracting required plugins from composer.json that led to spurious error in log (#7364)\n- Fix so the database setup description is compatible with MySQL 8 (#7340)\n- Markasjunk: Fix regression in jsevent driver (#7361)\n- Fix missing flag indication on collapsed thread in Larry and Elastic (#7366)\n- Fix default keyservers (use keys.openpgp.org), add note about CORS (#7373, #7367)\n- Password: Fix issue with Modoboa driver (#7372)\n- Mailvelope: Use sender's address to find pubkeys to check signatures (#7348)\n- Mailvelope: Fix Encrypt button hidden in Elastic (#7353)\n- Fix PHP warning: count(): Parameter must be an array or an object... in ID command handler (#7392)\n- Fix error when user-configured skin does not exist anymore (#7271)\n- Elastic: Fix aspect ratio of a contact photo in mail preview (#7339)\n- Fix bug where PDF attachments marked as inline could have not been attached on mail forward (#7382)\n- Security: Fix a couple of XSS issues in Installer (#7406)\n- Security: Fix XSS issue in template object 'username' (#7406)\n- Security: Better fix for CVE-2020-12641\n- Security: Fix cross-site scripting (XSS) via malicious XML attachment", "RELEASE 1.4.4\n-------------\n- Fix bug where attachments with Content-Id were attached to the message on reply (#7122)\n- Fix identity selection on reply when both sender and recipient addresses are included in identities (#7211)\n- Elastic: Fix text selection with Shift+PageUp and Shift+PageDown in plain text editor when using Chrome (#7230)\n- Elastic: Fix recipient input bug when using click to select a contact from autocomplete list (#7231)\n- Elastic: Fix color of a folder with recent messages (#7281)\n- Elastic: Restrict logo size in print view (#7275)\n- Fix invalid Content-Type for messages with only html part and inline images - Mail_Mime-1.10.7 (#7261)\n- Fix missing contact display name in QR Code data (#7257)\n- Fix so button label in Select image/media dialogs is \"Close\" not \"Cancel\" (#7246)\n- Fix regression in testing database schema on MSSQL (#7227)\n- Fix cursor position after inserting a group to a recipient input using autocompletion (#7267)\n- Fix string literals handling in IMAP STATUS (and various other) responses (#7290)\n- Fix bug where multiple images in a message were replaced by the first one on forward/reply/edit (#7293)\n- Fix handling keyservers configured with protocol prefix (#7295)\n- Markasjunk: Fix marking as spam/ham on moving messages with Move menu (#7189)\n- Markasjunk: Fix bug where moving to Junk was failing on messages selected with Select > All (#7206)\n- Fix so imap error message is displayed to the user on folder create/update (#7245)\n- Fix bug where a special folder couldn't be created if a special-use flag is not supported (#7147)\n- Mailvelope: Fix bug where recipients with name were not handled properly in mail compose (#7312)\n- Fix characters encoding in group rename input after group creation/rename (#7330)\n- Fix bug where some message/rfc822 parts could not be attached on forward (#7323)\n- Make install-jsdeps.sh script working without the 'file' program installed (#7325)\n- Fix performance issue of parsing big HTML messages by disabling HTML5 parser for these (#7331)\n- Fix so Print button for PDF attachments works on Firefox >= 75 (#5125)\n- Security: Fix XSS issue in handling of CDATA in HTML messages [CVE-2020-12625]\n- Security: Fix remote code execution via crafted 'im_convert_path' or 'im_identify_path' settings [CVE-2020-12641]\n- Security: Fix local file inclusion (and code execution) via crafted 'plugins' option [CVE-2020-12640]\n- Security: Fix CSRF bypass that could be used to log out an authenticated user [CVE-2020-12626] (#7302)", "RELEASE 1.4.3\n-------------\n- Enigma: Fix so key list selection is reset when opening key creation form (#7154)\n- Enigma: Fix so using list checkbox selection does not load the key preview frame\n- Enigma: Fix generation of key pairs for identities with IDN domains (#7181)\n- Enigma: Display IDN domains of key users and identities in UTF8\n- Enigma: Fix bug where \"Send unencrypted\" button didn't work in Elastic skin (#7205)\n- Managesieve: Fix bug where it wasn't possible to save flag actions (#7188)\n- Markasjunk: Fix bug where marking as spam/ham didn't work on moving messages with drag-and-drop (#7137)\n- Password: Make chpass-wrapper.py Python 3 compatible (#7135)\n- Elastic: Fix disappearing sidebar in mail compose after clicking Mail button\n- Elastic: Fix incorrect aria-disabled attribute on Mail taskmenu button in mail compose\n- Elastic: Fix bug where it was possible to switch editor mode when 'htmleditor' was in 'dont_override' (#7143)\n- Elastic: Fix text selection in recipient inputs (#7129)\n- Elastic: Fix missing Close button in \"more recipients\" dialog\n- Elastic: Fix non-working folder subscription checkbox for newly added folders (#7174)\n- Fix regression where \"Open in new window\" action didn't work (#7155)\n- Fix PHP Warning: array_filter() expects parameter 1 to be array, null given in subscriptions_option plugin (#7165)\n- Fix unexpected error message when mail refresh involves folder auto-unsubscribe (#6923)\n- Fix recipient duplicates in print-view when the recipient list has been expanded (#7169)\n- Fix bug where files in skins/ directory were listed on skins list (#7180)\n- Fix bug where message parts with no Content-Disposition header and no name were not listed on attachments list (#7117)\n- Fix display issues with mail subject that contains line-breaks (#7191)\n- Fix invalid Content-Transfer-Encoding on multipart messages - Mail_Mime fix (#7170)\n- Fix regression where using an absolute path to SQLite database file on Windows didn't work (#7196)\n- Fix using unix:///path/to/socket.file in memcached driver (#7210)", "RELEASE 1.4.2\n-------------\n- Plugin API: Make actionbefore, before<action>, actionafter and after<action> events working with plugin actions (#7106)\n- Managesieve: Replace \"Filter disabled\" with \"Filter enabled\" (#7028)\n- Managesieve: Fix so modifier type select wasn't hidden after hiding modifier select on header change\n- Managesieve: Fix filter selection after removing a first filter (#7079)\n- Markasjunk: Fix marking more than one message as spam/ham with email_learn driver (#7121)\n- Password: Fix kpasswd and smb drivers' double-escaping bug (#7092)\n- Enigma: Add script to import keys from filesystem to the db storage (for multihost)\n- Installer: Fix DB Write test on SQLite database (\"database is locked\" error) (#7064)\n- Installer: Fix so SQLite DSN with a relative path to the database file works in Installer\n- Elastic: Fix contrast of warning toasts (#7058)\n- Elastic: Simple search in pretty selects (#7072)\n- Elastic: Fix hidden list widget on mobile/tablet when selecting folder while search menu is open (#7120)\n- Fix so type attribute on script tags is not used on HTML5 pages (#6975)\n- Fix unread count after purge on a folder that is not currently selected (#7051)\n- Fix bug where Enter key didn't work on messages list in \"List\" layout (#7052)\n- Fix bug where deleting a saved search in addressbook caused display issue on sources/groups list (#7061)\n- Fix bug where a new saved search added after removing all searches wasn't added to the list (#7061)\n- Fix bug where a new contact group added after removing all groups from addressbook wasn't added to the list\n- Fix bug where Ctype extension wasn't required in Installer and INSTALL file (#7049)\n- Fix so install-jsdeps.sh removes Bootstrap's sourceMappingURL (#7035)\n- Fix so use of Ctrl+A does not scroll the list (#7020)\n- Fix/remove useless keyup event handler on username input in logon form (#6970)\n- Fix bug where cancelling switching from HTML to plain text didn't set the flag properly (#7077)\n- Fix bug where HTML reply could add an empty line with extra indentation above the original message (#7088)\n- Fix matching multiple X-Forwarded-For addresses with 'proxy_whitelist' (#7107)\n- Fix so displayed maximum attachment size depends also on 'max_message_size' (#7105)\n- Fix bug where 'skins_allowed' option didn't enforce user skin preference (#7080)\n- Fix so contact's organization field accepts up to 128 characters (it was 50)\n- Fix bug where listing tables in PostgreSQL database with db_prefix didn't work (#7093)\n- Fix bug where 'text' attribute on body tag was ignored when displaying HTML message (#7109)\n- Fix bug where next message wasn't displayed after delete in List mode (#7096)\n- Fix so number of contacts in a group is not limited to 200 when redirecting to mail composer from Contacts (#6972)\n- Fix malformed characters in HTML message with charset meta tag not in head (#7116)", "RELEASE 1.4.1\n-------------\n- Elastic: Change HTML editor widget to improve form flow (#6992)\n- Elastic: Fix position of mobile floating action button (#7038)\n- Managesieve: Fix locked UI after opening filter frame (#7007)\n- Fix PHP warning: \"array_merge(): Expected parameter 2 to be an array, null given in sendmail.inc (#7003)\n- Fix bug where cache keys could exceed length limit specified in db schema (#7004)\n- Fix invalid Signature button state after escaping Mailvelope mode (#7015)\n- Fix so 401 error is returned only on failed logon requests (#7010)\n- Fix db_prefix handling in queries with `TRUNCATE TABLE <name>` and `UNIQUE <name>` (#7013)\n- Fix so update.sh script warns about changed defaults (#7011)\n- Fix tables listing routine when DSN contained a database with unsupported suffix (#7034)\n- Fix so Elastic is also a default in jqueryui plugin (#7039)\n- Fix bug where the Installer would not warn about required schema upgrade (#7042)", "RELEASE 1.4.0\n-------------\n- Elastic: Resizeable columns (#6929)\n- Elastic: Fix position and style of auto-complete dropdown on small screens (#6951)\n- Elastic: Fix initial focus on recipients input in mail compose screen\n- Elastic: Fix inserting responses at cursor position (#6971)\n- Elastic: Fix unread filter icon and search state on folder change (#6978)\n- Elastic: Fix regression where Encrypt button wasn't displayed in mail compose toolbar (#6982)\n- Elastic: Fix regression where recipient input didn't update internal input state (#6988)\n- Enigma: Fix bug where signing option was set to disabled after saving a draft in Elastic skin (#6515)\n- Redis: Improve error handling and phpredis 5.X support (#6888)\n- Archive: Fix bug where next email was not displayed after Archive button use (#6965)\n- Archive: Fix missing Archive icon in folder selector popup in Elastic\n- Fix bug where cache keys were not case-sensitive on MySQL/MSSQL (#6942)\n- Fix so an error is logged when encryption fails (#6948)\n- Fix bug where inline images could have been ignored if Content-Id header contained redundant spaces (#6980)\n- Fix and document skin_logo setup (#6981)", "RELEASE 1.4-rc2\n---------------\n- Update to jQuery 3.4.1\n- Clarified 'address_book_type' option behavior (#6680)\n- Added cookie mismatch detection, display an error message informing the user to clear cookies\n- Renamed 'log_session' option to 'session_debug'\n- Removed 'delete_always' option (#6782)\n- Don't log full session identifiers in userlogins log (#6625)\n- Support $HasAttachment/$HasNoAttachment keywords (#6201)\n- Support PECL memcached extension as a session and cache storage driver (experimental)\n- Switch to IDNA2008 variant (#6806)\n- installto.sh: Add possibility to run the update even on the up-to-date installation (#6533)\n- Plugin API: Add 'render_folder_selector' hook\n- Added 'keyservers' option to define list of HKP servers for Enigma/Mailvelope (#6326)\n- Added flag to disable server certificate validation via Mysql DSN argument (#6848)\n- Select all records on the current list page with CTRL + A (#6813)\n- Use Left/Right Arrow keys to faster move over threaded messages list (#6399)\n- Changes in `display_next` setting (#6795):\n - Move it to Preferences > User Interface > Main Options\n - Make it apply to Contacts interface too\n - Make it apply only if deleting/moving a previewed message/contact\n- Redis: Support connection to unix socket\n- Put charset meta specification before a title tag, add page title automatically (#6811)\n- Elastic: Various internal refactorings\n- Elastic: Add Prev/Next buttons on message page toolbar (#6648)\n- Elastic: Close search options on Enter key press in quick-search input (#6660)\n- Elastic: Changed some icons (#6852)\n- Elastic: Changed read/unread icons (#6636)\n- Elastic: Changed \"Move to...\" icon (#6637)\n- Elastic: Add hide/show for advanced preferences (#6632)\n- Elastic: Add default icon on Settings/Preferences lists for external plugins (#6814)\n- Elastic: Add indicator for popover menu items that open a submenu (#6868)\n- Elastic: Move compose attachments/options to the right side (#6839)\n- Elastic: Add border/background to attachments list widget (#6842)\n- Elastic: Add \"Show unread messages\" button to the search bar (#6587)\n- Elastic: Fix bug where toolbar disappears on attachment menu use in Chrome (#6677)\n- Elastic: Fix folders list scrolling on touch devices (#6706)\n- Elastic: Fix non-working pretty selects in Chrome browser (#6705)\n- Elastic: Fix issue with absolute positioned mail content (#6739)\n- Elastic: Fix bug where some menu actions could cause a browser popup warning\n- Elastic: Fix handling mailto: URL parameters in contact menu (#6751)\n- Elastic: Fix keyboard navigation in some menus, e.g. the contact menu\n- Elastic: Fix visual issue with long buttons in .boxwarning (#6797)\n- Elastic: Fix handling new-line in text pasted to a recipient input\n- Elastic: Fix so search is not reset when returning from the message preview page (#6847)\n- Larry: Fix regression where menu actions didn't work with keyboard (#6740)\n- ACL: Display user/group names (from ldap) instead of acl identifier\n- Password: Added ldap_exop driver (#4992)\n- Password: Added support for SSHA512 password algorithm (#6805)\n- Managesieve: Fix bug where global includes were requested for vacation (#6716)\n- Managesieve: Use RFC-compliant line endings, CRLF instead of LF (#6686)\n- Managesieve: Fix so \"Create filter\" option does not show up when Filters menu is disabled (#6723)\n- Enigma: For verified signatures, display the user id associated with the sender address (#5958)\n- Enigma: Fix bug where revoked users/keys were not greyed out in key info\n- Enigma: Fix error message when trying to encrypt with a revoked key (#6607)\n- Enigma: Fix \"decryption oracle\" bug [CVE-2019-10740] (#6638)\n- Enigma: Fix bug where signature verification could have been skipped for some message structures (#6838)\n- Fix language selection for spellchecker in html mode (#6915)\n- Fix css styles leak from replied/forwarded message to the rest of the composed text (#6831)\n- Fix invalid path to \"add contact\" icon when using assets_path setting\n- Fix invalid path to blocked.gif when using assets_path setting (#6752)\n- Fix so advanced search dialog is not automatically displayed on searchonly addressbooks (#6679)\n- Fix so an error is logged when more than one attachment plugin has been enabled, initialize the first one (#6735)\n- Fix bug where flag change could have been passed to a preview frame when not expected\n- Fix bug in HTML parser that could cause missing text fragments when there was no head/body tag (#6713)\n- Fix bug where HTML messages with a xml:namespace tag were not rendered (#6697)\n- Fix TinyMCE download location (#6694)\n- Fix so \"Open in new window\" consistently displays \"external window\" interface (#6659)\n- Fix bug where next row wasn't selected after deleting a collapsed thread (#6655)\n- Fix bug where external content (e.g. mail body) was passed to templates parsing code (#6640)\n- Fix bug where attachment preview didn't work with x_frame_options=deny (#6688)\n- Fix so bin/install-jsdeps.sh returns error code on error (#6704)\n- Fix bug where bmp images couldn't be displayed on some systems (#6728)\n- Fix bug in parsing vCard data using PHP 7.3 due to an invalid regexp (#6744)\n- Fix bug where bold/strong text was converted to upper-case on html-to-text conversion (6758)\n- Fix bug in rcube_utils::parse_hosts() where %t, %d, %z could return only tld (#6746)\n- Fix bug where Next/Prev button in mail view didn't work with multi-folder search result (#6793)\n- Fix bug where selection of columns on messages list wasn't working\n- Fix bug in converting multi-page Tiff images to Jpeg (#6824)\n- Fix bug where handling multiple messages from multi-folder search result could not work (#6845)\n- Fix bug where unread count wasn't updated after moving multi-folder result (#6846)\n- Fix wrong messages order after returning to a multi-folder search result (#6836)\n- Fix some PHP 7.4 compat. issues (#6884, #6866)\n- Fix bug where it was possible to bypass the position:fixed CSS check in received messages (#6898)\n- Fix bug where some strict remote URIs in url() style were unintentionally blocked (#6899)\n- Fix bug where it was possible to bypass the CSS jail in HTML messages using :root pseudo-class (#6897)\n- Fix bug where it was possible to bypass href URI check with data:application/xhtml+xml URIs (#6896)", "RELEASE 1.4-rc1\n---------------\n- Changed 'password_charset' default to 'UTF-8' (#6522)\n- Add skins_allowed option (#6483)\n- SMTP GSSAPI support via krb_authentication plugin (#6417)\n- Avoid Referer leaking by using Referrer-Policy:same-origin header (#6385)\n- Removed 'referer_check' option (#6440)\n- Use constant prefix for temp file names, don't remove temp files from other apps (#6511)\n- Ignore 'Sender' header on Reply-All action (#6506)\n- deluser.sh: Add option to delete users who have not logged in for more than X days (#6340)\n- HTML5 Upload Progress - as a replacement for the old server-side solution (#6177)\n- Update to TinyMCE 4.8.2\n- Update to jQuery-MiniColors 2.3.4\n- Prevent from using deprecated timezone names from jsTimezoneDetect\n- Force session.gc_probability=1 when using custom session handlers (#6560)\n- Support simple field labels (e.g. LetterHub examples) in csv imports (#6541)\n- Add cache busters also to images used by templates (#6610)\n- Plugin API: Added 'raise_error' hook (#6199)\n- Plugin API: Added 'common_headers' hook (#6385)\n- Plugin API: Added 'ldap_connected' hook\n- Enigma: Update to OpenPGPjs 4.2.1 - fixes user name encoding issues in key generation (#6524)\n- Enigma: Fixed multi-host synchronization of private and deleted keys and pubring.kbx file\n- Managesieve: Added support for 'editheader' extension - RFC5293 (#5954)\n- Managesieve: Fix bug where custom header or variable could be lost on form submission (#6594)\n- Markasjunk: Integrate markasjunk2 features into markasjunk - marking as non-junk + learning engine (#6504)\n- Password: Added 'modoboa' driver (#6361)\n- Password: Fix bug where password_dovecotpw_with_method setting could be ignored (#6436)\n- Password: Fix bug where new users could skip forced password change (#6434)\n- Password: Allow drivers to override default password comparisons (eg new is not same as current) (#6473)\n- Password: Allow drivers to override default strength checks (eg allow for 'not the same as last x passwords') (#246)\n- Passowrd: Allow drivers to define password strength rules displayed to the user\n- Password: Allow separate password saving and strength drivers for use of strength checking services (#5040)\n- Password: Add zxcvbn driver for checking password strength (#6479)\n- Password: Disallow control characters in passwords\n- Password: Add support for Plesk >= 17.8 (#6526)\n- Elastic: Improved datepicker displayed always in parent window\n- Elastic: On touch devices display attachment icons on messages list (#6296)\n- Elastic: Make menu button inactive if all subactions are inactive (#6444)\n- Elastic: On mobile/tablet jump to the list on folder selection (#6415)\n- Elastic: Various improvements on mail compose screen (#6413)\n- Elastic: Support new-line char as a separator for pasted recipients (#6460)\n- Elastic: Improved UX of search dialogs (#6416)\n- Elastic: Fix unwanted thread expanding when selecting a collapsed thread in non-mobile mode (#6445)\n- Elastic: Fix too small height of mailvelope mail preview frame (#6600)\n- Elastic: Add \"status bar\" for mobile in mail composer\n- Elastic: Add selection options on contacts list (#6595)\n- Elastic: Fix unintentional layout preference overwrite (#6613)\n- Elastic: Fix bug where Enigma options in mail compose could sometimes be ignored (#6515)\n- Log errors caused by low pcre.backtrack_limit when sending a mail message (#6433)\n- Fix regression where drafts were not deleted after sending the message (#6756)\n- Fix so max_message_size limit is checked also when forwarding messages as attachments (#6580)\n- Fix so performance stats are logged to the main console log also when per_user_logging=true\n- Fix malformed message saved into Sent folder when using big attachments and low memory limit (#6498)\n- Fix incorrect IMAP SASL GSSAPI negotiation (#6308)\n- Fix so unicode in local part of the email address is also supported in recipient inputs (#6490)\n- Fix bug where autocomplete list could be displayed out of screen (#6469)\n- Fix style/navigation on error page depending on authentication state (#6362)\n- Fix so invalid smtp_helo_host is never used, fallback to localhost (#6408)\n- Fix custom logo size in Elastic (#6424)\n- Fix listing the same attachment multiple times on forwarded messages\n- Fix bug where a message/rfc822 part without a filename wasn't listed on the attachments list (#6494)\n- Fix inconsistent offset for various time zones - always display Standard Time offset (#6531)\n- Fix dummy Message-Id when resuming a draft without Message-Id header (#6548)\n- Fix handling of empty entries in vCard import (#6564)\n- Fix bug in parsing some IMAP command responses that include unsolicited replies (#6577)\n- Fix PHP 7.2 compatibility in debug_logger plugin (#6586)\n- Fix so ANY record is not used for email domain validation, use A, MX, CNAME, AAAA instead (#6581)\n- Fix so mime_content_type check in Installer uses files that should always be available (i.e. from program/resources) (#6599)\n- Fix missing CSRF token on a link to download too-big message part (#6621)\n- Fix bug when aborting dragging with ESC key didn't stop the move action (#6623)", "RELEASE 1.4-beta\n----------------\n- Added new skin with mobile support - the Elastic\n- Support Redis cache\n- Email Resent (Bounce) feature (#4985)\n- Improved Mailvelope integration\n - Added private key listing and generating to identity settings\n - Enable encrypt & sign option if Mailvelope supports it\n- Allow contacts without an email address (#5079)\n- Support SMTPUTF8 and relax email address validation to support unicode in local part (#5120)\n- Support for IMAP folders that cannot contain both folders and messages (#5057)\n- Update to jQuery-3.3.1\n- Update to jQuery-minicolors 2.2.6\n- Update to TinyMCE 4.7.13\n- Remove sample PHP configuration from .htaccess and .user.ini files (#5850)\n- Extend skin_logo setting to allow per skin logos (#6272)\n- Use Masterminds/HTML5 parser for better HTML5 support (#5761)\n- Add More actions button in Contacts toolbar with Copy/Move actions (#6081)\n- Display an error when clicking disabled link to register protocol handler (#6079)\n- Add option trusted_host_patterns (#6009, #5752)\n- Support additional connect parameters in PostgreSQL database wrapper\n- Use UI dialogs instead of confirm() and alert() where possible\n- Display value of the SMTP message size limit in the error message (#6032)\n- Show message flagged status in message view (#5080)\n- Skip redundant INSERT query on successful logon when using PHP7\n- Replace display_version with display_product_version (#5904)\n- Extend disabled_actions config so it accepts also button names (#5903)\n- Handle remote stylesheets the same as remote images, ask the user to allow them (#5994)\n- Add Message-ID to the sendmail log (#5871)\n- Add option to hide folders in share/other-user namespace or outside of the personal namespace root (#5073)\n- Archive: Fix archiving by sender address on cyrus-imap\n- Archive: Style Archive folder also on folder selector and folder manager lists\n- Archive: Add Thunderbird compatible Month option (#5623)\n- Archive: Create archive folder automatically if it's configured, but does not exist (#6076)\n- Enigma: Add button to send mail unencrypted if no key was found (#5913)\n- Enigma: Add options to set PGP cipher/digest algorithms (#5645)\n- Enigma: Multi-host support\n- Managesieve: Add ability to disable filter sets and other actions (#5496, #5898)\n- Managesieve: Add option managesieve_forward to enable settings dialog for simple forwarding (#6021)\n- Managesieve: Support filter action with custom IMAP flags (#6011)\n- Managesieve: Support 'mime' extension tests - RFC5703 (#5832)\n- Managesieve: Support GSSAPI authentication with krb_authentication plugin (#5779)\n- Managesieve: Support enabling the plugin for specified hosts only (#6292)\n- Password: Support host variables in password_db_dsn option (#5955)\n- Password: Automatic virtualmin domain setting, removed password_virtualmin_format option (#5759)\n- Password: Added password_username_format option (#5766)\n- subscriptions_option: show \\\\Noselect folders greyed out (#5621)\n- zipdownload: Added option to define size limit for multiple messages download (#5696)\n- vcard_attachments: Add possibility to send contact vCard from Contacts toolbar (#6080)\n- Changed defaults for smtp_user (%u), smtp_pass (%p) and smtp_port (587)\n- Composer: Fix certificate validation errors by using packagist only (#5148)\n- Add --get and --extract arguments and CACHEDIR env-variable support to install-jsdeps.sh (#5882)\n- Support _filter and _scope as GET arguments for opening mail UI (#5825)\n- Various improvements for templating engine and skin behaviours\n - Support conditional include\n - Support for 'link' objects\n - Support including files with path relative to templates directory\n - Use <button> instead of <input> for submit button on logon screen\n- Support skin localization (#5853)\n- Reset onerror on images if placeholder does not exist to prevent from requests storm\n- Unified and simplified code for loading content frame for responses and identities\n- Display contact import and advanced search in popup dialogs\n- Display a dialog for mail import with supported format description and upload size hint\n- Make possible to set (some) config options from a skin\n- Added optional checkbox selection for the list widget\n- Make 'compose' command always enabled\n- Add .log suffix to all log file names, add option log_file_ext to control this (#313)\n- Return \"401 Unauthorized\" status when login fails (#5663)\n- Support both comma and semicolon as recipient separator, drop recipients_separator option (#5092)\n- Plugin API: Added 'show_bytes' hook (#5001)\n- Add option to not indent quoted text on top-posting reply (#5105)\n- Removed global $CONFIG variable\n- Removed debug_level setting\n- Support AUTHENTICATE LOGIN for IMAP connections (#5563)\n- Support LDAP GSSAPI authentication (#5703)\n- Localized timezone selector (#4983)\n- Use 7bit encoding for ISO-2022-* charsets in sent mail (#5640)\n- Handle inline images also inside multipart/mixed messages (#5905)\n- Allow style tags in HTML editor on composed/reply messages (#5751)\n- Use Github API as a fallback to fetch js dependencies to workaround throttling issues (#6248)\n- Show confirm dialog when moving folders using drag and drop (#6119)\n- Fix bug where new_user_dialog email check could have been circumvented by deleting / abandoning session (#5929)\n- Fix skin extending for assets (#5115)\n- Fix handling of forwarded messages inside of a TNEF message (#5632)\n- Fix bug where attachment size wasn't visible when the filename was too long (#6033)\n- Fix checking table columns when there's more schemas/databases in postgres/mysql (#6047)\n- Fix css conflicts in user interface and e-mail content (#5891)\n- Fix duplicated signature when using Back button in Chrome (#5809)\n- Fix touch event issue on messages list in IE/Edge (#5781)\n- Fix so links over images are not removed in plain text signatures converted from HTML (#4473)\n- Fix various issues when downloading files with names containing non-ascii chars, use RFC 2231 (#5772)", "RELEASE 1.3.8\n-------------\n- Fix PHP warnings on dummy QUOTA responses in Courier-IMAP 4.17.1 (#6374)\n- Fix so fallback from BINARY to BODY FETCH is used also on [PARSE] errors in dovecot 2.3 (#6383)\n- Enigma: Fix deleting keys with authentication subkeys (#6381)\n- Fix invalid regular expressions that throw warnings on PHP 7.3 (#6398)\n- Fix so Classic skin splitter does not escape out of window (#6397)\n- Fix XSS issue in handling invalid style tag content [CVE-2018-19206] (#6410)\n- Fix compatibility with MySQL 8 - error on 'system' table use\n- Managesieve: Fix bug where show_real_foldernames setting wasn't respected (#6422)\n- New_user_identity: Fix %fu/%u vars substitution in user specific LDAP params (#6419)\n- Fix support for \"allow-from <uri>\" in \"x_frame_options\" config option (#6449)\n- Fix bug where valid content between HTML comments could have been skipped in some cases (#6464)\n- Fix multiple VCard field search (#6466)\n- Fix session issue on long running requests (#6470)", "RELEASE 1.3.7\n-------------\n- Fix PHP Warning: Use of undefined constant IDNA_DEFAULT on systems without php-intl (#6244)\n- Fix bug where some parts of quota information could have been ignored (#6280)\n- Fix bug where some escape sequences in html styles could bypass security checks\n- Fix bug where some forbidden characters on Cyrus-IMAP were not prevented from use in folder names\n- Fix bug where only attachments with the same name would be ignored on zip download (#6301)\n- Fix bug where unicode contact names could have been broken/emptied or caused DB errors (#6299)\n- Fix bug where after \"mark all folders as read\" action message counters were not reset (#6307)\n- Enigma: [EFAIL] Don't decrypt PGP messages with no MDC protection (#6289)\n- Fix bug where some HTML comments could have been malformed by HTML parser (#6333)", "RELEASE 1.3.6\n-------------\n- Fix parsing date strings (e.g. from a Date: mail header) with comments (#6216)\n- Fix PHP 7.2: count(): Parameter must be an array in enchant-based spellchecker (#6234)\n- Fix possible IMAP command injection and type juggling vulnerabilities (#6229)\n- Enigma: Fix key selection for signing\n- Enigma: Enable keypair generation on Internet Explorer 11\n- Fix check_request() bypass in places using get_uids() [CVE-2018-9846] (#6238)\n- Fix bug where usernames without domain part could be malformed or converted to lower-case on logon (#6224)", "RELEASE 1.3.5\n-------------\n- Managesieve: Fix bug where text: syntax was forced for strings longer than 1024 characters (#6143)\n- Managesieve: Fix missing Save button in Edit Filter Set page of Classic skin (#6154)\n- Fix duplicated labels in Test SMTP Config section (#6166)\n- Fix PHP Warning: exif_read_data(...): Illegal IFD size (#6169)\n- Enigma: Fix key generation in Safari by upgrade to OpenPGP 2.6.2 (#6149)\n- Fix security issue in remote content blocking on HTML image and style tags (#6178)\n- Added 9pt and 11pt to the list of font sizes in HTML editor\n- Fix handling encoding of HTML tags in \"inline\" JSON output (#6207)\n- Fix bug where some unix timestamps were not handled correctly by rcube_utils::anytodatetime() (#6212)", "RELEASE 1.3.4\n-------------\n- Fix bug where contacts search could skip some records (#6130)\n- Fix possible information leak - add more strict sql error check on user creation (#6125)\n- Fix a couple of warnings on PHP 7.2 (#6098)\n- Fix broken long filenames when using imap4d server - workaround server bug (#6048)\n- Fix so temp_dir misconfiguration prints an error to the log (#6045)\n- Fix untagged COPYUID responses handling - again (#5982)\n- Fix PHP warning \"idn_to_utf8(): INTL_IDNA_VARIANT_2003 is deprecated\" with PHP 7.2 (#6075)\n- Fix bug where Archive folder wasn't auto-created on login with create_default_folders=true\n- Fix performance issue when parsing malformed and long Date header (#6087)\n- Fix syntax error in mssql.initial.sql (#6097)\n- Fix bug where contacts export by selection returned no more than 10 entries (#6103)\n- Fix searching contacts by address in LDAP source (#6084)\n- Fix X-Frame-Options:ALLOW-FROM support, remove custom click-jacking protection (#6057)", "RELEASE 1.3.3\n-------------\n- Fix decoding of mailto: links with + character in HTML messages (#6020)\n- Fix false reporting of failed upgrade in installto.sh (#6019)\n- Fix file disclosure vulnerability caused by insufficient input validation [CVE-2017-16651] (#6026)\n- Fix mangled non-ASCII characters in links in HTML messages (#6028)", "RELEASE 1.3.2\n-------------\n- Fix bug where pink image was used instead of a thumbnail when image resize fails (#5933)\n- Fix so files size/count limit is verified (client-side) also on drag-n-drop uploads (#5940)\n- Fix invalid template loading on a message error in preview frame (#5941)\n- Fix bug where HTML messages could have been rendered empty on some systems (#5957)\n- Fix wording of \"Mark previewed messages as read\" to \"Mark messages as read\" (#5952)\n- Enigma: Fix decryption of messages encoded with non-ascii charset (#5962)\n- Fix missing cursor in HTML editor on mail reply (#5969)\n- Fix (again) bug where image data URIs in css style were treated as evil/remote in mail preview (#5580)\n- Fix bug where mail search could return empty result on servers without SORT capability (#5973)\n- Fix bug where assets_path wasn't added to some watermark frames\n- Fix so untagged COPYUID responses are also supported according to RFC6851 (#5982)\n- Fix issue caused by non-default session.cookie_lifetime setting (#5961)\n- Fix Edge encoding bug when pasting text into the HTML editor, update to TinyMCE 4.5.8 (#5885)\n- Fix handling of unknown Content-Disposition type (#6002)\n- Fix truncated folder name on messages list in multi-folder mode, for folders with non-ascii characters (#6004)\n- Fix bug where removing the last subfolder did not hide toggle button on its parent record (#6007)\n- Fix bug where ghost messages could be added to the list after fast delete (#5941)", "RELEASE 1.3.1\n-------------\n- Add Preferences > Mailbox View > Main Options > Layout (#5829)\n- Password: Fix compatibility with PHP 7+ in cpanel_webmail driver (#5820)\n- Managesieve: Fix parsing dot-staffed lines in multiline text (#5838)\n- Managesieve: Fix AM/PM suffix in vacation time selectors\n- Managesieve: Fix bug where 'exists' operator was reset to 'contains' (#5899)\n- Remove non-printable characters from filenames on download/display (#5880)\n- Fix decoding non-ascii attachment names from TNEF attachments (#5646, #5799)\n- Fix uninitialized string offset in rcube_utils::bin2ascii() and make sure rcube_utils::random_bytes() result has always requested length (#5788)\n- Fix bug where HTML messages with @media styles could moddify style of page body (#5811)\n- Fix style issue on selected and unfocused message that is part of a thread (#5798)\n- Fix bug where a.button style from managesieve plugin could impact other elements (#5800)\n- Fix position of selected icon for (Mailvelope) Encrypt button\n- Fix fatal error when using DMY- or MDY-based date format in PostgreSQL (#5808)\n- Fix bug where errors were not printed when using bin/update.sh (#5834)\n- Fix PHP 7.2 warnings on count() use (#5845)\n- Fix bug where Chrome could not upload the same file that was selected before (#5854)\n- Fix duplicate messages on the list after deleting messages on the next to the last page (#5862)\n- Fix bug where messages count was not updated after delete when imap_cache is set (#5872)\n- Fix potential XSS vulnerability with malformed HTML message markup\n- Fix sending message with \"Too many public recipients\" dialog buttons (#5924)\n- Bring back double-click behavior on the message list which was removed in 1.3.0 (#5823)\n- Enigma: Fix decrypting an encrypted+signed message when signature verification fails (#5914)", "RELEASE 1.3.0\n-------------\n- Update to TinyMCE 4.5.7\n- Fix bug where invalid recipients could be silently discarded (#5739)\n- Fix conflict with _gid cookie of Google Analytics (#5748)\n- Print error from CLI scripts when system/exec function is disabled (#5744)\n- Fix bug where comment notation within style tag would cause the whole style to be ignored (#5747)\n- Fix bug where it wasn't possible to scroll folders list in Edge (#5750)\n- Fix folders list sorting on Windows - if php-intl is available (#5732)\n- Fix addressbook searching by gender (#5757)\n- Fix prevention from using % and * characters in folder name (#5762)\n- Fix POST parameter reflection in default_charset selector (#5768)\n- Enigma: Fix compatibility with assets_dir\n- Managesieve: Skip redundant LISTSCRIPTS command\n- Fix SQL syntax error on MariaDB 10.2 (#5774)\n- Fix bug where zipdownload ignored files with the same name (#5777)\n- Fix bug where it wasn't possible to set timezone to auto-detected value (#5782)", "RELEASE 1.3-rc\n--------------\n- \"Flattened\" the larry theme: fresher look by removing shadows and gradients\n- Support logging to php://stdout (#5721)\n- Add support for DelSp=Yes in format=flowed messages (#5702)\n- Update to jQuery 3.2.1\n- Update to TinyMCE 4.5.6\n- Plugin API: Call message_part_structure hook for sub-parts of multipart/alternative message (#5678)\n- Enigma: Always use detached signatures (#5624)\n- Enigma: Fix handling of messages with nested PGP encrypted parts (#5634)\n- Minimize unwanted message loading in preview frame on drag (#5616)\n- Fix failing database schema check in all engines except mysql (#5730)\n- Fix autocomplete popup closing with click outside the input, don't handle Tab key as Enter (#5606)\n- Fix jsdeps.json synchronization on update, warn about missing requirements of install-jsdeps.sh (#5598)\n- Fix missing thread expand icon on search result in widescreen mode (#5613)\n- Fix bug where image data URIs in css style were treated as evil/remote in mail preview (#5580)\n- Fix bug where external content in src attribute of input/video tags was not secured (#5583)\n- Fix PHP error on update of a contact with multiple email addresses when using PHP 7.1 (#5587)\n- Fix bug where mail content frame couldn't be reset in some corner cases (#5608)\n- Fix bug where some classic skin images were not displayed in IE/Edge (#5614)\n- Fix bug where signature couldn't be added above the quote in Firefox 51 (#5628)\n- Fix regression where groups with email address were resolved to its members' addresses\n- Fix update of group name in the contacts list header on group rename (#5648)\n- Add rewrite rule to disable access to /vendor/bin folder in .htaccess (#5630)\n- Fix bug where it was too easy accidentally move a folder when using the subscription checkbox (#5655)\n- Managesieve: Fix parser issue with empty lines between comments (#5657)\n- Managesieve: Fix possible defect in handling \\r\\n in scripts (#5685)\n- Fix/rephrase \"unsaved changes\" warning when cancelling a draft (#5610)\n- Fix XSS issue in handling of a style tag inside of an svg element [CVE-2017-6820]\n- Fix bug where settings/upload.inc could not be used by plugins (#5694)\n- Fix regression in LDAP fuzzy search where it always used prefix search instead (#5713)\n- Fix bug where namespace prefix could not be truncated on folders list if show_real_foldernames=true (#5695)\n- Fix undesired effects when postgres database uses different timezone than PHP host (#5708)\n- Installer: Fix DB schema initialization on MS SQL Server\n- Fix bug where base_dn setting was ignored inside group_filters (#5720)\n- Password: Fix security issue in virtualmin and sasl drivers [CVE-2017-8114]", "RELEASE 1.3-beta\n----------------\n- Nicely handle contact deletion on contact edit (#5522)\n- vcard_attachments: Add possibility to attach contact vCard to composed message (#4997)\n- Preserve message internal/received date on import in mbox format (#5559)\n- Zipdownload: Fix date format in mbox \"From line\"\n- Possibility to display QR code for contacts data (#5030)\n- Added identicon plugin\n- Widescreen layout aka three column view (#5093)\n- Unify automatic marking as \\Seen in preview pane, full-page and extwin views (#5071)\n- Disable double-click on the list when preview pane is on (#5199)\n- Support hostname and hostname:port in force_https option (#5511)\n- Support ALLOW-FROM in x_frame_options (#5122)\n- Allow to omit a subject when sending an email (#5068)\n- Warn about too many disclosed recipients in composed email [max_disclosed_recipients] (#5132)\n- identity_select: Support Received header (#5085)\n- Plugin API: Added get_compose_responses hook (#5457)\n- Display error when trying to upload more files than specified in max_file_uploads (#5483)\n- Add missing sql upgrade file for 'ip' column resize in session table (#5465)\n- Do not show inline images of unsupported mimetype (#5463)\n- Password: Added replacement variables support in password_pop_host (#5539)\n- Password: Don't store passwords in temp files when using dovecotpw (#5531)\n- Password: Added LDAP PPolicy driver (#5364)\n- Password: Added cpanel_webmail driver (#5549)\n- Password: Added possibility to nicely redirect from other plugins on password expiration (#5468)\n- Implement separate action to mark all messages in a folder as \\Seen (#5006)\n- Implement marking as \\Seen in all folders or in a folder and its subfolders (#5076)\n- Archive: Don't reload messages list when it's not needed (#5225)\n- Archive: Add option to automatically mark archived messages as \\Seen (#5142)\n- Improve randomness of password salts and random hashes (#5266)\n- Password/cPanel: Add support for hash authentication and reseller accounts (#5252)\n- Support host-specific imap_conn_options/smtp_conn_options/managesieve_conn_options (#5136)\n- Center and scale images in attachment preview frame (#5421)\n- Added max_message_size option enforced when attaching files to a composed message (#4993)\n- Added Search button in quick search menus (#5312)\n- Implement \"one click\" attachment/messages/photo upload (#5024)\n- Squirrelmail_usercopy: Add option to define character set of data files\n- Removed useless 'created' column from 'session' table (#5389)\n- Dropped legacy browsers support (#5167)\n - Removed legacy_browser plugin\n - Removed hacks for IE < 10\n - Update to jQuery 3.1.1 and jQuery-UI 1.12.0\n - compile .min.js files with ECMASCRIPT5 option\n- Require PHP >= 5.4\n- Add possibility to preview and download attachments in mail compose (#5053)\n- Add possibility to rename attachments in mail compose (#4996)\n- Remove backward compatibility \"layer\" of bc.php (#4902)\n- Support WEBP images in mail messages (#5362)\n- Support MathML in HTML message preview (#5182)\n- Rename Addressbook to Contacts (#5233)\n- Remove PHP mail() support, smtp_server is required now (#5340)\n- Display full message subject in onmouseover on truncated subject in mail view (#5346)\n- Enigma: Support GnuPG 2.1 (#5313)\n- Enigma: Support key generation for multiple identities (#5383)\n- Enigma: Import keys from key-server(s) (#5286)\n- Enigma: Search missing public keys on a key-server in mail compose (#5286)\n- Enigma: Delete user keys when using deluser.sh script\n- Enigma: Fix redundant list-secret-keys/list-public-keys calls on signing/encryption\n- Enigma: Implement PGP encryption and signing in one go (#5302)\n- Enigma: Display signature verification status for encrypted+signed messages (#5302)\n- Display different attachment icon on encrypted messages\n- Display different confirmation text when moving messages to Trash (#5220)\n- Indicate that a collapsed thread has flagged children (#5013)\n- Implemented message/rfc822 attachment preview\n- Update to jsTimezoneDetect 1.0.6\n- Managesieve: Add (optional) RAW script editor (#5414)\n- Managesieve: Add option to automatically set vacation :from address (#5428)\n- Managesieve: Support 'string' test from variables extension [RFC 5229] (#5248)\n- Managesieve: Support 'duplicate' extension [RFC 7352]\n- Managesieve: Unhide advanced rule controls if there are inputs with errors\n- Managesieve: Display warning message when filter form contains errors\n- Control search engine crawlers via X-Robots-Tag header instead of <meta> and robots.txt (#5098)\n- Fixed redundancy in sql caching system and compatibility with Galera Cluster (#5439)\n - Removed redundant 'created' column from cache and cache_shared tables\n - Removed use of redundant data records\n - Added missing primary keys (dictionary, cache, cache_shared tables)\n- Fix so templating system does not mess with external (e.g. email) content (#5499)\n- Fix redundant keep-alive/refresh after session error on compose page (#5500)\n- Managesieve: Fix handling of scripts with nested rules (#5540)\n- Fix variable substitution in ldap host for some use-cases, e.g. new_user_identity (#5544)\n- Enigma: Fix PHP fatal error when decrypting a message with invalid signature (#5555)\n- Fix adding images to new identity signatures\n- Fix rsync error handling in installto.sh script (#5562)\n- Fix some advanced search issues with multiple addressbooks (#5572)\n- Fix so group/addressbook selection is retained on page refresh", "RELEASE 1.2.3\n-------------\n- Searching in both contacts and groups when LDAP addressbook with group_filters option is used\n- Fix vulnerability in handling of mail()'s 5th argument\n- Fix To: header encoding in mail sent with mail() method (#5475)\n- Fix flickering of header topline in min-mode (#5426)\n- Fix bug where folders list would scroll to top when clicking on subscription checkbox (#5447)\n- Fix decoding of GB2312/GBK text when iconv is not installed (#5448)\n- Fix regression where creation of default folders wasn't functioning without prefix (#5460)\n- Enigma: Fix bug where last records on keys list were hidden (#5461)\n- Enigma: Fix key search with keyword containing non-ascii characters (#5459)\n- Fix bug where deleting folders with subfolders could fail in some cases (#5466)\n- Fix bug where IMAP password could be exposed via error message (#5472)\n- Fix bug where it wasn't possible to store more that 2MB objects in memcache/apc,\n Added memcache_max_allowed_packet and apc_max_allowed_packet settings (#5452)\n- Fix \"Illegal string offset\" warning in rcube::log_bug() on PHP 7.1 (#5508)\n- Fix storing \"empty\" values in rcube_cache/rcube_cache_shared (#5519)\n- Fix missing content check when image resize fails on attachment thumbnail generation (#5485)\n- Fix displaying attached images with wrong Content-Type specified (#5527)", "RELEASE 1.2.2\n-------------\n- Enigma: Add possibility to configure gpg-agent binary location (enigma_pgp_agent)\n- Enigma: Fix signature verification with some IMAP servers, e.g. Gmail, DBMail (#5371)\n- Enigma: Make recipient key searches case-insensitive (#5434)\n- Fix regression in resizing JPEG images with Imagick (#5376)\n- Managesieve: Fix parsing of vacation date-time with non-default date_format (#5372)\n- Use SymLinksIfOwnerMatch in .htaccess instead of FollowSymLinks disabled on some hosts for security reasons (#5370)\n- Wash position:fixed style in HTML mail for better security (#5264)\n- Fix bug where memcache_debug didn't work for session operations\n- Fix bug where Message-ID domain part was tied to username instead of current identity (#5385)\n- Fix bug where blocked.gif couldn't be attached to reply/forward with insecure content\n- Fix E_DEPRECATED warning when using Auth_SASL::factory() (#5401)\n- Fix bug where names of downloaded files could be malformed when derived from the message subject (#5404)\n- Fix so \"All\" messages selection is resetted on search reset (#5413)\n- Fix bug where folder creation could fail if personal namespace contained more than one entry (#5403)\n- Fix error causing empty INBOX listing in Firefox when using an URL with user:password specified (#5400)\n- Fix PHP warning when handling shared namespace with empty prefix (#5420)\n- Fix so folders list is scrolled to the selected folder on page load (#5424)\n- Fix so when moving to Trash we make sure the folder exists (#5192)\n- Fix displaying size of attachments with zero size\n- Fix so \"Action disabled\" error uses more appropriate 404 code (#5440)", "RELEASE 1.2.1\n-------------\n- Update TinyMCE to version 4.3.13 (#5309)\n- Fix bug where errors could have been not logged when per_user_logging=true\n- Fix bug where message list columns could be in wrong order after column drag-n-drop and list sorting\n- Fix so minified publickey.js (with cache-buster) is used when available (#5254)\n- Fix (replace) application/x-tar file extension test as it might not exist in nginx config (#5253)\n- Fix PHP warning when password_hosts is set, but is not an array (#5260)\n- Fix redundant keep-alive requests when session_lifetime is greater than ~20000 (#5273)\n- Fix so subfolders of INBOX can be set as Archive (#5274)\n- Fix bug where multi-folder search could choose a wrong folder in \"this and subfolders\" scope (#5282)\n- Fix bug where multi-folder search didn't work for unsubscribed INBOX (#5259)\n- Fix bug where \"no body\" alert could be displayed when sending mailvelope email\n- Enigma: Fix keys import from inside of an encrypted message (#5285)\n- Enigma: Fix malformed signed messages with force_7bit=true (#5292)\n- Enigma: Add possibility to configure gpg binary location (enigma_pgp_binary)\n- Enigma: Add possibility to export private keys (#5321)\n- Fix searching by email address in contacts with multiple addresses (#5291)\n- Fix handling of --delete argument in moduserprefs.sh script (#5296)\n- Workaround PHP issue by calling closelog() on script shutdown when using log_driver=syslog (#5289)\n- Fix so upgrade script makes sure program/lib directory does not contain old libraries (#5287)\n- Fix subscription checkbox state on error in folder subscribe/unsubscribe action (#5243)\n- Fix bug where microsecond format in logged date didn't work in some cases\n- Fix conflict in new_user_dialog and password_force_new_user settings (#5275)\n- Don't create multipart/alternative messages with empty text/plain part (#5283)\n- Use contact_search_name format in popup on results in compose contacts search\n- Fix handling of 'mailto' and 'error' arguments in message_before_send hook (#5347)\n- Fix missing localization of HTML editor when assets_dir != INSTALL_PATH\n- Fix handling of blockquote tags with mixed case on html2text conversion (#5363)\n- Fix javascript errors in IE on page with iframe that points to another domain", "RELEASE 1.2.0\n-------------\n- Enigma: Added enigma_debug option\n- Fix message list multi-select/deselect issue (#5219)\n- Fix bug where getting HTML editor content could steal focus from other form controls (#5223)\n- Fix bug where contact search menu fields where always unchecked in Larry skin\n- Fix autoloading of 'html' class\n- Fix bug where Encrypt button appears when switching editor to HTML (#5235)\n- Fix XSS issue in href attribute on area tag (#5240)", "RELEASE 1.2-rc\n--------------\n- Managesieve: Refactored script parser to be 100x faster\n- Enigma: added option to force users to use signing/encryption\n- Enigma: Added option to attach public keys to sent mail (#5152)\n- Enigma: Handle messages with text before an encrypted block (#5149)\n- Enigma: Handle encrypted/signed content inside message/rfc822 attachments\n- Enigma: Fix missing html/plain switch on multipart/signed messages (#4963)\n- Enigma: Disable format=flowed for signed plain text messages (#4960)\n- Enigma: Fix handling of encrypted + signed messages (#4950)\n- Enigma: Fix invalid boundary use in signed messages structure\n- Enable use of TLSv1.1 and TLSv1.2 for IMAP (#4955)\n- Save copy of original .htaccess file when using installto.sh script (#4947)\n- Fix regression where some message attachments could be missing on edit/forward (#4939)\n- Fix regression in displaying contents of message/rfc822 parts (#4937)\n- Fix handling of message/rfc822 attachments on replies and forwards (#4938)\n- Fix PDF support detection in Firefox > 19 (#4941)\n- Fix path traversal vulnerability in setting a skin [CVE-2015-8770] (#4945)\n- Fix so drag-n-drop of text (e.g. recipient addresses) on compose page actually works (#4944)\n- Fix .htaccess rewrite rules to not block .well-known URIs (#4943)\n- Fix mail view scaling on iOS (#4915)\n- Fix PHP7 warning \"session_start(): Session callback expects true/false return value\" (#4948)\n- Fix XSS issue in SVG images handling [CVE-2015-8864, CVE-2016-4068] (#4949)\n- Fix missing language name in \"Add to Dictionary\" request in HTML mode (#4951)\n- Fix (again) security issue in DBMail driver of password plugin [CVE-2015-2181] (#4958)\n- Fix bug where Archive/Junk buttons were not active after page jump with select=all mode (#4961)\n- Fix bug in long recipients list parsing for cases where recipient name contained @-char (#4964)\n- Plugin API: Added addressbook_export hook\n- Fix additional_message_headers plugin compatibility with Mail_Mime >= 1.9 (#4966)\n- Hide DSN option in Preferences when smtp_server is not used (#4967)\n- Fix handling of body parameter in mail compose request\n- Protect download urls against CSRF using unique request tokens [CVE-2016-4069] (#4957)\n- newmail_notifier: Refactor desktop notifications\n- Fix so contactlist_fields option can be set via config file\n- Fix so SPECIAL-USE assignments are forced only until user sets special folders (#4782)\n- Fix performance in reverting order of THREAD result\n- Fix converting mail addresses with @www. into mailto links (#5197)", "RELEASE 1.2-beta\n----------------\n- Update TinyMCE to version 4.2\n- Added support for Redis session handler\n- Removed some deprecated methods: https://github.com/roundcube/roundcubemail/commit/454b0b1c\n- Remove backward compatibility \"layer\" of bc.php (#4902)\n- Add possibility to define date format in write operations for ldap attributes (#3956)\n- Display attachment size in compose (#1329)\n- Added possibility to drag-n-drop attachments from mail preview to compose window\n- Implemented mail messages searching with predefined date interval\n- PGP encryption support via Mailvelope integration\n- PGP encryption support via Enigma plugin\n- PHP7 compatibility fixes (#4836)\n- Security: Added brute-force attack prevention via login rate limit (#4922)\n- Security: Added options to validate username/password on logon (#4884)\n- Security: Improve randomness of security tokens (#4899)\n- Security: Use random security tokens instead of hashes based on encryption key (#4829)\n- Security: Improved encrypt/decrypt methods with option to choose the cipher_method (#4492)\n- Make optional adding of standard signature separator - sig_separator (#3276)\n- Optimize folder_size() on Cyrus IMAP by using special folder annotation (#4894)\n- Make optional hidding of folders with name starting with a dot - imap_skip_hidden_folders (#4870)\n- Add option to enable HTML editor always, except when replying to plain text messages (#4352)\n- Emoticons: Added option to switch on/off emoticons in compose editor (#2076)\n- Emoticons: Added option to switch on/off emoticons in plain text messages\n- Emoticons: All emoticons-related functionality is handled by the plugin now\n- Installer: Add button to save generated config file in system temp directory (#3553)\n- Remove common subject prefixes Re:, Re[x]:, Re-x: on reply (#4882)\n- Added GSSAPI/Kerberos authentication plugin - krb_authentication\n- Password: Allow temporarily disabling the plugin functionality with a notice\n- Require Mbstring and OpenSSL extensions (#5166)\n- Add --config and --type options to moduserprefs.sh script (#4651)\n- Implemented memcache_debug and apc_debug options\n- Installer: Remove system() function use (#4695)\n- Password plugin: Added 'kpasswd' driver by Peter Allgeyer\n- Add initdb.sh to create database from initial.sql script with prefix support (#4722)\n- Plugin API: Added disabled_plugins an disabled_buttons options in html_editor hook\n- Plugin API: Added html2text hook\n- Plugin API: Added message_part_body hook\n- Plugin API: Added message_ready hook\n- Plugin API: Add special onload() method to execute plugin actions before startup (session and GUI initialization)\n- Implemented UI element to jump to specified page of the messages list (#1677)\n- Fix searching of contacts to allow remote images for known senders (#4886)\n- Fix bug where clicking date column with 'arrival' sorting would switch to sorting by 'date' (#4690)\n- Fix bug where message content could overlap attachments list in Larry skin (#4876)\n- Fix so microseconds macro (u) in log_date_format works (#4855)\n- Fix so unrecognized TNEF attachments are displayed on the list of attachments (#5138)\n- Fix so database_attachments::cleanup() does not remove attachments from other sessions (#4907)\n- Fix responses list update issue after response name change (#4917)\n- Fix bug where message preview was unintentionally reset on check-recent action (#4921)\n- Fix bug where HTML messages with invalid/excessive css styles couldn't be displayed (#4905)\n- Fix redundant blank lines when using HTML and top posting (#4927)\n- Fix redundant blank lines on start of text after html to text conversion (#4928)\n- Fix HTML sanitizer to skip <!-- node type X --> in output (#4932)\n- Fix invalid LDAP query in ACL user autocompletion (#4934)", "RELEASE 1.1.3\n-------------\n- Fix closing of nested menus (#4854)\n- Fix so E_DEPRECATED errors from PEAR libs are ignored by error_reporting change (#4770)\n- Fix compatibility with PHP 5.3 in rcube_ldap class (#4842)\n- Get rid of Mail_mimeDecode package dependency (#4836)\n- Fix \"Importing...\" message does not hide on error (#4840)\n- Fix Compose action in addressbook for results from multiple addressbooks (#4834)\n- Fix bug where some messages in multi-folder search couldn't be viewed/printed/downloaded (#4843)\n- Fix unintentional messages list page change on page switch in compose addressbook (#4844)\n- Fix race-condition in saving user preferences and loading plugin config (#4845)\n- Fix so plain text signature field uses monospace font (#4848)\n- Fix so links with href == content aren't added to links list on html to text conversion (#4847)\n- Fix handling of non-break spaces in html to text conversion (#4849)\n- Fix self-reply detection issues (#4852)\n- Fix multi-folder search result sorting by arrival date (#4858)\n- Fix so *-request@ addresses in Sender: header are also ignored on reply-all (#4860)\n- Update to TinyMCE 4.1.10 (#5164)\n- Fix draft removal after a message is sent and storing sent message is disabled (#4869)\n- Fix so imap folder attribute comparisons are case-insensitive (#4868)\n- Fix bug where new messages weren't added to the list in search mode\n- Fix wrong positioning of message list header on page scroll in Webkit browsers (#4646)\n- Fix some javascript errors in rare situations (#4853)\n- Fix error when using back button after sending an email (#4628)\n- Fix removing signature when switching to identity with an empty sig in HTML mode (#4872)\n- Disable links list generation on html-to-text conversion of identities or composed message (#4850)\n- Fix \"washing\" of style elements wrapped into many lines\n- Fix so input field (e.g. search box) does not loose focus on list load (#4862)\n- Fix so css of one html part does not apply to other text parts on message display (#4887)\n- Fix XSS issue in drag-n-drop file uploads [CVE-2015-8105] (#4900)\n- Fix handling of plus character in mailto: links (#4891)\n- Fix so adding CC/BCC recipients from the sidebar unhides compose form fields in Classic skin (#4874)\n- Fix so gc.sh script removes also expired sessions from sql database (#4893)\n- Fix support for Mozilla-based browsers, e.g. Pale Moon (#4895)\n- Fix various issues with Turkish (and similar) locales (#4896)\n- Fix so In-Reply-To header is set also for MDN receipts (#4897)\n- Fix missing HTTP_X_FORWARDED_FOR address in generated Received header\n- Fix issue where Content-Length of some attachments could be set to wrong value causing browser errors (#4877)", "RELEASE 1.1.2\n-------------\n- Add new plugin hook 'identity_create_after' providing the ID of the inserted identity (#4807)\n- Add option to place signature at bottom of the quoted text even in top-posting mode [sig_below]\n- Fix handling of %-encoded entities in mailto: URLs (#4799)\n- Fix zipped messages downloads after selecting all messages in a folder (#4797)\n- Fix vpopmaild driver of password plugin\n- Fix PHP warning: Non-static method PEAR::setErrorHandling() should not be called statically (#4798)\n- Fix tables listing routine on mysql and postgres so it skips system or other database tables and views (#4796)\n- Fix message list header in classic skin on window resize in Internet Explorer (#4732)\n- Fix so text/calendar parts are listed as attachments even if not marked as such (#4795)\n- Fix lack of signature separator for plain text signatures in html mode (#4802)\n- Fix font artifact in Google Chrome on Windows (#4803)\n- Fix bug where forced extwin page reload could exit from the extwin mode (#4801)\n- Fix bug where some unrelated attachments in multipart/related message were not listed (#4805)\n- Fix mouseup event handling when dragging a list record (#4808)\n- Fix bug where preview_pane setting wasn't always saved into user preferences (#4809)\n- Fix bug where messages count was not updated after message move/delete with skip_deleted=false (#4814)\n- Fix security issue in contact photo handling (#4817)\n- Fix possible memcache/apc cache data consistency issues (#4820)\n- Fix bug where imap_conn_options were ignored in IMAP connection test (#4822)\n- Fix bug where some files could have \"executable\" extension when stored in temp folder (#4815)\n- Fix attached file path unsetting in database_attachments plugin (#4823)\n- Fix issues when using moduserprefs.sh without --user argument (#4825)\n- Fix potential info disclosure issue by protecting directory access (#4816)\n- Fix blank image in html_signature when saving identity changes (#4833)\n- Installer: Use openssl_random_pseudo_bytes() (if available) to generate des_key (#4827)\n- Fix XSS vulnerability in _mbox argument handling (#4837)", "RELEASE 1.1.1\n-------------\n- ACL: Allow other plugins to adjust the list of permissions and groups to edit\n- Add possibility to print contact information (of a single contact)\n- Add possibility to configure max_allowed_packet value for all database engines (#4772)\n- Improved handling of storage errors after message is sent\n- Update to TinyMCE 4.1.9\n- Unified request* event arguments handling, added support for _unlock and _action parameters\n- Security: Generate random hash for the per-user local storage prefix (#4768)\n- Fix refreshing of drafts list when sending a message which was saved in meantime (#4745)\n- Fix saving/sending emoticon images when assets_dir is set\n- Fix PHP fatal error when visiting Vacation interface and there's no sieve script yet (#4778)\n- Fix setting max packet size for DB caches and check packet size also in shared cache\n- Fix needless security warning on BMP attachments display (#4771)\n- Fix handling of some improper constructs in format=flowed text as per the RFC3676[4.5] (#4773)\n- Fix performance of rcube_db_mysql::get_variable()\n- Fix missing or not up-to-date CATEGORIES entry in vCard export (#4766)\n- Fix fatal errors on systems without mbstring extension or mb_regex_encoding() function (#4769)\n- Fix cursor position on reply below the quote in HTML mode (#4759)\n- Fix so \"over quota\" errors are displayed also in message compose page\n- Fix duplicate entries suppression in autocomplete result (#4776)\n- Fix \"Non-static method PEAR::isError() should not be called statically\" errors (#4770)\n- Fix parsing invalid HTML messages with BOM after <!DOCTYPE> (#4777)\n- Fix duplicate entry on timezones list in rcube_config::timezone_name_from_abbr() (#4779)\n- Fix so localized folder name is displayed in multi-folder search result (#4750)\n- Fix javascript error after creating a folder which is a subfolder of another one (#4781)\n- Fix bug where subject of sent/saved message was removed if mbstring wasn't installed (#4780)\n- Fix missing vcard_attachment icon on messages list (#4783)\n- Fix storing signatures with big images in MySQL database (#4785)\n- Fix Opera browser detection in javascript (#4786)\n- Fix so search filter, scope and fields are reset on folder change\n- Fix rows count when messages search fails (#4760)\n- Fix bug where spellchecking in HTML editor do not work after switching editor type more than once (#4789)\n- Fix bug where TinyMCE area height was too small on slow network connection (#4788)\n- Fix backtick character handling in sql queries (#4790)\n- Fix redirect URL for attachments loaded in an iframe when behind a proxy (#4724)\n- Fix menu container references to point to the actual <ul> element (#4791)\n- Fix javascripts errors in IE8 - lack of Event.which, focusing a hidden element (#4793)", "RELEASE 1.1.0\n-------------\n- Make SMTP error log more verbose - include server response and error code\n- Fix download options menu (added by zipdownload plugin) in classic skin (#4740)\n- Fix blocked.gif image usage with assets_dir set\n- Fix bug where max_group_members was ignored when adding a new contact (#4733)\n- Hide MDN and DSN options in compose if disabled by admin (#4735)\n- Fix checks based on window.ActiveXObject in IE > 10\n- Fix XSS issue in style attribute handling [CVE-2015-1433] (#4739)\n- Fix bug where Drafts list wasn't updated on draft-save action in new window (#4737)\n- Fix so \"set as default\" option is hidden if identities_level > 1 (#4738)\n- Fix bug where search was reset after returning from compose visited for reply\n- Fix javascript error in \"IE 8.0/Tablet PC\" browser (#4730)\n- Fix bug where Reply-To address was ignored on reply to messages sent by self (#4742)\n- Fix bug where empty fieldmap config entries caused empty results of ldap search (#4741)\n- Fix bug where drafts list wasn't refreshed after draft message was sent from another window (#4745)\n- Fix keyboard navigation and css in datepicker widget across many Firefox versions\n- Fix false warning when opening attached text/plain files (#4748)\n- Fix bug where signature could have been inserted twice after plain-to-html switch (#4746)\n- Fix security issue in DBMail driver of password plugin (#4757)\n- Enable FollowSymLinks option in .htaccess file which is required by rewrite rules (#4754)\n- Fix so JSON.parse() errors on localStorage items are ignored (#4752)", "RELEASE 1.1-rc\n--------------\n- Update jQuery to version 2.1.3\n- Allow to override any config option through env variables\n- Improve system security by using optional special URL with security token - use_secure_urls\n- Allow to define separate server/path for image/js/css files - assets_url/assets_dir\n- Sync vendor folder if exists in source package (#4700)\n- Avoid useless reloading list when resetting search with active filter (#4654)\n- Fix invalid folder selection if clicked while busy (#4709)\n- Fix import of multiple contact email addresses from Outlook-csv format (#4714)\n- Fix drag-n-drop to folders expanded while dragging (#4708)\n- Fix import of multiple contact groups from Google-csv format (#4710)\n- Fix import of contacts with multiple email addresses from Google-csv format (#4719)\n- Fix bugs where CSRF attacks were still possible on some requests [CVE-2014-9587]\n- Fix some rcube_utils::anytodatetime() corner cases with timezone mismatches (#4712)\n- Improve move-to and contact-export button in classic skin (#4713)\n- Fix wrong icon for download button in classic skin\n- Fix bug where sent message was saved in Sent folder even if disabled by user (#4729)", "RELEASE 1.1-beta\n----------------\n- Fix skin path handling in plugin context (#4111)\n- Prevent memory exhaustion on image resizing with GD on Windows (#4580)\n- Add plugin hook for database table name lookups as requested in #4538\n- Added Oracle database support\n- Support contacts import in GMail CSV format\n- Added namespace filter in Folder Manager\n- Added folder searching in Folder Manager\n- Fix restoring draft messages from localStorage if editor mode differs (#4631)\n- Added config option/user preference to disable saving messages in localStorage (#4606)\n- Added config option 'imap_log_session' to enable Roundcube <-> IMAP session ID logging\n- Added config option 'log_session_id' to control the length of the session identifier in logs\n- Implemented 'storage_connected' API hook after successful IMAP login (#4638)\n- Intergrate Net_LDAP3 and rcube_ldap_generic classes\n- Add option (disabled_actions) to disable UI elements/actions (#4478)\n- Support password encryption using openssl extension (#4614)\n- Create/rename groups in UI dialogs (#4592)\n- Added 'contact_search_name' option to define autocompletion entry format\n- Display quota information for current folder not INBOX only (#3442)\n- Support images in HTML signatures (#3917)\n- Display full quota information in popup (#2103, #2746)\n- Mail compose: Selecting contact inserts recipient to previously focused input - to/cc/bcc accordingly (#4487)\n- Close \"no subject\" prompt with Enter key (#4463)\n- Password: Add option to force new users to change their password (#2963)\n- Improve support for screen readers and assistive technology using WCAG 2.0 and WAI ARIA standards\n- Enable basic keyboard navigation throughout the UI (#3333)\n- Select/scroll to previously selected message when returning from message page (#4146)\n- Display a warning if popup window was blocked (#4472)\n- Remove (was: ...) from message subject on reply (#4359)\n- Update to TinyMCE 4.1 (#4168)\n- Enable autolink plugin in TinyMCE (#4029)\n- Support image operations with Imagick extension (#4498)\n- Support upload progress with session.upload_progress and PECL uploadprogress module (#3934)\n- Make identity name field optional (#4435)\n- Utility script to remove user records from the local database\n- Plugin API: Added message_saved hook (#4503)\n- Plugin API: Added imap_search_before hook\n- Support messages import from zip archives\n- Zipdownload: Added mbox format support (#2354)\n- Drop support for IE6, move IE7/IE8 support to legacy_browser plugin\n- Update to jQuery-2.1.1\n- Search across multiple folders (#1676)\n- Improve UI integration of ACL settings\n- Drop support for PHP < 5.3.7\n- Set In-Reply-To and References for forwarded messages (#4465)\n- Removed redundant default_folders config option (#4500)\n- Implemented IMAP SPECIAL-USE extension support [RFC6154] (#3326)\n- Optimize some framed pages content for better performance (#4517)\n- Improve text messages display and conversion to HTML (#4091)\n- Don't remove links when html signature is converted to text (#4473)\n- Fix page title when using search filter (#4636)\n- Fix mbox files import\n- Fix some character sets detection (#4694)\n- Fix so attachment charset is set in headers of forward/draft message (#4676)\n- Fix bug where wrong charset could be used for text attachment preview page (#4674)", "RELEASE 1.0.5\n-------------\n- Fix wrong icon for download button in classic skin\n- Fix checks based on window.ActiveXObject in IE > 10\n- Fix XSS issue in style attribute handling (#4739)\n- Fix bug where Drafts list wasn't updated on draft-save action in new window (#4737)\n- Fix so \"set as default\" option is hidden if identities_level > 1 (#4738)\n- Fix javascript error in \"IE 8.0/Tablet PC\" browser (#4730)\n- Fix bug where empty fieldmap config entries caused empty results of ldap search (#4741)\n- Fix bug where sent message was saved in Sent folder even if disabled by user (#4729)", "RELEASE 1.0.4\n-------------\n- Disable TinyMCE contextmenu plugin as there are more cons than pros in using it (#4684)\n- Fix bug where show_real_foldernames setting wasn't honored on compose page (#4705)\n- Fix issue where Archive folder wasn't protected in Folder Manager (#4706)\n- Fix compatibility with PHP 5.2. in rcube_imap_generic (#4682)\n- Fix setting flags on servers with no PERMANENTFLAGS response (#4667)\n- Fix regression in SHAA password generation in ldap driver of password plugin (#4670)\n- Fix displaying of HTML messages with absolutely positioned elements in Larry skin (#4672)\n- Fix font style display issue in HTML messages with styled <span> elements (#4671)\n- Fix download of attachments that are part of TNEF message (#4668)\n- Fix handling of uuencoded messages if messages_cache is enabled (#4675)\n- Fix handling of base64-encoded attachments with extra spaces (#4678)\n- Fix handling of UNKNOWN-CTE response, try do decode content client-side (#4650)\n- Fix bug where creating subfolders in shared folders wasn't possible without ACL extension (#4680)\n- Fix reply scrolling issue with text mode and start message below the quote (#4681)\n- Fix possible issues in skin/skin_path config handling (#4689)\n- Fix lack of delimiter for recipient addresses in smtp_log (#4703)\n- Fix generation of Blowfish-based password hashes (#4721)\n- Fix bugs where CSRF attacks were still possible on some requests [CVE-2014-9587]", "RELEASE 1.0.3\n-------------\n- Initialize HTML editor before restoring a message from localStorage (#4631)\n- Add 'sig_max_lines' config option to default config file (#5162)\n- Add config option to specify IMAP connection socket parameters - imap_conn_options (#4589)\n- Add option to set default message list mode - default_list_mode (#3157)\n- Enable contextmenu plugin for TinyMCE editor (#3062)\n- Fix insert-signature command in external compose window if opened from inline compose screen (#4663)\n- Fix some mime-type to extension mapping checks in Installer (#4610)\n- Fix errors when using localStorage in Safari's private browsing mode (#4619)\n- Fix bug where $Forwarded flag was being set even if server didn't support it (#4621)\n- Fix various iCloud vCard issues, added fallback for external photos (#4617)\n- Fix invalid Content-Type header when send_format_flowed=false (#4616)\n- Fix errors when adding/updating contacts in active search (#4630)\n- Fix incorrect thumbnail rotation with GD and exif orientation data (#4641)\n- Fix contacts list update after adding/deleting/moving a contact (#4640, #4644)\n- Fix handling of email addresses with quoted domain part (#4647)\n- Fix comm_path update on task switch (#4648)\n- Fix error in MSSQL update script 2013061000.sql (#4658)\n- Fix validation of email addresses with IDNA domains (#4661)", "RELEASE 1.0.2\n-------------\n- Fix storing unsaved drafts in localStorage (#4529)\n- Add configurable LDAP_OPT_DEREF option (#4546)\n- Fix so when switching editor mode original version of signature is used (#4032)\n- Fix unintentional draft autosave request if autosave is disabled (#4550)\n- Fix malformed References: header in send/saved mail (#4552)\n- Fix handling unicode characters in links (#4555)\n- Fix incorrect handling of HTML comments in messages sanitization code (#4558)\n- Fix so current page is reset on list-mode change (#4561)\n- Fix so responses menu hides on click in classic skin (#4566)\n- Fix unintentional line-height style modification in HTML messages (#4567)\n- Fix broken normalize_string(), add support for ISO-8859-2 (#4568)\n- Support csv contacts import in German localization (#4570)\n- Fix so message list and counters are updated when a message is opened in new window (#4569)\n- Fix malformed recipient name when composing a message by clicking on mailto link (#4583)\n- Fix list reload after sending message in another window (#4576)\n- Fix so address format errors are ignored when saving a draft (#4594)\n- Fix incorrect label translation in return receipt (#4598)\n- Fix security issue in delete-response action - allow only ajax request\n- Fix Delete button state after deleting identity/response (#4603)\n- Fix bug where contacts with no email address were listed on compose addressbook (#4602)\n- Fix images import from various vCard formats (#4604)\n- Fix sorting messages by size on servers without SORT capability (#4608)", "RELEASE 1.0.1\n-------------\n- Support 'error' and 'body_file' return attribs in 'message_before_send' hook (#4467)\n- Apply user-specific replacements to group's base_dn property (#4512)\n- Fix missing email address when importing contacts from outlook csv (#4535)\n- Fix bug where \"With attachment\" option in search filter wasn't selected after return from mail view (#4508)\n- Fix \"washing\" of unicoded style attributes (#4510)\n- Fix unintentional redirect from compose page in Webkit browsers (#4516)\n- Fix messages index cache update under some conditions (e.g. proxy) (#4505)\n- Fix lack of translation of special folders in some configurations (#4520)\n- Fix XSS issue in plain text spellchecker (#4524)\n- Fix invalid page title for some folders (1489804)\n- Fix redundant alert message on over-size uploads (#4528)\n- Fix next message display after removing a message (#4521)\n- Fix missing Mail-Followup-To header in sent mail (#4534)\n- Fix error when spell-checking an empty text (#4536)\n- Avoid popupmenus being closed when scrollbar is clicked (#4537)\n- Add proxy_whitelist configuration option (#4496)\n- Fix identities_level=4 handling in new_user_dialog plugin (#4540)\n- Fix various db_prefix issues (#4539)\n- Fix too small length of users.preferences column data type on MySQL\n- Fix redundant warning when switching from html to text in empty editor (#4530)\n- Fix invalid host validation on login (#4541)\n- Fix IMAP connection test in installer so it is aware of imap_auth_type (#4502)", "RELEASE 1.0.0\n-------------\n- Added toolbar button to move message in message view\n- Fix style of disabled protocol handler link on IE (#4460)\n- Fix message import dialog when no file is selected (#4488)\n- Fix opening compose screen in new window after saving as draft (#4479)\n- Fix directories check in Installer on Windows (#4462)\n- Fix issue when default_addressbook option is set to integer value (#4379)\n- Fix Opera > 15 detection (#4455)\n- Fix security issue in DomainFactory driver of Password plugin\n- Fix invalid X-Draft-Info on forwarded message draft (#4464)\n- Fix regression in handling of 'attachments' result in message_compose hook (#4474)\n- Fix issue where msgexport.sh printed the message to STDOUT instead of a file (#4476)\n- Fix fatal error in database_attachments plugin under some conditions (#4495)", "RELEASE 1.0-rc\n--------------\n- Small CSS fix with message notice boxes in Larry skin (#4429)\n- Include groups in contacts search on mail compose (#4186)\n- Add mime-type mapping for .7z files (#4436)\n- Invoke update scripts with php to circumvent execution restrictions (#4330)\n- Fix drag & drop message/contact moving on touch device (#4395)\n- Fix canned responses in HTML mode (#4446)\n- Check/create default folders on every login not only the first (#4391)\n- Update to jQuery-1.11.0 and jQuery-UI-1.9.2\n- Support SMTP socket context options via new config option 'smtp_conn_options'\n- Fix compatibility with PHP 5.2 in html.php file (#4438)\n- Remove expand/collapse with plus/minus keys (on numeric keypad) (#4437)\n- Fix issue where filesystem path was added to all-attachments (zip) file (#4433)\n- Fix case-sensitivity of email addresses handling on compose (#1899)\n- Don't alter Message-ID of a draft when sending (#4381)\n- Fix issue where deprecated syntax for HTML lists was not handled properly (#3975)\n- Display different icons when Trash folder is empty or full (#2108)\n- Remember last position of more headers switch (#3660)\n- Fix so message flags modified by another client are applied on the list on refresh (#1639)\n- Fix broken text/* attachments when forwarding/editing a message (#4393)\n- Improved minified files handling, added css minification (#3041)\n- Fix handling of X-Forwarded-For header with multiple addresses (#4424)\n- Fix border issue on folders list in classic skin (#4419)\n- Implemented menu actions to copy/move messages, added folder-selector widget (#863)\n- Fix security rules in .htaccess preventing access to base URL without the ending slash (#4422)\n- Fix regression where only first new folder was placed in correct place on the list (#4418)\n- Fix issue where children of selected and collapsed thread were skipped on various actions (#4410)\n- Fix issue where groups were not deleted when \"Replace entire addressbook\" option on contacts import was used (#4388)\n- Fix unreliable mimetype tests in Installer (#4408)\n- Fix performance of listing writeable folders (#4406)", "RELEASE 1.0-beta\n----------------\n- Fix handling of invalid closing tags in HTML messages (#4403)\n- Set real content-type for file downloads (#4400)\n- Update TinyMCE to version 3.5.10 (#4401)\n- Fix keyboard navigation in list widgets (#4367)\n- Allow plugins to grab the reference of opened windows (#4383)\n- Larry skin: Improved status message display for better visibility (#4115)\n- Fix Internet Explorer 11 detection (#4397)\n- Fix date column width to fit the widest possible date format (#4354)\n- Move certain user preference options to a collapsed \"advanced\" block (#4015)\n- Add file type icons for Powerpoint and Open Office presentations (#4269)\n- Fix operations on folders with trailing spaces in name (#4387)\n- Improve identity selection based on From: header (#4360)\n- Fix issue where mails with inline images of the same name contained only the first image multiple times (#4378)\n- Use left/right arrow keys to collapse/expand thread and spacebar to select a row, change Ctrl key behavior (#4367)\n- Fix an issue where using arrow keys to go up a list can result in selected message being under headers (#4375)\n- Fix an issue where Home/End keys don't focus list row properly, don't scrollTo properly (#4370)\n- Add an option to disable smart Reply-List behaviour - reply_all_mode (#3953)\n- Fix an issue where pressing minus key on contacts list was hiding list records (#4368)\n- Fix an issue where shift + arrow-up key wasn't selecting all messages in collapsed thread (#4371)\n- Added icon for priority column in messages list header (#4275)\n- New feature \"Canned Responses\" to save and recall boilerplate text snippets\n- Fix HTML part detection when encapsulated inside multipart/signed (#4357)\n- Add spellchecker backend for the After the Deadline service\n- Replace markdown-style [1] link indexes in plain text email bodies\n- Improved mailto: link arguments handling (#4351)\n- Use DOMDocument LIBXML_PARSEHUGE and LIBXML_COMPACT options if possible (#4316)\n- Support HTTP_HOST, SERVER_NAME and SERVER_ADDR values in include_host_config feature\n- Make default font size for HTML messages configurable (request #118)\n- Fix XSS issue in addressbook group name field [CVE-2013-5646] (#4337)\n- After message is sent refresh messages list of replied message folder (#4282)\n- Add option force specified domain in user login - username_domain_forced (#4290)\n- Add option to import Vcards with group assignments\n- Save groups membership in Vcard export (#3801)\n- Workaround broken PHP function timezone_name_from_abbr (#4289)\n- Make cached message size limit configurable - messages_cache_threshold (#4326)\n- Log also failed logins to userlogins log\n- Add temp_dir_ttl configuration option (#4318)\n- Allow setting INBOX as Sent folder (#4264)\n- Fix replacement variables in user-specific base_dn in some LDAP requests (#4299)\n- Fix image scaling issues when image has only one dimension smaller than the limit (#4296)\n- Fix issue where uploaded photo was lost when contact form did not validate (#4296)\n- Move identity selection based on non-standard headers into (new) identity_select plugin (#3835)\n- Fix downloading binary files with (wrong) text/* content-type (#4292)\n- Respect HTTP_X_FORWARDED_FOR and HTTP_X_REAL_IP variables for session IP check\n- Simplified configuration by merging it into one file + defaults (#3156)\n- Make message list header stay on top when scrolling (#353)\n- Add support for 'enchant' spellcheck engine\n- Check filetype detection in installer and update script (#4252)\n- Fix folder names truncation in Classic skin (#4265)\n- Make possible to disable some (broken) IMAP extensions with imap_disable_caps option (#4245)\n- Contacts drag-n-drop default action is to move contacts (#3962)\n- Added possibility to choose to move or copy contacts from drag-n-drop menu (#3962)\n- Fix Close link and remove About link on error pages (#4201)\n- Improved/unified attachment preview screen, added print button\n- Fix lack of space between searchfiler and quicksearchbar in Larry skin (#4233)\n- Cache LDAP's user_specific search and use vlv for better performance (#4247)\n- LDAP: auto-detect and use VLV indices for all search operations\n- LDAP: additional group configuration options for address books\n- LDAP: separated address book implementation from a generic LDAP wrapper class\n- Allow address books to browse a multi-level group hierarchy in the contacts list\n- Fix session issues when local and database time differs (#2401)\n- Fix thread cache syncronization/validation (#4150)\n- Added feature to import messages to the currently selected folder\n- Add option show_real_foldernames to disable localization of special folders\n- Fix database cache expunge issues (#4229)\n- Fix date format issues on MS SQL Server (#4078)\n- Add imap_cache_ttl option to configure TTL of imap_cache\n- Make LDAP cache engine configurable via ldap_cache and ldap_cache_ttl options\n- Fix \"duplicate entry\" errors on inserts to imap cache tables (#4228)\n- Improved handling of Reply-To/Bcc addresses of identity in compose form (#4142)\n- Added user preference to open all popups as standard windows\n- Implemented shared cache (rcube_cache_shared)\n- Change Reply-All button label/title when mailing list is detected (#4092)\n- Fix SMTP connection using IPv6 address in smtp_server option (#4147)\n- Added attachment_reminder plugin\n- Make PHP code eval() free, use create_function()\n- Add option to display email address together with a name in mail preview (#3952)\n- Support CSV import from Atmail (#4161)\n- Add db_prefix configuration option in place of db_table_*/db_sequence_* options\n- Make possible to use db_prefix for schema initialization in Installer (#4175)\n- Fix updatedb.sh script so it recognizes also table prefix for external DDL files\n- Fix parsing invalid date string (#4155)\n- Add \"with attachment\" option to messages list filter (#1795)\n- Call resize handler in intervals to prevent lags and double onresize calls in Chrome (#4137)\n- Add rel=\"noreferrer\" for links in displayed messages (#4976)\n- Add ability to toggle between HTML and text while viewing a message (#3005)\n- Remove \"HTML message\" from attachments list while viewing a message in text mode (#3005)\n- Support IMAP MOVE extension [RFC 6851]\n- Add attachment menu with Open and Download options (#4116)\n- Display user-friendly message on IMAP \"over quota\" errors (#914)\n- Extended archive plugin with user-configurable options to store messages into subfolders\n- Fix export of selected contacts from search result (#4070)\n- Feature to export only selected contacts from addressbook (by Phil Weir)", "RELEASE 0.9.5\n-------------\n- Fix failing vCard import when email address field contains spaces (#4363)\n- Fix default spell-check configuration after Google suspended their spell service\n- Fix vulnerability in handling _session argument of utils/save-prefs [CVE-2013-6172] (#4362)\n- Fix iframe onload for upload errors handling (#4361)\n- Fix address matching in Return-Path header on identity selection (#4358)\n- Fix text wrapping issue with long unwrappable lines (#4356)\n- Fixed issues where HTML comments inside style tag would hang Internet Explorer\n- Hide Delivery Status Notification option when smtp_server is unset (#4339)\n- Display full attachment name using title attribute when name is too long to display (#4328)\n- Fix attachment icon issue when rare font/language is used (#4334)\n- Fix expanded thread root message styling after refreshing messages list (#4335)\n- Fix issue where From address was removed from Cc and Bcc fields when editing a draft (#4327)\n- Fix error_reporting directive check (#4331)\n- Fix de_DE localization of \"About\" label in Help plugin (#4333)", "RELEASE 0.9.4\n-------------\n- Make identities matching case insensitive (#1881)\n- Fix issue where too big message data was stored in cache causing sql errors (#4325)\n- Fix iframe scrollbars on webkit desktop browsers (#4319)\n- Fix issue where legacy config was overridden by default config (#4305)\n- Fix newmail_notifier issue where favicon wasn't changed back to default (#4324)\n- Fix setting of Junk and NonJunk flags by markasjunk plugin (#4303)\n- Fix lack of Reply-To address in header of forwarded message body (#4314)\n- Fix bugs when invoking contact creation form when read-only addressbook is selected (#4313)\n- Fix identity selection on reply (#4308)\n- Fix so additional headers are added to all messages sent (#4302)\n- Fix display issue after moving folder in Folder Manager (#4310)\n- Fix handling of non-default date formats (#4311)\n- Fix unquoted path in PREG expression on Windows (#4307)\n- Fix wrong close tag in /template/mail.html (#4312)", "RELEASE 0.9.3\n-------------\n- Fix setting refresh_interval to \"Never\" in Preferences (#4304)\n- Fixed iframe scrolling on touch devices\n- Optimized message list for touch devices\n- Fix purge action in folder manager (#4300)\n- Fix base URL resolving on attribute values with no quotes (#4297)\n- Fix wrong handling of links with '|' character (#4298)\n- Fix colorspace issue on image conversion using ImageMagick (#4294)\n- Fix XSS vulnerability when editing a message \"as new\" or draft [CVE-2013-5645] (#4283)\n- Fix XSS vulnerability when saving HTML signatures [CVE-2013-5645] (#4283)\n- Fix rewrite rule in .htaccess (#4278)\n- Fix detecting Turkish language in ISO-8859-9 encoding (#4284)\n- Fix identity-selection using Return-Path headers (#4279)\n- Fix parsing of links with ... in URL (#4251)\n- Fix compose priority selector when opening in new window (#4286)\n- Fix bug where signature wasn't changed on identity selection when editing a draft (#4272)\n- Fix IMAP SETMETADATA parameters quoting (#4274)\n- Fix \"could not load message\" error on valid empty message body (#4271)\n- Fix handling of message/rfc822 attachments on message forward and edit (#4262)\n- Fix parsing of square bracket characters in IMAP response strings (#4267)\n- Don't clear References and in-Reply-To when a message is \"edited as new\" (#4263)\n- Fix messages list sorting with THREAD=REFS\n- Remove deprecated (in PHP 5.5) PREG /e modifier usage (#4239)\n- Fix empty messages list when register_globals is enabled (#4232)\n- Fix so valid and set date.timezone is not required by installer checks (#4242)\n- Canonize boolean ini_get() results (#4249)\n- Fix so install do not fail when one of DB driver checks fails but other drivers exist (#4240)\n- Fix so exported vCard specifies encoding in v3-compatible format (#4244)", "RELEASE 0.9.2\n-------------\n- Fix image thumbnails display in print mode (#4220)\n- Fix height of message headers block (#4200)\n- Fix timeout issue on drag&drop uploads (#4238)\n- Fix default sorting of threaded list when THREAD=REFS isn't supported\n- Fix list mode switch to 'List' after saving list settings in Larry skin (#4236)\n- Fix error when there's no writeable addressbook source (#4235)\n- Fix zipdownload plugin issue with filenames charset (#4231)\n- Fix so non-inline images aren't skipped on forward (#4230)\n- Fix \"null\" instead of empty string on messages list in IE10 (#4227)\n- Fix legacy options handling\n- Fix so bounces addresses in Sender headers are skipped on Reply-All (#4140)\n- Fix bug where serialized strings were truncated in PDO::quote() (#4226)\n- Fix displaying messages with invalid self-closing HTML tags (#4223)\n- Fix PHP warning when responding to a message with many Return-Path headers (#4222)\n- Fix unintentional compose window resize (#4206)\n- Fix performance regression in text wrapping function (#4219)\n- Fix connection to posgtres db using unix socket (#4218)\n- Fix handling of comma when adding contact from contacts widget (#4199)\n- Fix bug where a message was opened in both preview pane and new window on double-click (#4212)\n- Fix fatal error when xdebug.max_nesting_level was exceeded in rcube_washtml (#4202)\n- Fix PHP warning in html_table::set_row_attribs() in PHP 5.4 (#4194)\n- Fix invalid option selected in default_font selector when font is unset (#4204)\n- Fix displaying contact with ID divisible by 100 in sql addressbook (#4211)\n- Fix browser warnings on PDF plugin detection (#4209)\n- Fix fatal error when parsing UUencoded messages (#4210)", "RELEASE 0.9.1\n-------------\n- Better German labels for from/to to avoid conflicts with 'sender' (#4188)\n- Fix problem where security warning was displayed for valid images with image/jpg type (#4196)\n- Fix handling of invalid email addresses in headers (#4193)\n- Fix IMAP connection issue with default_socket_timeout < 0 and imap_timeout < 0 (#4191)\n- Fix various PHP code bugs found using static analysis (#4190)\n- Fix backslash character handling on vCard import (#4189)\n- Fix csv import from Thunderbird with French localization (#4170)\n- Fix messages list focus issue in Opera and Webkit (#4169)\n- Fix Reply-To header handling in Reply-All action (#4157)\n- Fix so Sender: address is added to Cc: field on reply to all (#4140)\n- Fix so addressbook_search_mode works also for group search (#4183)\n- Fix removal of a contact from a group in LDAP addressbook (#4185)\n- Include SQL query in the log on SQL error (#4172)\n- Fix handling untagged responses in IMAP FETCH - \"could not load message\" error (#4180)\n- Fix very small window size in Chrome (#4087)\n- Fix list page reset when viewing a message in Larry skin (#4182)\n- Fix min_refresh_interval handling on preferences save (#4179)\n- Fix PDF support detection for Firefox PDF.js (#4113)\n- Fix possible collision in generated thumbnail cache key (#4177)\n- Fix exit code on bootsrap errors in CLI mode (#4160)\n- Fix error handling in CLI mode, use STDERR and non-empty exit code (#5161)\n- Fix error when using check_referer=true\n- Fix incorrect handling of some specific links (#4171)\n- Fix incorrect handling of leading spaces in text wrapping\n- Fix unintentional messages list jumps on click in Internet Explorer (#4167)\n- Fix list of required configuration options (#4166)\n- Fix DB error when creating a new contact and a group is selected (#4164)\n- Fix handling of deprecated boolean value of reply_mode option (#4165)", "RELEASE 0.9.0\n-------------\n- Fix display of HTML entities in protected folder name (#4159)\n- Set minimal permissions to temp files (#4131)\n- Improve content check for embedded images without filename (#4151)\n- Fix handling of invalid characters in message headers and output (#4153)\n- Fix selecting collapsed rows on select-all (#4156)\n- Avoid race-conditions with concurrent attachment uploads (#3739)\n- Fix possible header duplicates when using additional headers (#4154)\n- Fix session issues with use_https=true (#4125)\n- Fix blockquote width in sent mail (#4152)\n- Fix keyboard events on list widgets in Internet Explorer (#4148)", "RELEASE 0.9-rc2\n---------------\n- Fix security issue in save-pref command\n- Remove sig_above configuration option, use reply_mode only (#4135)\n- Refresh current folder in opener window after draft save or message sent (#4132)\n- Fix saving draft just after entering compose window (#4141)\n- Fix javascript error in IE9 when loading form with placeholders into an iframe (#4138)\n- Fix handling of some conditional comment tags in HTML message (#4136)\n- Fix so forward as attachment works if additional attachment is added by message_compose hook (#4134)\n- Better handling of session errors in ajax requests (#4105)\n- Fix HTML part detection for some specific message structures (#4130)\n- Don't show fake address - phishing prevention (#4120)\n- Fix forward as attachment bug with editormode != 1 (#4129)\n- Fix LIMIT/OFFSET queries handling on MS SQL Server (#4123)\n- Fix so task name can really contain all from a-z0-9_- characters (#4095)\n- Fix javascript errors when working in a page opened with taget=\"_blank\"\n- Mention SQLite database format change in UPGRADING file (#4122)\n- Increase maxlength to 254 chars for email input fields in addressbook (#4126)\n- Fix thumbnail size when GD extension is used for image resize (#4124)\n- Display notice that message is encrypted also for application/pkcs7-mime messages (#3815)", "RELEASE 0.9-rc\n--------------\n- Fix plain text spellchecker incorrect highlighting in non-ASCII text (#4114)\n- Add workaround for invalid message charset detection by IMAP servers (#4112)\n- Fix NUL characters in content-type of ms-tnef attachment (#4108)\n- Fix regression in handling LDAP contact identifiers (#4104)\n- Updated translations from Transifex\n- Fix buggy error template in a frame (#4092)\n- Add addressbook widget on compose page in classic skin\n- Add search box to compose address book widget (#3710)\n- Fix login in case when default_host is an array with one element (#4085)\n- Use LDAP fallback hosts on connect + bind instead of ldap_connect() only.\n- Add config option for LDAP bind timeout (sets LDAP_OPT_NETWORK_TIMEOUT option)\n- Submit Addressbook advanced search form with Enter key (#3843)\n- Also block remote images in HTML part view (#4013)\n- Improved database schema upgrade procedure, added updatedb.sh script\n- Force autocommit mode in mysql database driver (#4068)", "RELEASE 0.9-beta\n----------------\n- Fix searching by date in address book (#4058)\n- Improve charset detection by prioritizing charset according to user language (#2032)\n- Fix handling of escaped separator in vCard file (#4064)\n- Add option to use envelope From address for MDN responses (#4052)\n- Add possibility to search in message body only (#3977)\n- Support \"multipart/relative\" as an alias for \"multipart/related\" type (#4057)\n- Display PGP/MIME signature attachments as \"Digital Signature\" (#3845)\n- Workaround UW-IMAP bug where hierarchy separator is added to the shared folder name (#4051)\n- Fix version comparisons with -stable suffix (#4050)\n- Add unsupported alternative parts to attachments list (#4046)\n- Add Compose button on message view page (#3959)\n- Display 'Sender' header in message preview\n- Plugin API: Added message_before_send hook\n- Fix contact copy/add-to-group operations on search result (#4042)\n- Use matching identity in MDN response (#4043)\n- Fix handling of signatures on draft edit (#3996)\n- Fix so compacting of non-empty folder is possible also when messages list is empty (#4039)\n- Allow forwarding of multiple emails (#2941)\n- Fix big memory consumption of DB layer (#4037)\n- Fix broken message/part bodies when FETCH response contains more untagged lines (#4020)\n- Fix empty email on identities list after identity update (#4018)\n- Add new identities_level: (4) one identity with possibility to edit only signature\n- Use Delivered-To and Envelope-To headers for identity selection (#4024, #3835)\n- Fix XSS vulnerability using Flash files (#4014)\n- Always save drafts with format=flowed in order to keep original line wraps (#3997)\n- Select default_addressbook on the list in Address Book (#3624)\n- Fix so mobile phone has TYPE=CELL in exported vCard (#4004)\n- Support contacts import from CSV file (#2605)\n- Improved keep-alive action. Now the interval is based on session_lifetime (#3799)\n- Added cross-task 'refresh' request for system state updates (#3799)\n- Renamed config options: keep_alive to refresh_interval, min_keep_alive to min_refresh_interval\n- Fix handling of text/enriched content on message reply/forward/edit\n- Option to display attached images as thumbnails below message body\n- Upgraded to jQuery 1.8.3 and jQuery UI 1.9.1\n- Add config option to automatically generate LDAP attributes for new entries\n- Add user settings to open message view and compose form in new windows (#1886)\n- Better client-side timezone detection using the jsTimezoneDetect library (#3947)\n- Add option to disable saving sent mail in Sent folder - no_save_sent_messages (#3923)\n- Fix handling dont_override with message_sort_col and message_sort_order settings (#3970)\n- Fix handling of URLs with asterisk characters (#3969)\n- Remove automatic to-lowercase conversion of usernames (#3941)\n- Plugin API: Add 'email_list' argument for identities data in user_create hook\n- Integrated zipdownload plugin to download all attachments (#617)\n- Fix HTML special characters handling in message list/header display (#3812)\n- List related text/html part as attachment in plain text mode (#3918)\n- Use IMAP BINARY (RFC3516) extension to fetch message/part bodies\n- Fix folder creation under public namespace root (#3910)\n- Fix so \"Edit as new\" on draft creates a new message (#3924)\n- Fix invalid error message on deleting mail from read only folder (#3929)\n- Replace data URIs of images (pasted in HTML editor) with inline attachments (#3795)\n- Remove (too big) min-width on mail screen\n- Added template object 'frame'\n- Add option to enable HTML editor on forwarding (#3807)\n- Add option to not include original message on reply, rename option top_posting to reply_mode (#1615)\n- Added session_path config option and unified cookies settings in javascript\n- Added \"Undeleted\" option to messages list filter\n- Rewritten test scripts for PHPUnit\n- Add new DB abstraction layer based on PHP PDO, supporting SQLite3 (#3668)\n- Removed PEAR::MDB2 package\n- Removed users.alias column, added option ('user_aliases')\n to use email address from identities as username (#3851)\n- Removed redundant cache.cache_id column (#3817)\n- Fix order of attachments in sent mail (#3740)\n- Fix Shift + delete button does not permanently delete messages (#3598)\n- Add Content-Length for attachments where possible (#1880)\n- Fix attachment sizes in message print page and attachment preview page (#3805)\n- Add mail attachments using drag & drop on HTML5 enabled browsers\n- Add workaround for invalid BODYSTRUCTURE response - parse message with Mail_mimeDecode package (#1966)\n- Display Tiff as Jpeg in browsers without Tiff support (#3757)\n- Don't display Pdf/Tiff/Flash attachments inline without browser support (#3757, #3394)\n- Add is_escaped attribute for html_select and html_textarea (#3782)\n- Fix issue where draft auto-save wasn't executed after some inactivity time\n- Add vCard import from multiple files at once (#3458)\n- Roundcube Framework:\n Add possibility to replace IMAP driver with custom class\n Add IMAP auto-connection feature, improving performance with caching enabled\n Replace imap_init hook with storage_init (with additional 'driver' argument)\n Improved performance by caching IMAP server's capabilities in session\n Unified global functions naming (rcube_ prefix)\n Better classes separation\n Framework files moved to lib/Roundcube", "RELEASE 0.8.5\n-------------\n- Fix #countcontrols issue in IE<=8 when text is very long (#4060)\n- Fix unwanted horizontal scrollbar in message preview header (#4044)\n- Add workaround for IE<=8 bug where Content-Disposition:inline was ignored (#4028)\n- Fix XSS vulnerability in vbscript: and data:text links handling [CVE-2012-6121] (#4033)\n- Fix absolute positioning in HTML messages (#4007)\n- Fix cache (in)validation after setting \\Deleted flag\n- Fix keybord events on messages list in opera browser (#4011)\n- Fix selection of collapsed thread rows (#3978)\n- Fix wrapping of quoted text with format=flowed (#3561)", "RELEASE 0.8.4\n-------------\n- Fix regression where unintentional page reload was done after request abort (#3999)\n- Fix XSS vulnerability in handling of text/enriched messages (#4000)\n- Fix handling of 'media' attribute on linked css (#3989)\n- Fix excessive LFs at the end of composed message with top_posting=true (#3995)\n- Fix bug where leading blanks were stripped from quoted lines (#3994)", "RELEASE 0.8.3\n-------------\n- Fix AREA links handling (#3992)\n- Fix possible HTTP DoS on error in keep-alive requests (#3983)\n- Fix compatybility with MDB2 2.5.0b4 (#3982)\n- Fix a bug where saving a message in INBOX wasn't possible\n- Fix HTML part detection in messages with attachments (#3976)\n- Fix bug where wrong words were highlighted on spell-before-send check\n- Fix scrolling quirk in email preview frame using Opera 12 (#3973)\n- Fix displaying of multipart/alternative messages with empty parts (#3961)\n- Fix threaded list sorting on PHP < 5.2.9 (#3960)\n- Fix Warning: htmlspecialchars(): charset `RCMAIL_CHARSET' not supported warning in Installer (#3958)", "RELEASE 0.8.2\n-------------\n- Fix XSS vulnerability from HTTP User-Agent header (#3954)\n- Force fonts in compose fields to be all the same (#3926)\n- Fix handling vCard entries with TEL;TYPE=CELL (#3949)\n- Fix error where session wasn't updated after folder rename/delete (#3928)\n- Fix PLAIN authentication for some IMAP servers (#3916)\n- Fix encoding vCard file when contains PHOTO;ENCODING=b (#3922)\n- Fix focus issue in IE when selecting message row (#3881)\n- Add full headers view in message preview window (#3823)\n- Fix message display page issues - unified with message preview (#3856, #3895)\n- Fix displaying all headers when they contain malformed characters (#3911)\n- Fix decoding of HTML messages with UTF-16 charset specified (#3902)\n- Fix quota capability detection so it can be overwritten by a plugin (#3903)\n- Fix identity selection on reply (#3516)\n- Fix Larry's messages list filter in IE (#3890)\n- Fix more IE issues by disabling Compat. mode with X-UA-Compatible meta tag (#3886)\n- Fix setting locales under Solaris - use additional .UTF-8 suffix (#3887)\n- Fix email address validation for addresses with IP address in domain part\n- Fix Larry skin issues in IE7 compat. mode (#3879)\n- Fix so subscribed non-existing/non-accessible shared folder can be unsubscribed", "RELEASE 0.8.1\n-------------\n- Fix bug where domain name was converted to lower-case even with login_lc=false (#3859)\n- Fix lower-casing email address on replies (#3863)\n- Fix line separator in exported messages (#3866)\n- Fix XSS issue where plain signatures wasn't secured in HTML mode [CVE-2012-4668] (#3875)\n- Fix XSS issue where href=\"javascript:\" wasn't secured [CVE-2012-3508] (#3875)\n- Fix impossible to create message with empty plain text part (#3873)\n- Fix stripped apostrophes when replying in plain text to HTML message (#3869)\n- Fix inactive Save search option after advanced search (#3870)\n- Fix Remove from group option is active for contact search result (#3871)\n- Disable autocapitalization in login form on iPad/iPhone (#3872)\n- Fix focus on the list when list row is clicked (#3865)\n- Added separate From and To columns apart from smart From/To column (#2970)\n- Fix fallback to Larry skin when configured skin isn't available (#3857)\n- Fix (workaround) delete operations with some versions of memcache (#3858)\n- Fix (disable) request validation for spell and spell_html actions", "RELEASE 0.8.0\n-------------\n- Don't show product version on login screen (can be enabled by config)\n- Renamed old default skin to 'classic'. Larry is the new default skin.\n- Support connections to memcached socket file (#3848)\n- Enable TinyMCE inlinepopups plugin\n- Update to TinyMCE 3.5.6\n- Correctly escape localized labels in javascript variable (#3842)\n- Update Net_SMTP/Auth_SASL packages to fix Digest-MD5/Cram-MD5 authentication (#3846)\n- Don't add attachments content into reply/forward/draft message body (#3837)\n- Fix 'no connection' errors on page unloads (#3832)\n- Plugin API: Add 'unauthenticated' hook (#3545)\n- Show explicit error message when provided hostname is invalid (#3834)\n- Fix wrong compose screen elements focus in IE9 (#3826)\n- Fix fatal error when date.timezone isn't set (#3831)\n- Update to TinyMCE 3.5.4.1\n- Better icons with distinct shapes for priority columns (#3706)\n- Show dedicated icon for multipart/report messages (#3813)\n- Properly hide text of icon links/buttons (#3820)\n- Fix handling of unitless CSS size values in HTML message (#3821)\n- Fix removing contact photo using LDAP addressbook (#3737)\n- Fix storing X-ANNIVERSARY date in vCard format (#3816)\n- Update to Mail_Mime-1.8.5 (#3810)\n- Fix XSS vulnerability in message subject handling using Larry skin [CVE-2012-3507] (#3809)\n- Fix handling of links with various URI schemes e.g. \"skype:\" (#3521)\n- Fix handling of links inside PRE elements on html to text conversion\n- Fix indexing of links on html to text conversion\n- Decode header value in rcube_mime::get() by default (#3803)\n- Fix errors with enabled PHP magic_quotes_sybase option (#3798)\n- Fix SQL query for contacts listing on MS SQL Server (#3797)\n- Fix window.resize handler on IE8 and Opera (#3758)\n- Don't let error message popups cover the login form (#3794)\n- Update to TinyMCE 3.5.2\n- Don't show errors when moving contacts into groups they are already in (#3788)\n- Make folders with unread messages in subfolders bold again (#2892)\n- Abbreviate long attachment file names with ellipsis (#3793)\n- Fix html2text conversion of strong|b|a|th|h tags when used in upper case\n- Add listcontrols template container in Larry skin (#3792)\n- Fix host autoselection when default_host is an array (#3790)\n- Move messages forwarding mode setting into Preferences\n- Fix HTML entities handling in HTML editor (#3780)\n- Fix listing shared folders on Courier IMAP (#3767)", "RELEASE 0.8-rc\n--------------\n- Added new translations in Belarusian, Interlingua and Malayalam\n- Flipped compose options arrow (#3772)\n- Fix handling of large uuencode attachments (#3771)\n- Fix handling of \"usemap\" attribute (#3770)\n- Fix handling of some HTML tags e.g. IMG (#3769)\n- Use similar language as a fallback for plugin localization (#3726)\n- Fix issue where signature wasn't re-added on draft compose (#3659)\n- Update to TinyMCE 3.5 (#3762)\n- Fixed multi-threaded autocompletion when number of threads > number of sources\n- Allow to configure the number of values allowed for each LDAP attribute\n- Support for serialized LDAP address values (usually delimited with a $)\n- Less restrictive session auth checks, repeat keep-alive requests on failure (#3755)\n- Fix redirect to mail/compose on re-login (#3585)\n- Add IE8 hack for messages list issue (#3317)\n- Fix handling errors on draft auto-save\n- Fix importing vCard photo with ENCODING param specified (#3746)\n- Support multiple name/email pairs for Bcc and Reply-To identity settings (#3752)\n- Set flexible width to login form fields (#3735)\n- Fix re-draw bug on list columns change in IE8 (#3318)\n- Allow mass-removal of addresses from a group (#3259)\n- Fix removing all contacts on import to LDAP addressbook\n- Fix so \"Back\" from compose/show doesn't reset search request (#3594)\n- Add option to delete messages instead of moving to Trash when in Junk folder (#2805)\n- Fix invisible cursor when replying to a html message (#3100)\n- Reset IP stored in session when destroying session data (#3485)\n- Fix bug where memory_limit = -1 wasn't handled properly\n- Support LDAP RFC2256's country object class read/write (#3535)\n- Upgraded to jQuery 1.7.2\n- Image resize with GD extension (#3712)\n- Fix lack of warning when switching task in compose window (#3725)\n- Fix bug where it wasn't possible to enter ( or & characters in autocomplete fields\n- Request all needed fields from address book backends (#3721)\n- Unified (single) spellchecker button\n- Scroll long lists on drag&drop (#2249)\n- Copy all skins in installto script (#3705)", "RELEASE 0.8-beta\n----------------\n- Upgraded to jQuery 1.7.1 (#3673) and jQuery UI 1.8.18\n- Add Russian to the spellchecker languages list (#3542)\n- Remember custom skin selection after logout (#3688)\n- Make sure About tab is always the last tab (#3609)\n- Fix issue with folder creation under INBOX. namespace (#3683)\n- Added mailto: protocol handler registration link in User Preferences (#2729)\n- Handle identity details box with an iframe (#3066)\n- Fix issue where some text from original message was missing on reply (#3675)\n- Fix autoselect_host() for login (#3639)\n- Changed license to GNU GPLv3+ with exceptions for skins & plugins\n- Added address book widget on compose screen\n- Use proper timezones from PHP's internal timezonedb (#1973)\n- Add separate pagesize setting for mail messages and contacts (#3617)\n- Deprecate $DB, $USER, $IMAP global variables, Use $RCMAIL instead\n- Add option to set default font for HTML message (#894)\n- Fix issues with big memory allocation of IMAP results\n- Prevent from memory_limit exceeding when trying to parse big messages bodies (#3164)\n- Add possibility to add SASL mechanisms for SMTP in smtp_connect hook (#3399)\n- Mark (with different color) folders with recent messages (#2479)\n- Added About tab in Settings\n- TinyMCE updated to 3.4.6", "RELEASE 0.7.2\n-------------\n- Fix encoding of attachment with comma in name (#3717)\n- Fix handling of % character in IMAP protocol (#3711)\n- Fix duplicate names handling in addressbook searches (#3704)\n- Fix displaying of HTML messages from Disqus (#3702)\n- Disable E_STRICT warnings on PHP 5.4\n- Prevent from folder selection on virtual folder collapsing (#3681)\n- Fix automatic unsubscribe of non-existent folders\n- Fix double-quotes handling in recipient names\n- User configurable setting how to display contact names in list\n- Make contacts list sorting configurable for the admin/user\n- Fix parse errors in DDL files for MS SQL Server\n- Revert SORT=DISPLAY support, removed by mistake (#3664)\n- Add lost translation label in de_DE (#3654)\n- Fix drafts update issues when edited from preview pane (#3653)\n- Fix wrong variable name in rcube_ldap.php (#3643)\n- Make mime type detection based on filename extension to be case-insensitive\n- Fix failure on MySQL database upgrade from 0.7 - text column can't have default value (#3642)", "\nRELEASE 0.7.1\n-------------\n- Fix bug in handling of base href and inline content (#3634)\n- Fix SQL Error when saving a contact with many email addresses (#3630)\n- Fix strict email address searching if contact has more than one address\n- Remove duplicated 'organization' label (#3631)\n- Fix so editor selector is hidden when 'htmleditor' is listed in 'dont_override'\n- Fix wrong (long) label usage (#3627)\n- Fix handling of INBOX's subfolders in special folders config (#3623)\n- Add ifModule statement for setting Options -Indexes in .htaccess file (#3620)\n- Fix crashes with eAccelerator (#3608)\n- Fix searching on IMAP servers without CHARSET specifier support (#3619)\n- Fix expanding folders during drag&drop (#3611)\n- Fix wrong postgres sequence name in upgrade from 0.6\n- Fix broken CREATE INDEX queries in SQLite DDL files (#3607)", "RELEASE 0.7\n-----------\n- Make Roundcube render the Email Standards Project Acid Test correctly\n- Replace prompt() with jQuery UI dialog (#1603)\n- Fix navigation in messages search results\n- Improved handling of some malformed values encoded with quoted-printable (#3590)\n- Add possibility to do LDAP bind before searching for bind DN\n- Fix handling of empty <U> tags in HTML messages (#3584)\n- Add content filter for embedded attachments to protect from XSS on IE [CVE-2012-1253] (#3372)\n- Use strpos() instead of strstr() when possible (#3581)\n- Fix handling HTML entities when converting HTML to text (#3582)\n- Fix fit_string_to_size() renders browser and ui unresponsive (#3577)\n- Fix handling of invalid characters in request (#3536)\n- Fix merging some configuration options in update.sh script (#2181)\n- Fix so TEXT key will remove all HEADER keys in IMAP SEARCH (#3578)\n- Fix handling contact photo url with https:// prefix (#3575)\n- Fix possible infinite redirect on attachment preview (#3572)\n- Improved clickjacking protection for browsers which don't support X-Frame-Options headers\n- Fixed bug where similar folder names were highlighted wrong (#3345)\n- Fixed bug in handling link with '!' character in it (#3569)\n- Fixed bug where session ID's length was limited to 40 characters (#3570)\n- TinyMCE security issue: removed moxieplayer (embedding flv and mp4 is not supported anymore)", "RELEASE 0.7-beta\n----------------\n- Fix handling of HTML form elements in messages (#1604)\n- Fix regression in setting recipient to self when replying to a Sent message (#3101)\n- Fix listing of folders in hidden namespaces (#2895)\n- Don't consider \\Noselect flag when building folders tree (#3448)\n- Fix sorting autocomplete results (#3504)\n- Add option to set session name (#2630)\n- Add option to skip alternative email addresses in autocompletion\n- Fix inconsistent behaviour of Compose button in Drafts folder, add Edit button for drafts\n- Fix problem with parsing HTML message body with non-unicode characters (#3312)\n- Add option to define matching method for addressbook search (#2720, #3378)\n- Make email recipients separator configurable\n- Fix so folders with \\Noinferiors attribute aren't listed in parent selector\n- Fix handling of curly brackets in URLs (#3555)\n- Fix handling of dates (birthday/anniversary) in contact data (#3552)\n- Fix error on opening searched LDAP contact (#3550)\n- Fix redundant line break in flowed format (#3551)\n- Fix IDN address validation issue (#3544)\n- Fix JS error when dst_active checkbox doesn't exist (#3540)\n- Autocomplete LDAP records when adding contacts from mail (#3498)\n- Plugin API: added 'ready' hook (#3492)\n- Ignore DSN request when it isn't supported by SMTP server (#3300)\n- Make sure LDAP name fields aren't arrays (#3523)\n- Fixed imap test to non-default port when using ssl (#3532)\n- Force all files to be overwritten when updating (#3531)\n- Fix issue where it wasn't possible to change list view mode in folder manager for INBOX (#3522)\n- Fix namespace handling in special folders settings (#3527)\n- Disable time limit for CLI scripts (#3524)\n- Fix misleading display when chaning editor type (#3519)\n- Add loading indicator on contact delete\n- Fix bug where after delete message rows can be added to the list of another folder (#3263)\n- Add notice on autocompletion that not all records were displayed\n- Add option 'searchonly' for LDAP address books\n- Add Priority filter to the messages list\n- Cache synchronization using QRESYNC/CONDSTORE\n- Trigger 'new_messages' hook for all checked folders (#3503)\n- Make date/time format user configurable; drop 'date_today' config option\n- Fix setting title for truncated subject in IE (#3141)\n- Fix displaying multipart/alternative messages with only one part (#3400)\n- Rewritten messages caching:\n Indexes are stored in a separate table, so there's no need to store all messages in a folder\n Added threads data caching\n Flags are stored separately, so flag change doesn't cause DELETE+INSERT, just UPDATE\n- Improved FETCH response handling\n- Improvements in response tokenization method\n- Use 'From' and 'To' labels instead of 'Sender' and 'Recipient'\n- Fix username case-insensitivity issue in MySQL (#3462)\n- Addressbook Saved Searches\n- Added spellchecker exceptions dictionary (shared or per-user)\n- Added possibility to ignore words containing caps, numbers, symbols (spellcheck_ignore_* options)\n- Added 'priority' column on messages list (#2884)\n- Localize forwarded message header (#3487)", "RELEASE 0.6\n-----------\n- Fix bug where the last identity is used on reply (#3516)\n- Fix locked folder rename option on servers supporting RFC2086 only (#3508)\n- Fix session race conditions when composing new messages\n- Fix encoding of LDAP contacts identifiers (#3501)\n- jQuery 1.6.4\n- Fix handling of binary attachments encoded with quoted-printable (#3494)\n- Fix text-overflow:ellipsis issues on messages list in FF7 and Webkit (#3490)\n- Fix handling of links with IP address\n- Fix compacting folder resets message list filter (#3499)", "RELEASE 0.6-rc\n----------------\n- Send X-Frame-Options headers to protect from clickjacking (#3079)\n- Fallback to mail_domain in LDAP variable replacements; added 'host' to 'user_create' hook arguments (#3464)\n- Fixed wrong vCard type parameter mobile (#3496)\n- Fixed vCard WORKFAX issue (#3476)\n- Add vCard's Profile URL support (#3491)\n- jQuery 1.6.3\n- Fix imap_cache setting to values other than 'db' (#3489)\n- Fix handling of attachments inside message/rfc822 parts (#3466)\n- Make list of mimetypes that open in preview window configurable (#3175)\n- Added plugin hook 'message_part_get' for attachment downloads\n- Added unique connection identifier to IMAP debug messages\n- Fix image type check for contact photo uploads", "RELEASE 0.6-beta\n----------------\n- Fixed selecting identity on reply/forward (#3434)\n- Add option to hide selected LDAP addressbook on the list\n- Add client-side checking of uploaded files size\n- Add newlines between organization, department, jobtitle (#3468)\n- Recalculate date when replying to a message and localize the cite header (#3212)\n- Fix handling of email addresses with quoted local part (#3401)\n- Fix EOL character in vCard exports (#3357)\n- Added optional \"multithreading\" autocomplete feature\n- Plugin API: Added 'config_get' hook\n- Fixed new_user_identity plugin to work with updated rcube_ldap class (#3443)\n- Plugin API: added folder_delete and folder_rename hooks\n- Added possibility to undo last contact delete operation\n- Fix sorting of contact groups after group create (#3258)\n- Add optional textual upload progress indicator (#2330)\n- Fix parsing URLs containing commas (#3425)\n- Added vertical splitter for books/groups list in addressbook (#3389)\n- Improved namespace roots handling in folder manager\n- Added searching in all addressbook sources\n- Added addressbook source selection in contacts import\n- Implement LDAPv3 Virtual List View (VLV) for paged results listing\n- Use 'address_template' config option when adding a new address block (#3406)\n- Added addressbook advanced search\n- Add popup with basic fields selection for addressbook search\n- Case-insensitive matching in autocompletion (#3398)\n- Added option to force spellchecking before sending a message (#1862)\n- Fix handling of \"<\" character in contact data, search fields and folder names (#3349)\n- Fix saving \"<\" character in identity name and organization fields (#3349)\n- Added option to specify to which address book add new contacts\n- Added plugin hook for keep-alive requests\n- Store user preferences in session when write-master is not available and session is stored in memcache, write them later\n- Improve performence of folder manager operations\n- Fix default_port option handling in Installer when config.inc.php file exists (#3390)\n- Removed option focus_on_new_message, added newmail_notifier plugin\n- Added general rcube_cache class with Memcache and APC support\n- Improved caching performance by skipping writes of unchanged data\n- Option enable_caching replaced by imap_cache and messages_cache options\n- Fix WORKFAX saving in address book (#3380)\n- Add forward-as-attachment feature\n- jQuery-1.6.2 (#5158, #3154)\n- Improve display name composition when saving contacts (#3153)\n- Fix problems with subfolders of INBOX folder on some IMAP servers (#3247)\n- Fix handling of folders that doesn't belong to any namespace (#3184)\n- Enable multiselection for attachments uploading in capable browsers (#2266)\n- Add possibility to change HTML editor configuration by skin\n- Fix a bug where selecting too many contacts would produce too large URI request (#3369)\n- Improve performance by including files with absolute path (#3337)\n- Move folder name truncation to client/skin (#1822)\n- Added plugin hook for request token creation\n- Replace LDAP vars in group queries (#3329)\n- Fix vcard folding with uncode characters (#3353)\n- Keep all submitted data if contact form validation fails (#3350)\n- Handle uncode strings in rcube_addressbook::normalize_string() (#3351)\n- Fix handling of debug_level=4 in ajax requests (#3327)\n- Enable TinyMCE's contextmenu (#3062)\n- Allow multiple concurrent compose sessions\n- New config option for custom logo\n- Allow skins to define/override texts with <roundcube:label />\n- Add simple ACL rights/namespace handling in folder manager\n- Force IE to send referers (#3306)\n- Better display of vcard import results (#1861)\n- Improved vcard import\n- Interactive update script with improved DB schema check\n- Fix problem with contactgroupmembers table creation on MySQL 4.x, add index on contact_id column\n- Add LDAP SASL bind and proxy authentication (#2810)\n- Replying to a sent message puts the old recipient as the new recipient (#3101)\n- Fulltext search over (almost) all data for contacts\n- Extend address book with rich contact information", "RELEASE 0.5.4\n-------------\n- Fix XSS vulnerability in UI messages [CVE-2011-2937] (#3469)", "RELEASE 0.5.3\n-------------\n- Fix identities \"reply-to\" and \"bcc\" fields have a bogus value when left empty (#3405)\n- Fix issue which cases IMAP disconnection when encrypt() method was used (#3374)\n- Fix some CSS issues in Settings for Internet Explorer \n- Fixed handling of folder with name \"0\" in folder selector\n- Fix bug where messages were deleted instead moved to trash folder after Shift key was used (#3376)\n- Fix relative URLs handling according to a <base> in HTML (#3368)\n- Fix handling of top-level domains with more than 5 chars or unicode chars (#3366)\n- Fix usage of non-standard HTTP error codes (#3297)\n- Fix PHP warning on mistaken in_array() usage (#3375)", "RELEASE 0.5.2\n-------------\n- TinyMCE 3.4.2 now compatible with IE9\n- PEAR::Net_SMTP 1.5.2, fixed timeout issue (#3332)\n- Fix bug where template name without plugin prefix was used in render_page hook\n- Support 'abort' and 'result' response in 'preferences_save' hook, add error handling\n- Fix bug where some content would cause hang on html2text conversion (#3348)\n- Improve space-stuffing handling in format=flowed messages (#3346)\n- Fix bug where some dates would produce SQL error in MySQL (#3342)\n- Added workaround for some IMAP server with broken STATUS response (#3344)\n- Fix bug where default_charset was not used for text messages (#3328)\n- Stateless request tokens. No keep-alive necessary on login page (#3325)\n- Force names of unique constraints in PostgreSQL DDL\n- Add code for prevention from IMAP connection hangs when server closes socket unexpectedly\n- Remove redundant DELETE query (for old session deletion) on login\n- Get around unreliable rand() and mt_rand() in session ID generation (#2516)\n- Fix some emails are not shown using Cyrus IMAP (#3316)\n- Fix handling of mime-encoded words with non-integral number of octets in a word (#3301)\n- Fix parsing links with non-printable characters inside (#3305)\n- Fixed de_CH Localization bugs (#3279)\n- Add variable for 'Today' label in date_today option (#2394)\n- Fix dont_override setting does not override existing user preferences (#3205)\n- Use only one from IMAP authentication methods to prevent login delays (1487784)\n- Support strftime format in date_today option\n- Fix SQL query in rcube_user::query() so it uses index on MySQL again\n- Removed redundant </form> tags from contact add/edit pages\n- Fix CSS error in contact details screen on IE7 (#3281)", "RELEASE 0.5.1\n-------------\n- Fix handling of attachments with invalid content type (#3275)\n- Add workaround for DBMail's bug http://www.dbmail.org/mantis/view.php?id=881 (#3274)\n- Use IMAP's ID extension (RFC2971) to print more info into debug log\n- Security: add optional referer check to prevent CSRF in GET requests\n- Fix email_dns_check setting not used for identities/contacts (#3251)\n- Fix ICANN example addresses doesn't validate (#3253)\n- Security: protect login form submission from CSRF [CVE-2011-1491]\n- Security: prevent from relaying malicious requests through modcss.inc [CVE-2011-1492]\n- Fix handling of non-image attachments in multipart/related messages (#3261)\n- Fix IDNA support when IDN/INTL modules are in use (#3253)\n- Fix handling of invalid HTML comments in messages (#3269)\n- Fix parsing FETCH response for very long headers (#3264)\n- Fix add/remove columns in message list when message_sort_order isn't set (#3262)\n- Check mime headers before attempt to parse them (#3256)\n- Quote header values in show_additional_headers plugin (#3255)\n- Fix settings UI on IE 6 (#3246)\n- Remove double borders in folder listing (#3236)\n- Separate full message headers UI element from headers table (#3238)\n- Add part MIME ID to message_part_* hooks (#3241) \n- Improve parsing of MS Outlook vCards (#3239)\n- Updated PEAR::Net_Socket to 1.0.10\n- Updated PEAR::Net_IDNA2 to 0.1.1\n- Fix handling of comments inside an email address spec. (#3210)\n- Show full mail subject as title when hovering a cut subject link (#3141)\n- Fix randomly disappearing folders list in IE (#3231)\n- Fix list column add/removal in IE (#3230)\n- Fix login redirect issues (#3221)\n- Require PHP 5.2.1 or greater\n- Fix %h/%z variables in username_domain option (#3228)\n- Workaround for setting charset in case of malformed bodystructure response (#3227)\n- Fix impossible to subscribe to protected folders (#3199)\n- Fix setting timezone in Preferences (#3232)", "RELEASE 0.5\n-----------\n- Fix double-login/session issue (#3124)\n- Wrap HTML parts with <html><body> and add Doctype declaration (#3119)\n- Make rcube_autoload silently skip unknown classes (#3128)\n- Fix charset detection in vcards with encoded values (#1934)\n- Better CSS cursors for splitters (#2954)\n- Show the same message only once (#3186)\n- Fix namespaces handling (#3192)\n- Add handling of multifolder METADATA/ANNOTATION responses\n- Fix handling of INBOX when personal namespace prefix is non-empty (#3200)\n- Fix handling square brackets in links (#3209)\n- Add description of 'use_https' option in main.inc.php.dist file", "RELEASE 0.5-RC\n--------------\n- Plugin API: Add 'pass' argument in 'authenticate' hook (#3147)\n- Fix attachments of type message/rfc822 are not listed on attachments list\n- Add 'login_lc' config option for case-insensitive authentication (#3131)\n- Fix window is blur'ed in IE when selecting a message (#3161)\n- Fix cursor position on compose form in Webkit browsers (#2796)\n- Fix setting charset of attachment filenames (#3136)\n- Allow setting autocomplete attribute for all inputs separately (#3158)\n- New Folder Manager UI\n- Fix invalid Request when creating a folder (#3165)\n- Add folder size and quota indicator in folder manager (#2112)\n- Add possibility to move a subfolder into root folder (#2890)\n- Fix copying all messages in a folder copies only messages from current page\n- Improve performance of moving or copying of all messages in a folder\n- Fix plaintext versions of HTML messages don't contain placeholders for emotions (#1657)\n- Improve performance of folder rename and delete actions\n- Better support for READ-ONLY and NOPERM responses handling (#3108)\n- Add confirmation message on purge/expunge command response\n- Fix handling of untagged responses for AUTHENTICATE command (#3171)\n- Add username and IP address to log message on unsuccessful login (#3176)\n- Improved Mail-Followup-To and Mail-Reply-To headers handling\n- Fix charset conversion for text attachments without charset specification (#3181)", "RELEASE 0.5-BETA\n----------------\n- Make session data storage more robust against garbage session data (#3148)\n- Config option for autocomplete on login screen\n- Allow plugin templates to include local files (#3146)\n- List groups in address detail view and allow to subscribe/unsubscribe from there (#2862)\n- Messages caching: performance improvements, fixed syncing, fixes related with #2857\n- Add link to identities in compose window (#2843)\n- Add Internationalized Domain Name (IDNA) support (#729)\n- Add option to automatically send read notifications for known senders (#2199)\n- Add option to \"Return receipt\" will be always checked (#2571)\n- Fix HTML to plain text conversion doesn't handle citation blocks (#2992)\n- Use custom sorting when SORT is disabled by IMAP admin (#3020)\n- Allow setting some washtml options from plugin (#2727)\n- Add option do bind for an individual LDAP address book (#3048)\n- Change reply prefix to display email address only if sender name doesn't exist (#2709)\n- Plugin API: improved 'abort' flag handling, added 'result' item in some hooks (#2988)\n- Fix mailto optional params in plain text messages aren't handled (#3071)\n- Add Reply-to-List feature (#977)\n- Add Mail-Followup-To/Mail-Reply-To support (#1937)\n- Fix confirmation message isn't displayed after sending mail on Chrome (#2437)\n- Fix keyboard doesn't work with autocomplete list with Chrome (#3073)\n- Improve tabs to fixed width and add tabs in identities info (#3030)\n- Add unique index on users.username+users.mail_host\n- Make htmleditor option more consistent and add option to use HTML on reply to HTML message (#2164)\n- Use empty envelope sender address for message disposition notifications (RFC 2298.3)\n- Support SMTP Delivery Status Notifications - RFC 3461 (#2409)\n- Use css sprite image for messages list\n- Add (different) attachment icon for messages of type multipart/report (#2426)\n- Prevent from inserting empty link when composing HTML message (#3007)\n- Add caching support in id2uid and uid2id functions (#3065)\n- Add SASL proxy authentication for SMTP (#2811)\n- Improve displaying of UI messages (#3033)\n- Fix double e-mail filed in identity form (#3088)\n- Display IMAP errors for LIST/THREAD/SEARCH commands (#2981)\n- Add LITERAL+ (IMAP4 non-synchronizing literals) support (RFC 2088)\n- Add separate column for message status icon (#2788)\n- Add ACL extension support into IMAP classes (RFC 4314)\n- Add ANNOTATEMORE extension support into IMAP classes (draft-daboo-imap-annotatemore)\n- Add METADATA extension support into IMAP classes (RFC 5464)\n- Fix decoding of e-mail address strings in message headers (#3097)\n- Fix handling of attachments when Content-Disposition is not inline nor attachment (#3086)\n- Improve performance of unseen messages counting (#3090)\n- Improve performance of messages counting using ESEARCH extension (RFC4731)\n- Add LIST-STATUS support in rcube_imap_generic class (RFC 5819)\n- Add SASL-IR support in IMAP (RFC 4959)\n- Add LOGINDISABLED support (RFC 2595)\n- Add support for AUTH=PLAIN in IMAP authentication\n- Re-implemented SMTP proxy authentication support\n- Add support for IMAP proxy authentication (#2808)\n- Add support for AUTH=DIGEST-MD5 in IMAP (RFC 2831)\n- Fix parent folder with unread subfolder not bold when message is open (#3104)\n- Add basic IMAP LIST's \\Noselect option support\n- Add support for selection options from LIST-EXTENDED extension (RFC 5258)\n- Don't list subscribed but non-existent folders (#2474)\n- Fix handling of URLs with tilde (~) or semicolon (;) character (#3110, #3111)\n- Plugin API: added 'contact_form' hook\n- Add SORT=DISPLAY support (RFC 5957)\n- Plugin API: add possibility to disable plugin in AJAX mode, 'noajax' property\n- Plugin API: add possibility to disable plugin in framed mode, 'noframe' property\n- Improve performance of setting IMAP flags using .SILENT suffix\n- Improve performance of message cache status checking with skip_disabled=true\n- Support contact's email addresses up to 255 characters long (#3116)\n- Add option to place replies in the folder of the message being replied to (#2248)\n- Add missing confirmation/error messages on contact/group/message actions (#2935)\n- Add 'loading' message on message move/copy/delete/mark actions\n- Improve responsiveness of messages displaying (#3039)\n- Add option for minimum length of autocomplete's string (#2625)\n- Fix operations on messages in unsubscribed folder (#3126)\n- Add support for shared folders (#525)\n- Fix handling of folders with name \"0\" (#3133)\n- Fix handling of folders with \"<>\" characters in name\n- jQuery 1.4.4\n- Fix handling of HTML entity strings in plain text messages\n- Fix focused elements aren't unfocused when clicking on the list (#3137)\n- Fix error in MSSQL DDL scripts (#3130)\n- Lock submit button in onsubmit event on login page (#3078)\n- Don't set attachment's charset in Content-type header (#3136)\n- Fix handling of message bodies (quoted-printable encoded) with NULL characters (#2448)\n- Add workaround for MSOE's multipart/related messages with non-related attachments", "RELEASE 0.4.2\n-------------\n- Fix handling of backslash as IMAP delimiter\n- Fix charset replacement in HTML message bodies (#3067)\n- Fix: contact group input is empty when using rename action more than once on the same group record\n- Fix \"Server Error! (Not Found)\" when using utils/save-pref action (#3069)\n- Fix handling of Thunderbird's vCards (#3070)", "RELEASE 0.4.1\n-------------\n- Fix space-stuffing in format=flowed messages (#3064)\n- Fix msgexport.sh now using the new imap wrapper\n- Avoid displaying password on shell (#3010)\n- Only lower-case user name if first login attempt failed (#2600)\n- Make alias setting in squirrelmail_usercopy plugin configurable (patch by pommi, #3056)\n- Prevent from saving a non-existing skin path in user prefs (#3004)\n- Improve handling of single-part messages with bogus BODYSTRUCTURE (#2976)\n- Fix path to SQL files when using pgsql/mysqli/sqlsrv drivers (#2979)\n- Fix upgrade script for SQLite (#2980)\n- Fixes in SQL init script + added update script for MSSQL database\n- Remove redundant date in syslog messages (#3008)\n- Fix contacts list page controls when a group is selected (#3009)\n- Fix SMTP test in Installer (#3014)\n- Fix \"Select all\" causes message to be opened in folder with exactly one message (#2987)\n- Fix Tab key doesn't work in HTML editor in Google Chrome (#2995)\n- Fix TinyMCE uses zh_CN when zh_TW locale is set (#2998)\n- Fix TinyMCE buttons are hidden in Opera (#2993)\n- Fix JS error on IE when trying to send HTML message with enabled spellchecker (#3006)\n- Display inline images with known extensions and non-image content-type (#3002)\n- Fix \"Threaded\" checkbox after subfolder creation (#2997)\n- Fix timezone string in sent mail (#3021)\n- Show disabled checkboxes for protected folders instead of dots (#1898)\n- Added fieldsets in Identity form, added 'identity_form' hook\n- Re-added 'Close' button in upload form (#2999, #2917)\n- Fix handling of charsets with LATIN-* label\n- Fix messages background image handling in some cases (#3043)\n- Fix format=flowed handling (#3042)\n- Fix when IMAP connection fails in 'get' action session shouldn't be destroyed (#3046)\n- Fix list_cols is not updated after column dragging (#3050)\n- Support %z variable in host configuration options (#3054)", "RELEASE 0.4\n-----------\n- Fix disappearing upload form disappears when user selects a file on Safari (#2917)\n- Don't replace error messages with loading info (#2534)\n- Fix JS errors on compose mode switch (#2952)\n- Fix message structure parsing when it lacks optional fields (#2960)\n- Include all recipients in sendmail log\n- Support HTTP_X_FORWARDED_PROTO header for HTTPS detecting (#2950)\n- Fix default IMAP port configuration (#2948)\n- Create Sent folder when starting to compose a new message (#2900)\n- Fix handling of messages with Content-Type: application/* and no filename (#840)\n- Improved compose screen: resizable body and attachments list, vertical splitter, options menu\n- Fix RC forgets search results (#722)\n- TinyMCE 3.3.7\n- Improve parsing of styled empty tags in HTML messages (#2908)\n- Add %dc variable support in base_dn/bind_dn config (#2881)\n- Add button to hide/unhide the preview pane (#955)\n- Fix no-cache headers on https to prevent content caching by proxies (#2897)\n- Fix attachment filenames broken with TNEF decoder using long filenames (#2894)\n- Use user's timezone in Date header, not server's timezone (#2393)\n- Add option to set separate footer for HTML messages (#2784)\n- Add real SMTP error description to displayed error messages (#2233)\n- Fix some IMAP errors handling when opening the message (#1848)\n- Fix related parts aren't displayed when got mimetype other than image/* (#2629)\n- Multiple identity and database support for squirrelmail_usercopy plugin (#2686)\n- Support dynamic hostname (%d/%n) variables in configuration options (#1843)\n- Add 'messages_list' hook (#2504)\n- Add request* event triggers in http_post/http_request (#2340)\n- Fix use RFC-compliant line-delimiter when saving messages on IMAP (#2828)\n- Add 'imap_timeout' option (#2869)\n- Fix forwarding of messages with winmail attachments\n- Fix handling of uuencoded attachments in message body (#2163)\n- Added list_mailboxes hook in rcube_imap::list_unsubscribed() (#2791)\n- Fix wrong message on file upload error (#2839)\n- Add support for data URI scheme [RFC2397] (#2851)\n- Added 'actionbefore', 'actionafter', 'responsebefore', 'responseafter' events\n- Fix double-addition of e-mail domain to content ID in HTML images\n- Read and send messages with format=flowed (#1052), fixes word wrapping issues (#2703)\n- Fix duplicated attachments when forwarding a message (#2670)\n- Fix message/rfc822 attachments containing only attachments are not parsed properly (#2854)\n- Fix %00 character in winmail.dat attachments names (#2850)\n- Fix handling errors of folder deletion (#2821)\n- Parse untagged CAPABILITY response for LOGIN command (#2853)\n- Renamed all php-cli scripts to use .sh extension\n- Some files from /bin + spellchecking actions moved to the new 'utils' task\n- Added thread tree icons\n- Extend contact groups support (#2802)\n- Fix check-recent action issues and performance (#2690)\n- Fix messages order after checking for recent (#1249)\n- Fix autocomplete shows entries without email (#2640)\n- Fix listupdate event doesn't trigger on search response (#2824)\n- Fix select_all_mode value after selecting a message (#2834)\n- Set focus to editor on reply in HTML mode (#2768)\n- Fix composing in HTML jumps cursor to body instead of recipients (#2796)\n- Allow columns order change per user - drag&drop (#2124)\n- Add References header in read receipt (#2801)\n- Fix database constraint violation when opening a message (#2814)\n- Add 'loading' message while login is in progress (#2790)\n- Fix quota_zero_as_unlimited (#2786)\n- Fix folder subscription checking (#2804)\n- Fix INBOX appears (sometimes) twice in mailbox list (#2794)\n- Fix listing of attachments of some types e.g. \"x-epoc/x-sisx-app\" (#2779)\n- Fix DB Schema checking when some db_table_* options are not set (#2780)", "RELEASE 0.4-beta\n----------------\n- Add sizelimit and timelimit variables in LDAP config (#2704)\n- Hide IMAP host dropdown when single host is defined (#2553)\n- Add images pre-loading on login page (#623)\n- Add HTTP_X_REAL_IP and HTTP_X_FORWARDED_FOR to successful logins log (#2634)\n- Fix setting spellcheck languages with extended codes (#2747)\n- Fix messages list scrolling in FF3.6 (#2657)\n- Fix quicksearch input focus (#2770)\n- Always set changed date when flagging a DB record as deleted + provide a cleanup script\n- Fix address book/group selection (#2760)\n- Assign newly created contacts to the active group (#2764)\n- Added option not to mark messages as read when viewed in preview pane (#1513)\n- Allow plugins modify the Sent folder when composing (#2708)\n- Added optional (max_recipients) support to restrict total number of recipients per message (#1167)\n- Re-organize editor buttons, add blockquote and search buttons\n- Make possible to write inside or after a quoted html message (#1878)\n- Fix bugs on unexpected IMAP connection close (#2449, #2507)\n- Iloha's imap.inc rewritten into rcube_imap_generic class\n- Added contact groups in address book (not finished yet)\n- Added PageUp/PageDown/Home/End keys support on lists (#2627)\n- Added possibility to select all messages in a folder (#1312)\n- Added 'imap_force_caps' option for after-login CAPABILITY checking (#2087)\n- Password: Support dovecotpw encryption\n- TinyMCE 3.3.1\n- Implemented messages copying using drag&drop + SHIFT (#863)\n- Improved performance of folders operations (#2689)\n- Fix blocked.gif attachment is not attached to the message (#2685)\n- Managesieve: import from Horde-INGO\n- Managesieve: support for more than one match (#2362)\n- Managesieve: support for selectively disabling rules within a single sieve script (#2198)\n- Threaded message listing now available\n- Added sorting by ARRIVAL and CC\n- Message list columns configurable by the user\n- Removed 'index_sort' option, now we're using empty 'message_sort_col' for this\n- virtuser_query: support other identity data (#2413)\n- Options virtuser_* replaced with virtuser_* plugins\n- Plugin API: Implemented 'email2user' and 'user2email' hooks\n- Fix forwarding message omits CC header (#2538)\n- Add 'default_charset' option to user preferences (#1855)\n- Add 'delete_always' option to user preferences\n- Support/Require tls:// prefix in 'smtp_server' option for TLS connections\n- Fix inconsistent behaviour of 'delete_always' option (#2533)\n- Fix deleting all messages from last list page (#2528)\n- Flag original messages when sending a draft (#2458)\n- Changed signature separator when top-posting (#2555)\n- Let the admin define defaults for search modifiers (#2211)\n- Fix long e-mail addresses validation (#2641)\n- Remember search modifiers in user prefs (#2411)\n- Added force_7bit option to force MIME encoding of plain/text messages (#2679)\n- Use case sensitive check when checking for default folders (#2567)\n- Fix checking for new mail: now checks unseen count of inbox (#2123)\n- Improve performance by avoiding unnecessary updates to the session table (#2552)\n- Fix invalid <font> tags which cause HTML message rendering problems (#2687)\n- Fix CVE-2010-0464: Disable DNS prefetching (#2639)\n- Fix Received headers to behave better with SpamAssassin (#2682)\n- Password: Make passwords encoding consistent with core, add 'password_charset' global option (#2658)\n- Fix adding contacts SQL error on mysql (#2645)\n- Squirrelmail_usercopy: support reply-to field (#2678)\n- Fix IE spellcheck suggestion popup issue (#2656)\n- Fix email address auto-completion shows regexp pattern (#2498)\n- Fix merging of configuration parameters: user prefs always survive (#2584) \n- Fix quota indicator value after folder purge/expunge (#2671)\n- Fix external mailto links support for use as protocol handler (#2328)\n- Fix attachment excessive memory use, support messages of any size (#1245)\n- Fix setting task name according to auth state\n- Password: fix vpopmaild driver (#2662)\n- Add workaround for MySQL bug [http://bugs.mysql.com/bug.php?id=46293] (#2659)\n- Fix quoted text wrapping when replying to an HTML email in plain text (#897)\n- Fix handling of extended mailto links (with params) (#2573)\n- Fix sorting by date of messages without date header on servers without SORT (#2521)\n- Fix inconsistency when not using default table names (#2652)\n- Fix folder rename/delete buttons do not appear on creation of first folder (#2653)\n- Fix character set conversion fails on systems where iconv doesn't accept //IGNORE (#2590)\n- Log in performance: Create default folders on first login only\n- Import contacts into the selected address book (by Phil Weir)\n- Add support for MDB2's 'sqlsrv' driver (#2602)\n- Use jQuery-1.4\n- Removed problematic browser-caching of messages\n- Fix incompatybility with suhosin.executor.disable_emodifier (#2549)\n- Use PLAIN auth when CRAM fails and imap_auth_type='check' (#2587)\n- Fix removal of <title> tag from HTML messages (#2629)\n- Fix 'force_https' to specified port when URL contains a port number (#2612)\n- Fix to-text converting of HTML entities inside b/strong/th/hX tags (#2621)\n- Bug in spellchecker suggestions when server charset != UTF8 (#2607)\n- Managesieve: Fix requires generation for multiple actions (#2603)\n- Fix LDAP problem with special characters in RDN (#2548)\n- Improved handling of message parts of type message/rfc822\n- Plugin API: added 'quota' hook\n- Fix parsing conditional comments in HTML messages (#2569)\n- Use built-in json_encode() for proper JSON format in AJAX replies\n- Allow setting only selected params in 'message_compose' hook (#2543)\n- Plugin API: added 'message_compose_body' hook (#2520)\n- Fix counters of all folders are checked in 'getunread' action with check_all_folders disabled (#2399)\n- Fix displaying alternative parts in messages of type message/rfc822 (#2488)\n- Fix possible messages exposure when using Roundcube behind a proxy (#2516)\n- Fix unicode para and line separators in javascript response (#2542)\n- Additional_message_headers: allow unsetting headers, support plugin's config file (#2505)\n- Fix displaying of hidden directories in skins list (#2535)\n- Fix open_basedir restriction error when reading skins list (#2537)\n- Fix pasting from Office apps into html editor (#2508)\n- Fix empty <a> tags parsing (#2509)\n- Don't cut off attachment names when using non-RFC2231 encoding (#1912)\n- Allow inserting signatures above replied message body (#991)\n- Managesieve 2.0: multi-script support\n- Fix imap_auth_type regression (#2502)", "RELEASE 0.3.1\n------------------\n- Specify toolbar container in compose template (#2489)\n- Fix $_SERVER['HTTPS'] check for SSL forcing on IIS (#2486)\n- Avoid unnecessary page loads for selected tab (#2324)\n- Fix quota indicator issues by content generation on client-size (#2454, #2470)\n- Don't display disabled sections in Settings (#2380)\n- Added server-side e-mail address validation with 'email_dns_check' option (#2175)\n- Fix login page loading into an iframe when session expires (#2253)\n- Allow setting port number in 'force_https' option (#2373)\n- Option 'force_https' replaced by 'force_https' plugin\n- Fix IE issue with non-UTF-8 characters in AJAX response (#2422)\n- Partially fixed \"empty body\" issue by showing raw body of malformed message (#2427)\n- Fix importing/sending to email address with whitespace (#2467)\n- Added XIMSS (CommuniGate) driver for Password plugin\n- Fix newly attached files are not saved in drafts w/o editing any text (#2457)\n- Added attachment upload indicator with parallel upload (#2344)\n- Use default_charset for bodies of messages without charset definition (#2446)\n- Password: added cPanel driver\n- Fix return to first page from e-mail screen (#2385)\n- Fix handling HTML comments in HTML messages (#2448)\n- Fix folder/messagelist controls alignment - icons used (#2356)\n- Fix LDAP addressbook shows 'Contact not found' error sometimes (#2438)\n- Fix cache status checking + improve cache operations performance (#2384)\n- Prevent from setting INBOX as any of special folders (#2390)\n- Fix regular expression for e-mail address (#2417)\n- Fix Received header format\n- Implemented sorting by message index - added 'index_sort' option (#2240)\n- Fix dl() use in installer (#2415)\n- Added 'ldap_debug' option\n- Fix \"Empty startup greeting\" bug (#2369)\n- Fix setting user name in 'new_user_identity' plugin (#2405)\n- Fix incorrect count of new messages in folder list when using multiple IMAP clients (#2289)\n- Fix all folders checking for new messages with disabled caching (#2399)\n- Support skins in 'archive' and 'markasjunk' plugins\n- Added 'html_editor' hook (#2353)\n- Fix DB constraint violation when populating messages cache (#2338)\n- Password: added password strength options (#2348)\n- Fix LDAP partial result warning (#1928)\n- Fix delete in message view deletes permanently with flag_for_deletion=true (#2382)\n- Use faster/secure mt_rand() (#2376)\n- Fix roundcube hangs on empty inbox with bincimapd (#2375)\n- Fix wrong headers for IE on servers without $_SERVER['HTTPS'] (#2232)\n- Force IE style headers for attachments in non-HTTPS session, 'use_https' option (#2023)\n- Check 'post_max_size' for upload max filesize (#2372) \n- Password Plugin: Fix %d inserts username instead of domain (#2371)\n- Fix rcube_mdb2::affected_rows() (#2366)", "RELEASE 0.3-stable\n------------------\n- Fix gn and givenName should be synonymous in LDAP addressbook (#2208)\n- Add mail_domain to LDAP email entries without @ sign (#1652)\n- Fix saving empty values in LDAP contact data (#2113)\n- Fix LDAP contact update when RDN field is changed (#2119)\n- Fix LDAP attributes case senitivity problems (#2155)\n- Fix LDAP addressbook browsing when only one directory is used (#2314)\n- Fix endless loop on error response for APPEND command (#2346)\n- Don't require date.timezone setting in installer (#2284)\n- Fix date sorting problem with Courier IMAP server (#2351)\n- Unselect pressed buttons on mouse up (#2283)\n- Don't set php_value error_log in .htaccess but mention in INSTALL (#2230)\n- Fix too small status/flag/attachment columns in Safari 4 (#2349)\n- Fix selection disabling while dragging splitter in webkit browsers (#2342)\n- Added 'new_messages' plugin hook (#2298)\n- Added 'logout_after' plugin hook (#2333)\n- Added 'message_compose' hook\n- Added 'imap_connect' hook (#2256)\n- Fix vcard_attachments plugin (#2326)\n- Updated PEAR::Auth_SASL to 1.0.3 version\n- Use sequence names only with PostgreSQL (#2310)\n- Re-designed User Preferences interface \n- Fix MS SQL DDL (#2312)\n- Fix rcube_mdb2.php: call to setCharset not implemented in mssql driver (#2311)\n- Added 'display_next' option\n- Fix rcube_mdb2::unixtimestamp for MS SQL (#2308)\n- Fix HTML washing to respect character encoding\n- Fix endless loop in iil_C_Login() with Courier IMAP (#2303)\n- Fix #messagemenu display on IE (#2299)\n- Speedup UI by using sprites for (toolbar) buttons\n- Fix charset names with X- prefix handling\n- Fix displaying of HTML messages with unknown/malformed tags (#2296)", "RELEASE 0.3-RC1\n---------------\n- Fix import of vCard entries with params (#1857)\n- Fix HTML messages output with empty block elements (#2271)\n- Use request tokens to protect POST requests from CSRF [CVE-2009-4076, CVE-2009-4077]\n- Added hook when killing a session\n- Added hook to write_log function (#2268)\n- Performance improvements by use UID commands (#2046)\n- Fix HTML editor tabIndex setting (#2269)\n- Added 'imap_debug' and 'smtp_debug' options\n- Support strftime's format modifiers in date_* options (#1354)\n- Support %h variable in 'smtp_server' option (#2101)\n- Show SMTP errors in browser (#2233)\n- Allow WBR tag in HTML message (#2259)\n- Use spl_autoload_register() instead of __autoload (#2250)\n- Add hook for identities listing (#2257)\n- Trigger hook 'smtp_connect' when opening an SMTP connection (#2255)\n- Added config option to enforce HTTPS connections\n- Fix non-unicode characters caching in unicode database (#1209)\n- Performance improvements of messages caching\n- Fix empty Date header issue (#2229)\n- Open collapsed folders during drag & drop (#2221)\n- Fixed link text replacements (#2120)\n- Also trigger 'insertrow' events on page load (#2151)\n- No link on subject in IE browsers (#1438)\n- Fixed filename encoding according to RFC2231 (#2192)\n- Added message Edit feature (#727, #1101)\n- Fix message Etag generation for counter issues (#1996)\n- Fix messages searching on MailEnable IMAP (#2097)\n- Fixed many 'skip_deleted' issues (#2006)\n- Fixed messages list sorting on servers without SORT capability\n- Colorized signatures in plain text messages\n- Reviewed/fixed skip_deleted/read_when_deleted/flag_for_deletion options handling in UI\n- Fix displaying of big maximum upload filesize (#2205)\n- Added possibility to invert messages selection\n- After move/delete from 'show' action display next message instead of messages list (#2203)\n- Fixed problem with double quote at the end of folder name (#2200)\n- Speedup UI by using CSS sprites and etags/expires/deflate in Apache config (#1397,#2128)\n- Support UID EXPUNGE: remove only moved/deleted messages\n- Add drag cancelling with ESC key (#1036)\n- Support initial identity name from virtuser_query (#807)\n- Added message menu, removed Print and Source buttons\n- Added possibility to save message as .eml file (#2178)\n- Added 1 minute interval in autosave options (#2173)\n- Support UTF-7 encoding in messages (#2156)\n- Better support for malformed character names (#2093)", "RELEASE 0.3-BETA\n----------------\n- Plugin API + jQuery engine\n- Added possibility to encrypt received header, option 'http_received_header_encrypt',\n added some more logic in encrypt/decrypt functions for security\n- Fix Answered/Forwarded flag setting for messages in subfolders\n- Fix autocomplete problem with capital letters (#2122)\n- Support UUencode content encoding (#2163)\n- Minimize chance of race condition in session handling (#1260)\n- Fix session handling on non-session SQL query error (#2078)\n- Fix html editor mode setting when reopening draft message (#2158)\n- Added quick search box menu (#1010)\n- Fix wrong column sort order icons (#2149)\n- Updated TinyMCE to 3.2.3 version\n- Fix attachment names encoding when charset isn't specified in attachment part (#1483)\n- Fix message normal priority problem (#2146)\n- Fix autocomplete spinning wheel does not disappear (#2132)\n- Added log_date_format option (#2060)\n- Fix text wrapping in HTML editor after switching from plain text to HTML (#1917)\n- Fix auto-complete function hangs with plus sign (#2141)\n- Fix AJAX requests errors handler (#1503)\n- Speed up message list displaying on IE\n- Fix read/write database recognition (#2137)", "RELEASE 0.2.2\n-------------\n- Fix quicksearchbox look in Chrome and Konqueror (#1380)\n- Fix UTF-8 byte-order mark removing (#1911)\n- Fix folders subscribtions on Konqueror (#1380) \n- Fix debug console on Konqueror and Safari\n- Fix messagelist focus issue when modifying status of selected messages (#2134)\n- Support STARTTLS in IMAP connection (#1714)\n- Fix DEL key problem in search boxes (#1923)\n- Support several e-mail addresses per user from virtuser_file (#2036)\n- Fix drag&drop with scrolling on IE (#2117)\n- Fix adding signature separator in html mode (#1768)\n- Fix opening attachment marks message as read (#2131)\n- Fix 'temp_dir' does not support relative path under Windows (#1157)\n- Fix \"Initialize Database\" button missing from installer (#2130)\n- Fix compose window doesn't fit 1024x768 window (#1807)\n- Fix service not available error when pressing back from compose dialog (#1942)\n- Fix using mail() on Windows (#2111)\n- Fix word wrapping in message-part's <PRE>s for printing (#2118)\n- Fix incorrect word wrapping in outgoing plaintext multibyte messages (#2062)\n- Fix double footer in HTML message with embedded images\n- Fix TNEF implementation bug (#2107)\n- Fix incorrect row id parsing for LDAP contacts list (#2116) \n- Fix 'mode' parameter in sqlite DSN (#2106)", "RELEASE 0.2.1\n------------------\n- Use US-ASCII as failover when Unicode searching fails (#2097)\n- Fix errors handling in IMAP command continuations (#2097)\n- Fix FETCH result parsing for servers returning flags at the end of result (#2098)\n- Fix datetime columns defaults in mysql's DDL (#2012)\n- Fix attaching more than nine inline images (#2094)\n- Support 'UNICODE-1-1-UTF-7' alias for UTF-7 encoding (#2093)\n- Fix mime-type detection using a hard-coded map (#1735)\n- Don't return empty string if charset conversion failed (#2092)\n- Disable concurrent autocomplete query results display (#2082)\n- Fix new lines stripped from message footer (#2088)\n- Fix IE problem with mouse click autocomplete (#2080)\n- Fix html body washing on reply/forward + fix attachments handling (#2034)\n- Fix multiple recipients input parsing (#2077)\n- Fix replying to message with html attachment (#2034)\n- Use default_charset for messages without specified charset (#2027, #1484961)\n- Support non-standard \"GMT-XXXX\" literal in date header (#2074)\n- Added TNEF support to decode MS Outlook attachments (winmail.dat)\n- Fix \"value continuation\" MIME headers by adding required semicolon (#2073)\n- Fix pressing select all/unread multiple times (#2069)\n- Fix selecting all unread does not honor new messages (#2070)\n- Fix some base64 encoded attachments handling (#2071)\n- Support NGINX as IMAP backend: better BAD response handling (#2066)\n- Performance fix: don't fetch attachment parts headers twice to parse filename\n- Fix checking for recent messages on various IMAP servers (#2055)\n- Performance fix: Don't fetch quota and recent messages in \"message view\" mode\n- Fix displaying of alternative-inside-alternative messages (#2061)\n- Fix MDNSent flag checking, use arbitrary keywords (asterisk) flag (#2059)\n- Fix creation of folders with '&' sign in name\n- Fix parsing of email addresses without angle brackets (#2048)\n- Save spellcheck corrections when switching from plain to html editor (and spellchecking is on)\n- Fix large search results on server without SORT capability (#2031)\n- Get rid of preg_replace() with eval modifier and create_function usage (#2042)\n- Bring back <base> and <link> tags in HTML messages\n- Fix XSS vulnerability through background attributes [CVE-2009-0413]\n- Fix problems with backslash as IMAP hierarchy delimiter (#1116)\n- Secure vcard export by getting rid of preg's 'e' modifier use (#2045)\n- Fix authentication when submitting form with existing session (#2037)\n- Allow absolute URLs to images in HTML messages/sigs (#2029)\n- Fix message body which contains both inline attachments and emotions\n- Fix SQL query execution errors handling in rcube_mdb2 class (#1907)\n- Fix address names with '@' sign handling (#2022)\n- Improve messages display performance\n- Fix messages searching with 'to:' modifier", "RELEASE 0.2-STABLE\n------------------\n- Fix mark popup in IE 7 (#1785)\n- Fix line-break issue when copy & paste in Firefox (#1832)\n- Fix autocomplete \"unknown server error\" (#2008)\n- Fix STARTTLS before AUTH in SMTP connection (#1415)\n- Support multiple quota values in QUOTAROOT resonse (#1999)\n- Only abbreviate file name for IE < 7 browsers (#1548)\n- Performance: allow setting imap rootdir and delimiter before connect (#1628)\n- Fix sorting of folders with more than 2 levels (#1953)\n- Fix search results page jumps in LDAP addressbook (#1689)\n- Fix empty line before the signature in IE (#1769)\n- Fix horizontal scrollbar in preview pane on IE (#1228)\n- Add Robots meta tag in login page and installer (#1385)\n- Added 'show_images' option, removed 'addrbook_show_images' (#1977)\n- Option to check for new mails in all folders (#1053)\n- Don't set client busy when checking for new messages (#1706)\n- Allow UTF-8 folder names in config (#1960)\n- Add junk_mbox option configuration in installer (#1960)\n- Do serverside addressbook queries for autocompletion (#1925)\n- Allow setting attachment col position in 'list_cols' option\n- Allow override 'list_cols' via skin (#1958)\n- Fix 'cache' table cleanup on session destroy (#1913)\n- Increase speed of session destroy and garbage clean up\n- Fix session timeout when DB server got clock skew (#1890)\n- Fix handling of some malformed messages (#1099)\n- Speed up raw message body handling\n- Better HTML entities conversion in html2text (#1916)\n- Fix big memory consumption and speed up searching on servers without SORT capability\n- Fix setting locale to tr_TR, ku and az_AZ (#1872) \n- Use SORT for searching on servers with SORT capability\n- Added message status filter\n- Fix empty file sending (#1801)\n- Improved searching with many criterias (calling one SEARCH command)\n- Fix HTML editor initialization on IE (#1731)\n- Add warning when switching editor mode from html to plain (#1888)\n- Make identities list scrollable (#1930)\n- Fix problem with numeric folder names (#1922)\n- Added BYE response simple support to prevent from endless loops in imap.inc (#777)\n- Fix unread message unintentionally marked as read if read_when_deleted=true (#1819)\n- Remove port number from SERVER_NAME in smtp_helo_host (#1915)\n- Don't send disposition notification receipts for messages marked as 'read' (#1918)\n- Added 'keep_alive' and 'min_keep_alive' options (#1777)\n- Added option 'identities_level', removed 'multiple_identities'\n- Allow deleting identities when multiple_identities=false (#1840)\n- Added option focus_on_new_message (#1789)\n- Fix html2text class autoloading on Windows (#1904)\n- Fix html signature formatting when identity save error occurred (#1833)\n- Add feedback and set busy when moving folder (#1897)\n- Fix 'Empty' link visibility for some languages e.g. Slovak (#1889)\n- Fix messages count bar overlapping (#1703)\n- Fix adding signature in drafts compose mode (#1884)\n- Fix iil_C_Sort() to support very long and/or divided responses (#1713)\n- Fix matching case sensitivity when setting identity on reply (#1881)\n- Prefer default identity on reply\n- Fix imap searching on ISMail server (#1870)\n- Add css class for flagged messages (#1868)\n- Write username instead of id in sendmail log (#1879)\n- Fix htmlspecialchars() use for PHP version < 5.2.3 (#1877)\n- Fix js keywords escaping in json_serialize() for IE/Opera (#1874)\n- Added bin/killcache.php script (#1839)\n- Add support for SJIS, GB2312, BIG5 in rc_detect_encoding()\n- Fix vCard file encoding detection for non-UTF-8 strings (#1820)\n- Add 'skip_deleted' option in User Preferences (#1850)\n- Minimize \"inline\" javascript scripts use (#1838)\n- Fix css class setting for folders with names matching defined classes names (#1772)\n- Fix race conditions when changing mailbox\n- Fix spellchecking when switching to html editor (#1779)\n- Fix compose window width/height (#1807)\n- Allow calling msgimport.sh/msgexport.sh from any directory (#1837)\n- Localized filesize units (#1760)\n- Better handling of \"no identity\" and \"no email in identity\" situations (#1592)\n- Added 'mime_param_folding' option with possibility to choose long/non-ascii attachment names encoding eg. to be readable in MS Outlook/OE (#1743)\n- Added \"advanced options\" feature in User Preferences\n- Fix unread counter when displaying cached massage in preview panel (#1720)\n- Fix htmleditor spellchecking on MS Windows (#1808)\n- Fix problem with non-ascii attachment names in Mail_mime (#1700, #1576)\n- Fix language autodetection (#1812)\n- Fix button label in folders management (#1816)\n- Fix collapsed folder not indicating unread msgs count of all subfolders (#1814)\n- Fix handling of apostrophes in filenames decoded according to rfc2231", "RELEASE 0.2-BETA\n----------------\n- Made config files location configurable (#1664)\n- Reduced memory footprint when forwarding attachments (#1764)\n- Allow and use spellcheck attribute for input/textarea fields (#1545)\n- Added icons for forwarded/forwarded+replied messages (#1691)\n- Added Reply-To to forwarded emails (#1739)\n- Display progress message for folders create/delete/rename (#1774)\n- Smart Tags and NOBR tag support in html messages (#1780, #1748)\n- Redesign of the identities settings (#836)\n- Add config option to disable creation/deletion of identities (#1139)\n- Added 'sendmail_delay' option to restrict messages sending interval (#1135)\n- Added vertical splitter for folders list resizing\n- Added possibility to view all headers in message view\n- Fixed splitter drag/resize on Opera (#1626)\n- Fixed quota img height/width setting from template (#1396)\n- Refactor drag & drop functionality. Don't rely on browser events anymore (#1108)\n- Insert \"virtual\" folders in subscription list (#1333)\n- Added link to open message in new window\n- Enable export of address book contacts as vCard\n- Add feature to import contacts from vcard files (#395)\n- Respect Content-Location headers in multipart/related messages according to RFC2110 (#1464)\n- Allowed max. attachment size now indicated in compose screen (#1523)\n- Also capture backspace key in list mode (#1186)\n- Allow application/pgp parts to be displayed (#1309)\n- Correctly handle options in mailto-links (#1671)\n- Immediately save sort_col/sort_order in user prefs (#1698)\n- Truncate very long (above 50 characters) attachment filenames when displaying\n- Allow to auto-detect client language if none set (#1095)\n- Auto-detect the client timezone (user configurable)\n- Add RFC2231 header value continuations support for attachment filenames + hack for servers that not support that feature\n- Fix Reply-To header displaying (#1738)\n- Mark form buttons that provide the most obvious operation (mainaction)\n- Added option 'quota_zero_as_unlimited' (#1206)\n- Added PRE handling in html2text class (#1301)\n- Added folder hierarchy collapsing\n- Added options to use syslog instead of log file (#1389)\n- Added Logging & Debugging section in Installer\n- Fix In-Reply-To and References headers when composing saved draft message (#1718)\n- Fix html message charset conversion for charsets with underline (#1717) \n- Fix buttons status after contacts deletion (#1675)\n- Fix escaping of To: and From: fields when building message body for reply or forward in the HTML editor (#1432)\n- Use current mailbox name in template (#1690)\n- Better fix for skipping untagged responses (#1694)\n- Added pspell support patch by Kris Steinhoff (#781)\n- Enable spellchecker for HTML editor (#1589)\n- Respect spellcheck_uri in tinyMCE spellchecker (#941)\n- Case insensitive contacts searching using PostgreSQL (#1692)\n- Make default imap folders configurable for each user (#1558)\n- Save outgoing mail to selectable folder (#1324581)\n- Fix hiding of mark menu when clicking th button again (#1463)\n- Use long date format in print mode (#1643)\n- Updated TinyMCE to version 3.1.0.1\n- Re-enable autocomplete attribute for login form (#1661)\n- Check PERMANENTFLAGS before saving $MDNSent flag (#1478, #1485163)\n- Added flag column on messages list (#1220)\n- Patched Mail/MimePart.php (http://pear.php.net/bugs/bug.php?id=14232)\n- Allow trash/junk subfolders to be purged (#1568)\n- Store compose parameters in session and redirect to a unique URL\n- Fixed CRAM-MD5 authentication (#1364)\n- Fixed forwarding messages with one HTML attachment (#1103)\n- Fixed encoding of message/rfc822 attachments and image/pjpeg handling (#1439)\n- Added option to select skin in user preferences\n- Added option to configure displaying of attached images below the message body\n- Added option to display images in messages from known senders (#1204)\n- User preferences grouped in more fieldsets\n- Fix corrupted MIME headers of messages in Sent folder (#1587)\n- Fixed bug in MDB2 package: http://pear.php.net/bugs/bug.php?id=14124\n- Use keypress instead of keydown to select list's row (#1362)\n- Don't call expunge and don't remove message row after message move if flag_for_deletion is set to true (#1505)", "RELEASE 0.2-ALPHA\n-----------------\n- Added option to disable autocompletion from selected LDAP address books (#1445)\n- TLS support in LDAP connections: 'use_tls' property (#1581)\n- Fixed removing messages from search set after deleting them (#1583)\n- imap.inc: Fixed iil_C_FetchStructureString() to handle many \n literal strings in response (#1483)\n- Support for subfolders in default/protected folders (#1250)\n- Disallowed delimiter in folder name (#1351)\n- Support \" and \\ in folder names\n- Escape \\ in login (#1214)\n- Better HTML sanitization with the DOM-based washtml script (#1276)\n- Fixed sorting of folders with non-ascii characters\n- Fixed Mysql DDL for default identities creation (#1554)\n- In Preferences added possibility to configure 'read_when_deleted',\n 'mdn_requests', 'flag_for_deletion' options\n- Made IMAP auth type configurable (#683)\n- Fixed empty values with FROM_UNIXTIME() in rcube_mdb2 (#1540)\n- Fixed attachment list on IE 6/7 (#1355)\n- Fixed JavaScript in compose.html that shows cc/bcc fields if populated\n- Make password input fields of type password in installer (#1417)\n- Don't attempt to delete cache entries if enable_caching is FALSE (#1537)\n- Optimized messages sorting on servers without sort capability (#1535)\n- Corrected message headers decoding when charset isn't specified and improved\n support for native languages (#1536, #1534)\n- Expanded LDAP configuration options to support LDAP server writes.\n- Installer: encode special characters in DB username/password (#1529)\n- Fixed management of folders with national characters in names (#1526, #1504)\n- Fixed identities saving when using MDB2 pgsql driver (#1525)\n- Fixed BCC header reset (#1501)\n- Improved messages list performance - patch from Justin Heesemann\n- Append skin_path to images location only when it starts with '/' sign (#1398)\n- Fix IMAP response in message body when message has no body (#1479)\n- Fixed non-RFC dates formatting (#1429)\n- Fixed typo in set_charset() (#1498)\n- Decode entities when inserting HTML signature to plain text message (#1497)\n- HTML editing is now working with PHP5 updates and TinyMCE v3.0.6\n- Fixed signature loading on Windows (#1169)\n- Added language support to HTML editing (#1401)\n- Fixed remove signature when replying (#446)\n- Fixed problem with line with a space at the end (#1440)\n- Fixed <!DOCTYPE> tag filtering (#1066)\n- Fixed <?xml> tag filtering (#1075)\n- Added sections (fieldset+label) in Settings interface\n- Mark as read in one action with message preview (#1486)\n- Deleted redundant quota reads (#1486)\n- Added options for empty trash and expunge inbox on logout (#707)\n- Removed lines wrapping when displaying message\n- Fixed month localization\n- Changed codebase to PHP5 with autoloader", "RELEASE 0.1.1\n-------------\n- Clear selection when selecting single item (#1461)\n- Remove hard-coded image size in skin templates (#1423)\n- Database schema improvements (dropped unnecessary indexes)\n- Fixed creating a new folder with a comma in its name (#1263)\n- Fixed sorting of messages when default mailbox is empty (#1020)\n- Improve message previewpane - less loading (#1019)\n- Fixed login form autoompletion (#1378)\n- Fixed virtuser_query option for mdb2 backend (#1409)\n- Fixed attachment resoting from Drafts when message body was empty (#1144)\n- Fixed usage of ob_gzhandler (#1390)\n- Fixed message part window in IE6 (#1211)\n- Fixed decoding of mime-encoded strings (#938)\n- Fixed some iconv/mb_string problems (#1202)\n- Correctly quote mailbox name when using in URL (#1016)\n- Fixed \"headers already sent\" errors (#1399)", "RELEASE 0.1-STABLE\n------------------\n- Added interactive installer script\n- Fix folder adding/renaming inspired by #1349\n- Localize folder name in page title (#1338)\n- Fix code using wrong variable name (#818)\n- Allow to send mail with BCC recipients only\n- condense TinyMCE toolbar down to one line, removing table buttons (#1306)\n- Add function to mark the selected messages as read/unread (#641)\n- Also do charset decoding as suggested in RFC 2231 (fix #1022)\n- Show message count in folder list and hint when creating a subfolder\n- Distinguish ssl and tls for imap connections (#1252)\n- Added some charset aliases to fix typical mis-labelling (#1185)\n- Remember decision to display images for a certain message during session (#1310)\n- Truncate attachment filenames to 55 characters due to an IE bug (#1313)\n- Make sending of read receipts configurable\n- Respect config when localize folder names (#1280)\n- Also respect receipt and priority settings when re-opening a draft message\n- Remember search results (closes #722), patch by the_glu\n- Add Received header on outgoing mail\n- Upgrade to TinyMCE 2.1.3\n- Allow inserting image attachments into HTML messages while composing (#1179)\n- Implement Message-Disposition-Notification (Receipts)\n- Fix overriding of session vars when register_globals is on (#1255)\n- Fix bug with case-sensitive folder names (#973)\n- Don't create default folders by default\n- Fixed some potential security risks (audited by Andris)\n- Only show new messages if they match the current search (#925)\n- Switch to/from when searcing in Sent folder (#1177)\n- Correctly read the References header (#1236)\n- Unset old cookie before sending a new value (#1232)\n- Correctly decode attachments when downloading them (#1235 and #1484642)\n- Suppress IE errors when clearing attachments form (#1043)\n- Log error when login fails due to auto_create_user turned off\n- Filter linked/imported CSS files (closes #844)\n- Improve message compose screen (closes #1060)\n- Select next row after removing one from list (#1063)", "RELEASE 0.1-RC2\n---------------\n- Enable drag-&-dropping of folders to a new parent and allow to create subfolders (#637)\n- Suppress IE errors when clearing attachments form (#1043)\n- Set preferences field in user table to NULL (#1062)\n- Log error when login fails due to auto_create_user turned off\n- Filter linked/imported CSS files (closes #844)\n- Improve message compose screen (closes #1060)\n- Select next row after removing one from list (#1063)\n- Make smtp HELO/EHLO hostname configurable (#851)\n- IPv6 Compatibility (#1023), Patch #1484373\n- Unlock interface when message sending fails (#1188)\n- Eval PHP code in template includes (if configured)\n- Show message when folder is empty. Mo more static text in table (#1068)\n- Only display unread count in page title when new messages arrived\n- Fixed wrong delete button tooltip (#785)\n- Fixed charset encoding bug (#1091)\n- Applied patch for LDAP version (#1175)\n- Improved XHTML validation\n- Fix message list selection (#1174)\n- Better fix lowercased usernames (#1120)\n- Update pngbehavior Script as suggested in #1134\n- Fixed moving/deleting messages when more than 1 is selected\n- Applied patch for LDAP contacts listing by Glen Ogilvie\n- Applied patch for more address fields in LDAP contacts (#1074)\n- Add alternative for getallheaders() (fix #1146)\n- Identify mailboxes case-sensitive\n- Sort mailbox list case-insensitive (closes #1032)\n- Fix display of multipart messages from Apple Mail (closes #823)\n- Protect AJAX request from being fetched by a foreign site (XSS)\n- Make autocomplete for loginform configurable by the skin template\n- Fix compose function from address book (closes #1089)\n- Added //IGNORE to iconv call (patch #1086, closes #821)\n- Check if mbstring supports charset (#1003 and #1004)\n- Prefer iconv over mbstring (as suggested in #1004)\n- Check filesize of template includes (#1079)\n- Fixed bug with buttons not dimming/enabling properly after switching folders\n- Fixed compose window becoming unresponsive after saving a draft (#1132)\n- Re-enabled \"Back\" button in compose window now that bug #1132 is fixed\n- Fixed unresponsive interface issue when downloading attachments (#1138)\n- Lowered status message time from 5 to 3 seconds to improve responsiveness\n- Raised .htaccess upload_max_filesize from 2M to 5M to differ from default php.ini\n- Increased \"mailboxcontrols\" mail.css width from 160 to 170px to fix non-english languages (#1140)\n- Fix status message bug #1114 with regard to #1041\n- Fix address adding bug reported by David Koblas\n- Applied socket error patch by Thomas Mangin\n- Pass-by-reference workarround for PHP5 in sendmail.inc\n- Fixed buggy imap_root settings (closes #1056)\n- Prevent default events on subject links (#1071)\n- Use HTTP-POST requests for actions that change state", "RELEASE 0.1-RC1\n---------------\n- Use global filters and bind username/ for Ldap searches (#909)\n- Hide quota display if imap server does not support it\n- Hide address groups if no LDAP servers configured\n- Add link to message subjects (closes #982)\n- Better SQL query for contact listing/search (closes #1051)\n- Fixed marking as read in preview pane (closes #1048)\n- CSS hack to display attachments correctly in IE6\n- Wrap message body text (closes #901)\n- LDAP access is back in address book (closes #864)\n- Added search function for contacts\n- New Template parsing and output encoding\n- Fixed bugs #884 and #793\n- Fixed message moving procedure (closes #1013)\n- Fixed display of multiple attachments (closes #647)\n- Fixed check for new messages (closes #1015)\n- List attachments without filename\n- New session authentication: Change sessid cookie when login, authentication with sessauth cookie is now configurable.\n Should close bugs #774 and #1484299\n- Correctly translate mailbox names (closes #993)\n- Quote e-mail address links (closes #1007)\n- Updated PEAR::Mail_mime package\n- Accept single quotes for HTML attributes when modifying message body (thanks Jason)\n- Sanitize input for new users/identities (thanks Colin Alston)\n- Don't download HTML message parts\n- Convert HTML parts to plaintext if 'prefer_html' is off\n- Correctly parse message/rfc822 parts (closes #838)\n- Also use user_id for unique key in messages table (closes #857)\n- Hide contacts drop down on blur (closes #946)\n- Make entries in contacts drop down clickable\n- Turn off browser autocompletion on login page\n- Quote <? in text/html message parts\n- Hide border around radio buttons\n- Applied patch for attachment download by crichardson (closes #943)\n- Fixed bug in Postgres DB handling (closes #852)\n- Fixed bug of invalid calls to fetchRow() in rcube_db.inc (closes #996)\n- Fixed array_merge bug (closes #997)\n- Fixed flag for deletion in list view (closes #987)\n- Finally support semicolons as recipient separator (closes ##976)\n- Fixed message headers (subject) encoding\n- check if safe mode is on or not (closes #990)\n- Show \"no subject\" in message list if subject is missing (closes #971)\n- Solved page caching of message preview (closes #905)\n- Only use gzip compression if configured (closes #967)\n- Fixed priority selector issue (#903)\n- Fixed some CSS issues in default skin (closes #951 and #911)\n- Prevent from double quoting of numeric HTML character references (closes #978)\n- Fixed display of HTML message attachments (closes #927)\n- Applied patch for preview caching (closes #933)\n- Added error handling for attachment uploads\n- Use multibyte safe string functions where necessary (closes #798)\n- Applied security patch to validate the submitted host value (by Kees Cook)\n- Applied security patch to validate input values when deleting contacts (by Kees Cook)\n- Applied security patch that sanitizes emoticon paths when attaching them (by Kees Cook)\n- Applied a patch to more aggressively sanitize a HTML message\n- Visualize blocked images in HTML messages\n- Fixed wrong message listing when showing search results (closes #890)\n- Show remote images when opening HTML message part as attachment\n- Improve memory usage when sending mail (closes #871)\n- Mark messages as read once the preview is loaded (closes #1484132)\n- Include smtp final response in log (closes #862)\n- Corrected date string in sent message header (closes #887)\n- Correclty choose \"To\" column in sent and draft mailboxes (closes #769)\n- Changed srong tooltips for message browse buttons (closes #757)\n- Fixed signature delimiter character to be standard (Bug #830)\n- Fixed XSS vulnerability (Bug #877)\n- Remove newlines from mail headers (Bug #827)\n- Selection issues when moving/deleting (Bug #837)\n- Applied patch of Clement Moulin for imap host auto-selection\n- ISO-encode IMAP password for plaintext login (Bugs #792 & #723)\n- Fixed folder name encoding in subscription list (Bug #879)\n- Fixed JS errors in identity list (Bug #885)\n- Translate foldernames in folder form (closes #879)\n- Added first and last buttons to message list, address book\n and message detail\n- Pressing Shift-Del bypasses Trash folder\n- Enable purge command for Junk folder\n- Fetch all aliases if virtuser_query is used instead\n- Re-enabled multi select of contacts (Bug #817)\n- Enable contact editing right after creation (Bug #644)\n- Correct UTF-7 to UTF-8 conversion if mbstring is not available\n- Fixed IMAP fetch of message body (Bug #819)\n- Fixed safe_mode problems (Bug #539)\n- Fixed wrong header encoding (Bug #1483976)\n- Made automatic draft saving configurable\n- Fixed JS bug when renaming folders (Bug #799)\n- Added quota display as image (by Brett Patterson)\n- Corrected creation of a message-id\n- New indentation for quoted message text\n- Improved HTML validity\n- Fixed URL character set (Ticket #616)\n- Fixed saving of contact into MySQL from LDAP query results (Ticket #681)\n- Fixed folder renaming: unsubscribe before rename (Bug #750)\n- Finalized new message parsing (+ chaching)\n- Fixed wrong usage of mbstring (Bug #645)\n- Set default spelling language (Ticket #764)\n- Added support for Nox Spell Server\n- Re-built message parsing (Bug #422)\n Now based on the message structure delivered by the IMAP server.\n- Fixed some XSS and SQL injection issues\n- Fixed charset problems with folder renaming" ]
[ 1, 1, 0, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [15, 533, 355], "buggy_code_start_loc": [15, 415, 319], "filenames": ["CHANGELOG", "program/lib/Roundcube/rcube_washtml.php", "tests/Framework/Washtml.php"], "fixing_code_end_loc": [18, 590, 480], "fixing_code_start_loc": [16, 415, 320], "message": "Roundcube Webmail before 1.3.15 and 1.4.8 allows stored XSS in HTML messages during message display via a crafted SVG document. This issue has been fixed in 1.4.8 and 1.3.15.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:roundcube:webmail:*:*:*:*:*:*:*:*", "matchCriteriaId": "6AA0D87C-F59C-4A8D-8527-8171BEB076E0", "versionEndExcluding": "1.3.15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:roundcube:webmail:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F4ECE92-6974-4D4F-9900-5F0C548B912A", "versionEndExcluding": "1.4.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.4.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:32:*:*:*:*:*:*:*", "matchCriteriaId": "36D96259-24BD-44E2-96D9-78CE1D41F956", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Roundcube Webmail before 1.3.15 and 1.4.8 allows stored XSS in HTML messages during message display via a crafted SVG document. This issue has been fixed in 1.4.8 and 1.3.15."}, {"lang": "es", "value": "Roundcube Webmail versiones anteriores a 1.3.15 y 1.4.8, permite un ataque de tipo XSS almacenado en mensajes HTML durante la visualizaci\u00f3n de mensajes por medio de un documento SVG dise\u00f1ado. Este problema se ha solucionado en la versi\u00f3n 1.4.8 y versi\u00f3n 1.3.15."}], "evaluatorComment": null, "id": "CVE-2020-16145", "lastModified": "2023-01-20T21:00:58.090", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-08-12T13:15:10.457", "references": [{"source": "cve@mitre.org", "tags": ["Broken Link"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-09/msg00083.html"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/commit/a71bf2e8d4a64ff2c83fdabc1e8cb0c045a41ef4"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/commit/d44ca2308a96576b88d6bf27528964d4fe1a6b8b#diff-d3bb3391c79904494c60ee2ac2f33070"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/releases/tag/1.3.15"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/releases/tag/1.4.8"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/3DAXK3565NYK4OEZVTW6S5LEVIDQEY2E/"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/OBLUQRIBAMEQVBO6GUZECCHJDJIWCYFU/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/roundcube/roundcubemail/commit/a71bf2e8d4a64ff2c83fdabc1e8cb0c045a41ef4"}, "type": "CWE-79"}
184
Determine whether the {function_name} code is vulnerable or not.
[ "CHANGELOG Roundcube Webmail\n===========================", "- Security: Fix potential XSS issue in HTML editor of the identity signature input (#7507)\n- Managesieve: Fix too-small input field in Elastic when using custom headers (#7498)\n- Fix support for an error as a string in message_before_send hook (#7475)\n- Elastic: Fix redundant scrollbar in plain text editor on mail reply (#7500)\n- Elastic: Fix deleted and replied+forwarded icons on messages list (#7503)\n- Managesieve: Allow angle brackets in out-of-office message body (#7518)\n- Fix bug in conversion of email addresses to mailto links in plain text messages (#7526)\n- Fix format=flowed formatting on plain text part derived from the HTML content (#7504)\n- Fix incorrect rewriting of internal links in HTML content (#7512)\n- Fix handling links without defined protocol (#7454)\n- Fix paging of search results on IMAP servers with no SORT capability (#7462)\n- Fix detecting special folders on servers with both SPECIAL-USE and LIST-STATUS (#7525)", "- Security: Fix cross-site scripting (XSS) via HTML messages with malicious svg content [CVE-2020-16145]\n- Security: Fix cross-site scripting (XSS) via HTML messages with malicious math content", "\nRELEASE 1.4.7\n-------------\n- Fix bug where subfolders of special folders could have been duplicated on folder list\n- Increase maximum size of contact jobtitle and department fields to 128 characters\n- Fix missing newline after the logged line when writing to stdout (#7418)\n- Elastic: Fix context menu (paste) on the recipient input (#7431)\n- Fix problem with forwarding inline images attached to messages with no HTML part (#7414)\n- Fix problem with handling attached images with same name when using database_attachments/redundant_attachments (#7455)\n- Security: Fix cross-site scripting (XSS) via HTML messages with malicious svg/namespace", "RELEASE 1.4.6\n-------------\n- Installer: Fix regression in SMTP test section (#7417)", "RELEASE 1.4.5\n-------------\n- Fix bug in extracting required plugins from composer.json that led to spurious error in log (#7364)\n- Fix so the database setup description is compatible with MySQL 8 (#7340)\n- Markasjunk: Fix regression in jsevent driver (#7361)\n- Fix missing flag indication on collapsed thread in Larry and Elastic (#7366)\n- Fix default keyservers (use keys.openpgp.org), add note about CORS (#7373, #7367)\n- Password: Fix issue with Modoboa driver (#7372)\n- Mailvelope: Use sender's address to find pubkeys to check signatures (#7348)\n- Mailvelope: Fix Encrypt button hidden in Elastic (#7353)\n- Fix PHP warning: count(): Parameter must be an array or an object... in ID command handler (#7392)\n- Fix error when user-configured skin does not exist anymore (#7271)\n- Elastic: Fix aspect ratio of a contact photo in mail preview (#7339)\n- Fix bug where PDF attachments marked as inline could have not been attached on mail forward (#7382)\n- Security: Fix a couple of XSS issues in Installer (#7406)\n- Security: Fix XSS issue in template object 'username' (#7406)\n- Security: Better fix for CVE-2020-12641\n- Security: Fix cross-site scripting (XSS) via malicious XML attachment", "RELEASE 1.4.4\n-------------\n- Fix bug where attachments with Content-Id were attached to the message on reply (#7122)\n- Fix identity selection on reply when both sender and recipient addresses are included in identities (#7211)\n- Elastic: Fix text selection with Shift+PageUp and Shift+PageDown in plain text editor when using Chrome (#7230)\n- Elastic: Fix recipient input bug when using click to select a contact from autocomplete list (#7231)\n- Elastic: Fix color of a folder with recent messages (#7281)\n- Elastic: Restrict logo size in print view (#7275)\n- Fix invalid Content-Type for messages with only html part and inline images - Mail_Mime-1.10.7 (#7261)\n- Fix missing contact display name in QR Code data (#7257)\n- Fix so button label in Select image/media dialogs is \"Close\" not \"Cancel\" (#7246)\n- Fix regression in testing database schema on MSSQL (#7227)\n- Fix cursor position after inserting a group to a recipient input using autocompletion (#7267)\n- Fix string literals handling in IMAP STATUS (and various other) responses (#7290)\n- Fix bug where multiple images in a message were replaced by the first one on forward/reply/edit (#7293)\n- Fix handling keyservers configured with protocol prefix (#7295)\n- Markasjunk: Fix marking as spam/ham on moving messages with Move menu (#7189)\n- Markasjunk: Fix bug where moving to Junk was failing on messages selected with Select > All (#7206)\n- Fix so imap error message is displayed to the user on folder create/update (#7245)\n- Fix bug where a special folder couldn't be created if a special-use flag is not supported (#7147)\n- Mailvelope: Fix bug where recipients with name were not handled properly in mail compose (#7312)\n- Fix characters encoding in group rename input after group creation/rename (#7330)\n- Fix bug where some message/rfc822 parts could not be attached on forward (#7323)\n- Make install-jsdeps.sh script working without the 'file' program installed (#7325)\n- Fix performance issue of parsing big HTML messages by disabling HTML5 parser for these (#7331)\n- Fix so Print button for PDF attachments works on Firefox >= 75 (#5125)\n- Security: Fix XSS issue in handling of CDATA in HTML messages [CVE-2020-12625]\n- Security: Fix remote code execution via crafted 'im_convert_path' or 'im_identify_path' settings [CVE-2020-12641]\n- Security: Fix local file inclusion (and code execution) via crafted 'plugins' option [CVE-2020-12640]\n- Security: Fix CSRF bypass that could be used to log out an authenticated user [CVE-2020-12626] (#7302)", "RELEASE 1.4.3\n-------------\n- Enigma: Fix so key list selection is reset when opening key creation form (#7154)\n- Enigma: Fix so using list checkbox selection does not load the key preview frame\n- Enigma: Fix generation of key pairs for identities with IDN domains (#7181)\n- Enigma: Display IDN domains of key users and identities in UTF8\n- Enigma: Fix bug where \"Send unencrypted\" button didn't work in Elastic skin (#7205)\n- Managesieve: Fix bug where it wasn't possible to save flag actions (#7188)\n- Markasjunk: Fix bug where marking as spam/ham didn't work on moving messages with drag-and-drop (#7137)\n- Password: Make chpass-wrapper.py Python 3 compatible (#7135)\n- Elastic: Fix disappearing sidebar in mail compose after clicking Mail button\n- Elastic: Fix incorrect aria-disabled attribute on Mail taskmenu button in mail compose\n- Elastic: Fix bug where it was possible to switch editor mode when 'htmleditor' was in 'dont_override' (#7143)\n- Elastic: Fix text selection in recipient inputs (#7129)\n- Elastic: Fix missing Close button in \"more recipients\" dialog\n- Elastic: Fix non-working folder subscription checkbox for newly added folders (#7174)\n- Fix regression where \"Open in new window\" action didn't work (#7155)\n- Fix PHP Warning: array_filter() expects parameter 1 to be array, null given in subscriptions_option plugin (#7165)\n- Fix unexpected error message when mail refresh involves folder auto-unsubscribe (#6923)\n- Fix recipient duplicates in print-view when the recipient list has been expanded (#7169)\n- Fix bug where files in skins/ directory were listed on skins list (#7180)\n- Fix bug where message parts with no Content-Disposition header and no name were not listed on attachments list (#7117)\n- Fix display issues with mail subject that contains line-breaks (#7191)\n- Fix invalid Content-Transfer-Encoding on multipart messages - Mail_Mime fix (#7170)\n- Fix regression where using an absolute path to SQLite database file on Windows didn't work (#7196)\n- Fix using unix:///path/to/socket.file in memcached driver (#7210)", "RELEASE 1.4.2\n-------------\n- Plugin API: Make actionbefore, before<action>, actionafter and after<action> events working with plugin actions (#7106)\n- Managesieve: Replace \"Filter disabled\" with \"Filter enabled\" (#7028)\n- Managesieve: Fix so modifier type select wasn't hidden after hiding modifier select on header change\n- Managesieve: Fix filter selection after removing a first filter (#7079)\n- Markasjunk: Fix marking more than one message as spam/ham with email_learn driver (#7121)\n- Password: Fix kpasswd and smb drivers' double-escaping bug (#7092)\n- Enigma: Add script to import keys from filesystem to the db storage (for multihost)\n- Installer: Fix DB Write test on SQLite database (\"database is locked\" error) (#7064)\n- Installer: Fix so SQLite DSN with a relative path to the database file works in Installer\n- Elastic: Fix contrast of warning toasts (#7058)\n- Elastic: Simple search in pretty selects (#7072)\n- Elastic: Fix hidden list widget on mobile/tablet when selecting folder while search menu is open (#7120)\n- Fix so type attribute on script tags is not used on HTML5 pages (#6975)\n- Fix unread count after purge on a folder that is not currently selected (#7051)\n- Fix bug where Enter key didn't work on messages list in \"List\" layout (#7052)\n- Fix bug where deleting a saved search in addressbook caused display issue on sources/groups list (#7061)\n- Fix bug where a new saved search added after removing all searches wasn't added to the list (#7061)\n- Fix bug where a new contact group added after removing all groups from addressbook wasn't added to the list\n- Fix bug where Ctype extension wasn't required in Installer and INSTALL file (#7049)\n- Fix so install-jsdeps.sh removes Bootstrap's sourceMappingURL (#7035)\n- Fix so use of Ctrl+A does not scroll the list (#7020)\n- Fix/remove useless keyup event handler on username input in logon form (#6970)\n- Fix bug where cancelling switching from HTML to plain text didn't set the flag properly (#7077)\n- Fix bug where HTML reply could add an empty line with extra indentation above the original message (#7088)\n- Fix matching multiple X-Forwarded-For addresses with 'proxy_whitelist' (#7107)\n- Fix so displayed maximum attachment size depends also on 'max_message_size' (#7105)\n- Fix bug where 'skins_allowed' option didn't enforce user skin preference (#7080)\n- Fix so contact's organization field accepts up to 128 characters (it was 50)\n- Fix bug where listing tables in PostgreSQL database with db_prefix didn't work (#7093)\n- Fix bug where 'text' attribute on body tag was ignored when displaying HTML message (#7109)\n- Fix bug where next message wasn't displayed after delete in List mode (#7096)\n- Fix so number of contacts in a group is not limited to 200 when redirecting to mail composer from Contacts (#6972)\n- Fix malformed characters in HTML message with charset meta tag not in head (#7116)", "RELEASE 1.4.1\n-------------\n- Elastic: Change HTML editor widget to improve form flow (#6992)\n- Elastic: Fix position of mobile floating action button (#7038)\n- Managesieve: Fix locked UI after opening filter frame (#7007)\n- Fix PHP warning: \"array_merge(): Expected parameter 2 to be an array, null given in sendmail.inc (#7003)\n- Fix bug where cache keys could exceed length limit specified in db schema (#7004)\n- Fix invalid Signature button state after escaping Mailvelope mode (#7015)\n- Fix so 401 error is returned only on failed logon requests (#7010)\n- Fix db_prefix handling in queries with `TRUNCATE TABLE <name>` and `UNIQUE <name>` (#7013)\n- Fix so update.sh script warns about changed defaults (#7011)\n- Fix tables listing routine when DSN contained a database with unsupported suffix (#7034)\n- Fix so Elastic is also a default in jqueryui plugin (#7039)\n- Fix bug where the Installer would not warn about required schema upgrade (#7042)", "RELEASE 1.4.0\n-------------\n- Elastic: Resizeable columns (#6929)\n- Elastic: Fix position and style of auto-complete dropdown on small screens (#6951)\n- Elastic: Fix initial focus on recipients input in mail compose screen\n- Elastic: Fix inserting responses at cursor position (#6971)\n- Elastic: Fix unread filter icon and search state on folder change (#6978)\n- Elastic: Fix regression where Encrypt button wasn't displayed in mail compose toolbar (#6982)\n- Elastic: Fix regression where recipient input didn't update internal input state (#6988)\n- Enigma: Fix bug where signing option was set to disabled after saving a draft in Elastic skin (#6515)\n- Redis: Improve error handling and phpredis 5.X support (#6888)\n- Archive: Fix bug where next email was not displayed after Archive button use (#6965)\n- Archive: Fix missing Archive icon in folder selector popup in Elastic\n- Fix bug where cache keys were not case-sensitive on MySQL/MSSQL (#6942)\n- Fix so an error is logged when encryption fails (#6948)\n- Fix bug where inline images could have been ignored if Content-Id header contained redundant spaces (#6980)\n- Fix and document skin_logo setup (#6981)", "RELEASE 1.4-rc2\n---------------\n- Update to jQuery 3.4.1\n- Clarified 'address_book_type' option behavior (#6680)\n- Added cookie mismatch detection, display an error message informing the user to clear cookies\n- Renamed 'log_session' option to 'session_debug'\n- Removed 'delete_always' option (#6782)\n- Don't log full session identifiers in userlogins log (#6625)\n- Support $HasAttachment/$HasNoAttachment keywords (#6201)\n- Support PECL memcached extension as a session and cache storage driver (experimental)\n- Switch to IDNA2008 variant (#6806)\n- installto.sh: Add possibility to run the update even on the up-to-date installation (#6533)\n- Plugin API: Add 'render_folder_selector' hook\n- Added 'keyservers' option to define list of HKP servers for Enigma/Mailvelope (#6326)\n- Added flag to disable server certificate validation via Mysql DSN argument (#6848)\n- Select all records on the current list page with CTRL + A (#6813)\n- Use Left/Right Arrow keys to faster move over threaded messages list (#6399)\n- Changes in `display_next` setting (#6795):\n - Move it to Preferences > User Interface > Main Options\n - Make it apply to Contacts interface too\n - Make it apply only if deleting/moving a previewed message/contact\n- Redis: Support connection to unix socket\n- Put charset meta specification before a title tag, add page title automatically (#6811)\n- Elastic: Various internal refactorings\n- Elastic: Add Prev/Next buttons on message page toolbar (#6648)\n- Elastic: Close search options on Enter key press in quick-search input (#6660)\n- Elastic: Changed some icons (#6852)\n- Elastic: Changed read/unread icons (#6636)\n- Elastic: Changed \"Move to...\" icon (#6637)\n- Elastic: Add hide/show for advanced preferences (#6632)\n- Elastic: Add default icon on Settings/Preferences lists for external plugins (#6814)\n- Elastic: Add indicator for popover menu items that open a submenu (#6868)\n- Elastic: Move compose attachments/options to the right side (#6839)\n- Elastic: Add border/background to attachments list widget (#6842)\n- Elastic: Add \"Show unread messages\" button to the search bar (#6587)\n- Elastic: Fix bug where toolbar disappears on attachment menu use in Chrome (#6677)\n- Elastic: Fix folders list scrolling on touch devices (#6706)\n- Elastic: Fix non-working pretty selects in Chrome browser (#6705)\n- Elastic: Fix issue with absolute positioned mail content (#6739)\n- Elastic: Fix bug where some menu actions could cause a browser popup warning\n- Elastic: Fix handling mailto: URL parameters in contact menu (#6751)\n- Elastic: Fix keyboard navigation in some menus, e.g. the contact menu\n- Elastic: Fix visual issue with long buttons in .boxwarning (#6797)\n- Elastic: Fix handling new-line in text pasted to a recipient input\n- Elastic: Fix so search is not reset when returning from the message preview page (#6847)\n- Larry: Fix regression where menu actions didn't work with keyboard (#6740)\n- ACL: Display user/group names (from ldap) instead of acl identifier\n- Password: Added ldap_exop driver (#4992)\n- Password: Added support for SSHA512 password algorithm (#6805)\n- Managesieve: Fix bug where global includes were requested for vacation (#6716)\n- Managesieve: Use RFC-compliant line endings, CRLF instead of LF (#6686)\n- Managesieve: Fix so \"Create filter\" option does not show up when Filters menu is disabled (#6723)\n- Enigma: For verified signatures, display the user id associated with the sender address (#5958)\n- Enigma: Fix bug where revoked users/keys were not greyed out in key info\n- Enigma: Fix error message when trying to encrypt with a revoked key (#6607)\n- Enigma: Fix \"decryption oracle\" bug [CVE-2019-10740] (#6638)\n- Enigma: Fix bug where signature verification could have been skipped for some message structures (#6838)\n- Fix language selection for spellchecker in html mode (#6915)\n- Fix css styles leak from replied/forwarded message to the rest of the composed text (#6831)\n- Fix invalid path to \"add contact\" icon when using assets_path setting\n- Fix invalid path to blocked.gif when using assets_path setting (#6752)\n- Fix so advanced search dialog is not automatically displayed on searchonly addressbooks (#6679)\n- Fix so an error is logged when more than one attachment plugin has been enabled, initialize the first one (#6735)\n- Fix bug where flag change could have been passed to a preview frame when not expected\n- Fix bug in HTML parser that could cause missing text fragments when there was no head/body tag (#6713)\n- Fix bug where HTML messages with a xml:namespace tag were not rendered (#6697)\n- Fix TinyMCE download location (#6694)\n- Fix so \"Open in new window\" consistently displays \"external window\" interface (#6659)\n- Fix bug where next row wasn't selected after deleting a collapsed thread (#6655)\n- Fix bug where external content (e.g. mail body) was passed to templates parsing code (#6640)\n- Fix bug where attachment preview didn't work with x_frame_options=deny (#6688)\n- Fix so bin/install-jsdeps.sh returns error code on error (#6704)\n- Fix bug where bmp images couldn't be displayed on some systems (#6728)\n- Fix bug in parsing vCard data using PHP 7.3 due to an invalid regexp (#6744)\n- Fix bug where bold/strong text was converted to upper-case on html-to-text conversion (6758)\n- Fix bug in rcube_utils::parse_hosts() where %t, %d, %z could return only tld (#6746)\n- Fix bug where Next/Prev button in mail view didn't work with multi-folder search result (#6793)\n- Fix bug where selection of columns on messages list wasn't working\n- Fix bug in converting multi-page Tiff images to Jpeg (#6824)\n- Fix bug where handling multiple messages from multi-folder search result could not work (#6845)\n- Fix bug where unread count wasn't updated after moving multi-folder result (#6846)\n- Fix wrong messages order after returning to a multi-folder search result (#6836)\n- Fix some PHP 7.4 compat. issues (#6884, #6866)\n- Fix bug where it was possible to bypass the position:fixed CSS check in received messages (#6898)\n- Fix bug where some strict remote URIs in url() style were unintentionally blocked (#6899)\n- Fix bug where it was possible to bypass the CSS jail in HTML messages using :root pseudo-class (#6897)\n- Fix bug where it was possible to bypass href URI check with data:application/xhtml+xml URIs (#6896)", "RELEASE 1.4-rc1\n---------------\n- Changed 'password_charset' default to 'UTF-8' (#6522)\n- Add skins_allowed option (#6483)\n- SMTP GSSAPI support via krb_authentication plugin (#6417)\n- Avoid Referer leaking by using Referrer-Policy:same-origin header (#6385)\n- Removed 'referer_check' option (#6440)\n- Use constant prefix for temp file names, don't remove temp files from other apps (#6511)\n- Ignore 'Sender' header on Reply-All action (#6506)\n- deluser.sh: Add option to delete users who have not logged in for more than X days (#6340)\n- HTML5 Upload Progress - as a replacement for the old server-side solution (#6177)\n- Update to TinyMCE 4.8.2\n- Update to jQuery-MiniColors 2.3.4\n- Prevent from using deprecated timezone names from jsTimezoneDetect\n- Force session.gc_probability=1 when using custom session handlers (#6560)\n- Support simple field labels (e.g. LetterHub examples) in csv imports (#6541)\n- Add cache busters also to images used by templates (#6610)\n- Plugin API: Added 'raise_error' hook (#6199)\n- Plugin API: Added 'common_headers' hook (#6385)\n- Plugin API: Added 'ldap_connected' hook\n- Enigma: Update to OpenPGPjs 4.2.1 - fixes user name encoding issues in key generation (#6524)\n- Enigma: Fixed multi-host synchronization of private and deleted keys and pubring.kbx file\n- Managesieve: Added support for 'editheader' extension - RFC5293 (#5954)\n- Managesieve: Fix bug where custom header or variable could be lost on form submission (#6594)\n- Markasjunk: Integrate markasjunk2 features into markasjunk - marking as non-junk + learning engine (#6504)\n- Password: Added 'modoboa' driver (#6361)\n- Password: Fix bug where password_dovecotpw_with_method setting could be ignored (#6436)\n- Password: Fix bug where new users could skip forced password change (#6434)\n- Password: Allow drivers to override default password comparisons (eg new is not same as current) (#6473)\n- Password: Allow drivers to override default strength checks (eg allow for 'not the same as last x passwords') (#246)\n- Passowrd: Allow drivers to define password strength rules displayed to the user\n- Password: Allow separate password saving and strength drivers for use of strength checking services (#5040)\n- Password: Add zxcvbn driver for checking password strength (#6479)\n- Password: Disallow control characters in passwords\n- Password: Add support for Plesk >= 17.8 (#6526)\n- Elastic: Improved datepicker displayed always in parent window\n- Elastic: On touch devices display attachment icons on messages list (#6296)\n- Elastic: Make menu button inactive if all subactions are inactive (#6444)\n- Elastic: On mobile/tablet jump to the list on folder selection (#6415)\n- Elastic: Various improvements on mail compose screen (#6413)\n- Elastic: Support new-line char as a separator for pasted recipients (#6460)\n- Elastic: Improved UX of search dialogs (#6416)\n- Elastic: Fix unwanted thread expanding when selecting a collapsed thread in non-mobile mode (#6445)\n- Elastic: Fix too small height of mailvelope mail preview frame (#6600)\n- Elastic: Add \"status bar\" for mobile in mail composer\n- Elastic: Add selection options on contacts list (#6595)\n- Elastic: Fix unintentional layout preference overwrite (#6613)\n- Elastic: Fix bug where Enigma options in mail compose could sometimes be ignored (#6515)\n- Log errors caused by low pcre.backtrack_limit when sending a mail message (#6433)\n- Fix regression where drafts were not deleted after sending the message (#6756)\n- Fix so max_message_size limit is checked also when forwarding messages as attachments (#6580)\n- Fix so performance stats are logged to the main console log also when per_user_logging=true\n- Fix malformed message saved into Sent folder when using big attachments and low memory limit (#6498)\n- Fix incorrect IMAP SASL GSSAPI negotiation (#6308)\n- Fix so unicode in local part of the email address is also supported in recipient inputs (#6490)\n- Fix bug where autocomplete list could be displayed out of screen (#6469)\n- Fix style/navigation on error page depending on authentication state (#6362)\n- Fix so invalid smtp_helo_host is never used, fallback to localhost (#6408)\n- Fix custom logo size in Elastic (#6424)\n- Fix listing the same attachment multiple times on forwarded messages\n- Fix bug where a message/rfc822 part without a filename wasn't listed on the attachments list (#6494)\n- Fix inconsistent offset for various time zones - always display Standard Time offset (#6531)\n- Fix dummy Message-Id when resuming a draft without Message-Id header (#6548)\n- Fix handling of empty entries in vCard import (#6564)\n- Fix bug in parsing some IMAP command responses that include unsolicited replies (#6577)\n- Fix PHP 7.2 compatibility in debug_logger plugin (#6586)\n- Fix so ANY record is not used for email domain validation, use A, MX, CNAME, AAAA instead (#6581)\n- Fix so mime_content_type check in Installer uses files that should always be available (i.e. from program/resources) (#6599)\n- Fix missing CSRF token on a link to download too-big message part (#6621)\n- Fix bug when aborting dragging with ESC key didn't stop the move action (#6623)", "RELEASE 1.4-beta\n----------------\n- Added new skin with mobile support - the Elastic\n- Support Redis cache\n- Email Resent (Bounce) feature (#4985)\n- Improved Mailvelope integration\n - Added private key listing and generating to identity settings\n - Enable encrypt & sign option if Mailvelope supports it\n- Allow contacts without an email address (#5079)\n- Support SMTPUTF8 and relax email address validation to support unicode in local part (#5120)\n- Support for IMAP folders that cannot contain both folders and messages (#5057)\n- Update to jQuery-3.3.1\n- Update to jQuery-minicolors 2.2.6\n- Update to TinyMCE 4.7.13\n- Remove sample PHP configuration from .htaccess and .user.ini files (#5850)\n- Extend skin_logo setting to allow per skin logos (#6272)\n- Use Masterminds/HTML5 parser for better HTML5 support (#5761)\n- Add More actions button in Contacts toolbar with Copy/Move actions (#6081)\n- Display an error when clicking disabled link to register protocol handler (#6079)\n- Add option trusted_host_patterns (#6009, #5752)\n- Support additional connect parameters in PostgreSQL database wrapper\n- Use UI dialogs instead of confirm() and alert() where possible\n- Display value of the SMTP message size limit in the error message (#6032)\n- Show message flagged status in message view (#5080)\n- Skip redundant INSERT query on successful logon when using PHP7\n- Replace display_version with display_product_version (#5904)\n- Extend disabled_actions config so it accepts also button names (#5903)\n- Handle remote stylesheets the same as remote images, ask the user to allow them (#5994)\n- Add Message-ID to the sendmail log (#5871)\n- Add option to hide folders in share/other-user namespace or outside of the personal namespace root (#5073)\n- Archive: Fix archiving by sender address on cyrus-imap\n- Archive: Style Archive folder also on folder selector and folder manager lists\n- Archive: Add Thunderbird compatible Month option (#5623)\n- Archive: Create archive folder automatically if it's configured, but does not exist (#6076)\n- Enigma: Add button to send mail unencrypted if no key was found (#5913)\n- Enigma: Add options to set PGP cipher/digest algorithms (#5645)\n- Enigma: Multi-host support\n- Managesieve: Add ability to disable filter sets and other actions (#5496, #5898)\n- Managesieve: Add option managesieve_forward to enable settings dialog for simple forwarding (#6021)\n- Managesieve: Support filter action with custom IMAP flags (#6011)\n- Managesieve: Support 'mime' extension tests - RFC5703 (#5832)\n- Managesieve: Support GSSAPI authentication with krb_authentication plugin (#5779)\n- Managesieve: Support enabling the plugin for specified hosts only (#6292)\n- Password: Support host variables in password_db_dsn option (#5955)\n- Password: Automatic virtualmin domain setting, removed password_virtualmin_format option (#5759)\n- Password: Added password_username_format option (#5766)\n- subscriptions_option: show \\\\Noselect folders greyed out (#5621)\n- zipdownload: Added option to define size limit for multiple messages download (#5696)\n- vcard_attachments: Add possibility to send contact vCard from Contacts toolbar (#6080)\n- Changed defaults for smtp_user (%u), smtp_pass (%p) and smtp_port (587)\n- Composer: Fix certificate validation errors by using packagist only (#5148)\n- Add --get and --extract arguments and CACHEDIR env-variable support to install-jsdeps.sh (#5882)\n- Support _filter and _scope as GET arguments for opening mail UI (#5825)\n- Various improvements for templating engine and skin behaviours\n - Support conditional include\n - Support for 'link' objects\n - Support including files with path relative to templates directory\n - Use <button> instead of <input> for submit button on logon screen\n- Support skin localization (#5853)\n- Reset onerror on images if placeholder does not exist to prevent from requests storm\n- Unified and simplified code for loading content frame for responses and identities\n- Display contact import and advanced search in popup dialogs\n- Display a dialog for mail import with supported format description and upload size hint\n- Make possible to set (some) config options from a skin\n- Added optional checkbox selection for the list widget\n- Make 'compose' command always enabled\n- Add .log suffix to all log file names, add option log_file_ext to control this (#313)\n- Return \"401 Unauthorized\" status when login fails (#5663)\n- Support both comma and semicolon as recipient separator, drop recipients_separator option (#5092)\n- Plugin API: Added 'show_bytes' hook (#5001)\n- Add option to not indent quoted text on top-posting reply (#5105)\n- Removed global $CONFIG variable\n- Removed debug_level setting\n- Support AUTHENTICATE LOGIN for IMAP connections (#5563)\n- Support LDAP GSSAPI authentication (#5703)\n- Localized timezone selector (#4983)\n- Use 7bit encoding for ISO-2022-* charsets in sent mail (#5640)\n- Handle inline images also inside multipart/mixed messages (#5905)\n- Allow style tags in HTML editor on composed/reply messages (#5751)\n- Use Github API as a fallback to fetch js dependencies to workaround throttling issues (#6248)\n- Show confirm dialog when moving folders using drag and drop (#6119)\n- Fix bug where new_user_dialog email check could have been circumvented by deleting / abandoning session (#5929)\n- Fix skin extending for assets (#5115)\n- Fix handling of forwarded messages inside of a TNEF message (#5632)\n- Fix bug where attachment size wasn't visible when the filename was too long (#6033)\n- Fix checking table columns when there's more schemas/databases in postgres/mysql (#6047)\n- Fix css conflicts in user interface and e-mail content (#5891)\n- Fix duplicated signature when using Back button in Chrome (#5809)\n- Fix touch event issue on messages list in IE/Edge (#5781)\n- Fix so links over images are not removed in plain text signatures converted from HTML (#4473)\n- Fix various issues when downloading files with names containing non-ascii chars, use RFC 2231 (#5772)", "RELEASE 1.3.8\n-------------\n- Fix PHP warnings on dummy QUOTA responses in Courier-IMAP 4.17.1 (#6374)\n- Fix so fallback from BINARY to BODY FETCH is used also on [PARSE] errors in dovecot 2.3 (#6383)\n- Enigma: Fix deleting keys with authentication subkeys (#6381)\n- Fix invalid regular expressions that throw warnings on PHP 7.3 (#6398)\n- Fix so Classic skin splitter does not escape out of window (#6397)\n- Fix XSS issue in handling invalid style tag content [CVE-2018-19206] (#6410)\n- Fix compatibility with MySQL 8 - error on 'system' table use\n- Managesieve: Fix bug where show_real_foldernames setting wasn't respected (#6422)\n- New_user_identity: Fix %fu/%u vars substitution in user specific LDAP params (#6419)\n- Fix support for \"allow-from <uri>\" in \"x_frame_options\" config option (#6449)\n- Fix bug where valid content between HTML comments could have been skipped in some cases (#6464)\n- Fix multiple VCard field search (#6466)\n- Fix session issue on long running requests (#6470)", "RELEASE 1.3.7\n-------------\n- Fix PHP Warning: Use of undefined constant IDNA_DEFAULT on systems without php-intl (#6244)\n- Fix bug where some parts of quota information could have been ignored (#6280)\n- Fix bug where some escape sequences in html styles could bypass security checks\n- Fix bug where some forbidden characters on Cyrus-IMAP were not prevented from use in folder names\n- Fix bug where only attachments with the same name would be ignored on zip download (#6301)\n- Fix bug where unicode contact names could have been broken/emptied or caused DB errors (#6299)\n- Fix bug where after \"mark all folders as read\" action message counters were not reset (#6307)\n- Enigma: [EFAIL] Don't decrypt PGP messages with no MDC protection (#6289)\n- Fix bug where some HTML comments could have been malformed by HTML parser (#6333)", "RELEASE 1.3.6\n-------------\n- Fix parsing date strings (e.g. from a Date: mail header) with comments (#6216)\n- Fix PHP 7.2: count(): Parameter must be an array in enchant-based spellchecker (#6234)\n- Fix possible IMAP command injection and type juggling vulnerabilities (#6229)\n- Enigma: Fix key selection for signing\n- Enigma: Enable keypair generation on Internet Explorer 11\n- Fix check_request() bypass in places using get_uids() [CVE-2018-9846] (#6238)\n- Fix bug where usernames without domain part could be malformed or converted to lower-case on logon (#6224)", "RELEASE 1.3.5\n-------------\n- Managesieve: Fix bug where text: syntax was forced for strings longer than 1024 characters (#6143)\n- Managesieve: Fix missing Save button in Edit Filter Set page of Classic skin (#6154)\n- Fix duplicated labels in Test SMTP Config section (#6166)\n- Fix PHP Warning: exif_read_data(...): Illegal IFD size (#6169)\n- Enigma: Fix key generation in Safari by upgrade to OpenPGP 2.6.2 (#6149)\n- Fix security issue in remote content blocking on HTML image and style tags (#6178)\n- Added 9pt and 11pt to the list of font sizes in HTML editor\n- Fix handling encoding of HTML tags in \"inline\" JSON output (#6207)\n- Fix bug where some unix timestamps were not handled correctly by rcube_utils::anytodatetime() (#6212)", "RELEASE 1.3.4\n-------------\n- Fix bug where contacts search could skip some records (#6130)\n- Fix possible information leak - add more strict sql error check on user creation (#6125)\n- Fix a couple of warnings on PHP 7.2 (#6098)\n- Fix broken long filenames when using imap4d server - workaround server bug (#6048)\n- Fix so temp_dir misconfiguration prints an error to the log (#6045)\n- Fix untagged COPYUID responses handling - again (#5982)\n- Fix PHP warning \"idn_to_utf8(): INTL_IDNA_VARIANT_2003 is deprecated\" with PHP 7.2 (#6075)\n- Fix bug where Archive folder wasn't auto-created on login with create_default_folders=true\n- Fix performance issue when parsing malformed and long Date header (#6087)\n- Fix syntax error in mssql.initial.sql (#6097)\n- Fix bug where contacts export by selection returned no more than 10 entries (#6103)\n- Fix searching contacts by address in LDAP source (#6084)\n- Fix X-Frame-Options:ALLOW-FROM support, remove custom click-jacking protection (#6057)", "RELEASE 1.3.3\n-------------\n- Fix decoding of mailto: links with + character in HTML messages (#6020)\n- Fix false reporting of failed upgrade in installto.sh (#6019)\n- Fix file disclosure vulnerability caused by insufficient input validation [CVE-2017-16651] (#6026)\n- Fix mangled non-ASCII characters in links in HTML messages (#6028)", "RELEASE 1.3.2\n-------------\n- Fix bug where pink image was used instead of a thumbnail when image resize fails (#5933)\n- Fix so files size/count limit is verified (client-side) also on drag-n-drop uploads (#5940)\n- Fix invalid template loading on a message error in preview frame (#5941)\n- Fix bug where HTML messages could have been rendered empty on some systems (#5957)\n- Fix wording of \"Mark previewed messages as read\" to \"Mark messages as read\" (#5952)\n- Enigma: Fix decryption of messages encoded with non-ascii charset (#5962)\n- Fix missing cursor in HTML editor on mail reply (#5969)\n- Fix (again) bug where image data URIs in css style were treated as evil/remote in mail preview (#5580)\n- Fix bug where mail search could return empty result on servers without SORT capability (#5973)\n- Fix bug where assets_path wasn't added to some watermark frames\n- Fix so untagged COPYUID responses are also supported according to RFC6851 (#5982)\n- Fix issue caused by non-default session.cookie_lifetime setting (#5961)\n- Fix Edge encoding bug when pasting text into the HTML editor, update to TinyMCE 4.5.8 (#5885)\n- Fix handling of unknown Content-Disposition type (#6002)\n- Fix truncated folder name on messages list in multi-folder mode, for folders with non-ascii characters (#6004)\n- Fix bug where removing the last subfolder did not hide toggle button on its parent record (#6007)\n- Fix bug where ghost messages could be added to the list after fast delete (#5941)", "RELEASE 1.3.1\n-------------\n- Add Preferences > Mailbox View > Main Options > Layout (#5829)\n- Password: Fix compatibility with PHP 7+ in cpanel_webmail driver (#5820)\n- Managesieve: Fix parsing dot-staffed lines in multiline text (#5838)\n- Managesieve: Fix AM/PM suffix in vacation time selectors\n- Managesieve: Fix bug where 'exists' operator was reset to 'contains' (#5899)\n- Remove non-printable characters from filenames on download/display (#5880)\n- Fix decoding non-ascii attachment names from TNEF attachments (#5646, #5799)\n- Fix uninitialized string offset in rcube_utils::bin2ascii() and make sure rcube_utils::random_bytes() result has always requested length (#5788)\n- Fix bug where HTML messages with @media styles could moddify style of page body (#5811)\n- Fix style issue on selected and unfocused message that is part of a thread (#5798)\n- Fix bug where a.button style from managesieve plugin could impact other elements (#5800)\n- Fix position of selected icon for (Mailvelope) Encrypt button\n- Fix fatal error when using DMY- or MDY-based date format in PostgreSQL (#5808)\n- Fix bug where errors were not printed when using bin/update.sh (#5834)\n- Fix PHP 7.2 warnings on count() use (#5845)\n- Fix bug where Chrome could not upload the same file that was selected before (#5854)\n- Fix duplicate messages on the list after deleting messages on the next to the last page (#5862)\n- Fix bug where messages count was not updated after delete when imap_cache is set (#5872)\n- Fix potential XSS vulnerability with malformed HTML message markup\n- Fix sending message with \"Too many public recipients\" dialog buttons (#5924)\n- Bring back double-click behavior on the message list which was removed in 1.3.0 (#5823)\n- Enigma: Fix decrypting an encrypted+signed message when signature verification fails (#5914)", "RELEASE 1.3.0\n-------------\n- Update to TinyMCE 4.5.7\n- Fix bug where invalid recipients could be silently discarded (#5739)\n- Fix conflict with _gid cookie of Google Analytics (#5748)\n- Print error from CLI scripts when system/exec function is disabled (#5744)\n- Fix bug where comment notation within style tag would cause the whole style to be ignored (#5747)\n- Fix bug where it wasn't possible to scroll folders list in Edge (#5750)\n- Fix folders list sorting on Windows - if php-intl is available (#5732)\n- Fix addressbook searching by gender (#5757)\n- Fix prevention from using % and * characters in folder name (#5762)\n- Fix POST parameter reflection in default_charset selector (#5768)\n- Enigma: Fix compatibility with assets_dir\n- Managesieve: Skip redundant LISTSCRIPTS command\n- Fix SQL syntax error on MariaDB 10.2 (#5774)\n- Fix bug where zipdownload ignored files with the same name (#5777)\n- Fix bug where it wasn't possible to set timezone to auto-detected value (#5782)", "RELEASE 1.3-rc\n--------------\n- \"Flattened\" the larry theme: fresher look by removing shadows and gradients\n- Support logging to php://stdout (#5721)\n- Add support for DelSp=Yes in format=flowed messages (#5702)\n- Update to jQuery 3.2.1\n- Update to TinyMCE 4.5.6\n- Plugin API: Call message_part_structure hook for sub-parts of multipart/alternative message (#5678)\n- Enigma: Always use detached signatures (#5624)\n- Enigma: Fix handling of messages with nested PGP encrypted parts (#5634)\n- Minimize unwanted message loading in preview frame on drag (#5616)\n- Fix failing database schema check in all engines except mysql (#5730)\n- Fix autocomplete popup closing with click outside the input, don't handle Tab key as Enter (#5606)\n- Fix jsdeps.json synchronization on update, warn about missing requirements of install-jsdeps.sh (#5598)\n- Fix missing thread expand icon on search result in widescreen mode (#5613)\n- Fix bug where image data URIs in css style were treated as evil/remote in mail preview (#5580)\n- Fix bug where external content in src attribute of input/video tags was not secured (#5583)\n- Fix PHP error on update of a contact with multiple email addresses when using PHP 7.1 (#5587)\n- Fix bug where mail content frame couldn't be reset in some corner cases (#5608)\n- Fix bug where some classic skin images were not displayed in IE/Edge (#5614)\n- Fix bug where signature couldn't be added above the quote in Firefox 51 (#5628)\n- Fix regression where groups with email address were resolved to its members' addresses\n- Fix update of group name in the contacts list header on group rename (#5648)\n- Add rewrite rule to disable access to /vendor/bin folder in .htaccess (#5630)\n- Fix bug where it was too easy accidentally move a folder when using the subscription checkbox (#5655)\n- Managesieve: Fix parser issue with empty lines between comments (#5657)\n- Managesieve: Fix possible defect in handling \\r\\n in scripts (#5685)\n- Fix/rephrase \"unsaved changes\" warning when cancelling a draft (#5610)\n- Fix XSS issue in handling of a style tag inside of an svg element [CVE-2017-6820]\n- Fix bug where settings/upload.inc could not be used by plugins (#5694)\n- Fix regression in LDAP fuzzy search where it always used prefix search instead (#5713)\n- Fix bug where namespace prefix could not be truncated on folders list if show_real_foldernames=true (#5695)\n- Fix undesired effects when postgres database uses different timezone than PHP host (#5708)\n- Installer: Fix DB schema initialization on MS SQL Server\n- Fix bug where base_dn setting was ignored inside group_filters (#5720)\n- Password: Fix security issue in virtualmin and sasl drivers [CVE-2017-8114]", "RELEASE 1.3-beta\n----------------\n- Nicely handle contact deletion on contact edit (#5522)\n- vcard_attachments: Add possibility to attach contact vCard to composed message (#4997)\n- Preserve message internal/received date on import in mbox format (#5559)\n- Zipdownload: Fix date format in mbox \"From line\"\n- Possibility to display QR code for contacts data (#5030)\n- Added identicon plugin\n- Widescreen layout aka three column view (#5093)\n- Unify automatic marking as \\Seen in preview pane, full-page and extwin views (#5071)\n- Disable double-click on the list when preview pane is on (#5199)\n- Support hostname and hostname:port in force_https option (#5511)\n- Support ALLOW-FROM in x_frame_options (#5122)\n- Allow to omit a subject when sending an email (#5068)\n- Warn about too many disclosed recipients in composed email [max_disclosed_recipients] (#5132)\n- identity_select: Support Received header (#5085)\n- Plugin API: Added get_compose_responses hook (#5457)\n- Display error when trying to upload more files than specified in max_file_uploads (#5483)\n- Add missing sql upgrade file for 'ip' column resize in session table (#5465)\n- Do not show inline images of unsupported mimetype (#5463)\n- Password: Added replacement variables support in password_pop_host (#5539)\n- Password: Don't store passwords in temp files when using dovecotpw (#5531)\n- Password: Added LDAP PPolicy driver (#5364)\n- Password: Added cpanel_webmail driver (#5549)\n- Password: Added possibility to nicely redirect from other plugins on password expiration (#5468)\n- Implement separate action to mark all messages in a folder as \\Seen (#5006)\n- Implement marking as \\Seen in all folders or in a folder and its subfolders (#5076)\n- Archive: Don't reload messages list when it's not needed (#5225)\n- Archive: Add option to automatically mark archived messages as \\Seen (#5142)\n- Improve randomness of password salts and random hashes (#5266)\n- Password/cPanel: Add support for hash authentication and reseller accounts (#5252)\n- Support host-specific imap_conn_options/smtp_conn_options/managesieve_conn_options (#5136)\n- Center and scale images in attachment preview frame (#5421)\n- Added max_message_size option enforced when attaching files to a composed message (#4993)\n- Added Search button in quick search menus (#5312)\n- Implement \"one click\" attachment/messages/photo upload (#5024)\n- Squirrelmail_usercopy: Add option to define character set of data files\n- Removed useless 'created' column from 'session' table (#5389)\n- Dropped legacy browsers support (#5167)\n - Removed legacy_browser plugin\n - Removed hacks for IE < 10\n - Update to jQuery 3.1.1 and jQuery-UI 1.12.0\n - compile .min.js files with ECMASCRIPT5 option\n- Require PHP >= 5.4\n- Add possibility to preview and download attachments in mail compose (#5053)\n- Add possibility to rename attachments in mail compose (#4996)\n- Remove backward compatibility \"layer\" of bc.php (#4902)\n- Support WEBP images in mail messages (#5362)\n- Support MathML in HTML message preview (#5182)\n- Rename Addressbook to Contacts (#5233)\n- Remove PHP mail() support, smtp_server is required now (#5340)\n- Display full message subject in onmouseover on truncated subject in mail view (#5346)\n- Enigma: Support GnuPG 2.1 (#5313)\n- Enigma: Support key generation for multiple identities (#5383)\n- Enigma: Import keys from key-server(s) (#5286)\n- Enigma: Search missing public keys on a key-server in mail compose (#5286)\n- Enigma: Delete user keys when using deluser.sh script\n- Enigma: Fix redundant list-secret-keys/list-public-keys calls on signing/encryption\n- Enigma: Implement PGP encryption and signing in one go (#5302)\n- Enigma: Display signature verification status for encrypted+signed messages (#5302)\n- Display different attachment icon on encrypted messages\n- Display different confirmation text when moving messages to Trash (#5220)\n- Indicate that a collapsed thread has flagged children (#5013)\n- Implemented message/rfc822 attachment preview\n- Update to jsTimezoneDetect 1.0.6\n- Managesieve: Add (optional) RAW script editor (#5414)\n- Managesieve: Add option to automatically set vacation :from address (#5428)\n- Managesieve: Support 'string' test from variables extension [RFC 5229] (#5248)\n- Managesieve: Support 'duplicate' extension [RFC 7352]\n- Managesieve: Unhide advanced rule controls if there are inputs with errors\n- Managesieve: Display warning message when filter form contains errors\n- Control search engine crawlers via X-Robots-Tag header instead of <meta> and robots.txt (#5098)\n- Fixed redundancy in sql caching system and compatibility with Galera Cluster (#5439)\n - Removed redundant 'created' column from cache and cache_shared tables\n - Removed use of redundant data records\n - Added missing primary keys (dictionary, cache, cache_shared tables)\n- Fix so templating system does not mess with external (e.g. email) content (#5499)\n- Fix redundant keep-alive/refresh after session error on compose page (#5500)\n- Managesieve: Fix handling of scripts with nested rules (#5540)\n- Fix variable substitution in ldap host for some use-cases, e.g. new_user_identity (#5544)\n- Enigma: Fix PHP fatal error when decrypting a message with invalid signature (#5555)\n- Fix adding images to new identity signatures\n- Fix rsync error handling in installto.sh script (#5562)\n- Fix some advanced search issues with multiple addressbooks (#5572)\n- Fix so group/addressbook selection is retained on page refresh", "RELEASE 1.2.3\n-------------\n- Searching in both contacts and groups when LDAP addressbook with group_filters option is used\n- Fix vulnerability in handling of mail()'s 5th argument\n- Fix To: header encoding in mail sent with mail() method (#5475)\n- Fix flickering of header topline in min-mode (#5426)\n- Fix bug where folders list would scroll to top when clicking on subscription checkbox (#5447)\n- Fix decoding of GB2312/GBK text when iconv is not installed (#5448)\n- Fix regression where creation of default folders wasn't functioning without prefix (#5460)\n- Enigma: Fix bug where last records on keys list were hidden (#5461)\n- Enigma: Fix key search with keyword containing non-ascii characters (#5459)\n- Fix bug where deleting folders with subfolders could fail in some cases (#5466)\n- Fix bug where IMAP password could be exposed via error message (#5472)\n- Fix bug where it wasn't possible to store more that 2MB objects in memcache/apc,\n Added memcache_max_allowed_packet and apc_max_allowed_packet settings (#5452)\n- Fix \"Illegal string offset\" warning in rcube::log_bug() on PHP 7.1 (#5508)\n- Fix storing \"empty\" values in rcube_cache/rcube_cache_shared (#5519)\n- Fix missing content check when image resize fails on attachment thumbnail generation (#5485)\n- Fix displaying attached images with wrong Content-Type specified (#5527)", "RELEASE 1.2.2\n-------------\n- Enigma: Add possibility to configure gpg-agent binary location (enigma_pgp_agent)\n- Enigma: Fix signature verification with some IMAP servers, e.g. Gmail, DBMail (#5371)\n- Enigma: Make recipient key searches case-insensitive (#5434)\n- Fix regression in resizing JPEG images with Imagick (#5376)\n- Managesieve: Fix parsing of vacation date-time with non-default date_format (#5372)\n- Use SymLinksIfOwnerMatch in .htaccess instead of FollowSymLinks disabled on some hosts for security reasons (#5370)\n- Wash position:fixed style in HTML mail for better security (#5264)\n- Fix bug where memcache_debug didn't work for session operations\n- Fix bug where Message-ID domain part was tied to username instead of current identity (#5385)\n- Fix bug where blocked.gif couldn't be attached to reply/forward with insecure content\n- Fix E_DEPRECATED warning when using Auth_SASL::factory() (#5401)\n- Fix bug where names of downloaded files could be malformed when derived from the message subject (#5404)\n- Fix so \"All\" messages selection is resetted on search reset (#5413)\n- Fix bug where folder creation could fail if personal namespace contained more than one entry (#5403)\n- Fix error causing empty INBOX listing in Firefox when using an URL with user:password specified (#5400)\n- Fix PHP warning when handling shared namespace with empty prefix (#5420)\n- Fix so folders list is scrolled to the selected folder on page load (#5424)\n- Fix so when moving to Trash we make sure the folder exists (#5192)\n- Fix displaying size of attachments with zero size\n- Fix so \"Action disabled\" error uses more appropriate 404 code (#5440)", "RELEASE 1.2.1\n-------------\n- Update TinyMCE to version 4.3.13 (#5309)\n- Fix bug where errors could have been not logged when per_user_logging=true\n- Fix bug where message list columns could be in wrong order after column drag-n-drop and list sorting\n- Fix so minified publickey.js (with cache-buster) is used when available (#5254)\n- Fix (replace) application/x-tar file extension test as it might not exist in nginx config (#5253)\n- Fix PHP warning when password_hosts is set, but is not an array (#5260)\n- Fix redundant keep-alive requests when session_lifetime is greater than ~20000 (#5273)\n- Fix so subfolders of INBOX can be set as Archive (#5274)\n- Fix bug where multi-folder search could choose a wrong folder in \"this and subfolders\" scope (#5282)\n- Fix bug where multi-folder search didn't work for unsubscribed INBOX (#5259)\n- Fix bug where \"no body\" alert could be displayed when sending mailvelope email\n- Enigma: Fix keys import from inside of an encrypted message (#5285)\n- Enigma: Fix malformed signed messages with force_7bit=true (#5292)\n- Enigma: Add possibility to configure gpg binary location (enigma_pgp_binary)\n- Enigma: Add possibility to export private keys (#5321)\n- Fix searching by email address in contacts with multiple addresses (#5291)\n- Fix handling of --delete argument in moduserprefs.sh script (#5296)\n- Workaround PHP issue by calling closelog() on script shutdown when using log_driver=syslog (#5289)\n- Fix so upgrade script makes sure program/lib directory does not contain old libraries (#5287)\n- Fix subscription checkbox state on error in folder subscribe/unsubscribe action (#5243)\n- Fix bug where microsecond format in logged date didn't work in some cases\n- Fix conflict in new_user_dialog and password_force_new_user settings (#5275)\n- Don't create multipart/alternative messages with empty text/plain part (#5283)\n- Use contact_search_name format in popup on results in compose contacts search\n- Fix handling of 'mailto' and 'error' arguments in message_before_send hook (#5347)\n- Fix missing localization of HTML editor when assets_dir != INSTALL_PATH\n- Fix handling of blockquote tags with mixed case on html2text conversion (#5363)\n- Fix javascript errors in IE on page with iframe that points to another domain", "RELEASE 1.2.0\n-------------\n- Enigma: Added enigma_debug option\n- Fix message list multi-select/deselect issue (#5219)\n- Fix bug where getting HTML editor content could steal focus from other form controls (#5223)\n- Fix bug where contact search menu fields where always unchecked in Larry skin\n- Fix autoloading of 'html' class\n- Fix bug where Encrypt button appears when switching editor to HTML (#5235)\n- Fix XSS issue in href attribute on area tag (#5240)", "RELEASE 1.2-rc\n--------------\n- Managesieve: Refactored script parser to be 100x faster\n- Enigma: added option to force users to use signing/encryption\n- Enigma: Added option to attach public keys to sent mail (#5152)\n- Enigma: Handle messages with text before an encrypted block (#5149)\n- Enigma: Handle encrypted/signed content inside message/rfc822 attachments\n- Enigma: Fix missing html/plain switch on multipart/signed messages (#4963)\n- Enigma: Disable format=flowed for signed plain text messages (#4960)\n- Enigma: Fix handling of encrypted + signed messages (#4950)\n- Enigma: Fix invalid boundary use in signed messages structure\n- Enable use of TLSv1.1 and TLSv1.2 for IMAP (#4955)\n- Save copy of original .htaccess file when using installto.sh script (#4947)\n- Fix regression where some message attachments could be missing on edit/forward (#4939)\n- Fix regression in displaying contents of message/rfc822 parts (#4937)\n- Fix handling of message/rfc822 attachments on replies and forwards (#4938)\n- Fix PDF support detection in Firefox > 19 (#4941)\n- Fix path traversal vulnerability in setting a skin [CVE-2015-8770] (#4945)\n- Fix so drag-n-drop of text (e.g. recipient addresses) on compose page actually works (#4944)\n- Fix .htaccess rewrite rules to not block .well-known URIs (#4943)\n- Fix mail view scaling on iOS (#4915)\n- Fix PHP7 warning \"session_start(): Session callback expects true/false return value\" (#4948)\n- Fix XSS issue in SVG images handling [CVE-2015-8864, CVE-2016-4068] (#4949)\n- Fix missing language name in \"Add to Dictionary\" request in HTML mode (#4951)\n- Fix (again) security issue in DBMail driver of password plugin [CVE-2015-2181] (#4958)\n- Fix bug where Archive/Junk buttons were not active after page jump with select=all mode (#4961)\n- Fix bug in long recipients list parsing for cases where recipient name contained @-char (#4964)\n- Plugin API: Added addressbook_export hook\n- Fix additional_message_headers plugin compatibility with Mail_Mime >= 1.9 (#4966)\n- Hide DSN option in Preferences when smtp_server is not used (#4967)\n- Fix handling of body parameter in mail compose request\n- Protect download urls against CSRF using unique request tokens [CVE-2016-4069] (#4957)\n- newmail_notifier: Refactor desktop notifications\n- Fix so contactlist_fields option can be set via config file\n- Fix so SPECIAL-USE assignments are forced only until user sets special folders (#4782)\n- Fix performance in reverting order of THREAD result\n- Fix converting mail addresses with @www. into mailto links (#5197)", "RELEASE 1.2-beta\n----------------\n- Update TinyMCE to version 4.2\n- Added support for Redis session handler\n- Removed some deprecated methods: https://github.com/roundcube/roundcubemail/commit/454b0b1c\n- Remove backward compatibility \"layer\" of bc.php (#4902)\n- Add possibility to define date format in write operations for ldap attributes (#3956)\n- Display attachment size in compose (#1329)\n- Added possibility to drag-n-drop attachments from mail preview to compose window\n- Implemented mail messages searching with predefined date interval\n- PGP encryption support via Mailvelope integration\n- PGP encryption support via Enigma plugin\n- PHP7 compatibility fixes (#4836)\n- Security: Added brute-force attack prevention via login rate limit (#4922)\n- Security: Added options to validate username/password on logon (#4884)\n- Security: Improve randomness of security tokens (#4899)\n- Security: Use random security tokens instead of hashes based on encryption key (#4829)\n- Security: Improved encrypt/decrypt methods with option to choose the cipher_method (#4492)\n- Make optional adding of standard signature separator - sig_separator (#3276)\n- Optimize folder_size() on Cyrus IMAP by using special folder annotation (#4894)\n- Make optional hidding of folders with name starting with a dot - imap_skip_hidden_folders (#4870)\n- Add option to enable HTML editor always, except when replying to plain text messages (#4352)\n- Emoticons: Added option to switch on/off emoticons in compose editor (#2076)\n- Emoticons: Added option to switch on/off emoticons in plain text messages\n- Emoticons: All emoticons-related functionality is handled by the plugin now\n- Installer: Add button to save generated config file in system temp directory (#3553)\n- Remove common subject prefixes Re:, Re[x]:, Re-x: on reply (#4882)\n- Added GSSAPI/Kerberos authentication plugin - krb_authentication\n- Password: Allow temporarily disabling the plugin functionality with a notice\n- Require Mbstring and OpenSSL extensions (#5166)\n- Add --config and --type options to moduserprefs.sh script (#4651)\n- Implemented memcache_debug and apc_debug options\n- Installer: Remove system() function use (#4695)\n- Password plugin: Added 'kpasswd' driver by Peter Allgeyer\n- Add initdb.sh to create database from initial.sql script with prefix support (#4722)\n- Plugin API: Added disabled_plugins an disabled_buttons options in html_editor hook\n- Plugin API: Added html2text hook\n- Plugin API: Added message_part_body hook\n- Plugin API: Added message_ready hook\n- Plugin API: Add special onload() method to execute plugin actions before startup (session and GUI initialization)\n- Implemented UI element to jump to specified page of the messages list (#1677)\n- Fix searching of contacts to allow remote images for known senders (#4886)\n- Fix bug where clicking date column with 'arrival' sorting would switch to sorting by 'date' (#4690)\n- Fix bug where message content could overlap attachments list in Larry skin (#4876)\n- Fix so microseconds macro (u) in log_date_format works (#4855)\n- Fix so unrecognized TNEF attachments are displayed on the list of attachments (#5138)\n- Fix so database_attachments::cleanup() does not remove attachments from other sessions (#4907)\n- Fix responses list update issue after response name change (#4917)\n- Fix bug where message preview was unintentionally reset on check-recent action (#4921)\n- Fix bug where HTML messages with invalid/excessive css styles couldn't be displayed (#4905)\n- Fix redundant blank lines when using HTML and top posting (#4927)\n- Fix redundant blank lines on start of text after html to text conversion (#4928)\n- Fix HTML sanitizer to skip <!-- node type X --> in output (#4932)\n- Fix invalid LDAP query in ACL user autocompletion (#4934)", "RELEASE 1.1.3\n-------------\n- Fix closing of nested menus (#4854)\n- Fix so E_DEPRECATED errors from PEAR libs are ignored by error_reporting change (#4770)\n- Fix compatibility with PHP 5.3 in rcube_ldap class (#4842)\n- Get rid of Mail_mimeDecode package dependency (#4836)\n- Fix \"Importing...\" message does not hide on error (#4840)\n- Fix Compose action in addressbook for results from multiple addressbooks (#4834)\n- Fix bug where some messages in multi-folder search couldn't be viewed/printed/downloaded (#4843)\n- Fix unintentional messages list page change on page switch in compose addressbook (#4844)\n- Fix race-condition in saving user preferences and loading plugin config (#4845)\n- Fix so plain text signature field uses monospace font (#4848)\n- Fix so links with href == content aren't added to links list on html to text conversion (#4847)\n- Fix handling of non-break spaces in html to text conversion (#4849)\n- Fix self-reply detection issues (#4852)\n- Fix multi-folder search result sorting by arrival date (#4858)\n- Fix so *-request@ addresses in Sender: header are also ignored on reply-all (#4860)\n- Update to TinyMCE 4.1.10 (#5164)\n- Fix draft removal after a message is sent and storing sent message is disabled (#4869)\n- Fix so imap folder attribute comparisons are case-insensitive (#4868)\n- Fix bug where new messages weren't added to the list in search mode\n- Fix wrong positioning of message list header on page scroll in Webkit browsers (#4646)\n- Fix some javascript errors in rare situations (#4853)\n- Fix error when using back button after sending an email (#4628)\n- Fix removing signature when switching to identity with an empty sig in HTML mode (#4872)\n- Disable links list generation on html-to-text conversion of identities or composed message (#4850)\n- Fix \"washing\" of style elements wrapped into many lines\n- Fix so input field (e.g. search box) does not loose focus on list load (#4862)\n- Fix so css of one html part does not apply to other text parts on message display (#4887)\n- Fix XSS issue in drag-n-drop file uploads [CVE-2015-8105] (#4900)\n- Fix handling of plus character in mailto: links (#4891)\n- Fix so adding CC/BCC recipients from the sidebar unhides compose form fields in Classic skin (#4874)\n- Fix so gc.sh script removes also expired sessions from sql database (#4893)\n- Fix support for Mozilla-based browsers, e.g. Pale Moon (#4895)\n- Fix various issues with Turkish (and similar) locales (#4896)\n- Fix so In-Reply-To header is set also for MDN receipts (#4897)\n- Fix missing HTTP_X_FORWARDED_FOR address in generated Received header\n- Fix issue where Content-Length of some attachments could be set to wrong value causing browser errors (#4877)", "RELEASE 1.1.2\n-------------\n- Add new plugin hook 'identity_create_after' providing the ID of the inserted identity (#4807)\n- Add option to place signature at bottom of the quoted text even in top-posting mode [sig_below]\n- Fix handling of %-encoded entities in mailto: URLs (#4799)\n- Fix zipped messages downloads after selecting all messages in a folder (#4797)\n- Fix vpopmaild driver of password plugin\n- Fix PHP warning: Non-static method PEAR::setErrorHandling() should not be called statically (#4798)\n- Fix tables listing routine on mysql and postgres so it skips system or other database tables and views (#4796)\n- Fix message list header in classic skin on window resize in Internet Explorer (#4732)\n- Fix so text/calendar parts are listed as attachments even if not marked as such (#4795)\n- Fix lack of signature separator for plain text signatures in html mode (#4802)\n- Fix font artifact in Google Chrome on Windows (#4803)\n- Fix bug where forced extwin page reload could exit from the extwin mode (#4801)\n- Fix bug where some unrelated attachments in multipart/related message were not listed (#4805)\n- Fix mouseup event handling when dragging a list record (#4808)\n- Fix bug where preview_pane setting wasn't always saved into user preferences (#4809)\n- Fix bug where messages count was not updated after message move/delete with skip_deleted=false (#4814)\n- Fix security issue in contact photo handling (#4817)\n- Fix possible memcache/apc cache data consistency issues (#4820)\n- Fix bug where imap_conn_options were ignored in IMAP connection test (#4822)\n- Fix bug where some files could have \"executable\" extension when stored in temp folder (#4815)\n- Fix attached file path unsetting in database_attachments plugin (#4823)\n- Fix issues when using moduserprefs.sh without --user argument (#4825)\n- Fix potential info disclosure issue by protecting directory access (#4816)\n- Fix blank image in html_signature when saving identity changes (#4833)\n- Installer: Use openssl_random_pseudo_bytes() (if available) to generate des_key (#4827)\n- Fix XSS vulnerability in _mbox argument handling (#4837)", "RELEASE 1.1.1\n-------------\n- ACL: Allow other plugins to adjust the list of permissions and groups to edit\n- Add possibility to print contact information (of a single contact)\n- Add possibility to configure max_allowed_packet value for all database engines (#4772)\n- Improved handling of storage errors after message is sent\n- Update to TinyMCE 4.1.9\n- Unified request* event arguments handling, added support for _unlock and _action parameters\n- Security: Generate random hash for the per-user local storage prefix (#4768)\n- Fix refreshing of drafts list when sending a message which was saved in meantime (#4745)\n- Fix saving/sending emoticon images when assets_dir is set\n- Fix PHP fatal error when visiting Vacation interface and there's no sieve script yet (#4778)\n- Fix setting max packet size for DB caches and check packet size also in shared cache\n- Fix needless security warning on BMP attachments display (#4771)\n- Fix handling of some improper constructs in format=flowed text as per the RFC3676[4.5] (#4773)\n- Fix performance of rcube_db_mysql::get_variable()\n- Fix missing or not up-to-date CATEGORIES entry in vCard export (#4766)\n- Fix fatal errors on systems without mbstring extension or mb_regex_encoding() function (#4769)\n- Fix cursor position on reply below the quote in HTML mode (#4759)\n- Fix so \"over quota\" errors are displayed also in message compose page\n- Fix duplicate entries suppression in autocomplete result (#4776)\n- Fix \"Non-static method PEAR::isError() should not be called statically\" errors (#4770)\n- Fix parsing invalid HTML messages with BOM after <!DOCTYPE> (#4777)\n- Fix duplicate entry on timezones list in rcube_config::timezone_name_from_abbr() (#4779)\n- Fix so localized folder name is displayed in multi-folder search result (#4750)\n- Fix javascript error after creating a folder which is a subfolder of another one (#4781)\n- Fix bug where subject of sent/saved message was removed if mbstring wasn't installed (#4780)\n- Fix missing vcard_attachment icon on messages list (#4783)\n- Fix storing signatures with big images in MySQL database (#4785)\n- Fix Opera browser detection in javascript (#4786)\n- Fix so search filter, scope and fields are reset on folder change\n- Fix rows count when messages search fails (#4760)\n- Fix bug where spellchecking in HTML editor do not work after switching editor type more than once (#4789)\n- Fix bug where TinyMCE area height was too small on slow network connection (#4788)\n- Fix backtick character handling in sql queries (#4790)\n- Fix redirect URL for attachments loaded in an iframe when behind a proxy (#4724)\n- Fix menu container references to point to the actual <ul> element (#4791)\n- Fix javascripts errors in IE8 - lack of Event.which, focusing a hidden element (#4793)", "RELEASE 1.1.0\n-------------\n- Make SMTP error log more verbose - include server response and error code\n- Fix download options menu (added by zipdownload plugin) in classic skin (#4740)\n- Fix blocked.gif image usage with assets_dir set\n- Fix bug where max_group_members was ignored when adding a new contact (#4733)\n- Hide MDN and DSN options in compose if disabled by admin (#4735)\n- Fix checks based on window.ActiveXObject in IE > 10\n- Fix XSS issue in style attribute handling [CVE-2015-1433] (#4739)\n- Fix bug where Drafts list wasn't updated on draft-save action in new window (#4737)\n- Fix so \"set as default\" option is hidden if identities_level > 1 (#4738)\n- Fix bug where search was reset after returning from compose visited for reply\n- Fix javascript error in \"IE 8.0/Tablet PC\" browser (#4730)\n- Fix bug where Reply-To address was ignored on reply to messages sent by self (#4742)\n- Fix bug where empty fieldmap config entries caused empty results of ldap search (#4741)\n- Fix bug where drafts list wasn't refreshed after draft message was sent from another window (#4745)\n- Fix keyboard navigation and css in datepicker widget across many Firefox versions\n- Fix false warning when opening attached text/plain files (#4748)\n- Fix bug where signature could have been inserted twice after plain-to-html switch (#4746)\n- Fix security issue in DBMail driver of password plugin (#4757)\n- Enable FollowSymLinks option in .htaccess file which is required by rewrite rules (#4754)\n- Fix so JSON.parse() errors on localStorage items are ignored (#4752)", "RELEASE 1.1-rc\n--------------\n- Update jQuery to version 2.1.3\n- Allow to override any config option through env variables\n- Improve system security by using optional special URL with security token - use_secure_urls\n- Allow to define separate server/path for image/js/css files - assets_url/assets_dir\n- Sync vendor folder if exists in source package (#4700)\n- Avoid useless reloading list when resetting search with active filter (#4654)\n- Fix invalid folder selection if clicked while busy (#4709)\n- Fix import of multiple contact email addresses from Outlook-csv format (#4714)\n- Fix drag-n-drop to folders expanded while dragging (#4708)\n- Fix import of multiple contact groups from Google-csv format (#4710)\n- Fix import of contacts with multiple email addresses from Google-csv format (#4719)\n- Fix bugs where CSRF attacks were still possible on some requests [CVE-2014-9587]\n- Fix some rcube_utils::anytodatetime() corner cases with timezone mismatches (#4712)\n- Improve move-to and contact-export button in classic skin (#4713)\n- Fix wrong icon for download button in classic skin\n- Fix bug where sent message was saved in Sent folder even if disabled by user (#4729)", "RELEASE 1.1-beta\n----------------\n- Fix skin path handling in plugin context (#4111)\n- Prevent memory exhaustion on image resizing with GD on Windows (#4580)\n- Add plugin hook for database table name lookups as requested in #4538\n- Added Oracle database support\n- Support contacts import in GMail CSV format\n- Added namespace filter in Folder Manager\n- Added folder searching in Folder Manager\n- Fix restoring draft messages from localStorage if editor mode differs (#4631)\n- Added config option/user preference to disable saving messages in localStorage (#4606)\n- Added config option 'imap_log_session' to enable Roundcube <-> IMAP session ID logging\n- Added config option 'log_session_id' to control the length of the session identifier in logs\n- Implemented 'storage_connected' API hook after successful IMAP login (#4638)\n- Intergrate Net_LDAP3 and rcube_ldap_generic classes\n- Add option (disabled_actions) to disable UI elements/actions (#4478)\n- Support password encryption using openssl extension (#4614)\n- Create/rename groups in UI dialogs (#4592)\n- Added 'contact_search_name' option to define autocompletion entry format\n- Display quota information for current folder not INBOX only (#3442)\n- Support images in HTML signatures (#3917)\n- Display full quota information in popup (#2103, #2746)\n- Mail compose: Selecting contact inserts recipient to previously focused input - to/cc/bcc accordingly (#4487)\n- Close \"no subject\" prompt with Enter key (#4463)\n- Password: Add option to force new users to change their password (#2963)\n- Improve support for screen readers and assistive technology using WCAG 2.0 and WAI ARIA standards\n- Enable basic keyboard navigation throughout the UI (#3333)\n- Select/scroll to previously selected message when returning from message page (#4146)\n- Display a warning if popup window was blocked (#4472)\n- Remove (was: ...) from message subject on reply (#4359)\n- Update to TinyMCE 4.1 (#4168)\n- Enable autolink plugin in TinyMCE (#4029)\n- Support image operations with Imagick extension (#4498)\n- Support upload progress with session.upload_progress and PECL uploadprogress module (#3934)\n- Make identity name field optional (#4435)\n- Utility script to remove user records from the local database\n- Plugin API: Added message_saved hook (#4503)\n- Plugin API: Added imap_search_before hook\n- Support messages import from zip archives\n- Zipdownload: Added mbox format support (#2354)\n- Drop support for IE6, move IE7/IE8 support to legacy_browser plugin\n- Update to jQuery-2.1.1\n- Search across multiple folders (#1676)\n- Improve UI integration of ACL settings\n- Drop support for PHP < 5.3.7\n- Set In-Reply-To and References for forwarded messages (#4465)\n- Removed redundant default_folders config option (#4500)\n- Implemented IMAP SPECIAL-USE extension support [RFC6154] (#3326)\n- Optimize some framed pages content for better performance (#4517)\n- Improve text messages display and conversion to HTML (#4091)\n- Don't remove links when html signature is converted to text (#4473)\n- Fix page title when using search filter (#4636)\n- Fix mbox files import\n- Fix some character sets detection (#4694)\n- Fix so attachment charset is set in headers of forward/draft message (#4676)\n- Fix bug where wrong charset could be used for text attachment preview page (#4674)", "RELEASE 1.0.5\n-------------\n- Fix wrong icon for download button in classic skin\n- Fix checks based on window.ActiveXObject in IE > 10\n- Fix XSS issue in style attribute handling (#4739)\n- Fix bug where Drafts list wasn't updated on draft-save action in new window (#4737)\n- Fix so \"set as default\" option is hidden if identities_level > 1 (#4738)\n- Fix javascript error in \"IE 8.0/Tablet PC\" browser (#4730)\n- Fix bug where empty fieldmap config entries caused empty results of ldap search (#4741)\n- Fix bug where sent message was saved in Sent folder even if disabled by user (#4729)", "RELEASE 1.0.4\n-------------\n- Disable TinyMCE contextmenu plugin as there are more cons than pros in using it (#4684)\n- Fix bug where show_real_foldernames setting wasn't honored on compose page (#4705)\n- Fix issue where Archive folder wasn't protected in Folder Manager (#4706)\n- Fix compatibility with PHP 5.2. in rcube_imap_generic (#4682)\n- Fix setting flags on servers with no PERMANENTFLAGS response (#4667)\n- Fix regression in SHAA password generation in ldap driver of password plugin (#4670)\n- Fix displaying of HTML messages with absolutely positioned elements in Larry skin (#4672)\n- Fix font style display issue in HTML messages with styled <span> elements (#4671)\n- Fix download of attachments that are part of TNEF message (#4668)\n- Fix handling of uuencoded messages if messages_cache is enabled (#4675)\n- Fix handling of base64-encoded attachments with extra spaces (#4678)\n- Fix handling of UNKNOWN-CTE response, try do decode content client-side (#4650)\n- Fix bug where creating subfolders in shared folders wasn't possible without ACL extension (#4680)\n- Fix reply scrolling issue with text mode and start message below the quote (#4681)\n- Fix possible issues in skin/skin_path config handling (#4689)\n- Fix lack of delimiter for recipient addresses in smtp_log (#4703)\n- Fix generation of Blowfish-based password hashes (#4721)\n- Fix bugs where CSRF attacks were still possible on some requests [CVE-2014-9587]", "RELEASE 1.0.3\n-------------\n- Initialize HTML editor before restoring a message from localStorage (#4631)\n- Add 'sig_max_lines' config option to default config file (#5162)\n- Add config option to specify IMAP connection socket parameters - imap_conn_options (#4589)\n- Add option to set default message list mode - default_list_mode (#3157)\n- Enable contextmenu plugin for TinyMCE editor (#3062)\n- Fix insert-signature command in external compose window if opened from inline compose screen (#4663)\n- Fix some mime-type to extension mapping checks in Installer (#4610)\n- Fix errors when using localStorage in Safari's private browsing mode (#4619)\n- Fix bug where $Forwarded flag was being set even if server didn't support it (#4621)\n- Fix various iCloud vCard issues, added fallback for external photos (#4617)\n- Fix invalid Content-Type header when send_format_flowed=false (#4616)\n- Fix errors when adding/updating contacts in active search (#4630)\n- Fix incorrect thumbnail rotation with GD and exif orientation data (#4641)\n- Fix contacts list update after adding/deleting/moving a contact (#4640, #4644)\n- Fix handling of email addresses with quoted domain part (#4647)\n- Fix comm_path update on task switch (#4648)\n- Fix error in MSSQL update script 2013061000.sql (#4658)\n- Fix validation of email addresses with IDNA domains (#4661)", "RELEASE 1.0.2\n-------------\n- Fix storing unsaved drafts in localStorage (#4529)\n- Add configurable LDAP_OPT_DEREF option (#4546)\n- Fix so when switching editor mode original version of signature is used (#4032)\n- Fix unintentional draft autosave request if autosave is disabled (#4550)\n- Fix malformed References: header in send/saved mail (#4552)\n- Fix handling unicode characters in links (#4555)\n- Fix incorrect handling of HTML comments in messages sanitization code (#4558)\n- Fix so current page is reset on list-mode change (#4561)\n- Fix so responses menu hides on click in classic skin (#4566)\n- Fix unintentional line-height style modification in HTML messages (#4567)\n- Fix broken normalize_string(), add support for ISO-8859-2 (#4568)\n- Support csv contacts import in German localization (#4570)\n- Fix so message list and counters are updated when a message is opened in new window (#4569)\n- Fix malformed recipient name when composing a message by clicking on mailto link (#4583)\n- Fix list reload after sending message in another window (#4576)\n- Fix so address format errors are ignored when saving a draft (#4594)\n- Fix incorrect label translation in return receipt (#4598)\n- Fix security issue in delete-response action - allow only ajax request\n- Fix Delete button state after deleting identity/response (#4603)\n- Fix bug where contacts with no email address were listed on compose addressbook (#4602)\n- Fix images import from various vCard formats (#4604)\n- Fix sorting messages by size on servers without SORT capability (#4608)", "RELEASE 1.0.1\n-------------\n- Support 'error' and 'body_file' return attribs in 'message_before_send' hook (#4467)\n- Apply user-specific replacements to group's base_dn property (#4512)\n- Fix missing email address when importing contacts from outlook csv (#4535)\n- Fix bug where \"With attachment\" option in search filter wasn't selected after return from mail view (#4508)\n- Fix \"washing\" of unicoded style attributes (#4510)\n- Fix unintentional redirect from compose page in Webkit browsers (#4516)\n- Fix messages index cache update under some conditions (e.g. proxy) (#4505)\n- Fix lack of translation of special folders in some configurations (#4520)\n- Fix XSS issue in plain text spellchecker (#4524)\n- Fix invalid page title for some folders (1489804)\n- Fix redundant alert message on over-size uploads (#4528)\n- Fix next message display after removing a message (#4521)\n- Fix missing Mail-Followup-To header in sent mail (#4534)\n- Fix error when spell-checking an empty text (#4536)\n- Avoid popupmenus being closed when scrollbar is clicked (#4537)\n- Add proxy_whitelist configuration option (#4496)\n- Fix identities_level=4 handling in new_user_dialog plugin (#4540)\n- Fix various db_prefix issues (#4539)\n- Fix too small length of users.preferences column data type on MySQL\n- Fix redundant warning when switching from html to text in empty editor (#4530)\n- Fix invalid host validation on login (#4541)\n- Fix IMAP connection test in installer so it is aware of imap_auth_type (#4502)", "RELEASE 1.0.0\n-------------\n- Added toolbar button to move message in message view\n- Fix style of disabled protocol handler link on IE (#4460)\n- Fix message import dialog when no file is selected (#4488)\n- Fix opening compose screen in new window after saving as draft (#4479)\n- Fix directories check in Installer on Windows (#4462)\n- Fix issue when default_addressbook option is set to integer value (#4379)\n- Fix Opera > 15 detection (#4455)\n- Fix security issue in DomainFactory driver of Password plugin\n- Fix invalid X-Draft-Info on forwarded message draft (#4464)\n- Fix regression in handling of 'attachments' result in message_compose hook (#4474)\n- Fix issue where msgexport.sh printed the message to STDOUT instead of a file (#4476)\n- Fix fatal error in database_attachments plugin under some conditions (#4495)", "RELEASE 1.0-rc\n--------------\n- Small CSS fix with message notice boxes in Larry skin (#4429)\n- Include groups in contacts search on mail compose (#4186)\n- Add mime-type mapping for .7z files (#4436)\n- Invoke update scripts with php to circumvent execution restrictions (#4330)\n- Fix drag & drop message/contact moving on touch device (#4395)\n- Fix canned responses in HTML mode (#4446)\n- Check/create default folders on every login not only the first (#4391)\n- Update to jQuery-1.11.0 and jQuery-UI-1.9.2\n- Support SMTP socket context options via new config option 'smtp_conn_options'\n- Fix compatibility with PHP 5.2 in html.php file (#4438)\n- Remove expand/collapse with plus/minus keys (on numeric keypad) (#4437)\n- Fix issue where filesystem path was added to all-attachments (zip) file (#4433)\n- Fix case-sensitivity of email addresses handling on compose (#1899)\n- Don't alter Message-ID of a draft when sending (#4381)\n- Fix issue where deprecated syntax for HTML lists was not handled properly (#3975)\n- Display different icons when Trash folder is empty or full (#2108)\n- Remember last position of more headers switch (#3660)\n- Fix so message flags modified by another client are applied on the list on refresh (#1639)\n- Fix broken text/* attachments when forwarding/editing a message (#4393)\n- Improved minified files handling, added css minification (#3041)\n- Fix handling of X-Forwarded-For header with multiple addresses (#4424)\n- Fix border issue on folders list in classic skin (#4419)\n- Implemented menu actions to copy/move messages, added folder-selector widget (#863)\n- Fix security rules in .htaccess preventing access to base URL without the ending slash (#4422)\n- Fix regression where only first new folder was placed in correct place on the list (#4418)\n- Fix issue where children of selected and collapsed thread were skipped on various actions (#4410)\n- Fix issue where groups were not deleted when \"Replace entire addressbook\" option on contacts import was used (#4388)\n- Fix unreliable mimetype tests in Installer (#4408)\n- Fix performance of listing writeable folders (#4406)", "RELEASE 1.0-beta\n----------------\n- Fix handling of invalid closing tags in HTML messages (#4403)\n- Set real content-type for file downloads (#4400)\n- Update TinyMCE to version 3.5.10 (#4401)\n- Fix keyboard navigation in list widgets (#4367)\n- Allow plugins to grab the reference of opened windows (#4383)\n- Larry skin: Improved status message display for better visibility (#4115)\n- Fix Internet Explorer 11 detection (#4397)\n- Fix date column width to fit the widest possible date format (#4354)\n- Move certain user preference options to a collapsed \"advanced\" block (#4015)\n- Add file type icons for Powerpoint and Open Office presentations (#4269)\n- Fix operations on folders with trailing spaces in name (#4387)\n- Improve identity selection based on From: header (#4360)\n- Fix issue where mails with inline images of the same name contained only the first image multiple times (#4378)\n- Use left/right arrow keys to collapse/expand thread and spacebar to select a row, change Ctrl key behavior (#4367)\n- Fix an issue where using arrow keys to go up a list can result in selected message being under headers (#4375)\n- Fix an issue where Home/End keys don't focus list row properly, don't scrollTo properly (#4370)\n- Add an option to disable smart Reply-List behaviour - reply_all_mode (#3953)\n- Fix an issue where pressing minus key on contacts list was hiding list records (#4368)\n- Fix an issue where shift + arrow-up key wasn't selecting all messages in collapsed thread (#4371)\n- Added icon for priority column in messages list header (#4275)\n- New feature \"Canned Responses\" to save and recall boilerplate text snippets\n- Fix HTML part detection when encapsulated inside multipart/signed (#4357)\n- Add spellchecker backend for the After the Deadline service\n- Replace markdown-style [1] link indexes in plain text email bodies\n- Improved mailto: link arguments handling (#4351)\n- Use DOMDocument LIBXML_PARSEHUGE and LIBXML_COMPACT options if possible (#4316)\n- Support HTTP_HOST, SERVER_NAME and SERVER_ADDR values in include_host_config feature\n- Make default font size for HTML messages configurable (request #118)\n- Fix XSS issue in addressbook group name field [CVE-2013-5646] (#4337)\n- After message is sent refresh messages list of replied message folder (#4282)\n- Add option force specified domain in user login - username_domain_forced (#4290)\n- Add option to import Vcards with group assignments\n- Save groups membership in Vcard export (#3801)\n- Workaround broken PHP function timezone_name_from_abbr (#4289)\n- Make cached message size limit configurable - messages_cache_threshold (#4326)\n- Log also failed logins to userlogins log\n- Add temp_dir_ttl configuration option (#4318)\n- Allow setting INBOX as Sent folder (#4264)\n- Fix replacement variables in user-specific base_dn in some LDAP requests (#4299)\n- Fix image scaling issues when image has only one dimension smaller than the limit (#4296)\n- Fix issue where uploaded photo was lost when contact form did not validate (#4296)\n- Move identity selection based on non-standard headers into (new) identity_select plugin (#3835)\n- Fix downloading binary files with (wrong) text/* content-type (#4292)\n- Respect HTTP_X_FORWARDED_FOR and HTTP_X_REAL_IP variables for session IP check\n- Simplified configuration by merging it into one file + defaults (#3156)\n- Make message list header stay on top when scrolling (#353)\n- Add support for 'enchant' spellcheck engine\n- Check filetype detection in installer and update script (#4252)\n- Fix folder names truncation in Classic skin (#4265)\n- Make possible to disable some (broken) IMAP extensions with imap_disable_caps option (#4245)\n- Contacts drag-n-drop default action is to move contacts (#3962)\n- Added possibility to choose to move or copy contacts from drag-n-drop menu (#3962)\n- Fix Close link and remove About link on error pages (#4201)\n- Improved/unified attachment preview screen, added print button\n- Fix lack of space between searchfiler and quicksearchbar in Larry skin (#4233)\n- Cache LDAP's user_specific search and use vlv for better performance (#4247)\n- LDAP: auto-detect and use VLV indices for all search operations\n- LDAP: additional group configuration options for address books\n- LDAP: separated address book implementation from a generic LDAP wrapper class\n- Allow address books to browse a multi-level group hierarchy in the contacts list\n- Fix session issues when local and database time differs (#2401)\n- Fix thread cache syncronization/validation (#4150)\n- Added feature to import messages to the currently selected folder\n- Add option show_real_foldernames to disable localization of special folders\n- Fix database cache expunge issues (#4229)\n- Fix date format issues on MS SQL Server (#4078)\n- Add imap_cache_ttl option to configure TTL of imap_cache\n- Make LDAP cache engine configurable via ldap_cache and ldap_cache_ttl options\n- Fix \"duplicate entry\" errors on inserts to imap cache tables (#4228)\n- Improved handling of Reply-To/Bcc addresses of identity in compose form (#4142)\n- Added user preference to open all popups as standard windows\n- Implemented shared cache (rcube_cache_shared)\n- Change Reply-All button label/title when mailing list is detected (#4092)\n- Fix SMTP connection using IPv6 address in smtp_server option (#4147)\n- Added attachment_reminder plugin\n- Make PHP code eval() free, use create_function()\n- Add option to display email address together with a name in mail preview (#3952)\n- Support CSV import from Atmail (#4161)\n- Add db_prefix configuration option in place of db_table_*/db_sequence_* options\n- Make possible to use db_prefix for schema initialization in Installer (#4175)\n- Fix updatedb.sh script so it recognizes also table prefix for external DDL files\n- Fix parsing invalid date string (#4155)\n- Add \"with attachment\" option to messages list filter (#1795)\n- Call resize handler in intervals to prevent lags and double onresize calls in Chrome (#4137)\n- Add rel=\"noreferrer\" for links in displayed messages (#4976)\n- Add ability to toggle between HTML and text while viewing a message (#3005)\n- Remove \"HTML message\" from attachments list while viewing a message in text mode (#3005)\n- Support IMAP MOVE extension [RFC 6851]\n- Add attachment menu with Open and Download options (#4116)\n- Display user-friendly message on IMAP \"over quota\" errors (#914)\n- Extended archive plugin with user-configurable options to store messages into subfolders\n- Fix export of selected contacts from search result (#4070)\n- Feature to export only selected contacts from addressbook (by Phil Weir)", "RELEASE 0.9.5\n-------------\n- Fix failing vCard import when email address field contains spaces (#4363)\n- Fix default spell-check configuration after Google suspended their spell service\n- Fix vulnerability in handling _session argument of utils/save-prefs [CVE-2013-6172] (#4362)\n- Fix iframe onload for upload errors handling (#4361)\n- Fix address matching in Return-Path header on identity selection (#4358)\n- Fix text wrapping issue with long unwrappable lines (#4356)\n- Fixed issues where HTML comments inside style tag would hang Internet Explorer\n- Hide Delivery Status Notification option when smtp_server is unset (#4339)\n- Display full attachment name using title attribute when name is too long to display (#4328)\n- Fix attachment icon issue when rare font/language is used (#4334)\n- Fix expanded thread root message styling after refreshing messages list (#4335)\n- Fix issue where From address was removed from Cc and Bcc fields when editing a draft (#4327)\n- Fix error_reporting directive check (#4331)\n- Fix de_DE localization of \"About\" label in Help plugin (#4333)", "RELEASE 0.9.4\n-------------\n- Make identities matching case insensitive (#1881)\n- Fix issue where too big message data was stored in cache causing sql errors (#4325)\n- Fix iframe scrollbars on webkit desktop browsers (#4319)\n- Fix issue where legacy config was overridden by default config (#4305)\n- Fix newmail_notifier issue where favicon wasn't changed back to default (#4324)\n- Fix setting of Junk and NonJunk flags by markasjunk plugin (#4303)\n- Fix lack of Reply-To address in header of forwarded message body (#4314)\n- Fix bugs when invoking contact creation form when read-only addressbook is selected (#4313)\n- Fix identity selection on reply (#4308)\n- Fix so additional headers are added to all messages sent (#4302)\n- Fix display issue after moving folder in Folder Manager (#4310)\n- Fix handling of non-default date formats (#4311)\n- Fix unquoted path in PREG expression on Windows (#4307)\n- Fix wrong close tag in /template/mail.html (#4312)", "RELEASE 0.9.3\n-------------\n- Fix setting refresh_interval to \"Never\" in Preferences (#4304)\n- Fixed iframe scrolling on touch devices\n- Optimized message list for touch devices\n- Fix purge action in folder manager (#4300)\n- Fix base URL resolving on attribute values with no quotes (#4297)\n- Fix wrong handling of links with '|' character (#4298)\n- Fix colorspace issue on image conversion using ImageMagick (#4294)\n- Fix XSS vulnerability when editing a message \"as new\" or draft [CVE-2013-5645] (#4283)\n- Fix XSS vulnerability when saving HTML signatures [CVE-2013-5645] (#4283)\n- Fix rewrite rule in .htaccess (#4278)\n- Fix detecting Turkish language in ISO-8859-9 encoding (#4284)\n- Fix identity-selection using Return-Path headers (#4279)\n- Fix parsing of links with ... in URL (#4251)\n- Fix compose priority selector when opening in new window (#4286)\n- Fix bug where signature wasn't changed on identity selection when editing a draft (#4272)\n- Fix IMAP SETMETADATA parameters quoting (#4274)\n- Fix \"could not load message\" error on valid empty message body (#4271)\n- Fix handling of message/rfc822 attachments on message forward and edit (#4262)\n- Fix parsing of square bracket characters in IMAP response strings (#4267)\n- Don't clear References and in-Reply-To when a message is \"edited as new\" (#4263)\n- Fix messages list sorting with THREAD=REFS\n- Remove deprecated (in PHP 5.5) PREG /e modifier usage (#4239)\n- Fix empty messages list when register_globals is enabled (#4232)\n- Fix so valid and set date.timezone is not required by installer checks (#4242)\n- Canonize boolean ini_get() results (#4249)\n- Fix so install do not fail when one of DB driver checks fails but other drivers exist (#4240)\n- Fix so exported vCard specifies encoding in v3-compatible format (#4244)", "RELEASE 0.9.2\n-------------\n- Fix image thumbnails display in print mode (#4220)\n- Fix height of message headers block (#4200)\n- Fix timeout issue on drag&drop uploads (#4238)\n- Fix default sorting of threaded list when THREAD=REFS isn't supported\n- Fix list mode switch to 'List' after saving list settings in Larry skin (#4236)\n- Fix error when there's no writeable addressbook source (#4235)\n- Fix zipdownload plugin issue with filenames charset (#4231)\n- Fix so non-inline images aren't skipped on forward (#4230)\n- Fix \"null\" instead of empty string on messages list in IE10 (#4227)\n- Fix legacy options handling\n- Fix so bounces addresses in Sender headers are skipped on Reply-All (#4140)\n- Fix bug where serialized strings were truncated in PDO::quote() (#4226)\n- Fix displaying messages with invalid self-closing HTML tags (#4223)\n- Fix PHP warning when responding to a message with many Return-Path headers (#4222)\n- Fix unintentional compose window resize (#4206)\n- Fix performance regression in text wrapping function (#4219)\n- Fix connection to posgtres db using unix socket (#4218)\n- Fix handling of comma when adding contact from contacts widget (#4199)\n- Fix bug where a message was opened in both preview pane and new window on double-click (#4212)\n- Fix fatal error when xdebug.max_nesting_level was exceeded in rcube_washtml (#4202)\n- Fix PHP warning in html_table::set_row_attribs() in PHP 5.4 (#4194)\n- Fix invalid option selected in default_font selector when font is unset (#4204)\n- Fix displaying contact with ID divisible by 100 in sql addressbook (#4211)\n- Fix browser warnings on PDF plugin detection (#4209)\n- Fix fatal error when parsing UUencoded messages (#4210)", "RELEASE 0.9.1\n-------------\n- Better German labels for from/to to avoid conflicts with 'sender' (#4188)\n- Fix problem where security warning was displayed for valid images with image/jpg type (#4196)\n- Fix handling of invalid email addresses in headers (#4193)\n- Fix IMAP connection issue with default_socket_timeout < 0 and imap_timeout < 0 (#4191)\n- Fix various PHP code bugs found using static analysis (#4190)\n- Fix backslash character handling on vCard import (#4189)\n- Fix csv import from Thunderbird with French localization (#4170)\n- Fix messages list focus issue in Opera and Webkit (#4169)\n- Fix Reply-To header handling in Reply-All action (#4157)\n- Fix so Sender: address is added to Cc: field on reply to all (#4140)\n- Fix so addressbook_search_mode works also for group search (#4183)\n- Fix removal of a contact from a group in LDAP addressbook (#4185)\n- Include SQL query in the log on SQL error (#4172)\n- Fix handling untagged responses in IMAP FETCH - \"could not load message\" error (#4180)\n- Fix very small window size in Chrome (#4087)\n- Fix list page reset when viewing a message in Larry skin (#4182)\n- Fix min_refresh_interval handling on preferences save (#4179)\n- Fix PDF support detection for Firefox PDF.js (#4113)\n- Fix possible collision in generated thumbnail cache key (#4177)\n- Fix exit code on bootsrap errors in CLI mode (#4160)\n- Fix error handling in CLI mode, use STDERR and non-empty exit code (#5161)\n- Fix error when using check_referer=true\n- Fix incorrect handling of some specific links (#4171)\n- Fix incorrect handling of leading spaces in text wrapping\n- Fix unintentional messages list jumps on click in Internet Explorer (#4167)\n- Fix list of required configuration options (#4166)\n- Fix DB error when creating a new contact and a group is selected (#4164)\n- Fix handling of deprecated boolean value of reply_mode option (#4165)", "RELEASE 0.9.0\n-------------\n- Fix display of HTML entities in protected folder name (#4159)\n- Set minimal permissions to temp files (#4131)\n- Improve content check for embedded images without filename (#4151)\n- Fix handling of invalid characters in message headers and output (#4153)\n- Fix selecting collapsed rows on select-all (#4156)\n- Avoid race-conditions with concurrent attachment uploads (#3739)\n- Fix possible header duplicates when using additional headers (#4154)\n- Fix session issues with use_https=true (#4125)\n- Fix blockquote width in sent mail (#4152)\n- Fix keyboard events on list widgets in Internet Explorer (#4148)", "RELEASE 0.9-rc2\n---------------\n- Fix security issue in save-pref command\n- Remove sig_above configuration option, use reply_mode only (#4135)\n- Refresh current folder in opener window after draft save or message sent (#4132)\n- Fix saving draft just after entering compose window (#4141)\n- Fix javascript error in IE9 when loading form with placeholders into an iframe (#4138)\n- Fix handling of some conditional comment tags in HTML message (#4136)\n- Fix so forward as attachment works if additional attachment is added by message_compose hook (#4134)\n- Better handling of session errors in ajax requests (#4105)\n- Fix HTML part detection for some specific message structures (#4130)\n- Don't show fake address - phishing prevention (#4120)\n- Fix forward as attachment bug with editormode != 1 (#4129)\n- Fix LIMIT/OFFSET queries handling on MS SQL Server (#4123)\n- Fix so task name can really contain all from a-z0-9_- characters (#4095)\n- Fix javascript errors when working in a page opened with taget=\"_blank\"\n- Mention SQLite database format change in UPGRADING file (#4122)\n- Increase maxlength to 254 chars for email input fields in addressbook (#4126)\n- Fix thumbnail size when GD extension is used for image resize (#4124)\n- Display notice that message is encrypted also for application/pkcs7-mime messages (#3815)", "RELEASE 0.9-rc\n--------------\n- Fix plain text spellchecker incorrect highlighting in non-ASCII text (#4114)\n- Add workaround for invalid message charset detection by IMAP servers (#4112)\n- Fix NUL characters in content-type of ms-tnef attachment (#4108)\n- Fix regression in handling LDAP contact identifiers (#4104)\n- Updated translations from Transifex\n- Fix buggy error template in a frame (#4092)\n- Add addressbook widget on compose page in classic skin\n- Add search box to compose address book widget (#3710)\n- Fix login in case when default_host is an array with one element (#4085)\n- Use LDAP fallback hosts on connect + bind instead of ldap_connect() only.\n- Add config option for LDAP bind timeout (sets LDAP_OPT_NETWORK_TIMEOUT option)\n- Submit Addressbook advanced search form with Enter key (#3843)\n- Also block remote images in HTML part view (#4013)\n- Improved database schema upgrade procedure, added updatedb.sh script\n- Force autocommit mode in mysql database driver (#4068)", "RELEASE 0.9-beta\n----------------\n- Fix searching by date in address book (#4058)\n- Improve charset detection by prioritizing charset according to user language (#2032)\n- Fix handling of escaped separator in vCard file (#4064)\n- Add option to use envelope From address for MDN responses (#4052)\n- Add possibility to search in message body only (#3977)\n- Support \"multipart/relative\" as an alias for \"multipart/related\" type (#4057)\n- Display PGP/MIME signature attachments as \"Digital Signature\" (#3845)\n- Workaround UW-IMAP bug where hierarchy separator is added to the shared folder name (#4051)\n- Fix version comparisons with -stable suffix (#4050)\n- Add unsupported alternative parts to attachments list (#4046)\n- Add Compose button on message view page (#3959)\n- Display 'Sender' header in message preview\n- Plugin API: Added message_before_send hook\n- Fix contact copy/add-to-group operations on search result (#4042)\n- Use matching identity in MDN response (#4043)\n- Fix handling of signatures on draft edit (#3996)\n- Fix so compacting of non-empty folder is possible also when messages list is empty (#4039)\n- Allow forwarding of multiple emails (#2941)\n- Fix big memory consumption of DB layer (#4037)\n- Fix broken message/part bodies when FETCH response contains more untagged lines (#4020)\n- Fix empty email on identities list after identity update (#4018)\n- Add new identities_level: (4) one identity with possibility to edit only signature\n- Use Delivered-To and Envelope-To headers for identity selection (#4024, #3835)\n- Fix XSS vulnerability using Flash files (#4014)\n- Always save drafts with format=flowed in order to keep original line wraps (#3997)\n- Select default_addressbook on the list in Address Book (#3624)\n- Fix so mobile phone has TYPE=CELL in exported vCard (#4004)\n- Support contacts import from CSV file (#2605)\n- Improved keep-alive action. Now the interval is based on session_lifetime (#3799)\n- Added cross-task 'refresh' request for system state updates (#3799)\n- Renamed config options: keep_alive to refresh_interval, min_keep_alive to min_refresh_interval\n- Fix handling of text/enriched content on message reply/forward/edit\n- Option to display attached images as thumbnails below message body\n- Upgraded to jQuery 1.8.3 and jQuery UI 1.9.1\n- Add config option to automatically generate LDAP attributes for new entries\n- Add user settings to open message view and compose form in new windows (#1886)\n- Better client-side timezone detection using the jsTimezoneDetect library (#3947)\n- Add option to disable saving sent mail in Sent folder - no_save_sent_messages (#3923)\n- Fix handling dont_override with message_sort_col and message_sort_order settings (#3970)\n- Fix handling of URLs with asterisk characters (#3969)\n- Remove automatic to-lowercase conversion of usernames (#3941)\n- Plugin API: Add 'email_list' argument for identities data in user_create hook\n- Integrated zipdownload plugin to download all attachments (#617)\n- Fix HTML special characters handling in message list/header display (#3812)\n- List related text/html part as attachment in plain text mode (#3918)\n- Use IMAP BINARY (RFC3516) extension to fetch message/part bodies\n- Fix folder creation under public namespace root (#3910)\n- Fix so \"Edit as new\" on draft creates a new message (#3924)\n- Fix invalid error message on deleting mail from read only folder (#3929)\n- Replace data URIs of images (pasted in HTML editor) with inline attachments (#3795)\n- Remove (too big) min-width on mail screen\n- Added template object 'frame'\n- Add option to enable HTML editor on forwarding (#3807)\n- Add option to not include original message on reply, rename option top_posting to reply_mode (#1615)\n- Added session_path config option and unified cookies settings in javascript\n- Added \"Undeleted\" option to messages list filter\n- Rewritten test scripts for PHPUnit\n- Add new DB abstraction layer based on PHP PDO, supporting SQLite3 (#3668)\n- Removed PEAR::MDB2 package\n- Removed users.alias column, added option ('user_aliases')\n to use email address from identities as username (#3851)\n- Removed redundant cache.cache_id column (#3817)\n- Fix order of attachments in sent mail (#3740)\n- Fix Shift + delete button does not permanently delete messages (#3598)\n- Add Content-Length for attachments where possible (#1880)\n- Fix attachment sizes in message print page and attachment preview page (#3805)\n- Add mail attachments using drag & drop on HTML5 enabled browsers\n- Add workaround for invalid BODYSTRUCTURE response - parse message with Mail_mimeDecode package (#1966)\n- Display Tiff as Jpeg in browsers without Tiff support (#3757)\n- Don't display Pdf/Tiff/Flash attachments inline without browser support (#3757, #3394)\n- Add is_escaped attribute for html_select and html_textarea (#3782)\n- Fix issue where draft auto-save wasn't executed after some inactivity time\n- Add vCard import from multiple files at once (#3458)\n- Roundcube Framework:\n Add possibility to replace IMAP driver with custom class\n Add IMAP auto-connection feature, improving performance with caching enabled\n Replace imap_init hook with storage_init (with additional 'driver' argument)\n Improved performance by caching IMAP server's capabilities in session\n Unified global functions naming (rcube_ prefix)\n Better classes separation\n Framework files moved to lib/Roundcube", "RELEASE 0.8.5\n-------------\n- Fix #countcontrols issue in IE<=8 when text is very long (#4060)\n- Fix unwanted horizontal scrollbar in message preview header (#4044)\n- Add workaround for IE<=8 bug where Content-Disposition:inline was ignored (#4028)\n- Fix XSS vulnerability in vbscript: and data:text links handling [CVE-2012-6121] (#4033)\n- Fix absolute positioning in HTML messages (#4007)\n- Fix cache (in)validation after setting \\Deleted flag\n- Fix keybord events on messages list in opera browser (#4011)\n- Fix selection of collapsed thread rows (#3978)\n- Fix wrapping of quoted text with format=flowed (#3561)", "RELEASE 0.8.4\n-------------\n- Fix regression where unintentional page reload was done after request abort (#3999)\n- Fix XSS vulnerability in handling of text/enriched messages (#4000)\n- Fix handling of 'media' attribute on linked css (#3989)\n- Fix excessive LFs at the end of composed message with top_posting=true (#3995)\n- Fix bug where leading blanks were stripped from quoted lines (#3994)", "RELEASE 0.8.3\n-------------\n- Fix AREA links handling (#3992)\n- Fix possible HTTP DoS on error in keep-alive requests (#3983)\n- Fix compatybility with MDB2 2.5.0b4 (#3982)\n- Fix a bug where saving a message in INBOX wasn't possible\n- Fix HTML part detection in messages with attachments (#3976)\n- Fix bug where wrong words were highlighted on spell-before-send check\n- Fix scrolling quirk in email preview frame using Opera 12 (#3973)\n- Fix displaying of multipart/alternative messages with empty parts (#3961)\n- Fix threaded list sorting on PHP < 5.2.9 (#3960)\n- Fix Warning: htmlspecialchars(): charset `RCMAIL_CHARSET' not supported warning in Installer (#3958)", "RELEASE 0.8.2\n-------------\n- Fix XSS vulnerability from HTTP User-Agent header (#3954)\n- Force fonts in compose fields to be all the same (#3926)\n- Fix handling vCard entries with TEL;TYPE=CELL (#3949)\n- Fix error where session wasn't updated after folder rename/delete (#3928)\n- Fix PLAIN authentication for some IMAP servers (#3916)\n- Fix encoding vCard file when contains PHOTO;ENCODING=b (#3922)\n- Fix focus issue in IE when selecting message row (#3881)\n- Add full headers view in message preview window (#3823)\n- Fix message display page issues - unified with message preview (#3856, #3895)\n- Fix displaying all headers when they contain malformed characters (#3911)\n- Fix decoding of HTML messages with UTF-16 charset specified (#3902)\n- Fix quota capability detection so it can be overwritten by a plugin (#3903)\n- Fix identity selection on reply (#3516)\n- Fix Larry's messages list filter in IE (#3890)\n- Fix more IE issues by disabling Compat. mode with X-UA-Compatible meta tag (#3886)\n- Fix setting locales under Solaris - use additional .UTF-8 suffix (#3887)\n- Fix email address validation for addresses with IP address in domain part\n- Fix Larry skin issues in IE7 compat. mode (#3879)\n- Fix so subscribed non-existing/non-accessible shared folder can be unsubscribed", "RELEASE 0.8.1\n-------------\n- Fix bug where domain name was converted to lower-case even with login_lc=false (#3859)\n- Fix lower-casing email address on replies (#3863)\n- Fix line separator in exported messages (#3866)\n- Fix XSS issue where plain signatures wasn't secured in HTML mode [CVE-2012-4668] (#3875)\n- Fix XSS issue where href=\"javascript:\" wasn't secured [CVE-2012-3508] (#3875)\n- Fix impossible to create message with empty plain text part (#3873)\n- Fix stripped apostrophes when replying in plain text to HTML message (#3869)\n- Fix inactive Save search option after advanced search (#3870)\n- Fix Remove from group option is active for contact search result (#3871)\n- Disable autocapitalization in login form on iPad/iPhone (#3872)\n- Fix focus on the list when list row is clicked (#3865)\n- Added separate From and To columns apart from smart From/To column (#2970)\n- Fix fallback to Larry skin when configured skin isn't available (#3857)\n- Fix (workaround) delete operations with some versions of memcache (#3858)\n- Fix (disable) request validation for spell and spell_html actions", "RELEASE 0.8.0\n-------------\n- Don't show product version on login screen (can be enabled by config)\n- Renamed old default skin to 'classic'. Larry is the new default skin.\n- Support connections to memcached socket file (#3848)\n- Enable TinyMCE inlinepopups plugin\n- Update to TinyMCE 3.5.6\n- Correctly escape localized labels in javascript variable (#3842)\n- Update Net_SMTP/Auth_SASL packages to fix Digest-MD5/Cram-MD5 authentication (#3846)\n- Don't add attachments content into reply/forward/draft message body (#3837)\n- Fix 'no connection' errors on page unloads (#3832)\n- Plugin API: Add 'unauthenticated' hook (#3545)\n- Show explicit error message when provided hostname is invalid (#3834)\n- Fix wrong compose screen elements focus in IE9 (#3826)\n- Fix fatal error when date.timezone isn't set (#3831)\n- Update to TinyMCE 3.5.4.1\n- Better icons with distinct shapes for priority columns (#3706)\n- Show dedicated icon for multipart/report messages (#3813)\n- Properly hide text of icon links/buttons (#3820)\n- Fix handling of unitless CSS size values in HTML message (#3821)\n- Fix removing contact photo using LDAP addressbook (#3737)\n- Fix storing X-ANNIVERSARY date in vCard format (#3816)\n- Update to Mail_Mime-1.8.5 (#3810)\n- Fix XSS vulnerability in message subject handling using Larry skin [CVE-2012-3507] (#3809)\n- Fix handling of links with various URI schemes e.g. \"skype:\" (#3521)\n- Fix handling of links inside PRE elements on html to text conversion\n- Fix indexing of links on html to text conversion\n- Decode header value in rcube_mime::get() by default (#3803)\n- Fix errors with enabled PHP magic_quotes_sybase option (#3798)\n- Fix SQL query for contacts listing on MS SQL Server (#3797)\n- Fix window.resize handler on IE8 and Opera (#3758)\n- Don't let error message popups cover the login form (#3794)\n- Update to TinyMCE 3.5.2\n- Don't show errors when moving contacts into groups they are already in (#3788)\n- Make folders with unread messages in subfolders bold again (#2892)\n- Abbreviate long attachment file names with ellipsis (#3793)\n- Fix html2text conversion of strong|b|a|th|h tags when used in upper case\n- Add listcontrols template container in Larry skin (#3792)\n- Fix host autoselection when default_host is an array (#3790)\n- Move messages forwarding mode setting into Preferences\n- Fix HTML entities handling in HTML editor (#3780)\n- Fix listing shared folders on Courier IMAP (#3767)", "RELEASE 0.8-rc\n--------------\n- Added new translations in Belarusian, Interlingua and Malayalam\n- Flipped compose options arrow (#3772)\n- Fix handling of large uuencode attachments (#3771)\n- Fix handling of \"usemap\" attribute (#3770)\n- Fix handling of some HTML tags e.g. IMG (#3769)\n- Use similar language as a fallback for plugin localization (#3726)\n- Fix issue where signature wasn't re-added on draft compose (#3659)\n- Update to TinyMCE 3.5 (#3762)\n- Fixed multi-threaded autocompletion when number of threads > number of sources\n- Allow to configure the number of values allowed for each LDAP attribute\n- Support for serialized LDAP address values (usually delimited with a $)\n- Less restrictive session auth checks, repeat keep-alive requests on failure (#3755)\n- Fix redirect to mail/compose on re-login (#3585)\n- Add IE8 hack for messages list issue (#3317)\n- Fix handling errors on draft auto-save\n- Fix importing vCard photo with ENCODING param specified (#3746)\n- Support multiple name/email pairs for Bcc and Reply-To identity settings (#3752)\n- Set flexible width to login form fields (#3735)\n- Fix re-draw bug on list columns change in IE8 (#3318)\n- Allow mass-removal of addresses from a group (#3259)\n- Fix removing all contacts on import to LDAP addressbook\n- Fix so \"Back\" from compose/show doesn't reset search request (#3594)\n- Add option to delete messages instead of moving to Trash when in Junk folder (#2805)\n- Fix invisible cursor when replying to a html message (#3100)\n- Reset IP stored in session when destroying session data (#3485)\n- Fix bug where memory_limit = -1 wasn't handled properly\n- Support LDAP RFC2256's country object class read/write (#3535)\n- Upgraded to jQuery 1.7.2\n- Image resize with GD extension (#3712)\n- Fix lack of warning when switching task in compose window (#3725)\n- Fix bug where it wasn't possible to enter ( or & characters in autocomplete fields\n- Request all needed fields from address book backends (#3721)\n- Unified (single) spellchecker button\n- Scroll long lists on drag&drop (#2249)\n- Copy all skins in installto script (#3705)", "RELEASE 0.8-beta\n----------------\n- Upgraded to jQuery 1.7.1 (#3673) and jQuery UI 1.8.18\n- Add Russian to the spellchecker languages list (#3542)\n- Remember custom skin selection after logout (#3688)\n- Make sure About tab is always the last tab (#3609)\n- Fix issue with folder creation under INBOX. namespace (#3683)\n- Added mailto: protocol handler registration link in User Preferences (#2729)\n- Handle identity details box with an iframe (#3066)\n- Fix issue where some text from original message was missing on reply (#3675)\n- Fix autoselect_host() for login (#3639)\n- Changed license to GNU GPLv3+ with exceptions for skins & plugins\n- Added address book widget on compose screen\n- Use proper timezones from PHP's internal timezonedb (#1973)\n- Add separate pagesize setting for mail messages and contacts (#3617)\n- Deprecate $DB, $USER, $IMAP global variables, Use $RCMAIL instead\n- Add option to set default font for HTML message (#894)\n- Fix issues with big memory allocation of IMAP results\n- Prevent from memory_limit exceeding when trying to parse big messages bodies (#3164)\n- Add possibility to add SASL mechanisms for SMTP in smtp_connect hook (#3399)\n- Mark (with different color) folders with recent messages (#2479)\n- Added About tab in Settings\n- TinyMCE updated to 3.4.6", "RELEASE 0.7.2\n-------------\n- Fix encoding of attachment with comma in name (#3717)\n- Fix handling of % character in IMAP protocol (#3711)\n- Fix duplicate names handling in addressbook searches (#3704)\n- Fix displaying of HTML messages from Disqus (#3702)\n- Disable E_STRICT warnings on PHP 5.4\n- Prevent from folder selection on virtual folder collapsing (#3681)\n- Fix automatic unsubscribe of non-existent folders\n- Fix double-quotes handling in recipient names\n- User configurable setting how to display contact names in list\n- Make contacts list sorting configurable for the admin/user\n- Fix parse errors in DDL files for MS SQL Server\n- Revert SORT=DISPLAY support, removed by mistake (#3664)\n- Add lost translation label in de_DE (#3654)\n- Fix drafts update issues when edited from preview pane (#3653)\n- Fix wrong variable name in rcube_ldap.php (#3643)\n- Make mime type detection based on filename extension to be case-insensitive\n- Fix failure on MySQL database upgrade from 0.7 - text column can't have default value (#3642)", "\nRELEASE 0.7.1\n-------------\n- Fix bug in handling of base href and inline content (#3634)\n- Fix SQL Error when saving a contact with many email addresses (#3630)\n- Fix strict email address searching if contact has more than one address\n- Remove duplicated 'organization' label (#3631)\n- Fix so editor selector is hidden when 'htmleditor' is listed in 'dont_override'\n- Fix wrong (long) label usage (#3627)\n- Fix handling of INBOX's subfolders in special folders config (#3623)\n- Add ifModule statement for setting Options -Indexes in .htaccess file (#3620)\n- Fix crashes with eAccelerator (#3608)\n- Fix searching on IMAP servers without CHARSET specifier support (#3619)\n- Fix expanding folders during drag&drop (#3611)\n- Fix wrong postgres sequence name in upgrade from 0.6\n- Fix broken CREATE INDEX queries in SQLite DDL files (#3607)", "RELEASE 0.7\n-----------\n- Make Roundcube render the Email Standards Project Acid Test correctly\n- Replace prompt() with jQuery UI dialog (#1603)\n- Fix navigation in messages search results\n- Improved handling of some malformed values encoded with quoted-printable (#3590)\n- Add possibility to do LDAP bind before searching for bind DN\n- Fix handling of empty <U> tags in HTML messages (#3584)\n- Add content filter for embedded attachments to protect from XSS on IE [CVE-2012-1253] (#3372)\n- Use strpos() instead of strstr() when possible (#3581)\n- Fix handling HTML entities when converting HTML to text (#3582)\n- Fix fit_string_to_size() renders browser and ui unresponsive (#3577)\n- Fix handling of invalid characters in request (#3536)\n- Fix merging some configuration options in update.sh script (#2181)\n- Fix so TEXT key will remove all HEADER keys in IMAP SEARCH (#3578)\n- Fix handling contact photo url with https:// prefix (#3575)\n- Fix possible infinite redirect on attachment preview (#3572)\n- Improved clickjacking protection for browsers which don't support X-Frame-Options headers\n- Fixed bug where similar folder names were highlighted wrong (#3345)\n- Fixed bug in handling link with '!' character in it (#3569)\n- Fixed bug where session ID's length was limited to 40 characters (#3570)\n- TinyMCE security issue: removed moxieplayer (embedding flv and mp4 is not supported anymore)", "RELEASE 0.7-beta\n----------------\n- Fix handling of HTML form elements in messages (#1604)\n- Fix regression in setting recipient to self when replying to a Sent message (#3101)\n- Fix listing of folders in hidden namespaces (#2895)\n- Don't consider \\Noselect flag when building folders tree (#3448)\n- Fix sorting autocomplete results (#3504)\n- Add option to set session name (#2630)\n- Add option to skip alternative email addresses in autocompletion\n- Fix inconsistent behaviour of Compose button in Drafts folder, add Edit button for drafts\n- Fix problem with parsing HTML message body with non-unicode characters (#3312)\n- Add option to define matching method for addressbook search (#2720, #3378)\n- Make email recipients separator configurable\n- Fix so folders with \\Noinferiors attribute aren't listed in parent selector\n- Fix handling of curly brackets in URLs (#3555)\n- Fix handling of dates (birthday/anniversary) in contact data (#3552)\n- Fix error on opening searched LDAP contact (#3550)\n- Fix redundant line break in flowed format (#3551)\n- Fix IDN address validation issue (#3544)\n- Fix JS error when dst_active checkbox doesn't exist (#3540)\n- Autocomplete LDAP records when adding contacts from mail (#3498)\n- Plugin API: added 'ready' hook (#3492)\n- Ignore DSN request when it isn't supported by SMTP server (#3300)\n- Make sure LDAP name fields aren't arrays (#3523)\n- Fixed imap test to non-default port when using ssl (#3532)\n- Force all files to be overwritten when updating (#3531)\n- Fix issue where it wasn't possible to change list view mode in folder manager for INBOX (#3522)\n- Fix namespace handling in special folders settings (#3527)\n- Disable time limit for CLI scripts (#3524)\n- Fix misleading display when chaning editor type (#3519)\n- Add loading indicator on contact delete\n- Fix bug where after delete message rows can be added to the list of another folder (#3263)\n- Add notice on autocompletion that not all records were displayed\n- Add option 'searchonly' for LDAP address books\n- Add Priority filter to the messages list\n- Cache synchronization using QRESYNC/CONDSTORE\n- Trigger 'new_messages' hook for all checked folders (#3503)\n- Make date/time format user configurable; drop 'date_today' config option\n- Fix setting title for truncated subject in IE (#3141)\n- Fix displaying multipart/alternative messages with only one part (#3400)\n- Rewritten messages caching:\n Indexes are stored in a separate table, so there's no need to store all messages in a folder\n Added threads data caching\n Flags are stored separately, so flag change doesn't cause DELETE+INSERT, just UPDATE\n- Improved FETCH response handling\n- Improvements in response tokenization method\n- Use 'From' and 'To' labels instead of 'Sender' and 'Recipient'\n- Fix username case-insensitivity issue in MySQL (#3462)\n- Addressbook Saved Searches\n- Added spellchecker exceptions dictionary (shared or per-user)\n- Added possibility to ignore words containing caps, numbers, symbols (spellcheck_ignore_* options)\n- Added 'priority' column on messages list (#2884)\n- Localize forwarded message header (#3487)", "RELEASE 0.6\n-----------\n- Fix bug where the last identity is used on reply (#3516)\n- Fix locked folder rename option on servers supporting RFC2086 only (#3508)\n- Fix session race conditions when composing new messages\n- Fix encoding of LDAP contacts identifiers (#3501)\n- jQuery 1.6.4\n- Fix handling of binary attachments encoded with quoted-printable (#3494)\n- Fix text-overflow:ellipsis issues on messages list in FF7 and Webkit (#3490)\n- Fix handling of links with IP address\n- Fix compacting folder resets message list filter (#3499)", "RELEASE 0.6-rc\n----------------\n- Send X-Frame-Options headers to protect from clickjacking (#3079)\n- Fallback to mail_domain in LDAP variable replacements; added 'host' to 'user_create' hook arguments (#3464)\n- Fixed wrong vCard type parameter mobile (#3496)\n- Fixed vCard WORKFAX issue (#3476)\n- Add vCard's Profile URL support (#3491)\n- jQuery 1.6.3\n- Fix imap_cache setting to values other than 'db' (#3489)\n- Fix handling of attachments inside message/rfc822 parts (#3466)\n- Make list of mimetypes that open in preview window configurable (#3175)\n- Added plugin hook 'message_part_get' for attachment downloads\n- Added unique connection identifier to IMAP debug messages\n- Fix image type check for contact photo uploads", "RELEASE 0.6-beta\n----------------\n- Fixed selecting identity on reply/forward (#3434)\n- Add option to hide selected LDAP addressbook on the list\n- Add client-side checking of uploaded files size\n- Add newlines between organization, department, jobtitle (#3468)\n- Recalculate date when replying to a message and localize the cite header (#3212)\n- Fix handling of email addresses with quoted local part (#3401)\n- Fix EOL character in vCard exports (#3357)\n- Added optional \"multithreading\" autocomplete feature\n- Plugin API: Added 'config_get' hook\n- Fixed new_user_identity plugin to work with updated rcube_ldap class (#3443)\n- Plugin API: added folder_delete and folder_rename hooks\n- Added possibility to undo last contact delete operation\n- Fix sorting of contact groups after group create (#3258)\n- Add optional textual upload progress indicator (#2330)\n- Fix parsing URLs containing commas (#3425)\n- Added vertical splitter for books/groups list in addressbook (#3389)\n- Improved namespace roots handling in folder manager\n- Added searching in all addressbook sources\n- Added addressbook source selection in contacts import\n- Implement LDAPv3 Virtual List View (VLV) for paged results listing\n- Use 'address_template' config option when adding a new address block (#3406)\n- Added addressbook advanced search\n- Add popup with basic fields selection for addressbook search\n- Case-insensitive matching in autocompletion (#3398)\n- Added option to force spellchecking before sending a message (#1862)\n- Fix handling of \"<\" character in contact data, search fields and folder names (#3349)\n- Fix saving \"<\" character in identity name and organization fields (#3349)\n- Added option to specify to which address book add new contacts\n- Added plugin hook for keep-alive requests\n- Store user preferences in session when write-master is not available and session is stored in memcache, write them later\n- Improve performence of folder manager operations\n- Fix default_port option handling in Installer when config.inc.php file exists (#3390)\n- Removed option focus_on_new_message, added newmail_notifier plugin\n- Added general rcube_cache class with Memcache and APC support\n- Improved caching performance by skipping writes of unchanged data\n- Option enable_caching replaced by imap_cache and messages_cache options\n- Fix WORKFAX saving in address book (#3380)\n- Add forward-as-attachment feature\n- jQuery-1.6.2 (#5158, #3154)\n- Improve display name composition when saving contacts (#3153)\n- Fix problems with subfolders of INBOX folder on some IMAP servers (#3247)\n- Fix handling of folders that doesn't belong to any namespace (#3184)\n- Enable multiselection for attachments uploading in capable browsers (#2266)\n- Add possibility to change HTML editor configuration by skin\n- Fix a bug where selecting too many contacts would produce too large URI request (#3369)\n- Improve performance by including files with absolute path (#3337)\n- Move folder name truncation to client/skin (#1822)\n- Added plugin hook for request token creation\n- Replace LDAP vars in group queries (#3329)\n- Fix vcard folding with uncode characters (#3353)\n- Keep all submitted data if contact form validation fails (#3350)\n- Handle uncode strings in rcube_addressbook::normalize_string() (#3351)\n- Fix handling of debug_level=4 in ajax requests (#3327)\n- Enable TinyMCE's contextmenu (#3062)\n- Allow multiple concurrent compose sessions\n- New config option for custom logo\n- Allow skins to define/override texts with <roundcube:label />\n- Add simple ACL rights/namespace handling in folder manager\n- Force IE to send referers (#3306)\n- Better display of vcard import results (#1861)\n- Improved vcard import\n- Interactive update script with improved DB schema check\n- Fix problem with contactgroupmembers table creation on MySQL 4.x, add index on contact_id column\n- Add LDAP SASL bind and proxy authentication (#2810)\n- Replying to a sent message puts the old recipient as the new recipient (#3101)\n- Fulltext search over (almost) all data for contacts\n- Extend address book with rich contact information", "RELEASE 0.5.4\n-------------\n- Fix XSS vulnerability in UI messages [CVE-2011-2937] (#3469)", "RELEASE 0.5.3\n-------------\n- Fix identities \"reply-to\" and \"bcc\" fields have a bogus value when left empty (#3405)\n- Fix issue which cases IMAP disconnection when encrypt() method was used (#3374)\n- Fix some CSS issues in Settings for Internet Explorer \n- Fixed handling of folder with name \"0\" in folder selector\n- Fix bug where messages were deleted instead moved to trash folder after Shift key was used (#3376)\n- Fix relative URLs handling according to a <base> in HTML (#3368)\n- Fix handling of top-level domains with more than 5 chars or unicode chars (#3366)\n- Fix usage of non-standard HTTP error codes (#3297)\n- Fix PHP warning on mistaken in_array() usage (#3375)", "RELEASE 0.5.2\n-------------\n- TinyMCE 3.4.2 now compatible with IE9\n- PEAR::Net_SMTP 1.5.2, fixed timeout issue (#3332)\n- Fix bug where template name without plugin prefix was used in render_page hook\n- Support 'abort' and 'result' response in 'preferences_save' hook, add error handling\n- Fix bug where some content would cause hang on html2text conversion (#3348)\n- Improve space-stuffing handling in format=flowed messages (#3346)\n- Fix bug where some dates would produce SQL error in MySQL (#3342)\n- Added workaround for some IMAP server with broken STATUS response (#3344)\n- Fix bug where default_charset was not used for text messages (#3328)\n- Stateless request tokens. No keep-alive necessary on login page (#3325)\n- Force names of unique constraints in PostgreSQL DDL\n- Add code for prevention from IMAP connection hangs when server closes socket unexpectedly\n- Remove redundant DELETE query (for old session deletion) on login\n- Get around unreliable rand() and mt_rand() in session ID generation (#2516)\n- Fix some emails are not shown using Cyrus IMAP (#3316)\n- Fix handling of mime-encoded words with non-integral number of octets in a word (#3301)\n- Fix parsing links with non-printable characters inside (#3305)\n- Fixed de_CH Localization bugs (#3279)\n- Add variable for 'Today' label in date_today option (#2394)\n- Fix dont_override setting does not override existing user preferences (#3205)\n- Use only one from IMAP authentication methods to prevent login delays (1487784)\n- Support strftime format in date_today option\n- Fix SQL query in rcube_user::query() so it uses index on MySQL again\n- Removed redundant </form> tags from contact add/edit pages\n- Fix CSS error in contact details screen on IE7 (#3281)", "RELEASE 0.5.1\n-------------\n- Fix handling of attachments with invalid content type (#3275)\n- Add workaround for DBMail's bug http://www.dbmail.org/mantis/view.php?id=881 (#3274)\n- Use IMAP's ID extension (RFC2971) to print more info into debug log\n- Security: add optional referer check to prevent CSRF in GET requests\n- Fix email_dns_check setting not used for identities/contacts (#3251)\n- Fix ICANN example addresses doesn't validate (#3253)\n- Security: protect login form submission from CSRF [CVE-2011-1491]\n- Security: prevent from relaying malicious requests through modcss.inc [CVE-2011-1492]\n- Fix handling of non-image attachments in multipart/related messages (#3261)\n- Fix IDNA support when IDN/INTL modules are in use (#3253)\n- Fix handling of invalid HTML comments in messages (#3269)\n- Fix parsing FETCH response for very long headers (#3264)\n- Fix add/remove columns in message list when message_sort_order isn't set (#3262)\n- Check mime headers before attempt to parse them (#3256)\n- Quote header values in show_additional_headers plugin (#3255)\n- Fix settings UI on IE 6 (#3246)\n- Remove double borders in folder listing (#3236)\n- Separate full message headers UI element from headers table (#3238)\n- Add part MIME ID to message_part_* hooks (#3241) \n- Improve parsing of MS Outlook vCards (#3239)\n- Updated PEAR::Net_Socket to 1.0.10\n- Updated PEAR::Net_IDNA2 to 0.1.1\n- Fix handling of comments inside an email address spec. (#3210)\n- Show full mail subject as title when hovering a cut subject link (#3141)\n- Fix randomly disappearing folders list in IE (#3231)\n- Fix list column add/removal in IE (#3230)\n- Fix login redirect issues (#3221)\n- Require PHP 5.2.1 or greater\n- Fix %h/%z variables in username_domain option (#3228)\n- Workaround for setting charset in case of malformed bodystructure response (#3227)\n- Fix impossible to subscribe to protected folders (#3199)\n- Fix setting timezone in Preferences (#3232)", "RELEASE 0.5\n-----------\n- Fix double-login/session issue (#3124)\n- Wrap HTML parts with <html><body> and add Doctype declaration (#3119)\n- Make rcube_autoload silently skip unknown classes (#3128)\n- Fix charset detection in vcards with encoded values (#1934)\n- Better CSS cursors for splitters (#2954)\n- Show the same message only once (#3186)\n- Fix namespaces handling (#3192)\n- Add handling of multifolder METADATA/ANNOTATION responses\n- Fix handling of INBOX when personal namespace prefix is non-empty (#3200)\n- Fix handling square brackets in links (#3209)\n- Add description of 'use_https' option in main.inc.php.dist file", "RELEASE 0.5-RC\n--------------\n- Plugin API: Add 'pass' argument in 'authenticate' hook (#3147)\n- Fix attachments of type message/rfc822 are not listed on attachments list\n- Add 'login_lc' config option for case-insensitive authentication (#3131)\n- Fix window is blur'ed in IE when selecting a message (#3161)\n- Fix cursor position on compose form in Webkit browsers (#2796)\n- Fix setting charset of attachment filenames (#3136)\n- Allow setting autocomplete attribute for all inputs separately (#3158)\n- New Folder Manager UI\n- Fix invalid Request when creating a folder (#3165)\n- Add folder size and quota indicator in folder manager (#2112)\n- Add possibility to move a subfolder into root folder (#2890)\n- Fix copying all messages in a folder copies only messages from current page\n- Improve performance of moving or copying of all messages in a folder\n- Fix plaintext versions of HTML messages don't contain placeholders for emotions (#1657)\n- Improve performance of folder rename and delete actions\n- Better support for READ-ONLY and NOPERM responses handling (#3108)\n- Add confirmation message on purge/expunge command response\n- Fix handling of untagged responses for AUTHENTICATE command (#3171)\n- Add username and IP address to log message on unsuccessful login (#3176)\n- Improved Mail-Followup-To and Mail-Reply-To headers handling\n- Fix charset conversion for text attachments without charset specification (#3181)", "RELEASE 0.5-BETA\n----------------\n- Make session data storage more robust against garbage session data (#3148)\n- Config option for autocomplete on login screen\n- Allow plugin templates to include local files (#3146)\n- List groups in address detail view and allow to subscribe/unsubscribe from there (#2862)\n- Messages caching: performance improvements, fixed syncing, fixes related with #2857\n- Add link to identities in compose window (#2843)\n- Add Internationalized Domain Name (IDNA) support (#729)\n- Add option to automatically send read notifications for known senders (#2199)\n- Add option to \"Return receipt\" will be always checked (#2571)\n- Fix HTML to plain text conversion doesn't handle citation blocks (#2992)\n- Use custom sorting when SORT is disabled by IMAP admin (#3020)\n- Allow setting some washtml options from plugin (#2727)\n- Add option do bind for an individual LDAP address book (#3048)\n- Change reply prefix to display email address only if sender name doesn't exist (#2709)\n- Plugin API: improved 'abort' flag handling, added 'result' item in some hooks (#2988)\n- Fix mailto optional params in plain text messages aren't handled (#3071)\n- Add Reply-to-List feature (#977)\n- Add Mail-Followup-To/Mail-Reply-To support (#1937)\n- Fix confirmation message isn't displayed after sending mail on Chrome (#2437)\n- Fix keyboard doesn't work with autocomplete list with Chrome (#3073)\n- Improve tabs to fixed width and add tabs in identities info (#3030)\n- Add unique index on users.username+users.mail_host\n- Make htmleditor option more consistent and add option to use HTML on reply to HTML message (#2164)\n- Use empty envelope sender address for message disposition notifications (RFC 2298.3)\n- Support SMTP Delivery Status Notifications - RFC 3461 (#2409)\n- Use css sprite image for messages list\n- Add (different) attachment icon for messages of type multipart/report (#2426)\n- Prevent from inserting empty link when composing HTML message (#3007)\n- Add caching support in id2uid and uid2id functions (#3065)\n- Add SASL proxy authentication for SMTP (#2811)\n- Improve displaying of UI messages (#3033)\n- Fix double e-mail filed in identity form (#3088)\n- Display IMAP errors for LIST/THREAD/SEARCH commands (#2981)\n- Add LITERAL+ (IMAP4 non-synchronizing literals) support (RFC 2088)\n- Add separate column for message status icon (#2788)\n- Add ACL extension support into IMAP classes (RFC 4314)\n- Add ANNOTATEMORE extension support into IMAP classes (draft-daboo-imap-annotatemore)\n- Add METADATA extension support into IMAP classes (RFC 5464)\n- Fix decoding of e-mail address strings in message headers (#3097)\n- Fix handling of attachments when Content-Disposition is not inline nor attachment (#3086)\n- Improve performance of unseen messages counting (#3090)\n- Improve performance of messages counting using ESEARCH extension (RFC4731)\n- Add LIST-STATUS support in rcube_imap_generic class (RFC 5819)\n- Add SASL-IR support in IMAP (RFC 4959)\n- Add LOGINDISABLED support (RFC 2595)\n- Add support for AUTH=PLAIN in IMAP authentication\n- Re-implemented SMTP proxy authentication support\n- Add support for IMAP proxy authentication (#2808)\n- Add support for AUTH=DIGEST-MD5 in IMAP (RFC 2831)\n- Fix parent folder with unread subfolder not bold when message is open (#3104)\n- Add basic IMAP LIST's \\Noselect option support\n- Add support for selection options from LIST-EXTENDED extension (RFC 5258)\n- Don't list subscribed but non-existent folders (#2474)\n- Fix handling of URLs with tilde (~) or semicolon (;) character (#3110, #3111)\n- Plugin API: added 'contact_form' hook\n- Add SORT=DISPLAY support (RFC 5957)\n- Plugin API: add possibility to disable plugin in AJAX mode, 'noajax' property\n- Plugin API: add possibility to disable plugin in framed mode, 'noframe' property\n- Improve performance of setting IMAP flags using .SILENT suffix\n- Improve performance of message cache status checking with skip_disabled=true\n- Support contact's email addresses up to 255 characters long (#3116)\n- Add option to place replies in the folder of the message being replied to (#2248)\n- Add missing confirmation/error messages on contact/group/message actions (#2935)\n- Add 'loading' message on message move/copy/delete/mark actions\n- Improve responsiveness of messages displaying (#3039)\n- Add option for minimum length of autocomplete's string (#2625)\n- Fix operations on messages in unsubscribed folder (#3126)\n- Add support for shared folders (#525)\n- Fix handling of folders with name \"0\" (#3133)\n- Fix handling of folders with \"<>\" characters in name\n- jQuery 1.4.4\n- Fix handling of HTML entity strings in plain text messages\n- Fix focused elements aren't unfocused when clicking on the list (#3137)\n- Fix error in MSSQL DDL scripts (#3130)\n- Lock submit button in onsubmit event on login page (#3078)\n- Don't set attachment's charset in Content-type header (#3136)\n- Fix handling of message bodies (quoted-printable encoded) with NULL characters (#2448)\n- Add workaround for MSOE's multipart/related messages with non-related attachments", "RELEASE 0.4.2\n-------------\n- Fix handling of backslash as IMAP delimiter\n- Fix charset replacement in HTML message bodies (#3067)\n- Fix: contact group input is empty when using rename action more than once on the same group record\n- Fix \"Server Error! (Not Found)\" when using utils/save-pref action (#3069)\n- Fix handling of Thunderbird's vCards (#3070)", "RELEASE 0.4.1\n-------------\n- Fix space-stuffing in format=flowed messages (#3064)\n- Fix msgexport.sh now using the new imap wrapper\n- Avoid displaying password on shell (#3010)\n- Only lower-case user name if first login attempt failed (#2600)\n- Make alias setting in squirrelmail_usercopy plugin configurable (patch by pommi, #3056)\n- Prevent from saving a non-existing skin path in user prefs (#3004)\n- Improve handling of single-part messages with bogus BODYSTRUCTURE (#2976)\n- Fix path to SQL files when using pgsql/mysqli/sqlsrv drivers (#2979)\n- Fix upgrade script for SQLite (#2980)\n- Fixes in SQL init script + added update script for MSSQL database\n- Remove redundant date in syslog messages (#3008)\n- Fix contacts list page controls when a group is selected (#3009)\n- Fix SMTP test in Installer (#3014)\n- Fix \"Select all\" causes message to be opened in folder with exactly one message (#2987)\n- Fix Tab key doesn't work in HTML editor in Google Chrome (#2995)\n- Fix TinyMCE uses zh_CN when zh_TW locale is set (#2998)\n- Fix TinyMCE buttons are hidden in Opera (#2993)\n- Fix JS error on IE when trying to send HTML message with enabled spellchecker (#3006)\n- Display inline images with known extensions and non-image content-type (#3002)\n- Fix \"Threaded\" checkbox after subfolder creation (#2997)\n- Fix timezone string in sent mail (#3021)\n- Show disabled checkboxes for protected folders instead of dots (#1898)\n- Added fieldsets in Identity form, added 'identity_form' hook\n- Re-added 'Close' button in upload form (#2999, #2917)\n- Fix handling of charsets with LATIN-* label\n- Fix messages background image handling in some cases (#3043)\n- Fix format=flowed handling (#3042)\n- Fix when IMAP connection fails in 'get' action session shouldn't be destroyed (#3046)\n- Fix list_cols is not updated after column dragging (#3050)\n- Support %z variable in host configuration options (#3054)", "RELEASE 0.4\n-----------\n- Fix disappearing upload form disappears when user selects a file on Safari (#2917)\n- Don't replace error messages with loading info (#2534)\n- Fix JS errors on compose mode switch (#2952)\n- Fix message structure parsing when it lacks optional fields (#2960)\n- Include all recipients in sendmail log\n- Support HTTP_X_FORWARDED_PROTO header for HTTPS detecting (#2950)\n- Fix default IMAP port configuration (#2948)\n- Create Sent folder when starting to compose a new message (#2900)\n- Fix handling of messages with Content-Type: application/* and no filename (#840)\n- Improved compose screen: resizable body and attachments list, vertical splitter, options menu\n- Fix RC forgets search results (#722)\n- TinyMCE 3.3.7\n- Improve parsing of styled empty tags in HTML messages (#2908)\n- Add %dc variable support in base_dn/bind_dn config (#2881)\n- Add button to hide/unhide the preview pane (#955)\n- Fix no-cache headers on https to prevent content caching by proxies (#2897)\n- Fix attachment filenames broken with TNEF decoder using long filenames (#2894)\n- Use user's timezone in Date header, not server's timezone (#2393)\n- Add option to set separate footer for HTML messages (#2784)\n- Add real SMTP error description to displayed error messages (#2233)\n- Fix some IMAP errors handling when opening the message (#1848)\n- Fix related parts aren't displayed when got mimetype other than image/* (#2629)\n- Multiple identity and database support for squirrelmail_usercopy plugin (#2686)\n- Support dynamic hostname (%d/%n) variables in configuration options (#1843)\n- Add 'messages_list' hook (#2504)\n- Add request* event triggers in http_post/http_request (#2340)\n- Fix use RFC-compliant line-delimiter when saving messages on IMAP (#2828)\n- Add 'imap_timeout' option (#2869)\n- Fix forwarding of messages with winmail attachments\n- Fix handling of uuencoded attachments in message body (#2163)\n- Added list_mailboxes hook in rcube_imap::list_unsubscribed() (#2791)\n- Fix wrong message on file upload error (#2839)\n- Add support for data URI scheme [RFC2397] (#2851)\n- Added 'actionbefore', 'actionafter', 'responsebefore', 'responseafter' events\n- Fix double-addition of e-mail domain to content ID in HTML images\n- Read and send messages with format=flowed (#1052), fixes word wrapping issues (#2703)\n- Fix duplicated attachments when forwarding a message (#2670)\n- Fix message/rfc822 attachments containing only attachments are not parsed properly (#2854)\n- Fix %00 character in winmail.dat attachments names (#2850)\n- Fix handling errors of folder deletion (#2821)\n- Parse untagged CAPABILITY response for LOGIN command (#2853)\n- Renamed all php-cli scripts to use .sh extension\n- Some files from /bin + spellchecking actions moved to the new 'utils' task\n- Added thread tree icons\n- Extend contact groups support (#2802)\n- Fix check-recent action issues and performance (#2690)\n- Fix messages order after checking for recent (#1249)\n- Fix autocomplete shows entries without email (#2640)\n- Fix listupdate event doesn't trigger on search response (#2824)\n- Fix select_all_mode value after selecting a message (#2834)\n- Set focus to editor on reply in HTML mode (#2768)\n- Fix composing in HTML jumps cursor to body instead of recipients (#2796)\n- Allow columns order change per user - drag&drop (#2124)\n- Add References header in read receipt (#2801)\n- Fix database constraint violation when opening a message (#2814)\n- Add 'loading' message while login is in progress (#2790)\n- Fix quota_zero_as_unlimited (#2786)\n- Fix folder subscription checking (#2804)\n- Fix INBOX appears (sometimes) twice in mailbox list (#2794)\n- Fix listing of attachments of some types e.g. \"x-epoc/x-sisx-app\" (#2779)\n- Fix DB Schema checking when some db_table_* options are not set (#2780)", "RELEASE 0.4-beta\n----------------\n- Add sizelimit and timelimit variables in LDAP config (#2704)\n- Hide IMAP host dropdown when single host is defined (#2553)\n- Add images pre-loading on login page (#623)\n- Add HTTP_X_REAL_IP and HTTP_X_FORWARDED_FOR to successful logins log (#2634)\n- Fix setting spellcheck languages with extended codes (#2747)\n- Fix messages list scrolling in FF3.6 (#2657)\n- Fix quicksearch input focus (#2770)\n- Always set changed date when flagging a DB record as deleted + provide a cleanup script\n- Fix address book/group selection (#2760)\n- Assign newly created contacts to the active group (#2764)\n- Added option not to mark messages as read when viewed in preview pane (#1513)\n- Allow plugins modify the Sent folder when composing (#2708)\n- Added optional (max_recipients) support to restrict total number of recipients per message (#1167)\n- Re-organize editor buttons, add blockquote and search buttons\n- Make possible to write inside or after a quoted html message (#1878)\n- Fix bugs on unexpected IMAP connection close (#2449, #2507)\n- Iloha's imap.inc rewritten into rcube_imap_generic class\n- Added contact groups in address book (not finished yet)\n- Added PageUp/PageDown/Home/End keys support on lists (#2627)\n- Added possibility to select all messages in a folder (#1312)\n- Added 'imap_force_caps' option for after-login CAPABILITY checking (#2087)\n- Password: Support dovecotpw encryption\n- TinyMCE 3.3.1\n- Implemented messages copying using drag&drop + SHIFT (#863)\n- Improved performance of folders operations (#2689)\n- Fix blocked.gif attachment is not attached to the message (#2685)\n- Managesieve: import from Horde-INGO\n- Managesieve: support for more than one match (#2362)\n- Managesieve: support for selectively disabling rules within a single sieve script (#2198)\n- Threaded message listing now available\n- Added sorting by ARRIVAL and CC\n- Message list columns configurable by the user\n- Removed 'index_sort' option, now we're using empty 'message_sort_col' for this\n- virtuser_query: support other identity data (#2413)\n- Options virtuser_* replaced with virtuser_* plugins\n- Plugin API: Implemented 'email2user' and 'user2email' hooks\n- Fix forwarding message omits CC header (#2538)\n- Add 'default_charset' option to user preferences (#1855)\n- Add 'delete_always' option to user preferences\n- Support/Require tls:// prefix in 'smtp_server' option for TLS connections\n- Fix inconsistent behaviour of 'delete_always' option (#2533)\n- Fix deleting all messages from last list page (#2528)\n- Flag original messages when sending a draft (#2458)\n- Changed signature separator when top-posting (#2555)\n- Let the admin define defaults for search modifiers (#2211)\n- Fix long e-mail addresses validation (#2641)\n- Remember search modifiers in user prefs (#2411)\n- Added force_7bit option to force MIME encoding of plain/text messages (#2679)\n- Use case sensitive check when checking for default folders (#2567)\n- Fix checking for new mail: now checks unseen count of inbox (#2123)\n- Improve performance by avoiding unnecessary updates to the session table (#2552)\n- Fix invalid <font> tags which cause HTML message rendering problems (#2687)\n- Fix CVE-2010-0464: Disable DNS prefetching (#2639)\n- Fix Received headers to behave better with SpamAssassin (#2682)\n- Password: Make passwords encoding consistent with core, add 'password_charset' global option (#2658)\n- Fix adding contacts SQL error on mysql (#2645)\n- Squirrelmail_usercopy: support reply-to field (#2678)\n- Fix IE spellcheck suggestion popup issue (#2656)\n- Fix email address auto-completion shows regexp pattern (#2498)\n- Fix merging of configuration parameters: user prefs always survive (#2584) \n- Fix quota indicator value after folder purge/expunge (#2671)\n- Fix external mailto links support for use as protocol handler (#2328)\n- Fix attachment excessive memory use, support messages of any size (#1245)\n- Fix setting task name according to auth state\n- Password: fix vpopmaild driver (#2662)\n- Add workaround for MySQL bug [http://bugs.mysql.com/bug.php?id=46293] (#2659)\n- Fix quoted text wrapping when replying to an HTML email in plain text (#897)\n- Fix handling of extended mailto links (with params) (#2573)\n- Fix sorting by date of messages without date header on servers without SORT (#2521)\n- Fix inconsistency when not using default table names (#2652)\n- Fix folder rename/delete buttons do not appear on creation of first folder (#2653)\n- Fix character set conversion fails on systems where iconv doesn't accept //IGNORE (#2590)\n- Log in performance: Create default folders on first login only\n- Import contacts into the selected address book (by Phil Weir)\n- Add support for MDB2's 'sqlsrv' driver (#2602)\n- Use jQuery-1.4\n- Removed problematic browser-caching of messages\n- Fix incompatybility with suhosin.executor.disable_emodifier (#2549)\n- Use PLAIN auth when CRAM fails and imap_auth_type='check' (#2587)\n- Fix removal of <title> tag from HTML messages (#2629)\n- Fix 'force_https' to specified port when URL contains a port number (#2612)\n- Fix to-text converting of HTML entities inside b/strong/th/hX tags (#2621)\n- Bug in spellchecker suggestions when server charset != UTF8 (#2607)\n- Managesieve: Fix requires generation for multiple actions (#2603)\n- Fix LDAP problem with special characters in RDN (#2548)\n- Improved handling of message parts of type message/rfc822\n- Plugin API: added 'quota' hook\n- Fix parsing conditional comments in HTML messages (#2569)\n- Use built-in json_encode() for proper JSON format in AJAX replies\n- Allow setting only selected params in 'message_compose' hook (#2543)\n- Plugin API: added 'message_compose_body' hook (#2520)\n- Fix counters of all folders are checked in 'getunread' action with check_all_folders disabled (#2399)\n- Fix displaying alternative parts in messages of type message/rfc822 (#2488)\n- Fix possible messages exposure when using Roundcube behind a proxy (#2516)\n- Fix unicode para and line separators in javascript response (#2542)\n- Additional_message_headers: allow unsetting headers, support plugin's config file (#2505)\n- Fix displaying of hidden directories in skins list (#2535)\n- Fix open_basedir restriction error when reading skins list (#2537)\n- Fix pasting from Office apps into html editor (#2508)\n- Fix empty <a> tags parsing (#2509)\n- Don't cut off attachment names when using non-RFC2231 encoding (#1912)\n- Allow inserting signatures above replied message body (#991)\n- Managesieve 2.0: multi-script support\n- Fix imap_auth_type regression (#2502)", "RELEASE 0.3.1\n------------------\n- Specify toolbar container in compose template (#2489)\n- Fix $_SERVER['HTTPS'] check for SSL forcing on IIS (#2486)\n- Avoid unnecessary page loads for selected tab (#2324)\n- Fix quota indicator issues by content generation on client-size (#2454, #2470)\n- Don't display disabled sections in Settings (#2380)\n- Added server-side e-mail address validation with 'email_dns_check' option (#2175)\n- Fix login page loading into an iframe when session expires (#2253)\n- Allow setting port number in 'force_https' option (#2373)\n- Option 'force_https' replaced by 'force_https' plugin\n- Fix IE issue with non-UTF-8 characters in AJAX response (#2422)\n- Partially fixed \"empty body\" issue by showing raw body of malformed message (#2427)\n- Fix importing/sending to email address with whitespace (#2467)\n- Added XIMSS (CommuniGate) driver for Password plugin\n- Fix newly attached files are not saved in drafts w/o editing any text (#2457)\n- Added attachment upload indicator with parallel upload (#2344)\n- Use default_charset for bodies of messages without charset definition (#2446)\n- Password: added cPanel driver\n- Fix return to first page from e-mail screen (#2385)\n- Fix handling HTML comments in HTML messages (#2448)\n- Fix folder/messagelist controls alignment - icons used (#2356)\n- Fix LDAP addressbook shows 'Contact not found' error sometimes (#2438)\n- Fix cache status checking + improve cache operations performance (#2384)\n- Prevent from setting INBOX as any of special folders (#2390)\n- Fix regular expression for e-mail address (#2417)\n- Fix Received header format\n- Implemented sorting by message index - added 'index_sort' option (#2240)\n- Fix dl() use in installer (#2415)\n- Added 'ldap_debug' option\n- Fix \"Empty startup greeting\" bug (#2369)\n- Fix setting user name in 'new_user_identity' plugin (#2405)\n- Fix incorrect count of new messages in folder list when using multiple IMAP clients (#2289)\n- Fix all folders checking for new messages with disabled caching (#2399)\n- Support skins in 'archive' and 'markasjunk' plugins\n- Added 'html_editor' hook (#2353)\n- Fix DB constraint violation when populating messages cache (#2338)\n- Password: added password strength options (#2348)\n- Fix LDAP partial result warning (#1928)\n- Fix delete in message view deletes permanently with flag_for_deletion=true (#2382)\n- Use faster/secure mt_rand() (#2376)\n- Fix roundcube hangs on empty inbox with bincimapd (#2375)\n- Fix wrong headers for IE on servers without $_SERVER['HTTPS'] (#2232)\n- Force IE style headers for attachments in non-HTTPS session, 'use_https' option (#2023)\n- Check 'post_max_size' for upload max filesize (#2372) \n- Password Plugin: Fix %d inserts username instead of domain (#2371)\n- Fix rcube_mdb2::affected_rows() (#2366)", "RELEASE 0.3-stable\n------------------\n- Fix gn and givenName should be synonymous in LDAP addressbook (#2208)\n- Add mail_domain to LDAP email entries without @ sign (#1652)\n- Fix saving empty values in LDAP contact data (#2113)\n- Fix LDAP contact update when RDN field is changed (#2119)\n- Fix LDAP attributes case senitivity problems (#2155)\n- Fix LDAP addressbook browsing when only one directory is used (#2314)\n- Fix endless loop on error response for APPEND command (#2346)\n- Don't require date.timezone setting in installer (#2284)\n- Fix date sorting problem with Courier IMAP server (#2351)\n- Unselect pressed buttons on mouse up (#2283)\n- Don't set php_value error_log in .htaccess but mention in INSTALL (#2230)\n- Fix too small status/flag/attachment columns in Safari 4 (#2349)\n- Fix selection disabling while dragging splitter in webkit browsers (#2342)\n- Added 'new_messages' plugin hook (#2298)\n- Added 'logout_after' plugin hook (#2333)\n- Added 'message_compose' hook\n- Added 'imap_connect' hook (#2256)\n- Fix vcard_attachments plugin (#2326)\n- Updated PEAR::Auth_SASL to 1.0.3 version\n- Use sequence names only with PostgreSQL (#2310)\n- Re-designed User Preferences interface \n- Fix MS SQL DDL (#2312)\n- Fix rcube_mdb2.php: call to setCharset not implemented in mssql driver (#2311)\n- Added 'display_next' option\n- Fix rcube_mdb2::unixtimestamp for MS SQL (#2308)\n- Fix HTML washing to respect character encoding\n- Fix endless loop in iil_C_Login() with Courier IMAP (#2303)\n- Fix #messagemenu display on IE (#2299)\n- Speedup UI by using sprites for (toolbar) buttons\n- Fix charset names with X- prefix handling\n- Fix displaying of HTML messages with unknown/malformed tags (#2296)", "RELEASE 0.3-RC1\n---------------\n- Fix import of vCard entries with params (#1857)\n- Fix HTML messages output with empty block elements (#2271)\n- Use request tokens to protect POST requests from CSRF [CVE-2009-4076, CVE-2009-4077]\n- Added hook when killing a session\n- Added hook to write_log function (#2268)\n- Performance improvements by use UID commands (#2046)\n- Fix HTML editor tabIndex setting (#2269)\n- Added 'imap_debug' and 'smtp_debug' options\n- Support strftime's format modifiers in date_* options (#1354)\n- Support %h variable in 'smtp_server' option (#2101)\n- Show SMTP errors in browser (#2233)\n- Allow WBR tag in HTML message (#2259)\n- Use spl_autoload_register() instead of __autoload (#2250)\n- Add hook for identities listing (#2257)\n- Trigger hook 'smtp_connect' when opening an SMTP connection (#2255)\n- Added config option to enforce HTTPS connections\n- Fix non-unicode characters caching in unicode database (#1209)\n- Performance improvements of messages caching\n- Fix empty Date header issue (#2229)\n- Open collapsed folders during drag & drop (#2221)\n- Fixed link text replacements (#2120)\n- Also trigger 'insertrow' events on page load (#2151)\n- No link on subject in IE browsers (#1438)\n- Fixed filename encoding according to RFC2231 (#2192)\n- Added message Edit feature (#727, #1101)\n- Fix message Etag generation for counter issues (#1996)\n- Fix messages searching on MailEnable IMAP (#2097)\n- Fixed many 'skip_deleted' issues (#2006)\n- Fixed messages list sorting on servers without SORT capability\n- Colorized signatures in plain text messages\n- Reviewed/fixed skip_deleted/read_when_deleted/flag_for_deletion options handling in UI\n- Fix displaying of big maximum upload filesize (#2205)\n- Added possibility to invert messages selection\n- After move/delete from 'show' action display next message instead of messages list (#2203)\n- Fixed problem with double quote at the end of folder name (#2200)\n- Speedup UI by using CSS sprites and etags/expires/deflate in Apache config (#1397,#2128)\n- Support UID EXPUNGE: remove only moved/deleted messages\n- Add drag cancelling with ESC key (#1036)\n- Support initial identity name from virtuser_query (#807)\n- Added message menu, removed Print and Source buttons\n- Added possibility to save message as .eml file (#2178)\n- Added 1 minute interval in autosave options (#2173)\n- Support UTF-7 encoding in messages (#2156)\n- Better support for malformed character names (#2093)", "RELEASE 0.3-BETA\n----------------\n- Plugin API + jQuery engine\n- Added possibility to encrypt received header, option 'http_received_header_encrypt',\n added some more logic in encrypt/decrypt functions for security\n- Fix Answered/Forwarded flag setting for messages in subfolders\n- Fix autocomplete problem with capital letters (#2122)\n- Support UUencode content encoding (#2163)\n- Minimize chance of race condition in session handling (#1260)\n- Fix session handling on non-session SQL query error (#2078)\n- Fix html editor mode setting when reopening draft message (#2158)\n- Added quick search box menu (#1010)\n- Fix wrong column sort order icons (#2149)\n- Updated TinyMCE to 3.2.3 version\n- Fix attachment names encoding when charset isn't specified in attachment part (#1483)\n- Fix message normal priority problem (#2146)\n- Fix autocomplete spinning wheel does not disappear (#2132)\n- Added log_date_format option (#2060)\n- Fix text wrapping in HTML editor after switching from plain text to HTML (#1917)\n- Fix auto-complete function hangs with plus sign (#2141)\n- Fix AJAX requests errors handler (#1503)\n- Speed up message list displaying on IE\n- Fix read/write database recognition (#2137)", "RELEASE 0.2.2\n-------------\n- Fix quicksearchbox look in Chrome and Konqueror (#1380)\n- Fix UTF-8 byte-order mark removing (#1911)\n- Fix folders subscribtions on Konqueror (#1380) \n- Fix debug console on Konqueror and Safari\n- Fix messagelist focus issue when modifying status of selected messages (#2134)\n- Support STARTTLS in IMAP connection (#1714)\n- Fix DEL key problem in search boxes (#1923)\n- Support several e-mail addresses per user from virtuser_file (#2036)\n- Fix drag&drop with scrolling on IE (#2117)\n- Fix adding signature separator in html mode (#1768)\n- Fix opening attachment marks message as read (#2131)\n- Fix 'temp_dir' does not support relative path under Windows (#1157)\n- Fix \"Initialize Database\" button missing from installer (#2130)\n- Fix compose window doesn't fit 1024x768 window (#1807)\n- Fix service not available error when pressing back from compose dialog (#1942)\n- Fix using mail() on Windows (#2111)\n- Fix word wrapping in message-part's <PRE>s for printing (#2118)\n- Fix incorrect word wrapping in outgoing plaintext multibyte messages (#2062)\n- Fix double footer in HTML message with embedded images\n- Fix TNEF implementation bug (#2107)\n- Fix incorrect row id parsing for LDAP contacts list (#2116) \n- Fix 'mode' parameter in sqlite DSN (#2106)", "RELEASE 0.2.1\n------------------\n- Use US-ASCII as failover when Unicode searching fails (#2097)\n- Fix errors handling in IMAP command continuations (#2097)\n- Fix FETCH result parsing for servers returning flags at the end of result (#2098)\n- Fix datetime columns defaults in mysql's DDL (#2012)\n- Fix attaching more than nine inline images (#2094)\n- Support 'UNICODE-1-1-UTF-7' alias for UTF-7 encoding (#2093)\n- Fix mime-type detection using a hard-coded map (#1735)\n- Don't return empty string if charset conversion failed (#2092)\n- Disable concurrent autocomplete query results display (#2082)\n- Fix new lines stripped from message footer (#2088)\n- Fix IE problem with mouse click autocomplete (#2080)\n- Fix html body washing on reply/forward + fix attachments handling (#2034)\n- Fix multiple recipients input parsing (#2077)\n- Fix replying to message with html attachment (#2034)\n- Use default_charset for messages without specified charset (#2027, #1484961)\n- Support non-standard \"GMT-XXXX\" literal in date header (#2074)\n- Added TNEF support to decode MS Outlook attachments (winmail.dat)\n- Fix \"value continuation\" MIME headers by adding required semicolon (#2073)\n- Fix pressing select all/unread multiple times (#2069)\n- Fix selecting all unread does not honor new messages (#2070)\n- Fix some base64 encoded attachments handling (#2071)\n- Support NGINX as IMAP backend: better BAD response handling (#2066)\n- Performance fix: don't fetch attachment parts headers twice to parse filename\n- Fix checking for recent messages on various IMAP servers (#2055)\n- Performance fix: Don't fetch quota and recent messages in \"message view\" mode\n- Fix displaying of alternative-inside-alternative messages (#2061)\n- Fix MDNSent flag checking, use arbitrary keywords (asterisk) flag (#2059)\n- Fix creation of folders with '&' sign in name\n- Fix parsing of email addresses without angle brackets (#2048)\n- Save spellcheck corrections when switching from plain to html editor (and spellchecking is on)\n- Fix large search results on server without SORT capability (#2031)\n- Get rid of preg_replace() with eval modifier and create_function usage (#2042)\n- Bring back <base> and <link> tags in HTML messages\n- Fix XSS vulnerability through background attributes [CVE-2009-0413]\n- Fix problems with backslash as IMAP hierarchy delimiter (#1116)\n- Secure vcard export by getting rid of preg's 'e' modifier use (#2045)\n- Fix authentication when submitting form with existing session (#2037)\n- Allow absolute URLs to images in HTML messages/sigs (#2029)\n- Fix message body which contains both inline attachments and emotions\n- Fix SQL query execution errors handling in rcube_mdb2 class (#1907)\n- Fix address names with '@' sign handling (#2022)\n- Improve messages display performance\n- Fix messages searching with 'to:' modifier", "RELEASE 0.2-STABLE\n------------------\n- Fix mark popup in IE 7 (#1785)\n- Fix line-break issue when copy & paste in Firefox (#1832)\n- Fix autocomplete \"unknown server error\" (#2008)\n- Fix STARTTLS before AUTH in SMTP connection (#1415)\n- Support multiple quota values in QUOTAROOT resonse (#1999)\n- Only abbreviate file name for IE < 7 browsers (#1548)\n- Performance: allow setting imap rootdir and delimiter before connect (#1628)\n- Fix sorting of folders with more than 2 levels (#1953)\n- Fix search results page jumps in LDAP addressbook (#1689)\n- Fix empty line before the signature in IE (#1769)\n- Fix horizontal scrollbar in preview pane on IE (#1228)\n- Add Robots meta tag in login page and installer (#1385)\n- Added 'show_images' option, removed 'addrbook_show_images' (#1977)\n- Option to check for new mails in all folders (#1053)\n- Don't set client busy when checking for new messages (#1706)\n- Allow UTF-8 folder names in config (#1960)\n- Add junk_mbox option configuration in installer (#1960)\n- Do serverside addressbook queries for autocompletion (#1925)\n- Allow setting attachment col position in 'list_cols' option\n- Allow override 'list_cols' via skin (#1958)\n- Fix 'cache' table cleanup on session destroy (#1913)\n- Increase speed of session destroy and garbage clean up\n- Fix session timeout when DB server got clock skew (#1890)\n- Fix handling of some malformed messages (#1099)\n- Speed up raw message body handling\n- Better HTML entities conversion in html2text (#1916)\n- Fix big memory consumption and speed up searching on servers without SORT capability\n- Fix setting locale to tr_TR, ku and az_AZ (#1872) \n- Use SORT for searching on servers with SORT capability\n- Added message status filter\n- Fix empty file sending (#1801)\n- Improved searching with many criterias (calling one SEARCH command)\n- Fix HTML editor initialization on IE (#1731)\n- Add warning when switching editor mode from html to plain (#1888)\n- Make identities list scrollable (#1930)\n- Fix problem with numeric folder names (#1922)\n- Added BYE response simple support to prevent from endless loops in imap.inc (#777)\n- Fix unread message unintentionally marked as read if read_when_deleted=true (#1819)\n- Remove port number from SERVER_NAME in smtp_helo_host (#1915)\n- Don't send disposition notification receipts for messages marked as 'read' (#1918)\n- Added 'keep_alive' and 'min_keep_alive' options (#1777)\n- Added option 'identities_level', removed 'multiple_identities'\n- Allow deleting identities when multiple_identities=false (#1840)\n- Added option focus_on_new_message (#1789)\n- Fix html2text class autoloading on Windows (#1904)\n- Fix html signature formatting when identity save error occurred (#1833)\n- Add feedback and set busy when moving folder (#1897)\n- Fix 'Empty' link visibility for some languages e.g. Slovak (#1889)\n- Fix messages count bar overlapping (#1703)\n- Fix adding signature in drafts compose mode (#1884)\n- Fix iil_C_Sort() to support very long and/or divided responses (#1713)\n- Fix matching case sensitivity when setting identity on reply (#1881)\n- Prefer default identity on reply\n- Fix imap searching on ISMail server (#1870)\n- Add css class for flagged messages (#1868)\n- Write username instead of id in sendmail log (#1879)\n- Fix htmlspecialchars() use for PHP version < 5.2.3 (#1877)\n- Fix js keywords escaping in json_serialize() for IE/Opera (#1874)\n- Added bin/killcache.php script (#1839)\n- Add support for SJIS, GB2312, BIG5 in rc_detect_encoding()\n- Fix vCard file encoding detection for non-UTF-8 strings (#1820)\n- Add 'skip_deleted' option in User Preferences (#1850)\n- Minimize \"inline\" javascript scripts use (#1838)\n- Fix css class setting for folders with names matching defined classes names (#1772)\n- Fix race conditions when changing mailbox\n- Fix spellchecking when switching to html editor (#1779)\n- Fix compose window width/height (#1807)\n- Allow calling msgimport.sh/msgexport.sh from any directory (#1837)\n- Localized filesize units (#1760)\n- Better handling of \"no identity\" and \"no email in identity\" situations (#1592)\n- Added 'mime_param_folding' option with possibility to choose long/non-ascii attachment names encoding eg. to be readable in MS Outlook/OE (#1743)\n- Added \"advanced options\" feature in User Preferences\n- Fix unread counter when displaying cached massage in preview panel (#1720)\n- Fix htmleditor spellchecking on MS Windows (#1808)\n- Fix problem with non-ascii attachment names in Mail_mime (#1700, #1576)\n- Fix language autodetection (#1812)\n- Fix button label in folders management (#1816)\n- Fix collapsed folder not indicating unread msgs count of all subfolders (#1814)\n- Fix handling of apostrophes in filenames decoded according to rfc2231", "RELEASE 0.2-BETA\n----------------\n- Made config files location configurable (#1664)\n- Reduced memory footprint when forwarding attachments (#1764)\n- Allow and use spellcheck attribute for input/textarea fields (#1545)\n- Added icons for forwarded/forwarded+replied messages (#1691)\n- Added Reply-To to forwarded emails (#1739)\n- Display progress message for folders create/delete/rename (#1774)\n- Smart Tags and NOBR tag support in html messages (#1780, #1748)\n- Redesign of the identities settings (#836)\n- Add config option to disable creation/deletion of identities (#1139)\n- Added 'sendmail_delay' option to restrict messages sending interval (#1135)\n- Added vertical splitter for folders list resizing\n- Added possibility to view all headers in message view\n- Fixed splitter drag/resize on Opera (#1626)\n- Fixed quota img height/width setting from template (#1396)\n- Refactor drag & drop functionality. Don't rely on browser events anymore (#1108)\n- Insert \"virtual\" folders in subscription list (#1333)\n- Added link to open message in new window\n- Enable export of address book contacts as vCard\n- Add feature to import contacts from vcard files (#395)\n- Respect Content-Location headers in multipart/related messages according to RFC2110 (#1464)\n- Allowed max. attachment size now indicated in compose screen (#1523)\n- Also capture backspace key in list mode (#1186)\n- Allow application/pgp parts to be displayed (#1309)\n- Correctly handle options in mailto-links (#1671)\n- Immediately save sort_col/sort_order in user prefs (#1698)\n- Truncate very long (above 50 characters) attachment filenames when displaying\n- Allow to auto-detect client language if none set (#1095)\n- Auto-detect the client timezone (user configurable)\n- Add RFC2231 header value continuations support for attachment filenames + hack for servers that not support that feature\n- Fix Reply-To header displaying (#1738)\n- Mark form buttons that provide the most obvious operation (mainaction)\n- Added option 'quota_zero_as_unlimited' (#1206)\n- Added PRE handling in html2text class (#1301)\n- Added folder hierarchy collapsing\n- Added options to use syslog instead of log file (#1389)\n- Added Logging & Debugging section in Installer\n- Fix In-Reply-To and References headers when composing saved draft message (#1718)\n- Fix html message charset conversion for charsets with underline (#1717) \n- Fix buttons status after contacts deletion (#1675)\n- Fix escaping of To: and From: fields when building message body for reply or forward in the HTML editor (#1432)\n- Use current mailbox name in template (#1690)\n- Better fix for skipping untagged responses (#1694)\n- Added pspell support patch by Kris Steinhoff (#781)\n- Enable spellchecker for HTML editor (#1589)\n- Respect spellcheck_uri in tinyMCE spellchecker (#941)\n- Case insensitive contacts searching using PostgreSQL (#1692)\n- Make default imap folders configurable for each user (#1558)\n- Save outgoing mail to selectable folder (#1324581)\n- Fix hiding of mark menu when clicking th button again (#1463)\n- Use long date format in print mode (#1643)\n- Updated TinyMCE to version 3.1.0.1\n- Re-enable autocomplete attribute for login form (#1661)\n- Check PERMANENTFLAGS before saving $MDNSent flag (#1478, #1485163)\n- Added flag column on messages list (#1220)\n- Patched Mail/MimePart.php (http://pear.php.net/bugs/bug.php?id=14232)\n- Allow trash/junk subfolders to be purged (#1568)\n- Store compose parameters in session and redirect to a unique URL\n- Fixed CRAM-MD5 authentication (#1364)\n- Fixed forwarding messages with one HTML attachment (#1103)\n- Fixed encoding of message/rfc822 attachments and image/pjpeg handling (#1439)\n- Added option to select skin in user preferences\n- Added option to configure displaying of attached images below the message body\n- Added option to display images in messages from known senders (#1204)\n- User preferences grouped in more fieldsets\n- Fix corrupted MIME headers of messages in Sent folder (#1587)\n- Fixed bug in MDB2 package: http://pear.php.net/bugs/bug.php?id=14124\n- Use keypress instead of keydown to select list's row (#1362)\n- Don't call expunge and don't remove message row after message move if flag_for_deletion is set to true (#1505)", "RELEASE 0.2-ALPHA\n-----------------\n- Added option to disable autocompletion from selected LDAP address books (#1445)\n- TLS support in LDAP connections: 'use_tls' property (#1581)\n- Fixed removing messages from search set after deleting them (#1583)\n- imap.inc: Fixed iil_C_FetchStructureString() to handle many \n literal strings in response (#1483)\n- Support for subfolders in default/protected folders (#1250)\n- Disallowed delimiter in folder name (#1351)\n- Support \" and \\ in folder names\n- Escape \\ in login (#1214)\n- Better HTML sanitization with the DOM-based washtml script (#1276)\n- Fixed sorting of folders with non-ascii characters\n- Fixed Mysql DDL for default identities creation (#1554)\n- In Preferences added possibility to configure 'read_when_deleted',\n 'mdn_requests', 'flag_for_deletion' options\n- Made IMAP auth type configurable (#683)\n- Fixed empty values with FROM_UNIXTIME() in rcube_mdb2 (#1540)\n- Fixed attachment list on IE 6/7 (#1355)\n- Fixed JavaScript in compose.html that shows cc/bcc fields if populated\n- Make password input fields of type password in installer (#1417)\n- Don't attempt to delete cache entries if enable_caching is FALSE (#1537)\n- Optimized messages sorting on servers without sort capability (#1535)\n- Corrected message headers decoding when charset isn't specified and improved\n support for native languages (#1536, #1534)\n- Expanded LDAP configuration options to support LDAP server writes.\n- Installer: encode special characters in DB username/password (#1529)\n- Fixed management of folders with national characters in names (#1526, #1504)\n- Fixed identities saving when using MDB2 pgsql driver (#1525)\n- Fixed BCC header reset (#1501)\n- Improved messages list performance - patch from Justin Heesemann\n- Append skin_path to images location only when it starts with '/' sign (#1398)\n- Fix IMAP response in message body when message has no body (#1479)\n- Fixed non-RFC dates formatting (#1429)\n- Fixed typo in set_charset() (#1498)\n- Decode entities when inserting HTML signature to plain text message (#1497)\n- HTML editing is now working with PHP5 updates and TinyMCE v3.0.6\n- Fixed signature loading on Windows (#1169)\n- Added language support to HTML editing (#1401)\n- Fixed remove signature when replying (#446)\n- Fixed problem with line with a space at the end (#1440)\n- Fixed <!DOCTYPE> tag filtering (#1066)\n- Fixed <?xml> tag filtering (#1075)\n- Added sections (fieldset+label) in Settings interface\n- Mark as read in one action with message preview (#1486)\n- Deleted redundant quota reads (#1486)\n- Added options for empty trash and expunge inbox on logout (#707)\n- Removed lines wrapping when displaying message\n- Fixed month localization\n- Changed codebase to PHP5 with autoloader", "RELEASE 0.1.1\n-------------\n- Clear selection when selecting single item (#1461)\n- Remove hard-coded image size in skin templates (#1423)\n- Database schema improvements (dropped unnecessary indexes)\n- Fixed creating a new folder with a comma in its name (#1263)\n- Fixed sorting of messages when default mailbox is empty (#1020)\n- Improve message previewpane - less loading (#1019)\n- Fixed login form autoompletion (#1378)\n- Fixed virtuser_query option for mdb2 backend (#1409)\n- Fixed attachment resoting from Drafts when message body was empty (#1144)\n- Fixed usage of ob_gzhandler (#1390)\n- Fixed message part window in IE6 (#1211)\n- Fixed decoding of mime-encoded strings (#938)\n- Fixed some iconv/mb_string problems (#1202)\n- Correctly quote mailbox name when using in URL (#1016)\n- Fixed \"headers already sent\" errors (#1399)", "RELEASE 0.1-STABLE\n------------------\n- Added interactive installer script\n- Fix folder adding/renaming inspired by #1349\n- Localize folder name in page title (#1338)\n- Fix code using wrong variable name (#818)\n- Allow to send mail with BCC recipients only\n- condense TinyMCE toolbar down to one line, removing table buttons (#1306)\n- Add function to mark the selected messages as read/unread (#641)\n- Also do charset decoding as suggested in RFC 2231 (fix #1022)\n- Show message count in folder list and hint when creating a subfolder\n- Distinguish ssl and tls for imap connections (#1252)\n- Added some charset aliases to fix typical mis-labelling (#1185)\n- Remember decision to display images for a certain message during session (#1310)\n- Truncate attachment filenames to 55 characters due to an IE bug (#1313)\n- Make sending of read receipts configurable\n- Respect config when localize folder names (#1280)\n- Also respect receipt and priority settings when re-opening a draft message\n- Remember search results (closes #722), patch by the_glu\n- Add Received header on outgoing mail\n- Upgrade to TinyMCE 2.1.3\n- Allow inserting image attachments into HTML messages while composing (#1179)\n- Implement Message-Disposition-Notification (Receipts)\n- Fix overriding of session vars when register_globals is on (#1255)\n- Fix bug with case-sensitive folder names (#973)\n- Don't create default folders by default\n- Fixed some potential security risks (audited by Andris)\n- Only show new messages if they match the current search (#925)\n- Switch to/from when searcing in Sent folder (#1177)\n- Correctly read the References header (#1236)\n- Unset old cookie before sending a new value (#1232)\n- Correctly decode attachments when downloading them (#1235 and #1484642)\n- Suppress IE errors when clearing attachments form (#1043)\n- Log error when login fails due to auto_create_user turned off\n- Filter linked/imported CSS files (closes #844)\n- Improve message compose screen (closes #1060)\n- Select next row after removing one from list (#1063)", "RELEASE 0.1-RC2\n---------------\n- Enable drag-&-dropping of folders to a new parent and allow to create subfolders (#637)\n- Suppress IE errors when clearing attachments form (#1043)\n- Set preferences field in user table to NULL (#1062)\n- Log error when login fails due to auto_create_user turned off\n- Filter linked/imported CSS files (closes #844)\n- Improve message compose screen (closes #1060)\n- Select next row after removing one from list (#1063)\n- Make smtp HELO/EHLO hostname configurable (#851)\n- IPv6 Compatibility (#1023), Patch #1484373\n- Unlock interface when message sending fails (#1188)\n- Eval PHP code in template includes (if configured)\n- Show message when folder is empty. Mo more static text in table (#1068)\n- Only display unread count in page title when new messages arrived\n- Fixed wrong delete button tooltip (#785)\n- Fixed charset encoding bug (#1091)\n- Applied patch for LDAP version (#1175)\n- Improved XHTML validation\n- Fix message list selection (#1174)\n- Better fix lowercased usernames (#1120)\n- Update pngbehavior Script as suggested in #1134\n- Fixed moving/deleting messages when more than 1 is selected\n- Applied patch for LDAP contacts listing by Glen Ogilvie\n- Applied patch for more address fields in LDAP contacts (#1074)\n- Add alternative for getallheaders() (fix #1146)\n- Identify mailboxes case-sensitive\n- Sort mailbox list case-insensitive (closes #1032)\n- Fix display of multipart messages from Apple Mail (closes #823)\n- Protect AJAX request from being fetched by a foreign site (XSS)\n- Make autocomplete for loginform configurable by the skin template\n- Fix compose function from address book (closes #1089)\n- Added //IGNORE to iconv call (patch #1086, closes #821)\n- Check if mbstring supports charset (#1003 and #1004)\n- Prefer iconv over mbstring (as suggested in #1004)\n- Check filesize of template includes (#1079)\n- Fixed bug with buttons not dimming/enabling properly after switching folders\n- Fixed compose window becoming unresponsive after saving a draft (#1132)\n- Re-enabled \"Back\" button in compose window now that bug #1132 is fixed\n- Fixed unresponsive interface issue when downloading attachments (#1138)\n- Lowered status message time from 5 to 3 seconds to improve responsiveness\n- Raised .htaccess upload_max_filesize from 2M to 5M to differ from default php.ini\n- Increased \"mailboxcontrols\" mail.css width from 160 to 170px to fix non-english languages (#1140)\n- Fix status message bug #1114 with regard to #1041\n- Fix address adding bug reported by David Koblas\n- Applied socket error patch by Thomas Mangin\n- Pass-by-reference workarround for PHP5 in sendmail.inc\n- Fixed buggy imap_root settings (closes #1056)\n- Prevent default events on subject links (#1071)\n- Use HTTP-POST requests for actions that change state", "RELEASE 0.1-RC1\n---------------\n- Use global filters and bind username/ for Ldap searches (#909)\n- Hide quota display if imap server does not support it\n- Hide address groups if no LDAP servers configured\n- Add link to message subjects (closes #982)\n- Better SQL query for contact listing/search (closes #1051)\n- Fixed marking as read in preview pane (closes #1048)\n- CSS hack to display attachments correctly in IE6\n- Wrap message body text (closes #901)\n- LDAP access is back in address book (closes #864)\n- Added search function for contacts\n- New Template parsing and output encoding\n- Fixed bugs #884 and #793\n- Fixed message moving procedure (closes #1013)\n- Fixed display of multiple attachments (closes #647)\n- Fixed check for new messages (closes #1015)\n- List attachments without filename\n- New session authentication: Change sessid cookie when login, authentication with sessauth cookie is now configurable.\n Should close bugs #774 and #1484299\n- Correctly translate mailbox names (closes #993)\n- Quote e-mail address links (closes #1007)\n- Updated PEAR::Mail_mime package\n- Accept single quotes for HTML attributes when modifying message body (thanks Jason)\n- Sanitize input for new users/identities (thanks Colin Alston)\n- Don't download HTML message parts\n- Convert HTML parts to plaintext if 'prefer_html' is off\n- Correctly parse message/rfc822 parts (closes #838)\n- Also use user_id for unique key in messages table (closes #857)\n- Hide contacts drop down on blur (closes #946)\n- Make entries in contacts drop down clickable\n- Turn off browser autocompletion on login page\n- Quote <? in text/html message parts\n- Hide border around radio buttons\n- Applied patch for attachment download by crichardson (closes #943)\n- Fixed bug in Postgres DB handling (closes #852)\n- Fixed bug of invalid calls to fetchRow() in rcube_db.inc (closes #996)\n- Fixed array_merge bug (closes #997)\n- Fixed flag for deletion in list view (closes #987)\n- Finally support semicolons as recipient separator (closes ##976)\n- Fixed message headers (subject) encoding\n- check if safe mode is on or not (closes #990)\n- Show \"no subject\" in message list if subject is missing (closes #971)\n- Solved page caching of message preview (closes #905)\n- Only use gzip compression if configured (closes #967)\n- Fixed priority selector issue (#903)\n- Fixed some CSS issues in default skin (closes #951 and #911)\n- Prevent from double quoting of numeric HTML character references (closes #978)\n- Fixed display of HTML message attachments (closes #927)\n- Applied patch for preview caching (closes #933)\n- Added error handling for attachment uploads\n- Use multibyte safe string functions where necessary (closes #798)\n- Applied security patch to validate the submitted host value (by Kees Cook)\n- Applied security patch to validate input values when deleting contacts (by Kees Cook)\n- Applied security patch that sanitizes emoticon paths when attaching them (by Kees Cook)\n- Applied a patch to more aggressively sanitize a HTML message\n- Visualize blocked images in HTML messages\n- Fixed wrong message listing when showing search results (closes #890)\n- Show remote images when opening HTML message part as attachment\n- Improve memory usage when sending mail (closes #871)\n- Mark messages as read once the preview is loaded (closes #1484132)\n- Include smtp final response in log (closes #862)\n- Corrected date string in sent message header (closes #887)\n- Correclty choose \"To\" column in sent and draft mailboxes (closes #769)\n- Changed srong tooltips for message browse buttons (closes #757)\n- Fixed signature delimiter character to be standard (Bug #830)\n- Fixed XSS vulnerability (Bug #877)\n- Remove newlines from mail headers (Bug #827)\n- Selection issues when moving/deleting (Bug #837)\n- Applied patch of Clement Moulin for imap host auto-selection\n- ISO-encode IMAP password for plaintext login (Bugs #792 & #723)\n- Fixed folder name encoding in subscription list (Bug #879)\n- Fixed JS errors in identity list (Bug #885)\n- Translate foldernames in folder form (closes #879)\n- Added first and last buttons to message list, address book\n and message detail\n- Pressing Shift-Del bypasses Trash folder\n- Enable purge command for Junk folder\n- Fetch all aliases if virtuser_query is used instead\n- Re-enabled multi select of contacts (Bug #817)\n- Enable contact editing right after creation (Bug #644)\n- Correct UTF-7 to UTF-8 conversion if mbstring is not available\n- Fixed IMAP fetch of message body (Bug #819)\n- Fixed safe_mode problems (Bug #539)\n- Fixed wrong header encoding (Bug #1483976)\n- Made automatic draft saving configurable\n- Fixed JS bug when renaming folders (Bug #799)\n- Added quota display as image (by Brett Patterson)\n- Corrected creation of a message-id\n- New indentation for quoted message text\n- Improved HTML validity\n- Fixed URL character set (Ticket #616)\n- Fixed saving of contact into MySQL from LDAP query results (Ticket #681)\n- Fixed folder renaming: unsubscribe before rename (Bug #750)\n- Finalized new message parsing (+ chaching)\n- Fixed wrong usage of mbstring (Bug #645)\n- Set default spelling language (Ticket #764)\n- Added support for Nox Spell Server\n- Re-built message parsing (Bug #422)\n Now based on the message structure delivered by the IMAP server.\n- Fixed some XSS and SQL injection issues\n- Fixed charset problems with folder renaming" ]
[ 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [15, 533, 355], "buggy_code_start_loc": [15, 415, 319], "filenames": ["CHANGELOG", "program/lib/Roundcube/rcube_washtml.php", "tests/Framework/Washtml.php"], "fixing_code_end_loc": [18, 590, 480], "fixing_code_start_loc": [16, 415, 320], "message": "Roundcube Webmail before 1.3.15 and 1.4.8 allows stored XSS in HTML messages during message display via a crafted SVG document. This issue has been fixed in 1.4.8 and 1.3.15.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:roundcube:webmail:*:*:*:*:*:*:*:*", "matchCriteriaId": "6AA0D87C-F59C-4A8D-8527-8171BEB076E0", "versionEndExcluding": "1.3.15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:roundcube:webmail:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F4ECE92-6974-4D4F-9900-5F0C548B912A", "versionEndExcluding": "1.4.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.4.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:32:*:*:*:*:*:*:*", "matchCriteriaId": "36D96259-24BD-44E2-96D9-78CE1D41F956", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Roundcube Webmail before 1.3.15 and 1.4.8 allows stored XSS in HTML messages during message display via a crafted SVG document. This issue has been fixed in 1.4.8 and 1.3.15."}, {"lang": "es", "value": "Roundcube Webmail versiones anteriores a 1.3.15 y 1.4.8, permite un ataque de tipo XSS almacenado en mensajes HTML durante la visualizaci\u00f3n de mensajes por medio de un documento SVG dise\u00f1ado. Este problema se ha solucionado en la versi\u00f3n 1.4.8 y versi\u00f3n 1.3.15."}], "evaluatorComment": null, "id": "CVE-2020-16145", "lastModified": "2023-01-20T21:00:58.090", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-08-12T13:15:10.457", "references": [{"source": "cve@mitre.org", "tags": ["Broken Link"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-09/msg00083.html"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/commit/a71bf2e8d4a64ff2c83fdabc1e8cb0c045a41ef4"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/commit/d44ca2308a96576b88d6bf27528964d4fe1a6b8b#diff-d3bb3391c79904494c60ee2ac2f33070"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/releases/tag/1.3.15"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/releases/tag/1.4.8"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/3DAXK3565NYK4OEZVTW6S5LEVIDQEY2E/"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/OBLUQRIBAMEQVBO6GUZECCHJDJIWCYFU/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/roundcube/roundcubemail/commit/a71bf2e8d4a64ff2c83fdabc1e8cb0c045a41ef4"}, "type": "CWE-79"}
184
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n +-----------------------------------------------------------------------+\n | This file is part of the Roundcube Webmail client |\n | |\n | Copyright (C) The Roundcube Dev Team |\n | |\n | Licensed under the GNU General Public License version 3 or |\n | any later version with exceptions for skins & plugins. |\n | See the README file for a full license statement. |\n | |\n | PURPOSE: |\n | Utility class providing HTML sanityzer (based on Washtml class) |\n +-----------------------------------------------------------------------+\n | Author: Thomas Bruederli <roundcube@gmail.com> |\n | Author: Aleksander Machniak <alec@alec.pl> |\n | Author: Frederic Motte <fmotte@ubixis.com> |\n +-----------------------------------------------------------------------+", " Washtml, a HTML sanityzer.", " Copyright (c) 2007 Frederic Motte <fmotte@ubixis.com>\n All rights reserved.", " Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n 1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.", " THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/", "/**\n * Utility class providing HTML sanityzer\n *\n * @package Framework\n * @subpackage Utils\n */\nclass rcube_washtml\n{\n /**\n * @var array Allowed HTML elements (default)\n */\n static $html_elements = array('a', 'abbr', 'acronym', 'address', 'area', 'b',\n 'basefont', 'bdo', 'big', 'blockquote', 'br', 'caption', 'center',\n 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl',\n 'dt', 'em', 'fieldset', 'font', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i',\n 'ins', 'label', 'legend', 'li', 'map', 'menu', 'nobr', 'ol', 'p', 'pre', 'q',\n 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table',\n 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var', 'wbr', 'img',\n 'video', 'source',\n // form elements\n 'button', 'input', 'textarea', 'select', 'option', 'optgroup',\n // SVG\n 'svg', 'altglyph', 'altglyphdef', 'altglyphitem', 'animate',\n 'animatecolor', 'animatetransform', 'circle', 'clippath', 'defs', 'desc',\n 'ellipse', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line',\n 'lineargradient', 'marker', 'mask', 'mpath', 'path', 'pattern',\n 'polygon', 'polyline', 'radialgradient', 'rect', 'set', 'stop', 'switch', 'symbol',\n 'text', 'textpath', 'tref', 'tspan', 'use', 'view', 'vkern', 'filter',\n // SVG Filters\n 'feblend', 'fecolormatrix', 'fecomponenttransfer', 'fecomposite',\n 'feconvolvematrix', 'fediffuselighting', 'fedisplacementmap',\n 'feflood', 'fefunca', 'fefuncb', 'fefuncg', 'fefuncr', 'fegaussianblur',\n 'feimage', 'femerge', 'femergenode', 'femorphology', 'feoffset',\n 'fespecularlighting', 'fetile', 'feturbulence',\n // MathML\n 'math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr',\n 'mmuliscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow',\n 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd',\n 'mtext', 'mtr', 'munder', 'munderover', 'maligngroup', 'malignmark',\n 'mprescripts', 'semantics', 'annotation', 'annotation-xml', 'none',\n 'infinity', 'matrix', 'matrixrow', 'ci', 'cn', 'sep', 'apply',\n 'plus', 'minus', 'eq', 'power', 'times', 'divide', 'csymbol', 'root',\n 'bvar', 'lowlimit', 'uplimit',\n );", " /**\n * @var array Ignore these HTML tags and their content\n */\n static $ignore_elements = array('script', 'applet', 'embed', 'object', 'style');", " /**\n * @var array Allowed HTML attributes\n */\n static $html_attribs = array('name', 'class', 'title', 'alt', 'width', 'height',\n 'align', 'nowrap', 'col', 'row', 'id', 'rowspan', 'colspan', 'cellspacing',\n 'cellpadding', 'valign', 'bgcolor', 'color', 'border', 'bordercolorlight',\n 'bordercolordark', 'face', 'marginwidth', 'marginheight', 'axis', 'border',\n 'abbr', 'char', 'charoff', 'clear', 'compact', 'coords', 'vspace', 'hspace',\n 'cellborder', 'size', 'lang', 'dir', 'usemap', 'shape', 'media',\n 'background', 'src', 'poster', 'href', 'headers',\n // attributes of form elements\n 'type', 'rows', 'cols', 'disabled', 'readonly', 'checked', 'multiple', 'value', 'for',\n // SVG\n 'accent-height', 'accumulate', 'additive', 'alignment-baseline', 'alphabetic',\n 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseprofile',\n 'baseline-shift', 'begin', 'bias', 'by', 'clip', 'clip-path', 'clip-rule',\n 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile',\n 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction',\n 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'fill', 'fill-opacity',\n 'fill-rule', 'filter', 'flood-color', 'flood-opacity', 'font-family', 'font-size',\n 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'from',\n 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform',\n 'image-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints',\n 'keysplines', 'keytimes', 'lengthadjust', 'letter-spacing', 'kernelmatrix',\n 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid',\n 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits',\n 'maskunits', 'max', 'mask', 'mode', 'min', 'numoctaves', 'offset', 'operator',\n 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order',\n 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits',\n 'points', 'preservealpha', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount',\n 'repeatdur', 'restart', 'rotate', 'scale', 'seed', 'shape-rendering', 'show', 'specularconstant',\n 'specularexponent', 'spreadmethod', 'stddeviation', 'stitchtiles', 'stop-color',\n 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap',\n 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width',\n 'surfacescale', 'targetx', 'targety', 'transform', 'text-anchor', 'text-decoration',\n 'text-rendering', 'textlength', 'to', 'u1', 'u2', 'unicode', 'values', 'viewbox',\n 'visibility', 'vert-adv-y', 'version', 'vert-origin-x', 'vert-origin-y', 'word-spacing',\n 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2',\n 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan',\n // MathML\n 'accent', 'accentunder', 'bevelled', 'close', 'columnalign', 'columnlines',\n 'columnspan', 'denomalign', 'depth', 'display', 'displaystyle', 'encoding', 'fence',\n 'frame', 'largeop', 'length', 'linethickness', 'lspace', 'lquote',\n 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize',\n 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign',\n 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel',\n 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator',\n 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset',\n 'fontsize', 'fontweight', 'fontstyle', 'fontfamily', 'groupalign', 'edge', 'side',\n );", " /**\n * @var array Elements which could be empty and be returned in short form (<tag />)\n */\n static $void_elements = array('area', 'base', 'br', 'col', 'command', 'embed', 'hr',\n 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr',\n // MathML\n 'sep', 'infinity', 'in', 'plus', 'eq', 'power', 'times', 'divide', 'root',\n 'maligngroup', 'none', 'mprescripts',\n );", " /**\n * @var array Additional allowed attributes of body element\n */\n static $body_attribs = array('alink', 'background', 'bgcolor', 'link', 'text', 'vlink');", " /** @var bool State indicating existence of linked objects in HTML */\n public $extlinks = false;", " /** @var array Current settings */\n private $config = array();", " /** @var array Registered callback functions for tags */\n private $handlers = array();", " /** @var array Allowed HTML elements */\n private $_html_elements = array();", " /** @var array Ignore these HTML tags but process their content */\n private $_ignore_elements = array();", " /** @var array Elements which could be empty and be returned in short form (<tag />) */\n private $_void_elements = array();", " /** @var array Allowed HTML attributes */\n private $_html_attribs = array();", " /** @var string A prefix to be added to id/class/for attribute values */\n private $_css_prefix;", " /** @var int Max nesting level */\n private $max_nesting_level;", " /** @var bool True if current document is XML */\n private $is_xml = false;", "\n /**\n * Class constructor\n *\n * @param array $p Configuration options:\n * allow_remote: is a boolean to allow link to remote resources (images/css)\n * blocked_src: string with image-src to be used for blocked remote images\n * show_washed: is a boolean to include washed out attributes as x-washed\n * cid_map: is an array where cid urls index urls to replace them\n * charset: is a string containing the charset of the HTML document,\n * to be used if the charset is not defined in the document\n * css_prefix: A prefix to be added to id/class/for attribute values\n * html_elements: Additional allowed HTML elements\n * ignore_elements: Additional HTML elements to ignore\n * html_attribs: Additional allowed HTML attributes\n * void_elements: Elements which could be empty and be returned in short form (<tag />)\n */\n public function __construct($p = array())\n {\n $this->_html_elements = array_flip((array)$p['html_elements']) + array_flip(self::$html_elements);\n $this->_html_attribs = array_flip((array)$p['html_attribs']) + array_flip(self::$html_attribs);\n $this->_ignore_elements = array_flip((array)$p['ignore_elements']) + array_flip(self::$ignore_elements);\n $this->_void_elements = array_flip((array)$p['void_elements']) + array_flip(self::$void_elements);\n $this->_css_prefix = is_string($p['css_prefix']) && strlen($p['css_prefix']) ? $p['css_prefix'] : null;", " unset($p['html_elements'], $p['html_attribs'], $p['ignore_elements'], $p['void_elements'], $p['css_prefix']);", " $this->config = $p + array('show_washed' => true, 'allow_remote' => false, 'cid_map' => array());\n }", " /**\n * Register a callback function for a certain tag\n *\n * @param string $tag HTML tag name\n * @param callback $callback Callback function\n */\n public function add_callback($tag, $callback)\n {\n $this->handlers[$tag] = $callback;\n }", " /**\n * Check CSS style\n *\n * @param string $style CSS style\n *\n * @return string Washed CSS style\n */\n private function wash_style($style)\n {\n $result = array();", " // Remove unwanted white-space characters so regular expressions below work better\n $style = preg_replace('/[\\n\\r\\s\\t]+/', ' ', $style);", " // Decode insecure character sequences\n $style = rcube_utils::xss_entity_decode($style);", " foreach (explode(';', $style) as $declaration) {\n if (preg_match('/^\\s*([a-z\\\\\\-]+)\\s*:\\s*(.*)\\s*$/i', $declaration, $match)) {\n $cssid = $match[1];\n $str = $match[2];\n $value = '';", " foreach ($this->explode_style($str) as $val) {\n if (preg_match('/^url\\(/i', $val)) {\n if (preg_match('/^url\\(\\s*[\\'\"]?([^\\'\"\\)]*)[\\'\"]?\\s*\\)/iu', $val, $match)) {\n if ($url = $this->wash_uri($match[1])) {\n $value .= ' url(' . htmlspecialchars($url, ENT_QUOTES, $this->config['charset']) . ')';\n }\n }\n }\n else if (!preg_match('/^(behavior|expression)/i', $val)) {\n // Set position:fixed to position:absolute for security (#5264)\n if (!strcasecmp($cssid, 'position') && !strcasecmp($val, 'fixed')) {\n $val = 'absolute';\n }", " // whitelist ?\n $value .= ' ' . $val;", " // #1488535: Fix size units, so width:800 would be changed to width:800px\n if (preg_match('/^(left|right|top|bottom|width|height)/i', $cssid)\n && preg_match('/^[0-9]+$/', $val)\n ) {\n $value .= 'px';\n }\n }\n }", " if (isset($value[0])) {\n $result[] = $cssid . ':' . $value;\n }\n }\n }", " return implode('; ', $result);\n }", " /**\n * Take a node and return allowed attributes and check values\n *\n * @param DOMNode $node Document element\n *\n * @return string Washed element attributes\n */\n private function wash_attribs($node)\n {\n $result = '';\n $washed = array();\n $additional_attribs = array();", " if ($node->nodeName == 'body') {\n $additional_attribs = self::$body_attribs;\n }", " foreach ($node->attributes as $name => $attr) {\n $key = strtolower($name);\n $value = $attr->nodeValue;", " if ($key == 'style' && ($style = $this->wash_style($value))) {\n // replace double quotes to prevent syntax error and XSS issues (#1490227)\n $result .= ' style=\"' . str_replace('\"', '&quot;', $style) . '\"';\n }\n else if (isset($this->_html_attribs[$key]) || in_array($key, $additional_attribs)) {\n $value = trim($value);\n $out = null;", " // in SVG to/from attribs may contain anything, including URIs\n if ($key == 'to' || $key == 'from') {\n $key = strtolower($node->getAttribute('attributeName'));\n if ($key && !isset($this->_html_attribs[$key])) {\n $key = null;\n }\n }", " if ($this->is_image_attribute($node->nodeName, $key)) {\n $out = $this->wash_uri($value, true);\n }\n else if ($this->is_link_attribute($node->nodeName, $key)) {\n $out = $this->wash_link($value);\n }\n else if ($this->is_funciri_attribute($node->nodeName, $key)) {\n if (preg_match('/^[a-z:]*url\\(/i', $val)) {\n if (preg_match('/^([a-z:]*url)\\(\\s*[\\'\"]?([^\\'\"\\)]*)[\\'\"]?\\s*\\)/iu', $value, $match)) {\n if ($url = $this->wash_uri($match[2])) {\n $result .= ' ' . $attr->nodeName . '=\"' . $match[1]\n . '(' . htmlspecialchars($url, ENT_QUOTES, $this->config['charset']) . ')'\n . substr($val, strlen($match[0])) . '\"';\n continue;\n }\n }\n else {\n $out = $value;\n }\n }\n else {\n $out = $value;\n }\n }\n else if ($this->_css_prefix !== null && in_array($key, array('id', 'class', 'for'))) {\n $out = preg_replace('/(\\S+)/', $this->_css_prefix . '\\1', $value);\n }\n else if ($key) {\n $out = $value;\n }", " if ($out !== null && $out !== '') {\n $result .= ' ' . $attr->nodeName . '=\"' . htmlspecialchars($out, ENT_QUOTES | ENT_SUBSTITUTE, $this->config['charset']) . '\"';\n }\n else if ($value) {\n $washed[] = htmlspecialchars($attr->nodeName, ENT_QUOTES, $this->config['charset']);\n }\n }\n else {\n $washed[] = htmlspecialchars($attr->nodeName, ENT_QUOTES, $this->config['charset']);\n }\n }", " if (!empty($washed) && $this->config['show_washed']) {\n $result .= ' x-washed=\"' . implode(' ', $washed) . '\"';\n }", " return $result;\n }", " /**\n * Wash URI value\n *\n * @param string $uri URI\n * @param bool $blocked_source Block remote source\n * @param bool $is_image URI points to an image\n *\n * @return string Washed URI\n */\n private function wash_uri($uri, $blocked_source = false, $is_image = true)\n {\n if (($src = $this->config['cid_map'][$uri])\n || ($src = $this->config['cid_map'][$this->config['base_url'].$uri])\n ) {\n return $src;\n }", " // allow url(#id) used in SVG\n if ($uri[0] == '#') {\n if ($this->_css_prefix !== null) {\n $uri = '#' . $this->_css_prefix . substr($uri, 1);\n }", " return $uri;\n }", " if (preg_match('/^(http|https|ftp):.+/i', $uri)) {\n if ($this->config['allow_remote']) {\n return $uri;\n }", " $this->extlinks = true;\n if ($is_image && $blocked_source && $this->config['blocked_src']) {\n return $this->config['blocked_src'];\n }\n }", " else if ($is_image && preg_match('/^data:image.+/i', $uri)) { // RFC2397", " return $uri;\n }\n }", " /**\n * Wash Href value\n *\n * @param string $href Href attribute value (link)\n *\n * @return string Washed href\n */\n private function wash_link($href)\n {\n if (strlen($href) && !preg_match('!^(javascript|vbscript|data:)!i', $href)) {\n if ($href[0] == '#' && $this->_css_prefix !== null) {\n return '#' . $this->_css_prefix . substr($href, 1);\n }", " if (preg_match('!^[a-zA-Z._-]+$!', $href)) {\n return 'http://' . $href;\n }", " if (preg_match('!^([a-z][a-z0-9.+-]+:|//|#).+!i', $href)) {\n return $href;\n }\n }\n }", " /**\n * Check it the tag/attribute may contain an URI\n *\n * @param string $tag Element name\n * @param string $attr Attribute name\n *\n * @return bool True if attribute may contain an URI, False otherwise\n */\n private function is_link_attribute($tag, $attr)\n {", " return ($tag == 'a' || $tag == 'area') && $attr == 'href';", " }", " /**\n * Check it the tag/attribute may contain an image URI\n *\n * @param string $tag Element name\n * @param string $attr Attribute name\n *\n * @return bool True if attribute may contain an image URI, False otherwise\n */\n private function is_image_attribute($tag, $attr)\n {\n return $attr == 'background'\n || $attr == 'color-profile' // SVG\n || ($attr == 'poster' && $tag == 'video')\n || ($attr == 'src' && preg_match('/^(img|image|source|input|video|audio)$/i', $tag))", "", " || ($tag == 'image' && $attr == 'href'); // SVG\n }", " /**\n * Check it the tag/attribute may contain a FUNCIRI value\n *\n * @param string $tag Element name\n * @param string $attr Attribute name\n *\n * @return bool True if attribute may contain a FUNCIRI value, False otherwise\n */\n private function is_funciri_attribute($tag, $attr)\n {\n return in_array($attr, array('fill', 'filter', 'stroke', 'marker-start',\n 'marker-end', 'marker-mid', 'clip-path', 'mask', 'cursor'));", "", " }", " /**\n * The main loop that recurse on a node tree.\n * It output only allowed tags with allowed attributes and allowed inline styles\n *\n * @param DOMNode $node HTML element\n * @param int $level Recurrence level (safe initial value found empirically)\n *\n * @return string HTML content\n */\n private function dumpHtml($node, $level = 20)\n {\n if (!$node->hasChildNodes()) {\n return '';\n }", " $level++;", " if ($this->max_nesting_level > 0 && $level == $this->max_nesting_level - 1) {\n // log error message once\n if (!$this->max_nesting_level_error) {\n $this->max_nesting_level_error = true;\n rcube::raise_error(array('code' => 500, 'type' => 'php',\n 'line' => __LINE__, 'file' => __FILE__,\n 'message' => \"Maximum nesting level exceeded (xdebug.max_nesting_level={$this->max_nesting_level})\"),\n true, false);\n }", " return '<!-- ignored -->';\n }", " $node = $node->firstChild;\n $dump = '';", " do {\n switch ($node->nodeType) {\n case XML_ELEMENT_NODE: //Check element\n $tagName = strtolower($node->nodeName);", " if ($tagName == 'link') {\n $uri = $this->wash_uri($node->getAttribute('href'), false, false);\n if (!$uri) {\n $dump .= '<!-- link ignored -->';\n break;\n }", " $node->setAttribute('href', (string) $uri);", "", " }", " if ($callback = $this->handlers[$tagName]) {\n $dump .= call_user_func($callback, $tagName,\n $this->wash_attribs($node), $this->dumpHtml($node, $level), $this);\n }\n else if (isset($this->_html_elements[$tagName])) {\n $content = $this->dumpHtml($node, $level);\n $dump .= '<' . $node->nodeName;", " if ($tagName == 'svg') {\n $xpath = new DOMXPath($node->ownerDocument);\n foreach ($xpath->query('namespace::*') as $ns) {\n if ($ns->nodeName != 'xmlns:xml') {\n $dump .= sprintf(' %s=\"%s\"',\n $ns->nodeName,\n htmlspecialchars($ns->nodeValue, ENT_QUOTES, $this->config['charset'])\n );\n }\n }\n }\n else if ($tagName == 'textarea' && strpos($content, '<') !== false) {\n $content = htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, $this->config['charset']);\n }", " $dump .= $this->wash_attribs($node);", " if ($content === '' && ($this->is_xml || isset($this->_void_elements[$tagName]))) {\n $dump .= ' />';\n }\n else {\n $dump .= '>' . $content . '</' . $node->nodeName . '>';\n }\n }\n else if (isset($this->_ignore_elements[$tagName])) {\n $dump .= '<!-- ' . htmlspecialchars($node->nodeName, ENT_QUOTES, $this->config['charset']) . ' not allowed -->';\n }\n else {\n $dump .= '<!-- ' . htmlspecialchars($node->nodeName, ENT_QUOTES, $this->config['charset']) . ' ignored -->';\n $dump .= $this->dumpHtml($node, $level); // ignore tags not its content\n }\n break;", " case XML_CDATA_SECTION_NODE:\n case XML_TEXT_NODE:\n $dump .= htmlspecialchars($node->nodeValue, ENT_COMPAT | ENT_HTML401 | ENT_SUBSTITUTE, $this->config['charset']);\n break;", " case XML_HTML_DOCUMENT_NODE:\n $dump .= $this->dumpHtml($node, $level);\n break;\n }\n }\n while($node = $node->nextSibling);", " return $dump;\n }", " /**\n * Main function, give it untrusted HTML, tell it if you allow loading\n * remote images and give it a map to convert \"cid:\" urls.\n *\n * @param string $html HTML content\n *\n * @return string Washed HTML content\n */\n public function wash($html)\n {\n $this->extlinks = false;", " $html = $this->cleanup($html);", " // Find base URL for images\n if (preg_match('/<base\\s+href=[\\'\"]*([^\\'\"]+)/is', $html, $matches)) {\n $this->config['base_url'] = $matches[1];\n }\n else {\n $this->config['base_url'] = '';\n }", " // Detect max nesting level (for dumpHTML) (#1489110)\n $this->max_nesting_level = (int) @ini_get('xdebug.max_nesting_level');", " // SVG need to be parsed as XML\n $this->is_xml = !preg_match('/<(html|head|body)/i', $html) && stripos($html, '<svg') !== false;\n $method = $this->is_xml ? 'loadXML' : 'loadHTML';", " // DOMDocument does not support HTML5, try Masterminds parser if available\n if (!$this->is_xml && class_exists('Masterminds\\HTML5')\n // HTML5 parser is slow with content that contains a lot of tags\n // disable it for such cases (https://github.com/Masterminds/html5-php/issues/181)\n && substr_count($html, '<') < 10000\n ) {\n try {\n $html5 = new Masterminds\\HTML5();\n $node = $html5->loadHTML($this->fix_html5($html));\n }\n catch (Exception $e) {\n // ignore, fallback to DOMDocument\n }\n }", " if (empty($node)) {\n // Charset seems to be ignored (probably if defined in the HTML document)\n $node = new DOMDocument('1.0', $this->config['charset']);\n @$node->{$method}($html, LIBXML_PARSEHUGE | LIBXML_COMPACT | LIBXML_NONET);\n }", " return $this->dumpHtml($node);\n }", " /**\n * Getter for config parameters\n *\n * @param string $prop Configuration parameter name\n *\n * @return mixed Configuration parameter value\n */\n public function get_config($prop)\n {\n return $this->config[$prop];\n }", " /**\n * Clean HTML input\n *\n * @param string $html HTML content\n *\n * @return string Clean HTML content\n */\n private function cleanup($html)\n {\n $html = trim($html);", " // special replacements (not properly handled by washtml class)\n $html_search = array(\n // space(s) between <NOBR>\n '/(<\\/nobr>)(\\s+)(<nobr>)/i',\n // PHP bug #32547 workaround: remove title tag\n '/<title[^>]*>[^<]*<\\/title>/i',\n // remove <!doctype> before BOM (#1490291)\n '/<\\!doctype[^>]+>[^<]*/im',\n // byte-order mark (only outlook?)\n '/^(\\0\\0\\xFE\\xFF|\\xFF\\xFE\\0\\0|\\xFE\\xFF|\\xFF\\xFE|\\xEF\\xBB\\xBF)/',\n // washtml/DOMDocument cannot handle xml namespaces\n '/<html\\s[^>]+>/i',\n // washtml/DOMDocument cannot handle xml namespaces\n '/<\\?xml:namespace\\s[^>]+>/i',\n );", " $html_replace = array(\n '\\\\1'.' &nbsp; '.'\\\\3',\n '',\n '',\n '',\n '<html>',\n '',\n );", " $html = preg_replace($html_search, $html_replace, $html);", " $err = array('line' => __LINE__, 'file' => __FILE__, 'message' => \"Could not clean up HTML!\");\n if ($html === null && rcube_utils::preg_error($err)) {\n return '';\n }", " // Replace all of those weird MS Word quotes and other high characters\n $badwordchars = array(\n \"\\xe2\\x80\\x98\", // left single quote\n \"\\xe2\\x80\\x99\", // right single quote\n \"\\xe2\\x80\\x9c\", // left double quote\n \"\\xe2\\x80\\x9d\", // right double quote\n \"\\xe2\\x80\\x94\", // em dash\n \"\\xe2\\x80\\xa6\" // elipses\n );", " $fixedwordchars = array(\n \"'\",\n \"'\",\n '\"',\n '\"',\n '&mdash;',\n '...'\n );", " $html = str_replace($badwordchars, $fixedwordchars, $html);", " // FIXME: HTML comments handling could be better. The code below can break comments (#6464),\n // we should probably do not modify content inside comments at all.", " // fix (unknown/malformed) HTML tags before \"wash\"\n $html = preg_replace_callback('/(<(?!\\!)[\\/]*)([^\\s>]+)([^>]*)/', array($this, 'html_tag_callback'), $html);", " // Remove invalid HTML comments (#1487759)\n // Note: We don't want to remove valid comments, conditional comments\n // and MSOutlook comments (<!-->)\n $html = preg_replace('/<!--[a-zA-Z0-9]+>/', '', $html);", " // fix broken nested lists\n self::fix_broken_lists($html);", " // turn relative into absolute urls\n $html = self::resolve_base($html);", " return $html;\n }", " /**\n * Callback function for HTML tags fixing\n *\n * @param array $matches Matched elements (from preg_replace_callback())\n *\n * @return string Replacement string\n */\n public static function html_tag_callback($matches)\n {\n // It might be an ending of a comment, ignore (#6464)\n if (substr($matches[3], -2) == '--') {\n $matches[0] = '';\n return implode('', $matches);\n }", " $tagname = $matches[2];\n $tagname = preg_replace(array(\n '/:.*$/', // Microsoft's Smart Tags <st1:xxxx>\n '/[^a-z0-9_\\[\\]\\!?-]/i', // forbidden characters\n ), '', $tagname);", " // fix invalid closing tags - remove any attributes (#1489446)\n if ($matches[1] == '</') {\n $matches[3] = '';\n }", " return $matches[1] . $tagname . $matches[3];\n }", " /**\n * Convert all relative URLs according to a <base> in HTML\n *\n * @param string $body HTML body\n *\n * @return string HTML body\n */\n public static function resolve_base($body)\n {\n // check for <base href=...>\n if (preg_match('!(<base.*href=[\"\\']?)([hftps]{3,5}://[a-z0-9/.%-]+)!i', $body, $regs)) {\n $replacer = new rcube_base_replacer($regs[2]);\n $body = $replacer->replace($body);\n }", " return $body;\n }", " /**\n * Fix broken nested lists, they are not handled properly by DOMDocument (#1488768)\n *\n * @param string &$html HTML content\n */\n public static function fix_broken_lists(&$html)\n {\n // do two rounds, one for <ol>, one for <ul>\n foreach (array('ol', 'ul') as $tag) {\n $pos = 0;\n while (($pos = stripos($html, '<' . $tag, $pos)) !== false) {\n $pos++;", " // make sure this is an ol/ul tag\n if (!in_array($html[$pos+2], array(' ', '>'))) {\n continue;\n }", " $p = $pos;\n $in_li = false;\n $li_pos = 0;", " while (($p = strpos($html, '<', $p)) !== false) {\n $tt = strtolower(substr($html, $p, 4));", " // li open tag\n if ($tt == '<li>' || $tt == '<li ') {\n $in_li = true;\n $p += 4;\n }\n // li close tag\n else if ($tt == '</li' && in_array($html[$p+4], array(' ', '>'))) {\n $li_pos = $p;\n $in_li = false;\n $p += 4;\n }\n // ul/ol closing tag\n else if ($tt == '</' . $tag && in_array($html[$p+4], array(' ', '>'))) {\n break;\n }\n // nested ol/ul element out of li\n else if (!$in_li && $li_pos && ($tt == '<ol>' || $tt == '<ol ' || $tt == '<ul>' || $tt == '<ul ')) {\n // find closing tag of this ul/ol element\n $element = substr($tt, 1, 2);\n $cpos = $p;\n do {\n $tpos = stripos($html, '<' . $element, $cpos+1);\n $cpos = stripos($html, '</' . $element, $cpos+1);\n }\n while ($tpos !== false && $cpos !== false && $cpos > $tpos);", " // not found, this is invalid HTML, skip it\n if ($cpos === false) {\n break;\n }", " // get element content\n $end = strpos($html, '>', $cpos);\n $len = $end - $p + 1;\n $element = substr($html, $p, $len);", " // move element to the end of the last li\n $html = substr_replace($html, '', $p, $len);\n $html = substr_replace($html, $element, $li_pos, 0);", " $p = $end;\n }\n else {\n $p++;\n }\n }\n }\n }\n }", " /**\n * Cleanup and workarounds on input to Masterminds/HTML5\n *\n * @param string $html HTML content\n *\n * @return string HTML content\n */\n protected function fix_html5($html)\n {\n // There might be content before html/body tag, we'll move it to the body\n // We'll wrap it by a div container, it's an invalid HTML anyway\n if (strpos($html, '<')) {\n $pos = stripos($html, '<!DOCTYPE') ?: stripos($html, '<html') ?: stripos($html, '<body');\n $prefix = '<div>' . substr($html, 0, $pos) . '</div>';\n $html = substr($html, $pos);\n }", " // HTML5 requires <head> or <body> (#6713)\n // https://github.com/Masterminds/html5-php/issues/166\n if (isset($prefix) || !preg_match('/<(head|body)/i', $html)) {\n $body_pos = stripos($html, '<body');\n $pos = $body_pos !== false ? $body_pos : stripos($html, '<html');", " // No HTML and no BODY tag\n if ($pos === false) {\n $html = '<html><body>' . $prefix . $html;\n }\n // Either HTML or BODY tag found\n else {\n $pos = strpos($html, '>', $pos);\n $html = substr_replace($html, ($body_pos === false ? '<body>' : '') . $prefix, $pos + 1, 0);\n }\n }", " return $html;\n }", " /**\n * Explode css style value\n *\n * @param string $style CSS style\n *\n * @return array List of CSS rules\n */\n protected function explode_style($style)\n {\n $pos = 0;", " // first remove comments\n while (($pos = strpos($style, '/*', $pos)) !== false) {\n $end = strpos($style, '*/', $pos+2);", " if ($end === false) {\n $style = substr($style, 0, $pos);\n }\n else {\n $style = substr_replace($style, '', $pos, $end - $pos + 2);\n }\n }", " $style = trim($style);\n $strlen = strlen($style);\n $result = array();", " // explode value\n for ($p=$i=0; $i < $strlen; $i++) {\n if (($style[$i] == \"\\\"\" || $style[$i] == \"'\") && $style[$i-1] != \"\\\\\") {\n if ($q == $style[$i]) {\n $q = false;\n }\n else if (!$q) {\n $q = $style[$i];\n }\n }", " if (!$q && $style[$i] == ' ' && !preg_match('/[,\\(]/', $style[$i-1])) {\n $result[] = substr($style, $p, $i - $p);\n $p = $i + 1;\n }\n }", " $result[] = (string) substr($style, $p);", " return $result;\n }\n}" ]
[ 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, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [15, 533, 355], "buggy_code_start_loc": [15, 415, 319], "filenames": ["CHANGELOG", "program/lib/Roundcube/rcube_washtml.php", "tests/Framework/Washtml.php"], "fixing_code_end_loc": [18, 590, 480], "fixing_code_start_loc": [16, 415, 320], "message": "Roundcube Webmail before 1.3.15 and 1.4.8 allows stored XSS in HTML messages during message display via a crafted SVG document. This issue has been fixed in 1.4.8 and 1.3.15.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:roundcube:webmail:*:*:*:*:*:*:*:*", "matchCriteriaId": "6AA0D87C-F59C-4A8D-8527-8171BEB076E0", "versionEndExcluding": "1.3.15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:roundcube:webmail:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F4ECE92-6974-4D4F-9900-5F0C548B912A", "versionEndExcluding": "1.4.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.4.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:32:*:*:*:*:*:*:*", "matchCriteriaId": "36D96259-24BD-44E2-96D9-78CE1D41F956", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Roundcube Webmail before 1.3.15 and 1.4.8 allows stored XSS in HTML messages during message display via a crafted SVG document. This issue has been fixed in 1.4.8 and 1.3.15."}, {"lang": "es", "value": "Roundcube Webmail versiones anteriores a 1.3.15 y 1.4.8, permite un ataque de tipo XSS almacenado en mensajes HTML durante la visualizaci\u00f3n de mensajes por medio de un documento SVG dise\u00f1ado. Este problema se ha solucionado en la versi\u00f3n 1.4.8 y versi\u00f3n 1.3.15."}], "evaluatorComment": null, "id": "CVE-2020-16145", "lastModified": "2023-01-20T21:00:58.090", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-08-12T13:15:10.457", "references": [{"source": "cve@mitre.org", "tags": ["Broken Link"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-09/msg00083.html"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/commit/a71bf2e8d4a64ff2c83fdabc1e8cb0c045a41ef4"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/commit/d44ca2308a96576b88d6bf27528964d4fe1a6b8b#diff-d3bb3391c79904494c60ee2ac2f33070"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/releases/tag/1.3.15"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/releases/tag/1.4.8"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/3DAXK3565NYK4OEZVTW6S5LEVIDQEY2E/"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/OBLUQRIBAMEQVBO6GUZECCHJDJIWCYFU/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/roundcube/roundcubemail/commit/a71bf2e8d4a64ff2c83fdabc1e8cb0c045a41ef4"}, "type": "CWE-79"}
184
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n +-----------------------------------------------------------------------+\n | This file is part of the Roundcube Webmail client |\n | |\n | Copyright (C) The Roundcube Dev Team |\n | |\n | Licensed under the GNU General Public License version 3 or |\n | any later version with exceptions for skins & plugins. |\n | See the README file for a full license statement. |\n | |\n | PURPOSE: |\n | Utility class providing HTML sanityzer (based on Washtml class) |\n +-----------------------------------------------------------------------+\n | Author: Thomas Bruederli <roundcube@gmail.com> |\n | Author: Aleksander Machniak <alec@alec.pl> |\n | Author: Frederic Motte <fmotte@ubixis.com> |\n +-----------------------------------------------------------------------+", " Washtml, a HTML sanityzer.", " Copyright (c) 2007 Frederic Motte <fmotte@ubixis.com>\n All rights reserved.", " Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n 1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.", " THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/", "/**\n * Utility class providing HTML sanityzer\n *\n * @package Framework\n * @subpackage Utils\n */\nclass rcube_washtml\n{\n /**\n * @var array Allowed HTML elements (default)\n */\n static $html_elements = array('a', 'abbr', 'acronym', 'address', 'area', 'b',\n 'basefont', 'bdo', 'big', 'blockquote', 'br', 'caption', 'center',\n 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl',\n 'dt', 'em', 'fieldset', 'font', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i',\n 'ins', 'label', 'legend', 'li', 'map', 'menu', 'nobr', 'ol', 'p', 'pre', 'q',\n 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table',\n 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var', 'wbr', 'img',\n 'video', 'source',\n // form elements\n 'button', 'input', 'textarea', 'select', 'option', 'optgroup',\n // SVG\n 'svg', 'altglyph', 'altglyphdef', 'altglyphitem', 'animate',\n 'animatecolor', 'animatetransform', 'circle', 'clippath', 'defs', 'desc',\n 'ellipse', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line',\n 'lineargradient', 'marker', 'mask', 'mpath', 'path', 'pattern',\n 'polygon', 'polyline', 'radialgradient', 'rect', 'set', 'stop', 'switch', 'symbol',\n 'text', 'textpath', 'tref', 'tspan', 'use', 'view', 'vkern', 'filter',\n // SVG Filters\n 'feblend', 'fecolormatrix', 'fecomponenttransfer', 'fecomposite',\n 'feconvolvematrix', 'fediffuselighting', 'fedisplacementmap',\n 'feflood', 'fefunca', 'fefuncb', 'fefuncg', 'fefuncr', 'fegaussianblur',\n 'feimage', 'femerge', 'femergenode', 'femorphology', 'feoffset',\n 'fespecularlighting', 'fetile', 'feturbulence',\n // MathML\n 'math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr',\n 'mmuliscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow',\n 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd',\n 'mtext', 'mtr', 'munder', 'munderover', 'maligngroup', 'malignmark',\n 'mprescripts', 'semantics', 'annotation', 'annotation-xml', 'none',\n 'infinity', 'matrix', 'matrixrow', 'ci', 'cn', 'sep', 'apply',\n 'plus', 'minus', 'eq', 'power', 'times', 'divide', 'csymbol', 'root',\n 'bvar', 'lowlimit', 'uplimit',\n );", " /**\n * @var array Ignore these HTML tags and their content\n */\n static $ignore_elements = array('script', 'applet', 'embed', 'object', 'style');", " /**\n * @var array Allowed HTML attributes\n */\n static $html_attribs = array('name', 'class', 'title', 'alt', 'width', 'height',\n 'align', 'nowrap', 'col', 'row', 'id', 'rowspan', 'colspan', 'cellspacing',\n 'cellpadding', 'valign', 'bgcolor', 'color', 'border', 'bordercolorlight',\n 'bordercolordark', 'face', 'marginwidth', 'marginheight', 'axis', 'border',\n 'abbr', 'char', 'charoff', 'clear', 'compact', 'coords', 'vspace', 'hspace',\n 'cellborder', 'size', 'lang', 'dir', 'usemap', 'shape', 'media',\n 'background', 'src', 'poster', 'href', 'headers',\n // attributes of form elements\n 'type', 'rows', 'cols', 'disabled', 'readonly', 'checked', 'multiple', 'value', 'for',\n // SVG\n 'accent-height', 'accumulate', 'additive', 'alignment-baseline', 'alphabetic',\n 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseprofile',\n 'baseline-shift', 'begin', 'bias', 'by', 'clip', 'clip-path', 'clip-rule',\n 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile',\n 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction',\n 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'fill', 'fill-opacity',\n 'fill-rule', 'filter', 'flood-color', 'flood-opacity', 'font-family', 'font-size',\n 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'from',\n 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform',\n 'image-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints',\n 'keysplines', 'keytimes', 'lengthadjust', 'letter-spacing', 'kernelmatrix',\n 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid',\n 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits',\n 'maskunits', 'max', 'mask', 'mode', 'min', 'numoctaves', 'offset', 'operator',\n 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order',\n 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits',\n 'points', 'preservealpha', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount',\n 'repeatdur', 'restart', 'rotate', 'scale', 'seed', 'shape-rendering', 'show', 'specularconstant',\n 'specularexponent', 'spreadmethod', 'stddeviation', 'stitchtiles', 'stop-color',\n 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap',\n 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width',\n 'surfacescale', 'targetx', 'targety', 'transform', 'text-anchor', 'text-decoration',\n 'text-rendering', 'textlength', 'to', 'u1', 'u2', 'unicode', 'values', 'viewbox',\n 'visibility', 'vert-adv-y', 'version', 'vert-origin-x', 'vert-origin-y', 'word-spacing',\n 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2',\n 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan',\n // MathML\n 'accent', 'accentunder', 'bevelled', 'close', 'columnalign', 'columnlines',\n 'columnspan', 'denomalign', 'depth', 'display', 'displaystyle', 'encoding', 'fence',\n 'frame', 'largeop', 'length', 'linethickness', 'lspace', 'lquote',\n 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize',\n 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign',\n 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel',\n 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator',\n 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset',\n 'fontsize', 'fontweight', 'fontstyle', 'fontfamily', 'groupalign', 'edge', 'side',\n );", " /**\n * @var array Elements which could be empty and be returned in short form (<tag />)\n */\n static $void_elements = array('area', 'base', 'br', 'col', 'command', 'embed', 'hr',\n 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr',\n // MathML\n 'sep', 'infinity', 'in', 'plus', 'eq', 'power', 'times', 'divide', 'root',\n 'maligngroup', 'none', 'mprescripts',\n );", " /**\n * @var array Additional allowed attributes of body element\n */\n static $body_attribs = array('alink', 'background', 'bgcolor', 'link', 'text', 'vlink');", " /** @var bool State indicating existence of linked objects in HTML */\n public $extlinks = false;", " /** @var array Current settings */\n private $config = array();", " /** @var array Registered callback functions for tags */\n private $handlers = array();", " /** @var array Allowed HTML elements */\n private $_html_elements = array();", " /** @var array Ignore these HTML tags but process their content */\n private $_ignore_elements = array();", " /** @var array Elements which could be empty and be returned in short form (<tag />) */\n private $_void_elements = array();", " /** @var array Allowed HTML attributes */\n private $_html_attribs = array();", " /** @var string A prefix to be added to id/class/for attribute values */\n private $_css_prefix;", " /** @var int Max nesting level */\n private $max_nesting_level;", " /** @var bool True if current document is XML */\n private $is_xml = false;", "\n /**\n * Class constructor\n *\n * @param array $p Configuration options:\n * allow_remote: is a boolean to allow link to remote resources (images/css)\n * blocked_src: string with image-src to be used for blocked remote images\n * show_washed: is a boolean to include washed out attributes as x-washed\n * cid_map: is an array where cid urls index urls to replace them\n * charset: is a string containing the charset of the HTML document,\n * to be used if the charset is not defined in the document\n * css_prefix: A prefix to be added to id/class/for attribute values\n * html_elements: Additional allowed HTML elements\n * ignore_elements: Additional HTML elements to ignore\n * html_attribs: Additional allowed HTML attributes\n * void_elements: Elements which could be empty and be returned in short form (<tag />)\n */\n public function __construct($p = array())\n {\n $this->_html_elements = array_flip((array)$p['html_elements']) + array_flip(self::$html_elements);\n $this->_html_attribs = array_flip((array)$p['html_attribs']) + array_flip(self::$html_attribs);\n $this->_ignore_elements = array_flip((array)$p['ignore_elements']) + array_flip(self::$ignore_elements);\n $this->_void_elements = array_flip((array)$p['void_elements']) + array_flip(self::$void_elements);\n $this->_css_prefix = is_string($p['css_prefix']) && strlen($p['css_prefix']) ? $p['css_prefix'] : null;", " unset($p['html_elements'], $p['html_attribs'], $p['ignore_elements'], $p['void_elements'], $p['css_prefix']);", " $this->config = $p + array('show_washed' => true, 'allow_remote' => false, 'cid_map' => array());\n }", " /**\n * Register a callback function for a certain tag\n *\n * @param string $tag HTML tag name\n * @param callback $callback Callback function\n */\n public function add_callback($tag, $callback)\n {\n $this->handlers[$tag] = $callback;\n }", " /**\n * Check CSS style\n *\n * @param string $style CSS style\n *\n * @return string Washed CSS style\n */\n private function wash_style($style)\n {\n $result = array();", " // Remove unwanted white-space characters so regular expressions below work better\n $style = preg_replace('/[\\n\\r\\s\\t]+/', ' ', $style);", " // Decode insecure character sequences\n $style = rcube_utils::xss_entity_decode($style);", " foreach (explode(';', $style) as $declaration) {\n if (preg_match('/^\\s*([a-z\\\\\\-]+)\\s*:\\s*(.*)\\s*$/i', $declaration, $match)) {\n $cssid = $match[1];\n $str = $match[2];\n $value = '';", " foreach ($this->explode_style($str) as $val) {\n if (preg_match('/^url\\(/i', $val)) {\n if (preg_match('/^url\\(\\s*[\\'\"]?([^\\'\"\\)]*)[\\'\"]?\\s*\\)/iu', $val, $match)) {\n if ($url = $this->wash_uri($match[1])) {\n $value .= ' url(' . htmlspecialchars($url, ENT_QUOTES, $this->config['charset']) . ')';\n }\n }\n }\n else if (!preg_match('/^(behavior|expression)/i', $val)) {\n // Set position:fixed to position:absolute for security (#5264)\n if (!strcasecmp($cssid, 'position') && !strcasecmp($val, 'fixed')) {\n $val = 'absolute';\n }", " // whitelist ?\n $value .= ' ' . $val;", " // #1488535: Fix size units, so width:800 would be changed to width:800px\n if (preg_match('/^(left|right|top|bottom|width|height)/i', $cssid)\n && preg_match('/^[0-9]+$/', $val)\n ) {\n $value .= 'px';\n }\n }\n }", " if (isset($value[0])) {\n $result[] = $cssid . ':' . $value;\n }\n }\n }", " return implode('; ', $result);\n }", " /**\n * Take a node and return allowed attributes and check values\n *\n * @param DOMNode $node Document element\n *\n * @return string Washed element attributes\n */\n private function wash_attribs($node)\n {\n $result = '';\n $washed = array();\n $additional_attribs = array();", " if ($node->nodeName == 'body') {\n $additional_attribs = self::$body_attribs;\n }", " foreach ($node->attributes as $name => $attr) {\n $key = strtolower($name);\n $value = $attr->nodeValue;", " if ($key == 'style' && ($style = $this->wash_style($value))) {\n // replace double quotes to prevent syntax error and XSS issues (#1490227)\n $result .= ' style=\"' . str_replace('\"', '&quot;', $style) . '\"';\n }\n else if (isset($this->_html_attribs[$key]) || in_array($key, $additional_attribs)) {\n $value = trim($value);\n $out = null;", " // in SVG to/from attribs may contain anything, including URIs\n if ($key == 'to' || $key == 'from') {\n $key = strtolower($node->getAttribute('attributeName'));\n if ($key && !isset($this->_html_attribs[$key])) {\n $key = null;\n }\n }", " if ($this->is_image_attribute($node->nodeName, $key)) {\n $out = $this->wash_uri($value, true);\n }\n else if ($this->is_link_attribute($node->nodeName, $key)) {\n $out = $this->wash_link($value);\n }\n else if ($this->is_funciri_attribute($node->nodeName, $key)) {\n if (preg_match('/^[a-z:]*url\\(/i', $val)) {\n if (preg_match('/^([a-z:]*url)\\(\\s*[\\'\"]?([^\\'\"\\)]*)[\\'\"]?\\s*\\)/iu', $value, $match)) {\n if ($url = $this->wash_uri($match[2])) {\n $result .= ' ' . $attr->nodeName . '=\"' . $match[1]\n . '(' . htmlspecialchars($url, ENT_QUOTES, $this->config['charset']) . ')'\n . substr($val, strlen($match[0])) . '\"';\n continue;\n }\n }\n else {\n $out = $value;\n }\n }\n else {\n $out = $value;\n }\n }\n else if ($this->_css_prefix !== null && in_array($key, array('id', 'class', 'for'))) {\n $out = preg_replace('/(\\S+)/', $this->_css_prefix . '\\1', $value);\n }\n else if ($key) {\n $out = $value;\n }", " if ($out !== null && $out !== '') {\n $result .= ' ' . $attr->nodeName . '=\"' . htmlspecialchars($out, ENT_QUOTES | ENT_SUBSTITUTE, $this->config['charset']) . '\"';\n }\n else if ($value) {\n $washed[] = htmlspecialchars($attr->nodeName, ENT_QUOTES, $this->config['charset']);\n }\n }\n else {\n $washed[] = htmlspecialchars($attr->nodeName, ENT_QUOTES, $this->config['charset']);\n }\n }", " if (!empty($washed) && $this->config['show_washed']) {\n $result .= ' x-washed=\"' . implode(' ', $washed) . '\"';\n }", " return $result;\n }", " /**\n * Wash URI value\n *\n * @param string $uri URI\n * @param bool $blocked_source Block remote source\n * @param bool $is_image URI points to an image\n *\n * @return string Washed URI\n */\n private function wash_uri($uri, $blocked_source = false, $is_image = true)\n {\n if (($src = $this->config['cid_map'][$uri])\n || ($src = $this->config['cid_map'][$this->config['base_url'].$uri])\n ) {\n return $src;\n }", " // allow url(#id) used in SVG\n if ($uri[0] == '#') {\n if ($this->_css_prefix !== null) {\n $uri = '#' . $this->_css_prefix . substr($uri, 1);\n }", " return $uri;\n }", " if (preg_match('/^(http|https|ftp):.+/i', $uri)) {\n if ($this->config['allow_remote']) {\n return $uri;\n }", " $this->extlinks = true;\n if ($is_image && $blocked_source && $this->config['blocked_src']) {\n return $this->config['blocked_src'];\n }\n }", " else if ($is_image && preg_match('/^data:image\\/([^,]+),(.+)$/i', $uri, $matches)) { // RFC2397\n // svg images can be insecure, we'll sanitize them\n if (stripos($matches[1], 'svg') !== false) {\n $svg = $matches[2];", " if (stripos($matches[1], ';base64') !== false) {\n $svg = base64_decode($svg);\n $type = $matches[1];\n }\n else {\n $type = $matches[1] . ';base64';\n }", " $washer = new self($this->config);\n $svg = $washer->wash($svg);", " // Invalid svg content\n if (empty($svg)) {\n return null;\n }", " return 'data:image/' . $type . ',' . base64_encode($svg);\n }\n", " return $uri;\n }\n }", " /**\n * Wash Href value\n *\n * @param string $href Href attribute value (link)\n *\n * @return string Washed href\n */\n private function wash_link($href)\n {\n if (strlen($href) && !preg_match('!^(javascript|vbscript|data:)!i', $href)) {\n if ($href[0] == '#' && $this->_css_prefix !== null) {\n return '#' . $this->_css_prefix . substr($href, 1);\n }", " if (preg_match('!^[a-zA-Z._-]+$!', $href)) {\n return 'http://' . $href;\n }", " if (preg_match('!^([a-z][a-z0-9.+-]+:|//|#).+!i', $href)) {\n return $href;\n }\n }\n }", " /**\n * Check it the tag/attribute may contain an URI\n *\n * @param string $tag Element name\n * @param string $attr Attribute name\n *\n * @return bool True if attribute may contain an URI, False otherwise\n */\n private function is_link_attribute($tag, $attr)\n {", " return $attr === 'href';", " }", " /**\n * Check it the tag/attribute may contain an image URI\n *\n * @param string $tag Element name\n * @param string $attr Attribute name\n *\n * @return bool True if attribute may contain an image URI, False otherwise\n */\n private function is_image_attribute($tag, $attr)\n {\n return $attr == 'background'\n || $attr == 'color-profile' // SVG\n || ($attr == 'poster' && $tag == 'video')\n || ($attr == 'src' && preg_match('/^(img|image|source|input|video|audio)$/i', $tag))", " || ($tag == 'use' && $attr == 'href') // SVG", " || ($tag == 'image' && $attr == 'href'); // SVG\n }", " /**\n * Check it the tag/attribute may contain a FUNCIRI value\n *\n * @param string $tag Element name\n * @param string $attr Attribute name\n *\n * @return bool True if attribute may contain a FUNCIRI value, False otherwise\n */\n private function is_funciri_attribute($tag, $attr)\n {\n return in_array($attr, array('fill', 'filter', 'stroke', 'marker-start',\n 'marker-end', 'marker-mid', 'clip-path', 'mask', 'cursor'));", " }", " /**\n * Check if a specified element has an attribute with specified value.\n * Do it in case-insensitive manner.\n *\n * @param DOMElement $node The element\n * @param string $attr_name The attribute name\n * @param string $attr_value The attribute value to find\n *\n * @return bool True if the specified attribute exists and has the expected value\n */\n private static function attribute_value($node, $attr_name, $attr_value)\n {\n $attr_name = strtolower($attr_name);", " foreach ($node->attributes as $name => $attr) {\n if (strtolower($name) === $attr_name) {\n if (strtolower($attr_value) === strtolower($attr->nodeValue)) {\n return true;\n }\n }\n }", " return false;", " }", " /**\n * The main loop that recurse on a node tree.\n * It output only allowed tags with allowed attributes and allowed inline styles\n *\n * @param DOMNode $node HTML element\n * @param int $level Recurrence level (safe initial value found empirically)\n *\n * @return string HTML content\n */\n private function dumpHtml($node, $level = 20)\n {\n if (!$node->hasChildNodes()) {\n return '';\n }", " $level++;", " if ($this->max_nesting_level > 0 && $level == $this->max_nesting_level - 1) {\n // log error message once\n if (!$this->max_nesting_level_error) {\n $this->max_nesting_level_error = true;\n rcube::raise_error(array('code' => 500, 'type' => 'php',\n 'line' => __LINE__, 'file' => __FILE__,\n 'message' => \"Maximum nesting level exceeded (xdebug.max_nesting_level={$this->max_nesting_level})\"),\n true, false);\n }", " return '<!-- ignored -->';\n }", " $node = $node->firstChild;\n $dump = '';", " do {\n switch ($node->nodeType) {\n case XML_ELEMENT_NODE: //Check element\n $tagName = strtolower($node->nodeName);", " if ($tagName == 'link') {\n $uri = $this->wash_uri($node->getAttribute('href'), false, false);\n if (!$uri) {\n $dump .= '<!-- link ignored -->';\n break;\n }", " $node->setAttribute('href', (string) $uri);", " }\n else if (in_array($tagName, array('animate', 'animatecolor', 'set', 'animatetransform'))\n && self::attribute_value($node, 'attributename', 'href')\n ) {\n // Insecure svg tags\n $dump .= \"<!-- $tagName blocked -->\";\n break;", " }", " if ($callback = $this->handlers[$tagName]) {\n $dump .= call_user_func($callback, $tagName,\n $this->wash_attribs($node), $this->dumpHtml($node, $level), $this);\n }\n else if (isset($this->_html_elements[$tagName])) {\n $content = $this->dumpHtml($node, $level);\n $dump .= '<' . $node->nodeName;", " if ($tagName == 'svg') {\n $xpath = new DOMXPath($node->ownerDocument);\n foreach ($xpath->query('namespace::*') as $ns) {\n if ($ns->nodeName != 'xmlns:xml') {\n $dump .= sprintf(' %s=\"%s\"',\n $ns->nodeName,\n htmlspecialchars($ns->nodeValue, ENT_QUOTES, $this->config['charset'])\n );\n }\n }\n }\n else if ($tagName == 'textarea' && strpos($content, '<') !== false) {\n $content = htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, $this->config['charset']);\n }", " $dump .= $this->wash_attribs($node);", " if ($content === '' && ($this->is_xml || isset($this->_void_elements[$tagName]))) {\n $dump .= ' />';\n }\n else {\n $dump .= '>' . $content . '</' . $node->nodeName . '>';\n }\n }\n else if (isset($this->_ignore_elements[$tagName])) {\n $dump .= '<!-- ' . htmlspecialchars($node->nodeName, ENT_QUOTES, $this->config['charset']) . ' not allowed -->';\n }\n else {\n $dump .= '<!-- ' . htmlspecialchars($node->nodeName, ENT_QUOTES, $this->config['charset']) . ' ignored -->';\n $dump .= $this->dumpHtml($node, $level); // ignore tags not its content\n }\n break;", " case XML_CDATA_SECTION_NODE:\n case XML_TEXT_NODE:\n $dump .= htmlspecialchars($node->nodeValue, ENT_COMPAT | ENT_HTML401 | ENT_SUBSTITUTE, $this->config['charset']);\n break;", " case XML_HTML_DOCUMENT_NODE:\n $dump .= $this->dumpHtml($node, $level);\n break;\n }\n }\n while($node = $node->nextSibling);", " return $dump;\n }", " /**\n * Main function, give it untrusted HTML, tell it if you allow loading\n * remote images and give it a map to convert \"cid:\" urls.\n *\n * @param string $html HTML content\n *\n * @return string Washed HTML content\n */\n public function wash($html)\n {\n $this->extlinks = false;", " $html = $this->cleanup($html);", " // Find base URL for images\n if (preg_match('/<base\\s+href=[\\'\"]*([^\\'\"]+)/is', $html, $matches)) {\n $this->config['base_url'] = $matches[1];\n }\n else {\n $this->config['base_url'] = '';\n }", " // Detect max nesting level (for dumpHTML) (#1489110)\n $this->max_nesting_level = (int) @ini_get('xdebug.max_nesting_level');", " // SVG need to be parsed as XML\n $this->is_xml = !preg_match('/<(html|head|body)/i', $html) && stripos($html, '<svg') !== false;\n $method = $this->is_xml ? 'loadXML' : 'loadHTML';", " // DOMDocument does not support HTML5, try Masterminds parser if available\n if (!$this->is_xml && class_exists('Masterminds\\HTML5')\n // HTML5 parser is slow with content that contains a lot of tags\n // disable it for such cases (https://github.com/Masterminds/html5-php/issues/181)\n && substr_count($html, '<') < 10000\n ) {\n try {\n $html5 = new Masterminds\\HTML5();\n $node = $html5->loadHTML($this->fix_html5($html));\n }\n catch (Exception $e) {\n // ignore, fallback to DOMDocument\n }\n }", " if (empty($node)) {\n // Charset seems to be ignored (probably if defined in the HTML document)\n $node = new DOMDocument('1.0', $this->config['charset']);\n @$node->{$method}($html, LIBXML_PARSEHUGE | LIBXML_COMPACT | LIBXML_NONET);\n }", " return $this->dumpHtml($node);\n }", " /**\n * Getter for config parameters\n *\n * @param string $prop Configuration parameter name\n *\n * @return mixed Configuration parameter value\n */\n public function get_config($prop)\n {\n return $this->config[$prop];\n }", " /**\n * Clean HTML input\n *\n * @param string $html HTML content\n *\n * @return string Clean HTML content\n */\n private function cleanup($html)\n {\n $html = trim($html);", " // special replacements (not properly handled by washtml class)\n $html_search = array(\n // space(s) between <NOBR>\n '/(<\\/nobr>)(\\s+)(<nobr>)/i',\n // PHP bug #32547 workaround: remove title tag\n '/<title[^>]*>[^<]*<\\/title>/i',\n // remove <!doctype> before BOM (#1490291)\n '/<\\!doctype[^>]+>[^<]*/im',\n // byte-order mark (only outlook?)\n '/^(\\0\\0\\xFE\\xFF|\\xFF\\xFE\\0\\0|\\xFE\\xFF|\\xFF\\xFE|\\xEF\\xBB\\xBF)/',\n // washtml/DOMDocument cannot handle xml namespaces\n '/<html\\s[^>]+>/i',\n // washtml/DOMDocument cannot handle xml namespaces\n '/<\\?xml:namespace\\s[^>]+>/i',\n );", " $html_replace = array(\n '\\\\1'.' &nbsp; '.'\\\\3',\n '',\n '',\n '',\n '<html>',\n '',\n );", " $html = preg_replace($html_search, $html_replace, $html);", " $err = array('line' => __LINE__, 'file' => __FILE__, 'message' => \"Could not clean up HTML!\");\n if ($html === null && rcube_utils::preg_error($err)) {\n return '';\n }", " // Replace all of those weird MS Word quotes and other high characters\n $badwordchars = array(\n \"\\xe2\\x80\\x98\", // left single quote\n \"\\xe2\\x80\\x99\", // right single quote\n \"\\xe2\\x80\\x9c\", // left double quote\n \"\\xe2\\x80\\x9d\", // right double quote\n \"\\xe2\\x80\\x94\", // em dash\n \"\\xe2\\x80\\xa6\" // elipses\n );", " $fixedwordchars = array(\n \"'\",\n \"'\",\n '\"',\n '\"',\n '&mdash;',\n '...'\n );", " $html = str_replace($badwordchars, $fixedwordchars, $html);", " // FIXME: HTML comments handling could be better. The code below can break comments (#6464),\n // we should probably do not modify content inside comments at all.", " // fix (unknown/malformed) HTML tags before \"wash\"\n $html = preg_replace_callback('/(<(?!\\!)[\\/]*)([^\\s>]+)([^>]*)/', array($this, 'html_tag_callback'), $html);", " // Remove invalid HTML comments (#1487759)\n // Note: We don't want to remove valid comments, conditional comments\n // and MSOutlook comments (<!-->)\n $html = preg_replace('/<!--[a-zA-Z0-9]+>/', '', $html);", " // fix broken nested lists\n self::fix_broken_lists($html);", " // turn relative into absolute urls\n $html = self::resolve_base($html);", " return $html;\n }", " /**\n * Callback function for HTML tags fixing\n *\n * @param array $matches Matched elements (from preg_replace_callback())\n *\n * @return string Replacement string\n */\n public static function html_tag_callback($matches)\n {\n // It might be an ending of a comment, ignore (#6464)\n if (substr($matches[3], -2) == '--') {\n $matches[0] = '';\n return implode('', $matches);\n }", " $tagname = $matches[2];\n $tagname = preg_replace(array(\n '/:.*$/', // Microsoft's Smart Tags <st1:xxxx>\n '/[^a-z0-9_\\[\\]\\!?-]/i', // forbidden characters\n ), '', $tagname);", " // fix invalid closing tags - remove any attributes (#1489446)\n if ($matches[1] == '</') {\n $matches[3] = '';\n }", " return $matches[1] . $tagname . $matches[3];\n }", " /**\n * Convert all relative URLs according to a <base> in HTML\n *\n * @param string $body HTML body\n *\n * @return string HTML body\n */\n public static function resolve_base($body)\n {\n // check for <base href=...>\n if (preg_match('!(<base.*href=[\"\\']?)([hftps]{3,5}://[a-z0-9/.%-]+)!i', $body, $regs)) {\n $replacer = new rcube_base_replacer($regs[2]);\n $body = $replacer->replace($body);\n }", " return $body;\n }", " /**\n * Fix broken nested lists, they are not handled properly by DOMDocument (#1488768)\n *\n * @param string &$html HTML content\n */\n public static function fix_broken_lists(&$html)\n {\n // do two rounds, one for <ol>, one for <ul>\n foreach (array('ol', 'ul') as $tag) {\n $pos = 0;\n while (($pos = stripos($html, '<' . $tag, $pos)) !== false) {\n $pos++;", " // make sure this is an ol/ul tag\n if (!in_array($html[$pos+2], array(' ', '>'))) {\n continue;\n }", " $p = $pos;\n $in_li = false;\n $li_pos = 0;", " while (($p = strpos($html, '<', $p)) !== false) {\n $tt = strtolower(substr($html, $p, 4));", " // li open tag\n if ($tt == '<li>' || $tt == '<li ') {\n $in_li = true;\n $p += 4;\n }\n // li close tag\n else if ($tt == '</li' && in_array($html[$p+4], array(' ', '>'))) {\n $li_pos = $p;\n $in_li = false;\n $p += 4;\n }\n // ul/ol closing tag\n else if ($tt == '</' . $tag && in_array($html[$p+4], array(' ', '>'))) {\n break;\n }\n // nested ol/ul element out of li\n else if (!$in_li && $li_pos && ($tt == '<ol>' || $tt == '<ol ' || $tt == '<ul>' || $tt == '<ul ')) {\n // find closing tag of this ul/ol element\n $element = substr($tt, 1, 2);\n $cpos = $p;\n do {\n $tpos = stripos($html, '<' . $element, $cpos+1);\n $cpos = stripos($html, '</' . $element, $cpos+1);\n }\n while ($tpos !== false && $cpos !== false && $cpos > $tpos);", " // not found, this is invalid HTML, skip it\n if ($cpos === false) {\n break;\n }", " // get element content\n $end = strpos($html, '>', $cpos);\n $len = $end - $p + 1;\n $element = substr($html, $p, $len);", " // move element to the end of the last li\n $html = substr_replace($html, '', $p, $len);\n $html = substr_replace($html, $element, $li_pos, 0);", " $p = $end;\n }\n else {\n $p++;\n }\n }\n }\n }\n }", " /**\n * Cleanup and workarounds on input to Masterminds/HTML5\n *\n * @param string $html HTML content\n *\n * @return string HTML content\n */\n protected function fix_html5($html)\n {\n // There might be content before html/body tag, we'll move it to the body\n // We'll wrap it by a div container, it's an invalid HTML anyway\n if (strpos($html, '<')) {\n $pos = stripos($html, '<!DOCTYPE') ?: stripos($html, '<html') ?: stripos($html, '<body');\n $prefix = '<div>' . substr($html, 0, $pos) . '</div>';\n $html = substr($html, $pos);\n }", " // HTML5 requires <head> or <body> (#6713)\n // https://github.com/Masterminds/html5-php/issues/166\n if (isset($prefix) || !preg_match('/<(head|body)/i', $html)) {\n $body_pos = stripos($html, '<body');\n $pos = $body_pos !== false ? $body_pos : stripos($html, '<html');", " // No HTML and no BODY tag\n if ($pos === false) {\n $html = '<html><body>' . $prefix . $html;\n }\n // Either HTML or BODY tag found\n else {\n $pos = strpos($html, '>', $pos);\n $html = substr_replace($html, ($body_pos === false ? '<body>' : '') . $prefix, $pos + 1, 0);\n }\n }", " return $html;\n }", " /**\n * Explode css style value\n *\n * @param string $style CSS style\n *\n * @return array List of CSS rules\n */\n protected function explode_style($style)\n {\n $pos = 0;", " // first remove comments\n while (($pos = strpos($style, '/*', $pos)) !== false) {\n $end = strpos($style, '*/', $pos+2);", " if ($end === false) {\n $style = substr($style, 0, $pos);\n }\n else {\n $style = substr_replace($style, '', $pos, $end - $pos + 2);\n }\n }", " $style = trim($style);\n $strlen = strlen($style);\n $result = array();", " // explode value\n for ($p=$i=0; $i < $strlen; $i++) {\n if (($style[$i] == \"\\\"\" || $style[$i] == \"'\") && $style[$i-1] != \"\\\\\") {\n if ($q == $style[$i]) {\n $q = false;\n }\n else if (!$q) {\n $q = $style[$i];\n }\n }", " if (!$q && $style[$i] == ' ' && !preg_match('/[,\\(]/', $style[$i-1])) {\n $result[] = substr($style, $p, $i - $p);\n $p = $i + 1;\n }\n }", " $result[] = (string) substr($style, $p);", " return $result;\n }\n}" ]
[ 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, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [15, 533, 355], "buggy_code_start_loc": [15, 415, 319], "filenames": ["CHANGELOG", "program/lib/Roundcube/rcube_washtml.php", "tests/Framework/Washtml.php"], "fixing_code_end_loc": [18, 590, 480], "fixing_code_start_loc": [16, 415, 320], "message": "Roundcube Webmail before 1.3.15 and 1.4.8 allows stored XSS in HTML messages during message display via a crafted SVG document. This issue has been fixed in 1.4.8 and 1.3.15.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:roundcube:webmail:*:*:*:*:*:*:*:*", "matchCriteriaId": "6AA0D87C-F59C-4A8D-8527-8171BEB076E0", "versionEndExcluding": "1.3.15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:roundcube:webmail:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F4ECE92-6974-4D4F-9900-5F0C548B912A", "versionEndExcluding": "1.4.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.4.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:32:*:*:*:*:*:*:*", "matchCriteriaId": "36D96259-24BD-44E2-96D9-78CE1D41F956", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Roundcube Webmail before 1.3.15 and 1.4.8 allows stored XSS in HTML messages during message display via a crafted SVG document. This issue has been fixed in 1.4.8 and 1.3.15."}, {"lang": "es", "value": "Roundcube Webmail versiones anteriores a 1.3.15 y 1.4.8, permite un ataque de tipo XSS almacenado en mensajes HTML durante la visualizaci\u00f3n de mensajes por medio de un documento SVG dise\u00f1ado. Este problema se ha solucionado en la versi\u00f3n 1.4.8 y versi\u00f3n 1.3.15."}], "evaluatorComment": null, "id": "CVE-2020-16145", "lastModified": "2023-01-20T21:00:58.090", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-08-12T13:15:10.457", "references": [{"source": "cve@mitre.org", "tags": ["Broken Link"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-09/msg00083.html"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/commit/a71bf2e8d4a64ff2c83fdabc1e8cb0c045a41ef4"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/commit/d44ca2308a96576b88d6bf27528964d4fe1a6b8b#diff-d3bb3391c79904494c60ee2ac2f33070"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/releases/tag/1.3.15"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/releases/tag/1.4.8"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/3DAXK3565NYK4OEZVTW6S5LEVIDQEY2E/"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/OBLUQRIBAMEQVBO6GUZECCHJDJIWCYFU/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/roundcube/roundcubemail/commit/a71bf2e8d4a64ff2c83fdabc1e8cb0c045a41ef4"}, "type": "CWE-79"}
184
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Test class to test rcube_washtml class\n *\n * @package Tests\n */\nclass Framework_Washtml extends PHPUnit_Framework_TestCase\n{\n /**\n * A helper method to remove comments added by rcube_washtml\n */\n function cleanupResult($html)\n {\n return preg_replace('/<!-- [a-z]+ (ignored|not allowed) -->/', '', $html);\n }", "\n /**\n * Test the elimination of some XSS vulnerabilities\n */\n function test_html_xss()\n {\n // #1488850\n $html = '<a href=\"data:text/html,&lt;script&gt;alert(document.cookie)&lt;/script&gt;\">Firefox</a>'\n .'<a href=\"vbscript:alert(document.cookie)\">Internet Explorer</a></p>'\n .'<A href=\"data:text/html,&lt;script&gt;alert(document.cookie)&lt;/script&gt;\">Firefox</a>'\n .'<A HREF=\"vbscript:alert(document.cookie)\">Internet Explorer</a>'\n .'<a href=\"data:application/xhtml+xml;base64,PGh0bW\">CLICK ME</a>'; // #6896", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertNotRegExp('/data:text/', $washed, \"Remove data:text/html links\");\n $this->assertNotRegExp('/vbscript:/', $washed, \"Remove vbscript: links\");\n $this->assertNotRegExp('/data:application/', $washed, \"Remove data:application links\");\n }", " /**\n * Test fixing of invalid href\n */\n function test_href()\n {\n $html = \"<p><a href=\\\"\\nhttp://test.com\\n\\\">Firefox</a><a href=\\\"domain.com\\\">Firefox</a>\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertRegExp('|href=\"http://test\\.com\"|', $washed, \"Link href with newlines (#1488940)\");\n $this->assertRegExp('|href=\"http://domain\\.com\"|', $washed, \"Link href with no protocol (#7454)\");\n }", " /**\n * Test XSS in area's href (#5240)\n */\n function test_href_area()\n {\n $html = '<p><area href=\"data:text/html,&lt;script&gt;alert(document.cookie)&lt;/script&gt;\">'\n . '<area href=\"vbscript:alert(document.cookie)\">Internet Explorer</p>'\n . '<area href=\"javascript:alert(document.domain)\" shape=default>'\n . '<p><AREA HREF=\"data:text/html,&lt;script&gt;alert(document.cookie)&lt;/script&gt;\">'\n . '<Area href=\"vbscript:alert(document.cookie)\">Internet Explorer</p>'\n . '<area HREF=\"javascript:alert(document.domain)\" shape=default>';", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertNotRegExp('/data:text/', $washed, \"data:text/html in area href\");\n $this->assertNotRegExp('/vbscript:/', $washed, \"vbscript: in area href\");\n $this->assertNotRegExp('/javascript:/', $washed, \"javascript: in area href\");\n }", " /**\n * Test handling HTML comments\n */\n function test_comments()\n {\n $washer = new rcube_washtml;", " $html = \"<!--[if gte mso 10]><p>p1</p><!--><p>p2</p>\";\n $washed = $this->cleanupResult($washer->wash($html));", " $this->assertEquals('<p>p2</p>', $washed, \"HTML conditional comments (#1489004)\");", " $html = \"<!--TestCommentInvalid><p>test</p>\";\n $washed = $this->cleanupResult($washer->wash($html));", " $this->assertEquals('<p>test</p>', $washed, \"HTML invalid comments (#1487759)\");", " $html = \"<p>para1</p><!-- comment --><p>para2</p>\";\n $washed = $this->cleanupResult($washer->wash($html));", " $this->assertEquals('<p>para1</p><p>para2</p>', $washed, \"HTML comments - simple comment\");", " $html = \"<p>para1</p><!-- <hr> comment --><p>para2</p>\";\n $washed = $this->cleanupResult($washer->wash($html));", " $this->assertEquals('<p>para1</p><p>para2</p>', $washed, \"HTML comments - tags inside (#1489904)\");", " $html = \"<p>para1</p><!-- comment => comment --><p>para2</p>\";\n $washed = $this->cleanupResult($washer->wash($html));", " $this->assertEquals('<p>para1</p><p>para2</p>', $washed, \"HTML comments - bracket inside\");", " $html = \"<p><!-- span>1</span -->\\n<span>2</span>\\n<!-- >3</span --><span>4</span></p>\";\n $washed = $this->cleanupResult($washer->wash($html));", " $this->assertEquals(\"<p>\\n<span>2</span>\\n<span>4</span></p>\", $washed, \"HTML comments (#6464)\");\n }", " /**\n * Test fixing of invalid self-closing elements (#1489137)\n */\n function test_self_closing()\n {\n $html = \"<textarea>test\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertRegExp('|<textarea>test</textarea>|', $washed, \"Self-closing textarea (#1489137)\");\n }", " /**\n * Test fixing of invalid closing tags (#1489446)\n */\n function test_closing_tag_attrs()\n {\n $html = \"<a href=\\\"http://test.com\\\">test</a href>\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertRegExp('|</a>|', $washed, \"Invalid closing tag (#1489446)\");\n }", " /**\n * Test fixing of invalid lists nesting (#1488768)\n */\n function test_lists()\n {\n $data = array(\n array(\n \"<ol><li>First</li><li>Second</li><ul><li>First sub</li></ul><li>Third</li></ol>\",\n \"<ol><li>First</li><li>Second<ul><li>First sub</li></ul></li><li>Third</li></ol>\"\n ),\n array(\n \"<ol><li>First<ul><li>First sub</li></ul></li></ol>\",\n \"<ol><li>First<ul><li>First sub</li></ul></li></ol>\",\n ),\n array(\n \"<ol><li>First<ol><li>First sub</li></ol></li></ol>\",\n \"<ol><li>First<ol><li>First sub</li></ol></li></ol>\",\n ),\n array(\n \"<ul><li>First</li><ul><li>First sub</li><ul><li>sub sub</li></ul></ul><li></li></ul>\",\n \"<ul><li>First<ul><li>First sub<ul><li>sub sub</li></ul></li></ul></li><li></li></ul>\",\n ),\n array(\n \"<ul><li>First</li><li>second</li><ul><ul><li>sub sub</li></ul></ul></ul>\",\n \"<ul><li>First</li><li>second<ul><ul><li>sub sub</li></ul></ul></li></ul>\",\n ),\n array(\n \"<ol><ol><ol></ol></ol></ol>\",\n \"<ol><ol><ol></ol></ol></ol>\",\n ),\n array(\n \"<div><ol><ol><ol></ol></ol></ol></div>\",\n \"<div><ol><ol><ol></ol></ol></ol></div>\",\n ),\n );", " foreach ($data as $element) {\n rcube_washtml::fix_broken_lists($element[0]);", " $this->assertSame($element[1], $element[0], \"Broken nested lists (#1488768)\");\n }\n }", " /**\n * Test color style handling (#1489697)\n */\n function test_color_style()\n {\n $html = \"<p style=\\\"font-size: 10px; color: rgb(241, 245, 218)\\\">a</p>\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertRegExp('|color: rgb\\(241, 245, 218\\)|', $washed, \"Color style (#1489697)\");\n $this->assertRegExp('|font-size: 10px|', $washed, \"Font-size style\");\n }", " /**\n * Test handling of unicode chars in style (#1489777)\n */\n function test_style_unicode()\n {\n $html = \"<html><meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=utf-8\\\" />\n <body><span style='font-family:\\\"新細明體\\\",\\\"serif\\\";color:red'>test</span></body></html>\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertRegExp('|style=\"font-family: \\&quot;新細明體\\&quot;,\\&quot;serif\\&quot;; color: red\"|', $washed, \"Unicode chars in style attribute - quoted (#1489697)\");", " $html = \"<html><meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=utf-8\\\" />\n <body><span style='font-family:新細明體;color:red'>test</span></body></html>\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertRegExp('|style=\"font-family: 新細明體; color: red\"|', $washed, \"Unicode chars in style attribute (#1489697)\");\n }", " /**\n * Test deprecated body attributes (#7109)\n */\n function test_style_body_attrs()\n {\n $html = \"<html><meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=utf-8\\\" />\n <body bgcolor=\\\"#fff\\\" text=\\\"#000\\\" background=\\\"#test\\\" link=\\\"#111\\\" alink=\\\"#222\\\" vlink=\\\"#333\\\">\n </body></html>\";", " $washer = new rcube_washtml(array('html_elements' => array('body')));\n $washed = $washer->wash($html);", " $this->assertRegExp('|bgcolor=\"#fff\"|', $washed, \"Body bgcolor attribute\");\n $this->assertRegExp('|text=\"#000\"|', $washed, \"Body text attribute\");\n $this->assertRegExp('|background=\"#test\"|', $washed, \"Body background attribute\");\n $this->assertRegExp('|link=\"#111\"|', $washed, \"Body link attribute\");\n $this->assertRegExp('|alink=\"#222\"|', $washed, \"Body alink attribute\");\n $this->assertRegExp('|vlink=\"#333\"|', $washed, \"Body vlink attribute\");\n }", " /**\n * Test style item fixes\n */\n function test_style_wash()\n {\n $html = \"<p style=\\\"line-height: 1; height: 10\\\">a</p>\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertRegExp('|line-height: 1;|', $washed, \"Untouched line-height (#1489917)\");\n $this->assertRegExp('|; height: 10px|', $washed, \"Fixed height units\");", " $html = \"<div style=\\\"padding: 0px\\n 20px;border:1px solid #000;\\\"></div>\";\n $expected = \"<div style=\\\"padding: 0px 20px; border: 1px solid #000\\\"></div>\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertTrue(strpos($washed, $expected) !== false, \"White-space and new-line characters handling\");\n }", " /**\n * Test invalid style cleanup - XSS prevention (#1490227)\n */\n function test_style_wash_xss()\n {\n $html = \"<img style=aaa:'\\\"/onerror=alert(1)//'>\";\n $exp = \"<img style=\\\"aaa: '&quot;/onerror=alert(1)//'\\\" />\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertTrue(strpos($washed, $exp) !== false, \"Style quotes XSS issue (#1490227)\");", " $html = \"<img style=aaa:'&quot;/onerror=alert(1)//'>\";\n $exp = \"<img style=\\\"aaa: '&quot;/onerror=alert(1)//'\\\" />\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertTrue(strpos($washed, $exp) !== false, \"Style quotes XSS issue (#1490227)\");\n }", " /**\n * Test SVG cleanup\n */\n function test_wash_svg()\n {\n $svg = '<?xml version=\"1.0\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg version=\"1.1\" baseProfile=\"full\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" viewBox=\"0 0 100 100\">\n <polygon id=\"triangle\" points=\"0,0 0,50 50,0\" fill=\"#009900\" stroke=\"#004400\" onmouseover=\"alert(1)\" />\n <text x=\"50\" y=\"68\" font-size=\"48\" fill=\"#FFF\" text-anchor=\"middle\"><![CDATA[410]]></text>\n <script type=\"text/javascript\">\n alert(document.cookie);\n </script>\n <text x=\"10\" y=\"25\" >An example text</text>\n <a xlink:href=\"http://www.w.pl\"><rect width=\"100%\" height=\"100%\" /></a>\n <foreignObject xlink:href=\"data:text/xml,%3Cscript xmlns=\\'http://www.w3.org/1999/xhtml\\'%3Ealert(1)%3C/script%3E\"/>\n <set attributeName=\"onmouseover\" to=\"alert(1)\"/>\n <animate attributeName=\"onunload\" to=\"alert(1)\"/>\n <animate attributeName=\"xlink:href\" begin=\"0\" from=\"javascript:alert(1)\" />\n</svg>';", " $exp = '<svg xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" baseProfile=\"full\" viewBox=\"0 0 100 100\">\n <polygon id=\"triangle\" points=\"0,0 0,50 50,0\" fill=\"#009900\" stroke=\"#004400\" x-washed=\"onmouseover\" />\n <text x=\"50\" y=\"68\" font-size=\"48\" fill=\"#FFF\" text-anchor=\"middle\">410</text>\n <!-- script not allowed -->\n <text x=\"10\" y=\"25\">An example text</text>\n <a xlink:href=\"http://www.w.pl\"><rect width=\"100%\" height=\"100%\" /></a>\n <!-- foreignObject ignored -->\n <set attributeName=\"onmouseover\" x-washed=\"to\" />\n <animate attributeName=\"onunload\" x-washed=\"to\" />\n <animate attributeName=\"xlink:href\" begin=\"0\" x-washed=\"from\" />\n</svg>';", " $washer = new rcube_washtml;\n $washed = $washer->wash($svg);", " $this->assertSame($washed, $exp, \"SVG content\");\n }", " /**", "", " * Test SVG cleanup", " */\n function test_wash_svg2()\n {\n $svg = '<head xmlns=\"&quot;&gt;&lt;script&gt;alert(document.domain)&lt;/script&gt;\"><svg></svg></head>';\n $exp = '<!-- html ignored --><!-- head ignored --><svg xmlns=\"http://www.w3.org/1999/xhtml\"></svg>';", " $washer = new rcube_washtml;\n $washed = $washer->wash($svg);", " $this->assertSame($washed, $exp, \"SVG content\");", " $svg = '<head xmlns=\"&quot; onload=&quot;alert(document.domain)\">Hello victim!<svg></svg></head>';\n $exp = '<!-- html ignored --><!-- head ignored -->Hello victim!<svg xmlns=\"http://www.w3.org/1999/xhtml\"></svg>';", " $washer = new rcube_washtml;\n $washed = $washer->wash($svg);", " $this->assertSame($washed, $exp, \"SVG content\");", " $svg = '<p>Hello victim!<svg xmlns=\"&quot; onload=&quot;alert(document.domain)\"></svg></p>';\n $exp = '<p>Hello victim!<svg /></p>';", " $washer = new rcube_washtml;\n $washed = $washer->wash($svg);", " $this->assertSame($washed, $exp, \"SVG content\");", " $svg = '<svg xmlns=\"&quot; onload=&quot;alert(document.domain)\" />';\n $exp = '<svg xmlns=\"&quot; onload=&quot;alert(document.domain)\" />';", " $washer = new rcube_washtml;\n $washed = $washer->wash($svg);", " $this->assertSame($washed, $exp, \"SVG content\");", " }", " /**\n * Test position:fixed cleanup - (#5264)\n */\n function test_style_wash_position_fixed()\n {\n $html = \"<img style='position:fixed' /><img style=\\\"position:/**/ fixed; top:10px\\\" />\";\n $exp = \"<img style=\\\"position: absolute\\\" /><img style=\\\"position: absolute; top: 10px\\\" />\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertTrue(strpos($washed, $exp) !== false, \"Position:fixed (#5264)\");\n }", " /**\n * Test MathML cleanup\n */\n function test_wash_mathml()\n {\n $mathml = '<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"></head><body>\n <math><semantics>\n <mrow>\n <msub><mi>I</mi><mi>D</mi></msub>\n <mo>=</mo>\n <mfrac><mn>1</mn><mn>2</mn></mfrac>\n <msub><mi>k</mi><mi>n</mi></msub>\n <mfrac><mi>W</mi><mi>L</mi></mfrac>\n <mo stretchy=\"false\">(</mo>\n <msub><mi>V</mi><mrow><mi>G</mi><mi>S</mi></mrow></msub>\n <mo>-</mo><msub><mi>V</mi><mi>t</mi></msub><msup>\n <mo stretchy=\"false\">)</mo><mn>2</mn></msup>\n </mrow>\n <annotation encoding=\"TeX\">I_D = \\frac{1}{2} k_n \\frac{W}{L} (V_{GS}-V_t)^2</annotation>\n </semantics></math>\n </body></html>';", " $exp = '<!-- html ignored --><!-- head ignored --><!-- meta ignored --><!-- body ignored -->\n <math><semantics>\n <mrow>\n <msub><mi>I</mi><mi>D</mi></msub>\n <mo>=</mo>\n <mfrac><mn>1</mn><mn>2</mn></mfrac>\n <msub><mi>k</mi><mi>n</mi></msub>\n <mfrac><mi>W</mi><mi>L</mi></mfrac>\n <mo stretchy=\"false\">(</mo>\n <msub><mi>V</mi><mrow><mi>G</mi><mi>S</mi></mrow></msub>\n <mo>-</mo><msub><mi>V</mi><mi>t</mi></msub><msup>\n <mo stretchy=\"false\">)</mo><mn>2</mn></msup>\n </mrow>\n <annotation encoding=\"TeX\">I_D = \\frac{1}{2} k_n \\frac{W}{L} (V_{GS}-V_t)^2</annotation>\n </semantics></math>';", " $washer = new rcube_washtml;\n $washed = $washer->wash($mathml);", " // remove whitespace between tags\n $washed = preg_replace('/>[\\s\\r\\n\\t]+</', '><', $washed);\n $exp = preg_replace('/>[\\s\\r\\n\\t]+</', '><', $exp);", " $this->assertSame(trim($washed), trim($exp), \"MathML content\");\n }", " /**\n * Test external links in src of input/video elements (#5583)\n */\n function test_src_wash()\n {\n $html = \"<input type=\\\"image\\\" src=\\\"http://TRACKING_URL/\\\">\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertTrue($washer->extlinks);\n $this->assertNotContains('TRACKING', $washed, \"Src attribute of <input> tag (#5583)\");", " $html = \"<video src=\\\"http://TRACKING_URL/\\\">\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertTrue($washer->extlinks);\n $this->assertNotContains('TRACKING', $washed, \"Src attribute of <video> tag (#5583)\");\n }", " /**\n * Test external links\n */\n function test_extlinks()\n {\n $html = array(\n array(\"<link href=\\\"http://TRACKING_URL/\\\">\", true),\n array(\"<link href=\\\"src:abc\\\">\", false),\n array(\"<img src=\\\"http://TRACKING_URL/\\\">\", true),\n array(\"<img src=\\\"data:image\\\">\", false),\n array('<p style=\"backgr\\\\ound-image: \\\\ur\\\\l(\\'http://TRACKING_URL\\')\"></p>', true),\n );", " foreach ($html as $item) {\n $washer = new rcube_washtml;\n $washed = $washer->wash($item[0]);", " $this->assertSame($item[1], $washer->extlinks);\n }", " foreach ($html as $item) {\n $washer = new rcube_washtml(array('allow_remote' => true));\n $washed = $washer->wash($item[0]);", " $this->assertFalse($washer->extlinks);\n }\n }", " function test_textarea_content_escaping()\n {\n $html = '<textarea><p style=\"x:</textarea><img src=x onerror=alert(1)>\">';", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertNotContains('onerror=alert(1)>', $washed);\n $this->assertContains('&lt;p style=&quot;x:', $washed);\n }", " /**\n * Test css_prefix feature\n */\n function test_css_prefix()\n {\n $washer = new rcube_washtml(array('css_prefix' => 'test'));", " $html = '<p id=\"my-id\">'\n . '<label for=\"my-other-id\" class=\"my-class1 my-class2\">test</label>'\n . '<a href=\"#my-id\">link</a>'\n . '</p>';\n $washed = $washer->wash($html);", " $this->assertContains('id=\"testmy-id\"', $washed);\n $this->assertContains('for=\"testmy-other-id\"', $washed);\n $this->assertContains('href=\"#testmy-id\"', $washed);\n $this->assertContains('class=\"testmy-class1 testmy-class2\"', $washed);\n }", " /**\n * Test removing xml:namespace tag\n */\n function test_xml_namespace()\n {\n $html = '<p><?xml:namespace prefix = \"xsl\" /></p>';", " $washer = new rcube_washtml;\n $washed = $this->cleanupResult($washer->wash($html));", " $this->assertNotContains('&lt;?xml:namespace\"', $washed);\n $this->assertSame($washed, '<p></p>');\n }", " /**\n * Test missing main HTML hierarchy tags (#6713)\n */\n function test_missing_tags()\n {\n $washer = new rcube_washtml();", " $html = '<head></head>First line<br />Second line';\n $washed = $washer->wash($html);", " $this->assertContains('First line', $washed);", " $html = 'First line<br />Second line';\n $washed = $washer->wash($html);", " $this->assertContains('First line', $washed);", " $html = '<html>First line<br />Second line</html>';\n $washed = $washer->wash($html);", " $this->assertContains('>First line', $washed);", " $html = '<html><head></head>First line<br />Second line</html>';\n $washed = $washer->wash($html);", " $this->assertContains('First line', $washed);", " // Not really valid HTML, but because its common in email world\n // and because it works with DOMDocument, we make sure its supported\n $html = 'First line<br /><html><body>Second line';\n $washed = $washer->wash($html);", " $this->assertContains('First line', $washed);", " $html = 'First line<br /><html>Second line';\n $washed = $washer->wash($html);", " $this->assertContains('First line', $washed);\n }", " /**\n * Test CDATA cleanup\n */\n function test_cdata()\n {\n $html = '<p><![CDATA[<script>alert(document.cookie)</script>]]></p>';", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertTrue(strpos($washed, '<script>') === false, \"CDATA content\");\n }\n}" ]
[ 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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 ]
PreciseBugs
{"buggy_code_end_loc": [15, 533, 355], "buggy_code_start_loc": [15, 415, 319], "filenames": ["CHANGELOG", "program/lib/Roundcube/rcube_washtml.php", "tests/Framework/Washtml.php"], "fixing_code_end_loc": [18, 590, 480], "fixing_code_start_loc": [16, 415, 320], "message": "Roundcube Webmail before 1.3.15 and 1.4.8 allows stored XSS in HTML messages during message display via a crafted SVG document. This issue has been fixed in 1.4.8 and 1.3.15.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:roundcube:webmail:*:*:*:*:*:*:*:*", "matchCriteriaId": "6AA0D87C-F59C-4A8D-8527-8171BEB076E0", "versionEndExcluding": "1.3.15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:roundcube:webmail:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F4ECE92-6974-4D4F-9900-5F0C548B912A", "versionEndExcluding": "1.4.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.4.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:32:*:*:*:*:*:*:*", "matchCriteriaId": "36D96259-24BD-44E2-96D9-78CE1D41F956", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Roundcube Webmail before 1.3.15 and 1.4.8 allows stored XSS in HTML messages during message display via a crafted SVG document. This issue has been fixed in 1.4.8 and 1.3.15."}, {"lang": "es", "value": "Roundcube Webmail versiones anteriores a 1.3.15 y 1.4.8, permite un ataque de tipo XSS almacenado en mensajes HTML durante la visualizaci\u00f3n de mensajes por medio de un documento SVG dise\u00f1ado. Este problema se ha solucionado en la versi\u00f3n 1.4.8 y versi\u00f3n 1.3.15."}], "evaluatorComment": null, "id": "CVE-2020-16145", "lastModified": "2023-01-20T21:00:58.090", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-08-12T13:15:10.457", "references": [{"source": "cve@mitre.org", "tags": ["Broken Link"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-09/msg00083.html"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/commit/a71bf2e8d4a64ff2c83fdabc1e8cb0c045a41ef4"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/commit/d44ca2308a96576b88d6bf27528964d4fe1a6b8b#diff-d3bb3391c79904494c60ee2ac2f33070"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/releases/tag/1.3.15"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/releases/tag/1.4.8"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/3DAXK3565NYK4OEZVTW6S5LEVIDQEY2E/"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/OBLUQRIBAMEQVBO6GUZECCHJDJIWCYFU/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/roundcube/roundcubemail/commit/a71bf2e8d4a64ff2c83fdabc1e8cb0c045a41ef4"}, "type": "CWE-79"}
184
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Test class to test rcube_washtml class\n *\n * @package Tests\n */\nclass Framework_Washtml extends PHPUnit_Framework_TestCase\n{\n /**\n * A helper method to remove comments added by rcube_washtml\n */\n function cleanupResult($html)\n {\n return preg_replace('/<!-- [a-z]+ (ignored|not allowed) -->/', '', $html);\n }", "\n /**\n * Test the elimination of some XSS vulnerabilities\n */\n function test_html_xss()\n {\n // #1488850\n $html = '<a href=\"data:text/html,&lt;script&gt;alert(document.cookie)&lt;/script&gt;\">Firefox</a>'\n .'<a href=\"vbscript:alert(document.cookie)\">Internet Explorer</a></p>'\n .'<A href=\"data:text/html,&lt;script&gt;alert(document.cookie)&lt;/script&gt;\">Firefox</a>'\n .'<A HREF=\"vbscript:alert(document.cookie)\">Internet Explorer</a>'\n .'<a href=\"data:application/xhtml+xml;base64,PGh0bW\">CLICK ME</a>'; // #6896", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertNotRegExp('/data:text/', $washed, \"Remove data:text/html links\");\n $this->assertNotRegExp('/vbscript:/', $washed, \"Remove vbscript: links\");\n $this->assertNotRegExp('/data:application/', $washed, \"Remove data:application links\");\n }", " /**\n * Test fixing of invalid href\n */\n function test_href()\n {\n $html = \"<p><a href=\\\"\\nhttp://test.com\\n\\\">Firefox</a><a href=\\\"domain.com\\\">Firefox</a>\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertRegExp('|href=\"http://test\\.com\"|', $washed, \"Link href with newlines (#1488940)\");\n $this->assertRegExp('|href=\"http://domain\\.com\"|', $washed, \"Link href with no protocol (#7454)\");\n }", " /**\n * Test XSS in area's href (#5240)\n */\n function test_href_area()\n {\n $html = '<p><area href=\"data:text/html,&lt;script&gt;alert(document.cookie)&lt;/script&gt;\">'\n . '<area href=\"vbscript:alert(document.cookie)\">Internet Explorer</p>'\n . '<area href=\"javascript:alert(document.domain)\" shape=default>'\n . '<p><AREA HREF=\"data:text/html,&lt;script&gt;alert(document.cookie)&lt;/script&gt;\">'\n . '<Area href=\"vbscript:alert(document.cookie)\">Internet Explorer</p>'\n . '<area HREF=\"javascript:alert(document.domain)\" shape=default>';", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertNotRegExp('/data:text/', $washed, \"data:text/html in area href\");\n $this->assertNotRegExp('/vbscript:/', $washed, \"vbscript: in area href\");\n $this->assertNotRegExp('/javascript:/', $washed, \"javascript: in area href\");\n }", " /**\n * Test handling HTML comments\n */\n function test_comments()\n {\n $washer = new rcube_washtml;", " $html = \"<!--[if gte mso 10]><p>p1</p><!--><p>p2</p>\";\n $washed = $this->cleanupResult($washer->wash($html));", " $this->assertEquals('<p>p2</p>', $washed, \"HTML conditional comments (#1489004)\");", " $html = \"<!--TestCommentInvalid><p>test</p>\";\n $washed = $this->cleanupResult($washer->wash($html));", " $this->assertEquals('<p>test</p>', $washed, \"HTML invalid comments (#1487759)\");", " $html = \"<p>para1</p><!-- comment --><p>para2</p>\";\n $washed = $this->cleanupResult($washer->wash($html));", " $this->assertEquals('<p>para1</p><p>para2</p>', $washed, \"HTML comments - simple comment\");", " $html = \"<p>para1</p><!-- <hr> comment --><p>para2</p>\";\n $washed = $this->cleanupResult($washer->wash($html));", " $this->assertEquals('<p>para1</p><p>para2</p>', $washed, \"HTML comments - tags inside (#1489904)\");", " $html = \"<p>para1</p><!-- comment => comment --><p>para2</p>\";\n $washed = $this->cleanupResult($washer->wash($html));", " $this->assertEquals('<p>para1</p><p>para2</p>', $washed, \"HTML comments - bracket inside\");", " $html = \"<p><!-- span>1</span -->\\n<span>2</span>\\n<!-- >3</span --><span>4</span></p>\";\n $washed = $this->cleanupResult($washer->wash($html));", " $this->assertEquals(\"<p>\\n<span>2</span>\\n<span>4</span></p>\", $washed, \"HTML comments (#6464)\");\n }", " /**\n * Test fixing of invalid self-closing elements (#1489137)\n */\n function test_self_closing()\n {\n $html = \"<textarea>test\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertRegExp('|<textarea>test</textarea>|', $washed, \"Self-closing textarea (#1489137)\");\n }", " /**\n * Test fixing of invalid closing tags (#1489446)\n */\n function test_closing_tag_attrs()\n {\n $html = \"<a href=\\\"http://test.com\\\">test</a href>\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertRegExp('|</a>|', $washed, \"Invalid closing tag (#1489446)\");\n }", " /**\n * Test fixing of invalid lists nesting (#1488768)\n */\n function test_lists()\n {\n $data = array(\n array(\n \"<ol><li>First</li><li>Second</li><ul><li>First sub</li></ul><li>Third</li></ol>\",\n \"<ol><li>First</li><li>Second<ul><li>First sub</li></ul></li><li>Third</li></ol>\"\n ),\n array(\n \"<ol><li>First<ul><li>First sub</li></ul></li></ol>\",\n \"<ol><li>First<ul><li>First sub</li></ul></li></ol>\",\n ),\n array(\n \"<ol><li>First<ol><li>First sub</li></ol></li></ol>\",\n \"<ol><li>First<ol><li>First sub</li></ol></li></ol>\",\n ),\n array(\n \"<ul><li>First</li><ul><li>First sub</li><ul><li>sub sub</li></ul></ul><li></li></ul>\",\n \"<ul><li>First<ul><li>First sub<ul><li>sub sub</li></ul></li></ul></li><li></li></ul>\",\n ),\n array(\n \"<ul><li>First</li><li>second</li><ul><ul><li>sub sub</li></ul></ul></ul>\",\n \"<ul><li>First</li><li>second<ul><ul><li>sub sub</li></ul></ul></li></ul>\",\n ),\n array(\n \"<ol><ol><ol></ol></ol></ol>\",\n \"<ol><ol><ol></ol></ol></ol>\",\n ),\n array(\n \"<div><ol><ol><ol></ol></ol></ol></div>\",\n \"<div><ol><ol><ol></ol></ol></ol></div>\",\n ),\n );", " foreach ($data as $element) {\n rcube_washtml::fix_broken_lists($element[0]);", " $this->assertSame($element[1], $element[0], \"Broken nested lists (#1488768)\");\n }\n }", " /**\n * Test color style handling (#1489697)\n */\n function test_color_style()\n {\n $html = \"<p style=\\\"font-size: 10px; color: rgb(241, 245, 218)\\\">a</p>\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertRegExp('|color: rgb\\(241, 245, 218\\)|', $washed, \"Color style (#1489697)\");\n $this->assertRegExp('|font-size: 10px|', $washed, \"Font-size style\");\n }", " /**\n * Test handling of unicode chars in style (#1489777)\n */\n function test_style_unicode()\n {\n $html = \"<html><meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=utf-8\\\" />\n <body><span style='font-family:\\\"新細明體\\\",\\\"serif\\\";color:red'>test</span></body></html>\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertRegExp('|style=\"font-family: \\&quot;新細明體\\&quot;,\\&quot;serif\\&quot;; color: red\"|', $washed, \"Unicode chars in style attribute - quoted (#1489697)\");", " $html = \"<html><meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=utf-8\\\" />\n <body><span style='font-family:新細明體;color:red'>test</span></body></html>\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertRegExp('|style=\"font-family: 新細明體; color: red\"|', $washed, \"Unicode chars in style attribute (#1489697)\");\n }", " /**\n * Test deprecated body attributes (#7109)\n */\n function test_style_body_attrs()\n {\n $html = \"<html><meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=utf-8\\\" />\n <body bgcolor=\\\"#fff\\\" text=\\\"#000\\\" background=\\\"#test\\\" link=\\\"#111\\\" alink=\\\"#222\\\" vlink=\\\"#333\\\">\n </body></html>\";", " $washer = new rcube_washtml(array('html_elements' => array('body')));\n $washed = $washer->wash($html);", " $this->assertRegExp('|bgcolor=\"#fff\"|', $washed, \"Body bgcolor attribute\");\n $this->assertRegExp('|text=\"#000\"|', $washed, \"Body text attribute\");\n $this->assertRegExp('|background=\"#test\"|', $washed, \"Body background attribute\");\n $this->assertRegExp('|link=\"#111\"|', $washed, \"Body link attribute\");\n $this->assertRegExp('|alink=\"#222\"|', $washed, \"Body alink attribute\");\n $this->assertRegExp('|vlink=\"#333\"|', $washed, \"Body vlink attribute\");\n }", " /**\n * Test style item fixes\n */\n function test_style_wash()\n {\n $html = \"<p style=\\\"line-height: 1; height: 10\\\">a</p>\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertRegExp('|line-height: 1;|', $washed, \"Untouched line-height (#1489917)\");\n $this->assertRegExp('|; height: 10px|', $washed, \"Fixed height units\");", " $html = \"<div style=\\\"padding: 0px\\n 20px;border:1px solid #000;\\\"></div>\";\n $expected = \"<div style=\\\"padding: 0px 20px; border: 1px solid #000\\\"></div>\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertTrue(strpos($washed, $expected) !== false, \"White-space and new-line characters handling\");\n }", " /**\n * Test invalid style cleanup - XSS prevention (#1490227)\n */\n function test_style_wash_xss()\n {\n $html = \"<img style=aaa:'\\\"/onerror=alert(1)//'>\";\n $exp = \"<img style=\\\"aaa: '&quot;/onerror=alert(1)//'\\\" />\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertTrue(strpos($washed, $exp) !== false, \"Style quotes XSS issue (#1490227)\");", " $html = \"<img style=aaa:'&quot;/onerror=alert(1)//'>\";\n $exp = \"<img style=\\\"aaa: '&quot;/onerror=alert(1)//'\\\" />\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertTrue(strpos($washed, $exp) !== false, \"Style quotes XSS issue (#1490227)\");\n }", " /**\n * Test SVG cleanup\n */\n function test_wash_svg()\n {\n $svg = '<?xml version=\"1.0\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg version=\"1.1\" baseProfile=\"full\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" viewBox=\"0 0 100 100\">\n <polygon id=\"triangle\" points=\"0,0 0,50 50,0\" fill=\"#009900\" stroke=\"#004400\" onmouseover=\"alert(1)\" />\n <text x=\"50\" y=\"68\" font-size=\"48\" fill=\"#FFF\" text-anchor=\"middle\"><![CDATA[410]]></text>\n <script type=\"text/javascript\">\n alert(document.cookie);\n </script>\n <text x=\"10\" y=\"25\" >An example text</text>\n <a xlink:href=\"http://www.w.pl\"><rect width=\"100%\" height=\"100%\" /></a>\n <foreignObject xlink:href=\"data:text/xml,%3Cscript xmlns=\\'http://www.w3.org/1999/xhtml\\'%3Ealert(1)%3C/script%3E\"/>\n <set attributeName=\"onmouseover\" to=\"alert(1)\"/>\n <animate attributeName=\"onunload\" to=\"alert(1)\"/>\n <animate attributeName=\"xlink:href\" begin=\"0\" from=\"javascript:alert(1)\" />\n</svg>';", " $exp = '<svg xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" baseProfile=\"full\" viewBox=\"0 0 100 100\">\n <polygon id=\"triangle\" points=\"0,0 0,50 50,0\" fill=\"#009900\" stroke=\"#004400\" x-washed=\"onmouseover\" />\n <text x=\"50\" y=\"68\" font-size=\"48\" fill=\"#FFF\" text-anchor=\"middle\">410</text>\n <!-- script not allowed -->\n <text x=\"10\" y=\"25\">An example text</text>\n <a xlink:href=\"http://www.w.pl\"><rect width=\"100%\" height=\"100%\" /></a>\n <!-- foreignObject ignored -->\n <set attributeName=\"onmouseover\" x-washed=\"to\" />\n <animate attributeName=\"onunload\" x-washed=\"to\" />\n <animate attributeName=\"xlink:href\" begin=\"0\" x-washed=\"from\" />\n</svg>';", " $washer = new rcube_washtml;\n $washed = $washer->wash($svg);", " $this->assertSame($washed, $exp, \"SVG content\");\n }", " /**", " * Test cases for SVG tests\n */\n function data_wash_svg_tests()\n {\n $svg1 = \"<svg id='x' width='100' height='100'><a xlink:href='javascript:alert(1)'><rect x='0' y='0' width='100' height='100' /></a></svg>\";", " return [\n [\n '<head xmlns=\"&quot;&gt;&lt;script&gt;alert(document.domain)&lt;/script&gt;\"><svg></svg></head>',\n '<!-- html ignored --><!-- head ignored --><svg xmlns=\"http://www.w3.org/1999/xhtml\"></svg>'\n ],\n [\n '<head xmlns=\"&quot; onload=&quot;alert(document.domain)\">Hello victim!<svg></svg></head>',\n '<!-- html ignored --><!-- head ignored -->Hello victim!<svg xmlns=\"http://www.w3.org/1999/xhtml\"></svg>'\n ],\n [\n '<p>Hello victim!<svg xmlns=\"&quot; onload=&quot;alert(document.domain)\"></svg></p>',\n '<p>Hello victim!<svg /></p>'\n ],\n [\n '<html><p>Hello victim!<svg xmlns=\"&quot; onload=&quot;alert(document.domain)\"></svg></p>',\n '<!-- html ignored --><!-- body ignored --><p>Hello victim!<svg xmlns=\"http://www.w3.org/1999/xhtml\"></svg></p>'\n ],\n [\n '<svg xmlns=\"&quot; onload=&quot;alert(document.domain)\" />',\n '<svg xmlns=\"&quot; onload=&quot;alert(document.domain)\" />'\n ],\n [\n '<html><svg xmlns=\"&quot; onload=&quot;alert(document.domain)\" />',\n '<!-- html ignored --><!-- body ignored --><svg xmlns=\"http://www.w3.org/1999/xhtml\"></svg>'\n ],\n [\n '<svg><a xlink:href=\"javascript:alert(1)\"><text x=\"20\" y=\"20\">XSS</text></a></svg>',\n '<svg><a x-washed=\"xlink:href\"><text x=\"20\" y=\"20\">XSS</text></a></svg>'\n ],\n [\n '<html><svg><a xlink:href=\"javascript:alert(1)\"><text x=\"20\" y=\"20\">XSS</text></a></svg>',\n '<!-- html ignored --><!-- body ignored --><svg xmlns=\"http://www.w3.org/1999/xhtml\"><a x-washed=\"xlink:href\"><text x=\"20\" y=\"20\">XSS</text></a></svg>'\n ],\n [\n '<svg><animate xlink:href=\"#xss\" attributeName=\"href\" values=\"javascript:alert(1)\" />'\n . '<a id=\"xss\"><text x=\"20\" y=\"20\">XSS</text></a></svg>',\n '<svg><!-- animate blocked --><a id=\"xss\"><text x=\"20\" y=\"20\">XSS</text></a></svg>',\n ],\n [\n '<html><svg><animate xlink:href=\"#xss\" attributeName=\"href\" values=\"javascript:alert(1)\" />'\n . '<a id=\"xss\"><text x=\"20\" y=\"20\">XSS</text></a></svg>',\n '<!-- html ignored --><!-- body ignored --><svg xmlns=\"http://www.w3.org/1999/xhtml\">'\n . '<!-- animate blocked --><a id=\"xss\"><text x=\"20\" y=\"20\">XSS</text></a></svg>',\n ],\n [\n '<svg><animate xlink:href=\"#xss\" attributeName=\"href\" from=\"javascript:alert(1)\" to=\"1\" />'\n . '<a id=\"xss\"><text x=\"20\" y=\"20\">XSS</text></a></svg>',\n '<svg><!-- animate blocked --><a id=\"xss\"><text x=\"20\" y=\"20\">XSS</text></a></svg>',\n ],\n [\n '<svg><set xlink:href=\"#xss\" attributeName=\"href\" from=\"?\" to=\"javascript:alert(1)\" />'\n . '<a id=\"xss\"><text x=\"20\" y=\"20\">XSS</text></a></svg>',\n '<svg><!-- set blocked --><a id=\"xss\"><text x=\"20\" y=\"20\">XSS</text></a></svg>',\n ],\n [\n '<svg><animate xlink:href=\"#xss\" attributename=\"href\" dur=\"5s\" repeatCount=\"indefinite\" keytimes=\"0;0;1\" values=\"https://portswigger.net?;javascript:alert(1);0\" />'\n . '<a id=\"xss\"><text x=\"20\" y=\"20\">XSS</text></a></svg>',\n '<svg><!-- animate blocked --><a id=\"xss\"><text x=\"20\" y=\"20\">XSS</text></a></svg>',\n ],\n [\n \"<svg><use href=\\\"data:image/svg+xml,&lt;svg id='x' xmlns='http://www.w3.org/2000/svg' \"\n . \"xmlns:xlink='http://www.w3.org/1999/xlink' width='100' height='100'&gt;&lt;a xlink:href='javascript:alert(1)'&gt;\"\n . \"&lt;rect x='0' y='0' width='100' height='100' /&gt;&lt;/a&gt;&lt;/svg&gt;\\\"></use></svg>\",\n \"<svg><use href=\\\"data:image/svg+xml;base64,PHN2ZyB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53\"\n . \"My5vcmcvMTk5OS94bGluayIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiBpZD0ie\"\n . \"CIgd2lkdGg9IjEwMCIgaGVpZ2h0PSIxMDAiPjxhIHgtd2FzaGVkPSJ4bGluazpocmVmIj48cmVjdC\"\n . \"B4PSIwIiB5PSIwIiB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgLz48L2E+PC9zdmc+\\\" /></svg>\"\n ],\n [\n \"<svg><use href=\\\"data:image/svg+xml;base64,\" . base64_encode($svg1) . \"\\\"></use></svg>\",\n \"<svg><use href=\\\"data:image/svg+xml;base64,PHN2ZyBpZD0ieCIgd2lkdGg9IjEwMCIgaGVpZ2h\"\n . \"0PSIxMDAiPjxhIHgtd2FzaGVkPSJ4bGluazpocmVmIj48cmVjdCB4PSIwIiB5PSIwIiB3aWR0aD0\"\n . \"iMTAwIiBoZWlnaHQ9IjEwMCIgLz48L2E+PC9zdmc+\\\" /></svg>\"\n ],\n [\n '<svg><script href=\"data:text/javascript,alert(1)\" /><text x=\"20\" y=\"20\">XSS</text></svg>',\n '<svg><!-- script not allowed --><text x=\"20\" y=\"20\">XSS</text></svg>'\n ],\n ];\n }", " /**", " * Test SVG cleanup", " *\n * @dataProvider data_wash_svg_tests\n */\n function test_wash_svg_tests($input, $expected)\n {\n $washer = new rcube_washtml;\n $washed = $washer->wash($input);", " $this->assertSame($expected, $washed, \"SVG content\");\n }", " /**\n * Test cases for various XSS issues\n */\n function data_wash_xss_tests()\n {\n return [\n [\n '<html><base href=\"javascript:/a/-alert(1)///////\"><a href=\"../lol/safari.html\">test</a>',\n '<!-- html ignored --><body><!-- base ignored --><a x-washed=\"href\">test</a></body>'\n ],\n [\n '<html><math><x href=\"javascript:alert(1)\">blah</x>',\n '<!-- html ignored --><body><math><!-- x ignored -->blah</math></body>'\n ],\n [\n '<html><a href=\"j&#x61vascript:alert(1)\">XSS</a>',\n '<!-- html ignored --><body><a x-washed=\"href\">XSS</a></body>'\n ],\n [\n '<html><a href=\"&#x6a avascript:alert(1)\">XSS</a>',\n '<!-- html ignored --><body><a x-washed=\"href\">XSS</a></body>'\n ],\n [\n '<html><a href=\"&#x6a avascript:alert(1)\">XSS</a>',\n '<!-- html ignored --><body><a x-washed=\"href\">XSS</a></body>'\n ],\n [\n '<html><body background=\"javascript:alert(1)\">',\n '<!-- html ignored --><body x-washed=\"background\"></body>'\n ],\n [\n '<html><math href=\"javascript:alert(location);\"><mi>clickme</mi></math>',\n '<!-- html ignored --><body><math x-washed=\"href\"><mi>clickme</mi></math></body>',\n ],\n [\n '<html><math><mstyle href=\"javascript:alert(location);\"><mi>clickme</mi></mstyle></math>',\n '<!-- html ignored --><body><math><mstyle x-washed=\"href\"><mi>clickme</mi></mstyle></math></body>',\n ],\n [\n '<html><math><msubsup href=\"javascript:alert(location);\"><mi>clickme</mi></msubsup></math>',\n '<!-- html ignored --><body><math><msubsup x-washed=\"href\"><mi>clickme</mi></msubsup></math></body>',\n ],\n [\n '<html><math><ms HREF=\"javascript:alert(location);\">clickme</ms></math>',\n '<!-- html ignored --><body><math><ms x-washed=\"href\">clickme</ms></math></body>',\n ],\n ];\n }", " /**\n * Test various XSS issues\n *\n * @dataProvider data_wash_xss_tests\n */\n function test_wash_xss_tests($input, $expected)\n {\n $washer = new rcube_washtml(['allow_remote' => true, 'html_elements' => ['body']]);\n $washed = $washer->wash($input);", " $this->assertSame($expected, $washed, \"XSS issues\");", " }", " /**\n * Test position:fixed cleanup - (#5264)\n */\n function test_style_wash_position_fixed()\n {\n $html = \"<img style='position:fixed' /><img style=\\\"position:/**/ fixed; top:10px\\\" />\";\n $exp = \"<img style=\\\"position: absolute\\\" /><img style=\\\"position: absolute; top: 10px\\\" />\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertTrue(strpos($washed, $exp) !== false, \"Position:fixed (#5264)\");\n }", " /**\n * Test MathML cleanup\n */\n function test_wash_mathml()\n {\n $mathml = '<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"></head><body>\n <math><semantics>\n <mrow>\n <msub><mi>I</mi><mi>D</mi></msub>\n <mo>=</mo>\n <mfrac><mn>1</mn><mn>2</mn></mfrac>\n <msub><mi>k</mi><mi>n</mi></msub>\n <mfrac><mi>W</mi><mi>L</mi></mfrac>\n <mo stretchy=\"false\">(</mo>\n <msub><mi>V</mi><mrow><mi>G</mi><mi>S</mi></mrow></msub>\n <mo>-</mo><msub><mi>V</mi><mi>t</mi></msub><msup>\n <mo stretchy=\"false\">)</mo><mn>2</mn></msup>\n </mrow>\n <annotation encoding=\"TeX\">I_D = \\frac{1}{2} k_n \\frac{W}{L} (V_{GS}-V_t)^2</annotation>\n </semantics></math>\n </body></html>';", " $exp = '<!-- html ignored --><!-- head ignored --><!-- meta ignored --><!-- body ignored -->\n <math><semantics>\n <mrow>\n <msub><mi>I</mi><mi>D</mi></msub>\n <mo>=</mo>\n <mfrac><mn>1</mn><mn>2</mn></mfrac>\n <msub><mi>k</mi><mi>n</mi></msub>\n <mfrac><mi>W</mi><mi>L</mi></mfrac>\n <mo stretchy=\"false\">(</mo>\n <msub><mi>V</mi><mrow><mi>G</mi><mi>S</mi></mrow></msub>\n <mo>-</mo><msub><mi>V</mi><mi>t</mi></msub><msup>\n <mo stretchy=\"false\">)</mo><mn>2</mn></msup>\n </mrow>\n <annotation encoding=\"TeX\">I_D = \\frac{1}{2} k_n \\frac{W}{L} (V_{GS}-V_t)^2</annotation>\n </semantics></math>';", " $washer = new rcube_washtml;\n $washed = $washer->wash($mathml);", " // remove whitespace between tags\n $washed = preg_replace('/>[\\s\\r\\n\\t]+</', '><', $washed);\n $exp = preg_replace('/>[\\s\\r\\n\\t]+</', '><', $exp);", " $this->assertSame(trim($washed), trim($exp), \"MathML content\");\n }", " /**\n * Test external links in src of input/video elements (#5583)\n */\n function test_src_wash()\n {\n $html = \"<input type=\\\"image\\\" src=\\\"http://TRACKING_URL/\\\">\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertTrue($washer->extlinks);\n $this->assertNotContains('TRACKING', $washed, \"Src attribute of <input> tag (#5583)\");", " $html = \"<video src=\\\"http://TRACKING_URL/\\\">\";", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertTrue($washer->extlinks);\n $this->assertNotContains('TRACKING', $washed, \"Src attribute of <video> tag (#5583)\");\n }", " /**\n * Test external links\n */\n function test_extlinks()\n {\n $html = array(\n array(\"<link href=\\\"http://TRACKING_URL/\\\">\", true),\n array(\"<link href=\\\"src:abc\\\">\", false),\n array(\"<img src=\\\"http://TRACKING_URL/\\\">\", true),\n array(\"<img src=\\\"data:image\\\">\", false),\n array('<p style=\"backgr\\\\ound-image: \\\\ur\\\\l(\\'http://TRACKING_URL\\')\"></p>', true),\n );", " foreach ($html as $item) {\n $washer = new rcube_washtml;\n $washed = $washer->wash($item[0]);", " $this->assertSame($item[1], $washer->extlinks);\n }", " foreach ($html as $item) {\n $washer = new rcube_washtml(array('allow_remote' => true));\n $washed = $washer->wash($item[0]);", " $this->assertFalse($washer->extlinks);\n }\n }", " function test_textarea_content_escaping()\n {\n $html = '<textarea><p style=\"x:</textarea><img src=x onerror=alert(1)>\">';", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertNotContains('onerror=alert(1)>', $washed);\n $this->assertContains('&lt;p style=&quot;x:', $washed);\n }", " /**\n * Test css_prefix feature\n */\n function test_css_prefix()\n {\n $washer = new rcube_washtml(array('css_prefix' => 'test'));", " $html = '<p id=\"my-id\">'\n . '<label for=\"my-other-id\" class=\"my-class1 my-class2\">test</label>'\n . '<a href=\"#my-id\">link</a>'\n . '</p>';\n $washed = $washer->wash($html);", " $this->assertContains('id=\"testmy-id\"', $washed);\n $this->assertContains('for=\"testmy-other-id\"', $washed);\n $this->assertContains('href=\"#testmy-id\"', $washed);\n $this->assertContains('class=\"testmy-class1 testmy-class2\"', $washed);\n }", " /**\n * Test removing xml:namespace tag\n */\n function test_xml_namespace()\n {\n $html = '<p><?xml:namespace prefix = \"xsl\" /></p>';", " $washer = new rcube_washtml;\n $washed = $this->cleanupResult($washer->wash($html));", " $this->assertNotContains('&lt;?xml:namespace\"', $washed);\n $this->assertSame($washed, '<p></p>');\n }", " /**\n * Test missing main HTML hierarchy tags (#6713)\n */\n function test_missing_tags()\n {\n $washer = new rcube_washtml();", " $html = '<head></head>First line<br />Second line';\n $washed = $washer->wash($html);", " $this->assertContains('First line', $washed);", " $html = 'First line<br />Second line';\n $washed = $washer->wash($html);", " $this->assertContains('First line', $washed);", " $html = '<html>First line<br />Second line</html>';\n $washed = $washer->wash($html);", " $this->assertContains('>First line', $washed);", " $html = '<html><head></head>First line<br />Second line</html>';\n $washed = $washer->wash($html);", " $this->assertContains('First line', $washed);", " // Not really valid HTML, but because its common in email world\n // and because it works with DOMDocument, we make sure its supported\n $html = 'First line<br /><html><body>Second line';\n $washed = $washer->wash($html);", " $this->assertContains('First line', $washed);", " $html = 'First line<br /><html>Second line';\n $washed = $washer->wash($html);", " $this->assertContains('First line', $washed);\n }", " /**\n * Test CDATA cleanup\n */\n function test_cdata()\n {\n $html = '<p><![CDATA[<script>alert(document.cookie)</script>]]></p>';", " $washer = new rcube_washtml;\n $washed = $washer->wash($html);", " $this->assertTrue(strpos($washed, '<script>') === false, \"CDATA content\");\n }\n}" ]
[ 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [15, 533, 355], "buggy_code_start_loc": [15, 415, 319], "filenames": ["CHANGELOG", "program/lib/Roundcube/rcube_washtml.php", "tests/Framework/Washtml.php"], "fixing_code_end_loc": [18, 590, 480], "fixing_code_start_loc": [16, 415, 320], "message": "Roundcube Webmail before 1.3.15 and 1.4.8 allows stored XSS in HTML messages during message display via a crafted SVG document. This issue has been fixed in 1.4.8 and 1.3.15.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:roundcube:webmail:*:*:*:*:*:*:*:*", "matchCriteriaId": "6AA0D87C-F59C-4A8D-8527-8171BEB076E0", "versionEndExcluding": "1.3.15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:roundcube:webmail:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F4ECE92-6974-4D4F-9900-5F0C548B912A", "versionEndExcluding": "1.4.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.4.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:32:*:*:*:*:*:*:*", "matchCriteriaId": "36D96259-24BD-44E2-96D9-78CE1D41F956", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Roundcube Webmail before 1.3.15 and 1.4.8 allows stored XSS in HTML messages during message display via a crafted SVG document. This issue has been fixed in 1.4.8 and 1.3.15."}, {"lang": "es", "value": "Roundcube Webmail versiones anteriores a 1.3.15 y 1.4.8, permite un ataque de tipo XSS almacenado en mensajes HTML durante la visualizaci\u00f3n de mensajes por medio de un documento SVG dise\u00f1ado. Este problema se ha solucionado en la versi\u00f3n 1.4.8 y versi\u00f3n 1.3.15."}], "evaluatorComment": null, "id": "CVE-2020-16145", "lastModified": "2023-01-20T21:00:58.090", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-08-12T13:15:10.457", "references": [{"source": "cve@mitre.org", "tags": ["Broken Link"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-09/msg00083.html"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/commit/a71bf2e8d4a64ff2c83fdabc1e8cb0c045a41ef4"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/commit/d44ca2308a96576b88d6bf27528964d4fe1a6b8b#diff-d3bb3391c79904494c60ee2ac2f33070"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/releases/tag/1.3.15"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/roundcube/roundcubemail/releases/tag/1.4.8"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/3DAXK3565NYK4OEZVTW6S5LEVIDQEY2E/"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/OBLUQRIBAMEQVBO6GUZECCHJDJIWCYFU/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/roundcube/roundcubemail/commit/a71bf2e8d4a64ff2c83fdabc1e8cb0c045a41ef4"}, "type": "CWE-79"}
184
Determine whether the {function_name} code is vulnerable or not.
[ "@push('css')\n<link rel=\"stylesheet\" href=\"{{ url(mix('css/dist/bootstrap-table.css')) }}\">", "@endpush", "@push('js')\n<script src=\"{{ url(mix('js/dist/bootstrap-table.js')) }}\"></script>\n<script nonce=\"{{ csrf_token() }}\">", " $(function () {", "\n var stickyHeaderOffsetY = 0;", " if ( $('.navbar-fixed-top').css('height') ) {\n stickyHeaderOffsetY = +$('.navbar-fixed-top').css('height').replace('px','');\n }\n if ( $('.navbar-fixed-top').css('margin-bottom') ) {\n stickyHeaderOffsetY += +$('.navbar-fixed-top').css('margin-bottom').replace('px','');\n }", " var blockedFields = \"searchable,sortable,switchable,title,visible,formatter,class\".split(\",\");", " var keyBlocked = function(key) {\n for(var j in blockedFields) {\n if (key === blockedFields[j]) {\n return true;\n }\n }\n return false;\n }", " $('.snipe-table').bootstrapTable('destroy').bootstrapTable({\n classes: 'table table-responsive table-no-bordered',\n ajaxOptions: {\n headers: {\n 'X-CSRF-TOKEN': $('meta[name=\"csrf-token\"]').attr('content')\n }\n },\n stickyHeader: true,\n stickyHeaderOffsetY: stickyHeaderOffsetY + 'px',\n undefinedText: '',\n iconsPrefix: 'fa',\n cookie: true,\n cookieExpire: '2y',\n mobileResponsive: true,\n maintainSelected: true,\n trimOnSearch: false,\n showSearchClearButton: true,\n paginationFirstText: \"{{ trans('general.first') }}\",\n paginationLastText: \"{{ trans('general.last') }}\",\n paginationPreText: \"{{ trans('general.previous') }}\",\n paginationNextText: \"{{ trans('general.next') }}\",\n pageList: ['10','20', '30','50','100','150','200', '500', '1000'],\n pageSize: {{ (($snipeSettings->per_page!='') && ($snipeSettings->per_page > 0)) ? $snipeSettings->per_page : 20 }},\n paginationVAlign: 'both',\n queryParams: function (params) {\n var newParams = {};\n for(var i in params) {\n if(!keyBlocked(i)) { // only send the field if it's not in blockedFields\n newParams[i] = params[i];\n }\n }\n return newParams;\n },\n formatLoadingMessage: function () {\n return '<h2><i class=\"fa fa-spinner fa-spin\" aria-hidden=\"true\"></i> Loading... please wait.... </h4>';\n },\n icons: {\n advancedSearchIcon: 'fa fa-search-plus',\n paginationSwitchDown: 'fa-caret-square-o-down',\n paginationSwitchUp: 'fa-caret-square-o-up',\n columns: 'fa-columns',\n refresh: 'fa-refresh',\n export: 'fa-download',\n clearSearch: 'fa-times'\n },", "", " exportTypes: ['csv', 'excel', 'doc', 'txt','json', 'xml', 'pdf'],\n onLoadSuccess: function () {\n $('[data-toggle=\"tooltip\"]').tooltip(); // Needed to attach tooltips after ajax call\n }", " }); ", " });", "", "", " function dateRowCheckStyle(value) {\n if ((value.days_to_next_audit) && (value.days_to_next_audit < {{ $snipeSettings->audit_warning_days ?: 0 }})) {\n return { classes : \"danger\" }\n }\n return {};\n }", "\n // These methods dynamically add/remove hidden input values in the bulk actions form\n $('.snipe-table').on('check.bs.table .btSelectItem', function (row, $element) {\n $('#bulkEdit').removeAttr('disabled');\n $('#bulkEdit').prepend('<input id=\"checkbox_' + $element.id + '\" type=\"hidden\" name=\"ids[]\" value=\"' + $element.id + '\">');\n });", " $('.snipe-table').on('uncheck.bs.table .btSelectItem', function (row, $element) {\n $( \"#checkbox_\" + $element.id).remove();\n });\n ", " // Handle whether or not the edit button should be disabled\n $('.snipe-table').on('uncheck.bs.table', function () {\n if ($('.snipe-table').bootstrapTable('getSelections').length == 0) {\n $('#bulkEdit').attr('disabled', 'disabled');\n }\n });", " $('.snipe-table').on('uncheck-all.bs.table', function (event, rowsAfter, rowsBefore) {\n $('#bulkEdit').attr('disabled', 'disabled');\n //console.dir(rowsBefore);", " for (var i in rowsBefore) {\n $( \"#checkbox_\" + rowsBefore[i].id).remove();\n }", " });", " $('.snipe-table').on('check-all.bs.table', function (event, rowsAfter, rowsBefore) {\n \n $('#bulkEdit').removeAttr('disabled');\n //console.dir(rowsAfter);\n \n for (var i in rowsAfter) {\n // console.log(rowsAfter[i].id);\n $('#bulkEdit').prepend('<input id=\"checkbox_' + rowsAfter[i].id + '\" type=\"hidden\" name=\"ids[]\" value=\"' + rowsAfter[i].id + '\">');\n }\n });", " ", " // This only works for model index pages because it uses the row's model ID\n function genericRowLinkFormatter(destination) {\n return function (value,row) {\n if (value) {\n return '<a href=\"{{ url('/') }}/' + destination + '/' + row.id + '\"> ' + value + '</a>';\n }\n };\n }", " // Use this when we're introspecting into a column object and need to link\n function genericColumnObjLinkFormatter(destination) {\n return function (value,row) {\n if ((value) && (value.status_meta)) {", " var text_color;\n var icon_style;\n var text_help;\n var status_meta = {\n 'deployed': '{{ strtolower(trans('general.deployed')) }}',\n 'deployable': '{{ strtolower(trans('admin/hardware/general.deployable')) }}',\n 'pending': '{{ strtolower(trans('general.pending')) }}'\n }", " switch (value.status_meta) {\n case 'deployed':\n text_color = 'blue';\n icon_style = 'fa-circle';\n text_help = '<label class=\"label label-default\">{{ trans('general.deployed') }}</label>';\n break;\n case 'deployable':\n text_color = 'green';\n icon_style = 'fa-circle';\n text_help = '';\n break;\n case 'pending':\n text_color = 'orange';\n icon_style = 'fa-circle';\n text_help = '';\n break;\n default:\n text_color = 'red';\n icon_style = 'fa-times';\n text_help = '';\n }", " return '<nobr><a href=\"{{ url('/') }}/' + destination + '/' + value.id + '\" data-toggle=\"tooltip\" title=\"'+ status_meta[value.status_meta] + '\"> <i class=\"fa ' + icon_style + ' text-' + text_color + '\"></i> ' + value.name + ' ' + text_help + ' </a> </nobr>';\n } else if ((value) && (value.name)) {", " // Add some overrides for any funny urls we have\n var dest = destination;\n var dpolymorphicItemFormatterest = '';\n if (destination=='fieldsets') {\n var dpolymorphicItemFormatterest = 'fields/';\n }", " return '<nobr><a href=\"{{ url('/') }}/' + dpolymorphicItemFormatterest + dest + '/' + value.id + '\"> ' + value.name + '</a></span>';\n }\n };\n }", " function hardwareAuditFormatter(value, row) {\n return '<a href=\"{{ url('/') }}/hardware/audit/' + row.id + '/\" class=\"btn btn-sm bg-yellow\" data-tooltip=\"true\" title=\"Audit this item\">{{ trans('general.audit') }}</a>';\n }", "\n // Make the edit/delete buttons\n function genericActionsFormatter(owner_name, element_name) {\n if (!element_name) {\n element_name = '';\n }", " return function (value,row) {", " var actions = '<nobr>';", " // Add some overrides for any funny urls we have\n var dest = owner_name;", " if (dest =='groups') {\n var dest = 'admin/groups';\n }", " if (dest =='maintenances') {\n var dest = 'hardware/maintenances';\n }", " if(element_name != '') {\n dest = dest + '/' + row.owner_id + '/' + element_name;\n }", " if ((row.available_actions) && (row.available_actions.clone === true)) {\n actions += '<a href=\"{{ url('/') }}/' + dest + '/' + row.id + '/clone\" class=\"btn btn-sm btn-info\" data-tooltip=\"true\" title=\"Clone Item\"><i class=\"fa fa-copy\" aria-hidden=\"true\"></i><span class=\"sr-only\">Clone</span></a>&nbsp;';\n }", " if ((row.available_actions) && (row.available_actions.update === true)) {\n actions += '<a href=\"{{ url('/') }}/' + dest + '/' + row.id + '/edit\" class=\"btn btn-sm btn-warning\" data-tooltip=\"true\" title=\"{{ trans('general.update') }}\"><i class=\"fa fa-pencil\" aria-hidden=\"true\"></i><span class=\"sr-only\">{{ trans('general.update') }}</span></a>&nbsp;';\n }", " if ((row.available_actions) && (row.available_actions.delete === true)) {\n actions += '<a href=\"{{ url('/') }}/' + dest + '/' + row.id + '\" '\n + ' class=\"btn btn-danger btn-sm delete-asset\" data-toggle=\"tooltip\" '\n + ' data-toggle=\"modal\" '\n + ' data-content=\"{{ trans('general.sure_to_delete') }} ' + row.name + '?\" '\n + ' data-title=\"{{ trans('general.delete') }}\" onClick=\"return false;\">'\n + '<i class=\"fa fa-trash\" aria-hidden=\"true\"></i><span class=\"sr-only\">{{ trans('general.delete') }}</span></a>&nbsp;';\n } else {\n actions += '<a class=\"btn btn-danger btn-sm delete-asset disabled\" onClick=\"return false;\"><i class=\"fa fa-trash\"></i></a>&nbsp;';\n }\n ", " if ((row.available_actions) && (row.available_actions.restore === true)) {\n actions += '<form style=\"display: inline;\" method=\"POST\" action=\"{{ url('/') }}/' + dest + '/' + row.id + '/restore\"> ';\n actions += '@csrf';\n actions += '<button class=\"btn btn-sm btn-warning\" data-toggle=\"tooltip\" title=\"{{ trans('general.restore') }}\">';\n actions += '<i class=\"fa fa-retweet\" aria-hidden=\"true\"></i><span class=\"sr-only\">{{ trans('general.restore') }}</span></button></form>&nbsp;';\n }", " actions +='</nobr>';\n return actions;", " };\n }", "\n // This handles the icons and display of polymorphic entries\n function polymorphicItemFormatter(value) {", " var item_destination = '';\n var item_icon;", " if ((value) && (value.type)) {", " if (value.type == 'asset') {\n item_destination = 'hardware';\n item_icon = 'fa-barcode';\n } else if (value.type == 'accessory') {\n item_destination = 'accessories';\n item_icon = 'fa-keyboard-o';\n } else if (value.type == 'component') {\n item_destination = 'components';\n item_icon = 'fa-hdd-o';\n } else if (value.type == 'consumable') {\n item_destination = 'consumables';\n item_icon = 'fa-tint';\n } else if (value.type == 'license') {\n item_destination = 'licenses';\n item_icon = 'fa-floppy-o';\n } else if (value.type == 'user') {\n item_destination = 'users';\n item_icon = 'fa-user';\n } else if (value.type == 'location') {\n item_destination = 'locations'\n item_icon = 'fa-map-marker';\n }", " return '<nobr><a href=\"{{ url('/') }}/' + item_destination +'/' + value.id + '\" data-tooltip=\"true\" title=\"' + value.type + '\"><i class=\"fa ' + item_icon + ' text-{{ $snipeSettings->skin!='' ? $snipeSettings->skin : 'blue' }} \"></i> ' + value.name + '</a></nobr>';", " } else {\n return '';\n }", "\n }", " // This just prints out the item type in the activity report\n function itemTypeFormatter(value, row) {", " if ((row) && (row.item) && (row.item.type)) {\n return row.item.type;\n }\n }", "\n // Convert line breaks to <br>\n function notesFormatter(value) {\n if (value) {\n return value.replace(/(?:\\r\\n|\\r|\\n)/g, '<br />');;\n }\n }", "\n // We need a special formatter for license seats, since they don't work exactly the same\n // Checkouts need the license ID, checkins need the specific seat ID", " function licenseSeatInOutFormatter(value, row) {\n // The user is allowed to check the license seat out and it's available\n if ((row.available_actions.checkout == true) && (row.user_can_checkout == true) && ((!row.asset_id) && (!row.assigned_to))) {\n return '<a href=\"{{ url('/') }}/licenses/' + row.license_id + '/checkout/'+row.id+'\" class=\"btn btn-sm bg-maroon\" data-toggle=\"tooltip\" title=\"Check this item out\">{{ trans('general.checkout') }}</a>';\n } else {\n return '<a href=\"{{ url('/') }}/licenses/' + row.id + '/checkin\" class=\"btn btn-sm bg-purple\" data-toggle=\"tooltip\" title=\"Check in this license seat.\">{{ trans('general.checkin') }}</a>';\n }", " }", " function genericCheckinCheckoutFormatter(destination) {\n return function (value,row) {", " // The user is allowed to check items out, AND the item is deployable\n if ((row.available_actions.checkout == true) && (row.user_can_checkout == true) && ((!row.asset_id) && (!row.assigned_to))) {\n return '<a href=\"{{ url('/') }}/' + destination + '/' + row.id + '/checkout\" class=\"btn btn-sm bg-maroon\" data-toggle=\"tooltip\" title=\"Check this item out\">{{ trans('general.checkout') }}</a>';", " // The user is allowed to check items out, but the item is not deployable\n } else if (((row.user_can_checkout == false)) && (row.available_actions.checkout == true) && (!row.assigned_to)) {\n return '<div data-toggle=\"tooltip\" title=\"This item has a status label that is undeployable and cannot be checked out at this time.\"><a class=\"btn btn-sm bg-maroon disabled\">{{ trans('general.checkout') }}</a></div>';", " // The user is allowed to check items in\n } else if (row.available_actions.checkin == true) {\n if (row.assigned_to) {\n return '<a href=\"{{ url('/') }}/' + destination + '/' + row.id + '/checkin\" class=\"btn btn-sm bg-purple\" data-toggle=\"tooltip\" title=\"Check this item in so it is available for re-imaging, re-issue, etc.\">{{ trans('general.checkin') }}</a>';\n } else if (row.assigned_pivot_id) {\n return '<a href=\"{{ url('/') }}/' + destination + '/' + row.assigned_pivot_id + '/checkin\" class=\"btn btn-sm bg-purple\" data-toggle=\"tooltip\" title=\"Check this item in so it is available for re-imaging, re-issue, etc.\">{{ trans('general.checkin') }}</a>';\n }", " }", " }", "\n }", "\n // This is only used by the requestable assets section\n function assetRequestActionsFormatter (row, value) {\n if (value.available_actions.cancel == true) {\n return '<form action=\"{{ url('/') }}/account/request-asset/'+ value.id + '\" method=\"GET\"><button class=\"btn btn-danger btn-sm\" data-toggle=\"tooltip\" title=\"Cancel this item request\">{{ trans('button.cancel') }}</button></form>';\n } else if (value.available_actions.request == true) {\n return '<form action=\"{{ url('/') }}/account/request-asset/'+ value.id + '\" method=\"GET\"><button class=\"btn btn-primary btn-sm\" data-toggle=\"tooltip\" title=\"Request this item\">{{ trans('button.request') }}</button></form>';\n }", " }", "", " var formatters = [\n 'hardware',\n 'accessories',\n 'consumables',\n 'components',\n 'locations',\n 'users',\n 'manufacturers',\n 'maintenances',\n 'statuslabels',\n 'models',\n 'licenses',\n 'categories',\n 'suppliers',\n 'departments',\n 'companies',\n 'depreciations',\n 'fieldsets',\n 'groups',\n 'kits'\n ];", " for (var i in formatters) {\n window[formatters[i] + 'LinkFormatter'] = genericRowLinkFormatter(formatters[i]);\n window[formatters[i] + 'LinkObjFormatter'] = genericColumnObjLinkFormatter(formatters[i]);\n window[formatters[i] + 'ActionsFormatter'] = genericActionsFormatter(formatters[i]);\n window[formatters[i] + 'InOutFormatter'] = genericCheckinCheckoutFormatter(formatters[i]);\n }", " var child_formatters = [\n ['kits', 'models'],\n ['kits', 'licenses'],\n ['kits', 'consumables'],\n ['kits', 'accessories'],\n ];", " for (var i in child_formatters) {\n var owner_name = child_formatters[i][0];\n var child_name = child_formatters[i][1];\n window[owner_name + '_' + child_name + 'ActionsFormatter'] = genericActionsFormatter(owner_name, child_name);\n }", "", " // This is gross, but necessary so that we can package the API response\n // for custom fields in a more useful way.\n function customFieldsFormatter(value, row) {", "\n if ((!this) || (!this.title)) {\n return '';\n }", " var field_column = this.title;", " // Pull out any HTMl that might be passed via the presenter\n // (for example, the locked icon for encrypted fields)\n var field_column_plain = field_column.replace(/<(?:.|\\n)*?> ?/gm, '');\n if ((row.custom_fields) && (row.custom_fields[field_column_plain])) {", " // If the field type needs special formatting, do that here\n if ((row.custom_fields[field_column_plain].field_format) && (row.custom_fields[field_column_plain].value)) {\n if (row.custom_fields[field_column_plain].field_format=='URL') {\n return '<a href=\"' + row.custom_fields[field_column_plain].value + '\" target=\"_blank\" rel=\"noopener\">' + row.custom_fields[field_column_plain].value + '</a>';\n } else if (row.custom_fields[field_column_plain].field_format=='EMAIL') {\n return '<a href=\"mailto:' + row.custom_fields[field_column_plain].value + '\">' + row.custom_fields[field_column_plain].value + '</a>';\n }\n }\n return row.custom_fields[field_column_plain].value;", " }", " }", "\n function createdAtFormatter(value) {\n if ((value) && (value.formatted)) {\n return value.formatted;\n }\n }", " function externalLinkFormatter(value) {\n if (value) {\n return '<a href=\"' + value + '\" target=\"_blank\">' + value + '</a>';\n }\n }", " function groupsFormatter(value) {", " if (value) {\n var groups = '';\n for (var index in value.rows) {\n groups += '<a href=\"{{ url('/') }}/admin/groups/' + value.rows[index].id + '\" class=\"label label-default\"> ' + value.rows[index].name + '</a> ';\n }\n return groups;\n }\n }", "", " function changeLogFormatter(value) {\n var result = '';\n for (var index in value) {\n result += index + ': <del>' + value[index].old + '</del> <i class=\"fa fa-long-arrow-right\" aria-hidden=\"true\"></i> ' + value[index].new + '<br>'\n }", " return result;", " }", "\n // Create a linked phone number in the table list\n function phoneFormatter(value) {\n if (value) {\n return '<a href=\"tel:' + value + '\">' + value + '</a>';\n }\n }", "\n function deployedLocationFormatter(row, value) {\n if ((row) && (row!=undefined)) {\n return '<a href=\"{{ url('/') }}/locations/' + row.id + '\"> ' + row.name + '</a>';\n } else if (value.rtd_location) {\n return '<a href=\"{{ url('/') }}/locations/' + value.rtd_location.id + '\" data-toggle=\"tooltip\" title=\"Default Location\"> ' + value.rtd_location.name + '</a>';\n }", " }", " function groupsAdminLinkFormatter(value, row) {\n return '<a href=\"{{ url('/') }}/admin/groups/' + row.id + '\"> ' + value + '</a>';\n }", " function assetTagLinkFormatter(value, row) {\n if ((row.asset) && (row.asset.id)) {\n return '<a href=\"{{ url('/') }}/hardware/' + row.asset.id + '\"> ' + row.asset.asset_tag + '</a>';\n }\n return '';", " }", " function departmentNameLinkFormatter(value, row) {\n if ((row.assigned_user) && (row.assigned_user.department) && (row.assigned_user.department.name)) {\n return '<a href=\"{{ url('/') }}/department/' + row.assigned_user.department.id + '\"> ' + row.assigned_user.department.name + '</a>';\n }", " }", " function assetNameLinkFormatter(value, row) {\n if ((row.asset) && (row.asset.name)) {\n return '<a href=\"{{ url('/') }}/hardware/' + row.asset.id + '\"> ' + row.asset.name + '</a>';\n }", " }", " function trueFalseFormatter(value) {\n if ((value) && ((value == 'true') || (value == '1'))) {\n return '<i class=\"fa fa-check text-success\"></i>';\n } else {\n return '<i class=\"fa fa-times text-danger\"></i>';\n }\n }", " function dateDisplayFormatter(value) {\n if (value) {\n return value.formatted;\n }\n }", " function iconFormatter(value) {\n if (value) {\n return '<i class=\"' + value + ' icon-med\"></i>';\n }\n }", " function emailFormatter(value) {\n if (value) {\n return '<a href=\"mailto:' + value + '\"> ' + value + '</a>';\n }\n }", " function linkFormatter(value) {\n if (value) {\n return '<a href=\"' + value + '\"> ' + value + '</a>';\n }\n }", " function assetCompanyFilterFormatter(value, row) {\n if (value) {\n return '<a href=\"{{ url('/') }}/hardware/?company_id=' + row.id + '\"> ' + value + '</a>';\n }\n }", " function assetCompanyObjFilterFormatter(value, row) {\n if ((row) && (row.company)) {\n return '<a href=\"{{ url('/') }}/hardware/?company_id=' + row.company.id + '\"> ' + row.company.name + '</a>';\n }\n }", " function usersCompanyObjFilterFormatter(value, row) {\n if (value) {\n return '<a href=\"{{ url('/') }}/users/?company_id=' + row.id + '\"> ' + value + '</a>';\n } else {\n return value;\n }\n }", " function employeeNumFormatter(value, row) {", " if ((row) && (row.assigned_to) && ((row.assigned_to.employee_number))) {\n return '<a href=\"{{ url('/') }}/users/' + row.assigned_to.id + '\"> ' + row.assigned_to.employee_number + '</a>';\n }\n }", " function orderNumberObjFilterFormatter(value, row) {\n if (value) {\n return '<a href=\"{{ url('/') }}/hardware/?order_number=' + row.order_number + '\"> ' + row.order_number + '</a>';\n }\n }", "\n function imageFormatter(value, row) {", "", " if (value) {", " if (row.name) {\n var altName = row.name;\n }\n else if ((row) && (row.model)) {\n var altName = row.model.name;\n }\n return '<a href=\"' + value + '\" data-toggle=\"lightbox\" data-type=\"image\"><img src=\"' + value + '\" style=\"max-height: {{ $snipeSettings->thumbnail_max_h }}px; width: auto;\" class=\"img-responsive\" alt=\"' + altName + '\"></a>';\n }\n }", " function fileUploadFormatter(value) {\n if ((value) && (value.url) && (value.inlineable)) {\n return '<a href=\"' + value.url + '\" data-toggle=\"lightbox\" data-type=\"image\"><img src=\"' + value.url + '\" style=\"max-height: {{ $snipeSettings->thumbnail_max_h }}px; width: auto;\" class=\"img-responsive\"></a>';\n } else if ((value) && (value.url)) {\n return '<a href=\"' + value.url + '\" class=\"btn btn-default\"><i class=\"fa fa-download\"></i></a>';\n }\n }", "\n function fileUploadNameFormatter(value) {\n console.dir(value);\n if ((value) && (value.filename) && (value.url)) {\n return '<a href=\"' + value.url + '\">' + value.filename + '</a>';\n }\n }", " function cleanFloat(number) {\n if(!number) { // in a JavaScript context, meaning, if it's null or zero or unset\n return 0.0;\n }\n if (\"{{$snipeSettings->digit_separator}}\" == \"1.234,56\") {\n // yank periods, change commas to periods\n periodless = number.toString().replace(/\\./g,\"\");\n decimalfixed = periodless.replace(/,/g,\".\");\n } else {\n // yank commas, that's it.\n decimalfixed = number.toString().replace(\",\",\"\");\n }\n return parseFloat(decimalfixed);\n }", " function sumFormatter(data) {\n if (Array.isArray(data)) {\n var field = this.field;\n var total_sum = data.reduce(function(sum, row) {\n return (sum) + (cleanFloat(row[field]) || 0);\n }, 0);\n return numberWithCommas(total_sum.toFixed(2));\n }\n return 'not an array';\n }", " function numberWithCommas(value) {\n if ((value) && (\"{{$snipeSettings->digit_separator}}\" == \"1.234,56\")){\n var parts = value.toString().split(\".\");\n parts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, \".\");\n return parts.join(\",\");\n } else {\n var parts = value.toString().split(\",\");\n parts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n return parts.join(\".\");\n }\n return value\n }", " $(function () {\n $('#bulkEdit').click(function () {\n var selectedIds = $('.snipe-table').bootstrapTable('getSelections');\n $.each(selectedIds, function(key,value) {\n $( \"#bulkForm\" ).append($('<input type=\"hidden\" name=\"ids[' + value.id + ']\" value=\"' + value.id + '\">' ));\n });", " });\n });", "", " $(function() {", " // This handles the search box highlighting on both ajax and client-side\n // bootstrap tables\n var searchboxHighlighter = function (event) {", " $('.search-input').each(function (index, element) {", " if ($(element).val() != '') {\n $(element).addClass('search-highlight');\n $(element).next().children().addClass('search-highlight');\n } else {\n $(element).removeClass('search-highlight');\n $(element).next().children().removeClass('search-highlight');\n }\n });\n };", " $('.search button[name=clearSearch]').click(searchboxHighlighter);\n searchboxHighlighter({ name:'pageload'});\n $('.search-input').keyup(searchboxHighlighter);", " // This is necessary to make the bootstrap tooltips work inside of the\n // wenzhixin/bootstrap-table formatters\n $('#table').on('post-body.bs.table', function () {\n $('[data-toggle=\"tooltip\"]').tooltip({\n container: 'body'\n });", "\n });\n });", "</script>\n \n@endpush" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [77], "buggy_code_start_loc": [77], "filenames": ["resources/views/partials/bootstrap-table.blade.php"], "fixing_code_end_loc": [82], "fixing_code_start_loc": [78], "message": "snipe-it is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:snipeitapp:snipe-it:*:*:*:*:*:*:*:*", "matchCriteriaId": "85B46A84-DED5-4BBA-B245-16C07FABC847", "versionEndExcluding": "5.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "snipe-it is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"}, {"lang": "es", "value": "snipe-it es vulnerable a una Neutralizaci\u00f3n Inapropiada de Entradas Durante la Generaci\u00f3n de P\u00e1ginas Web (\"Cross-site Scripting\")"}], "evaluatorComment": null, "id": "CVE-2021-3879", "lastModified": "2021-10-21T23:57:43.137", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:H/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-10-19T13:15:11.870", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/snipe/snipe-it/commit/bda23bb1e66fd7ce42c75c69cf5eea4e80865c1c"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/6dccc49e-3843-4a4a-b397-5c659e5f8bfe"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/snipe/snipe-it/commit/bda23bb1e66fd7ce42c75c69cf5eea4e80865c1c"}, "type": "CWE-79"}
185
Determine whether the {function_name} code is vulnerable or not.
[ "@push('css')\n<link rel=\"stylesheet\" href=\"{{ url(mix('css/dist/bootstrap-table.css')) }}\">", "@endpush", "@push('js')\n<script src=\"{{ url(mix('js/dist/bootstrap-table.js')) }}\"></script>\n<script nonce=\"{{ csrf_token() }}\">", " $(function () {", "\n var stickyHeaderOffsetY = 0;", " if ( $('.navbar-fixed-top').css('height') ) {\n stickyHeaderOffsetY = +$('.navbar-fixed-top').css('height').replace('px','');\n }\n if ( $('.navbar-fixed-top').css('margin-bottom') ) {\n stickyHeaderOffsetY += +$('.navbar-fixed-top').css('margin-bottom').replace('px','');\n }", " var blockedFields = \"searchable,sortable,switchable,title,visible,formatter,class\".split(\",\");", " var keyBlocked = function(key) {\n for(var j in blockedFields) {\n if (key === blockedFields[j]) {\n return true;\n }\n }\n return false;\n }", " $('.snipe-table').bootstrapTable('destroy').bootstrapTable({\n classes: 'table table-responsive table-no-bordered',\n ajaxOptions: {\n headers: {\n 'X-CSRF-TOKEN': $('meta[name=\"csrf-token\"]').attr('content')\n }\n },\n stickyHeader: true,\n stickyHeaderOffsetY: stickyHeaderOffsetY + 'px',\n undefinedText: '',\n iconsPrefix: 'fa',\n cookie: true,\n cookieExpire: '2y',\n mobileResponsive: true,\n maintainSelected: true,\n trimOnSearch: false,\n showSearchClearButton: true,\n paginationFirstText: \"{{ trans('general.first') }}\",\n paginationLastText: \"{{ trans('general.last') }}\",\n paginationPreText: \"{{ trans('general.previous') }}\",\n paginationNextText: \"{{ trans('general.next') }}\",\n pageList: ['10','20', '30','50','100','150','200', '500', '1000'],\n pageSize: {{ (($snipeSettings->per_page!='') && ($snipeSettings->per_page > 0)) ? $snipeSettings->per_page : 20 }},\n paginationVAlign: 'both',\n queryParams: function (params) {\n var newParams = {};\n for(var i in params) {\n if(!keyBlocked(i)) { // only send the field if it's not in blockedFields\n newParams[i] = params[i];\n }\n }\n return newParams;\n },\n formatLoadingMessage: function () {\n return '<h2><i class=\"fa fa-spinner fa-spin\" aria-hidden=\"true\"></i> Loading... please wait.... </h4>';\n },\n icons: {\n advancedSearchIcon: 'fa fa-search-plus',\n paginationSwitchDown: 'fa-caret-square-o-down',\n paginationSwitchUp: 'fa-caret-square-o-up',\n columns: 'fa-columns',\n refresh: 'fa-refresh',\n export: 'fa-download',\n clearSearch: 'fa-times'\n },", " exportOptions: {\n htmlContent: true,\n },\n", " exportTypes: ['csv', 'excel', 'doc', 'txt','json', 'xml', 'pdf'],\n onLoadSuccess: function () {\n $('[data-toggle=\"tooltip\"]').tooltip(); // Needed to attach tooltips after ajax call\n }", " }); ", " });", "", "", " function dateRowCheckStyle(value) {\n if ((value.days_to_next_audit) && (value.days_to_next_audit < {{ $snipeSettings->audit_warning_days ?: 0 }})) {\n return { classes : \"danger\" }\n }\n return {};\n }", "\n // These methods dynamically add/remove hidden input values in the bulk actions form\n $('.snipe-table').on('check.bs.table .btSelectItem', function (row, $element) {\n $('#bulkEdit').removeAttr('disabled');\n $('#bulkEdit').prepend('<input id=\"checkbox_' + $element.id + '\" type=\"hidden\" name=\"ids[]\" value=\"' + $element.id + '\">');\n });", " $('.snipe-table').on('uncheck.bs.table .btSelectItem', function (row, $element) {\n $( \"#checkbox_\" + $element.id).remove();\n });\n ", " // Handle whether or not the edit button should be disabled\n $('.snipe-table').on('uncheck.bs.table', function () {\n if ($('.snipe-table').bootstrapTable('getSelections').length == 0) {\n $('#bulkEdit').attr('disabled', 'disabled');\n }\n });", " $('.snipe-table').on('uncheck-all.bs.table', function (event, rowsAfter, rowsBefore) {\n $('#bulkEdit').attr('disabled', 'disabled');\n //console.dir(rowsBefore);", " for (var i in rowsBefore) {\n $( \"#checkbox_\" + rowsBefore[i].id).remove();\n }", " });", " $('.snipe-table').on('check-all.bs.table', function (event, rowsAfter, rowsBefore) {\n \n $('#bulkEdit').removeAttr('disabled');\n //console.dir(rowsAfter);\n \n for (var i in rowsAfter) {\n // console.log(rowsAfter[i].id);\n $('#bulkEdit').prepend('<input id=\"checkbox_' + rowsAfter[i].id + '\" type=\"hidden\" name=\"ids[]\" value=\"' + rowsAfter[i].id + '\">');\n }\n });", " ", " // This only works for model index pages because it uses the row's model ID\n function genericRowLinkFormatter(destination) {\n return function (value,row) {\n if (value) {\n return '<a href=\"{{ url('/') }}/' + destination + '/' + row.id + '\"> ' + value + '</a>';\n }\n };\n }", " // Use this when we're introspecting into a column object and need to link\n function genericColumnObjLinkFormatter(destination) {\n return function (value,row) {\n if ((value) && (value.status_meta)) {", " var text_color;\n var icon_style;\n var text_help;\n var status_meta = {\n 'deployed': '{{ strtolower(trans('general.deployed')) }}',\n 'deployable': '{{ strtolower(trans('admin/hardware/general.deployable')) }}',\n 'pending': '{{ strtolower(trans('general.pending')) }}'\n }", " switch (value.status_meta) {\n case 'deployed':\n text_color = 'blue';\n icon_style = 'fa-circle';\n text_help = '<label class=\"label label-default\">{{ trans('general.deployed') }}</label>';\n break;\n case 'deployable':\n text_color = 'green';\n icon_style = 'fa-circle';\n text_help = '';\n break;\n case 'pending':\n text_color = 'orange';\n icon_style = 'fa-circle';\n text_help = '';\n break;\n default:\n text_color = 'red';\n icon_style = 'fa-times';\n text_help = '';\n }", " return '<nobr><a href=\"{{ url('/') }}/' + destination + '/' + value.id + '\" data-toggle=\"tooltip\" title=\"'+ status_meta[value.status_meta] + '\"> <i class=\"fa ' + icon_style + ' text-' + text_color + '\"></i> ' + value.name + ' ' + text_help + ' </a> </nobr>';\n } else if ((value) && (value.name)) {", " // Add some overrides for any funny urls we have\n var dest = destination;\n var dpolymorphicItemFormatterest = '';\n if (destination=='fieldsets') {\n var dpolymorphicItemFormatterest = 'fields/';\n }", " return '<nobr><a href=\"{{ url('/') }}/' + dpolymorphicItemFormatterest + dest + '/' + value.id + '\"> ' + value.name + '</a></span>';\n }\n };\n }", " function hardwareAuditFormatter(value, row) {\n return '<a href=\"{{ url('/') }}/hardware/audit/' + row.id + '/\" class=\"btn btn-sm bg-yellow\" data-tooltip=\"true\" title=\"Audit this item\">{{ trans('general.audit') }}</a>';\n }", "\n // Make the edit/delete buttons\n function genericActionsFormatter(owner_name, element_name) {\n if (!element_name) {\n element_name = '';\n }", " return function (value,row) {", " var actions = '<nobr>';", " // Add some overrides for any funny urls we have\n var dest = owner_name;", " if (dest =='groups') {\n var dest = 'admin/groups';\n }", " if (dest =='maintenances') {\n var dest = 'hardware/maintenances';\n }", " if(element_name != '') {\n dest = dest + '/' + row.owner_id + '/' + element_name;\n }", " if ((row.available_actions) && (row.available_actions.clone === true)) {\n actions += '<a href=\"{{ url('/') }}/' + dest + '/' + row.id + '/clone\" class=\"btn btn-sm btn-info\" data-tooltip=\"true\" title=\"Clone Item\"><i class=\"fa fa-copy\" aria-hidden=\"true\"></i><span class=\"sr-only\">Clone</span></a>&nbsp;';\n }", " if ((row.available_actions) && (row.available_actions.update === true)) {\n actions += '<a href=\"{{ url('/') }}/' + dest + '/' + row.id + '/edit\" class=\"btn btn-sm btn-warning\" data-tooltip=\"true\" title=\"{{ trans('general.update') }}\"><i class=\"fa fa-pencil\" aria-hidden=\"true\"></i><span class=\"sr-only\">{{ trans('general.update') }}</span></a>&nbsp;';\n }", " if ((row.available_actions) && (row.available_actions.delete === true)) {\n actions += '<a href=\"{{ url('/') }}/' + dest + '/' + row.id + '\" '\n + ' class=\"btn btn-danger btn-sm delete-asset\" data-toggle=\"tooltip\" '\n + ' data-toggle=\"modal\" '\n + ' data-content=\"{{ trans('general.sure_to_delete') }} ' + row.name + '?\" '\n + ' data-title=\"{{ trans('general.delete') }}\" onClick=\"return false;\">'\n + '<i class=\"fa fa-trash\" aria-hidden=\"true\"></i><span class=\"sr-only\">{{ trans('general.delete') }}</span></a>&nbsp;';\n } else {\n actions += '<a class=\"btn btn-danger btn-sm delete-asset disabled\" onClick=\"return false;\"><i class=\"fa fa-trash\"></i></a>&nbsp;';\n }\n ", " if ((row.available_actions) && (row.available_actions.restore === true)) {\n actions += '<form style=\"display: inline;\" method=\"POST\" action=\"{{ url('/') }}/' + dest + '/' + row.id + '/restore\"> ';\n actions += '@csrf';\n actions += '<button class=\"btn btn-sm btn-warning\" data-toggle=\"tooltip\" title=\"{{ trans('general.restore') }}\">';\n actions += '<i class=\"fa fa-retweet\" aria-hidden=\"true\"></i><span class=\"sr-only\">{{ trans('general.restore') }}</span></button></form>&nbsp;';\n }", " actions +='</nobr>';\n return actions;", " };\n }", "\n // This handles the icons and display of polymorphic entries\n function polymorphicItemFormatter(value) {", " var item_destination = '';\n var item_icon;", " if ((value) && (value.type)) {", " if (value.type == 'asset') {\n item_destination = 'hardware';\n item_icon = 'fa-barcode';\n } else if (value.type == 'accessory') {\n item_destination = 'accessories';\n item_icon = 'fa-keyboard-o';\n } else if (value.type == 'component') {\n item_destination = 'components';\n item_icon = 'fa-hdd-o';\n } else if (value.type == 'consumable') {\n item_destination = 'consumables';\n item_icon = 'fa-tint';\n } else if (value.type == 'license') {\n item_destination = 'licenses';\n item_icon = 'fa-floppy-o';\n } else if (value.type == 'user') {\n item_destination = 'users';\n item_icon = 'fa-user';\n } else if (value.type == 'location') {\n item_destination = 'locations'\n item_icon = 'fa-map-marker';\n }", " return '<nobr><a href=\"{{ url('/') }}/' + item_destination +'/' + value.id + '\" data-tooltip=\"true\" title=\"' + value.type + '\"><i class=\"fa ' + item_icon + ' text-{{ $snipeSettings->skin!='' ? $snipeSettings->skin : 'blue' }} \"></i> ' + value.name + '</a></nobr>';", " } else {\n return '';\n }", "\n }", " // This just prints out the item type in the activity report\n function itemTypeFormatter(value, row) {", " if ((row) && (row.item) && (row.item.type)) {\n return row.item.type;\n }\n }", "\n // Convert line breaks to <br>\n function notesFormatter(value) {\n if (value) {\n return value.replace(/(?:\\r\\n|\\r|\\n)/g, '<br />');;\n }\n }", "\n // We need a special formatter for license seats, since they don't work exactly the same\n // Checkouts need the license ID, checkins need the specific seat ID", " function licenseSeatInOutFormatter(value, row) {\n // The user is allowed to check the license seat out and it's available\n if ((row.available_actions.checkout == true) && (row.user_can_checkout == true) && ((!row.asset_id) && (!row.assigned_to))) {\n return '<a href=\"{{ url('/') }}/licenses/' + row.license_id + '/checkout/'+row.id+'\" class=\"btn btn-sm bg-maroon\" data-toggle=\"tooltip\" title=\"Check this item out\">{{ trans('general.checkout') }}</a>';\n } else {\n return '<a href=\"{{ url('/') }}/licenses/' + row.id + '/checkin\" class=\"btn btn-sm bg-purple\" data-toggle=\"tooltip\" title=\"Check in this license seat.\">{{ trans('general.checkin') }}</a>';\n }", " }", " function genericCheckinCheckoutFormatter(destination) {\n return function (value,row) {", " // The user is allowed to check items out, AND the item is deployable\n if ((row.available_actions.checkout == true) && (row.user_can_checkout == true) && ((!row.asset_id) && (!row.assigned_to))) {\n return '<a href=\"{{ url('/') }}/' + destination + '/' + row.id + '/checkout\" class=\"btn btn-sm bg-maroon\" data-toggle=\"tooltip\" title=\"Check this item out\">{{ trans('general.checkout') }}</a>';", " // The user is allowed to check items out, but the item is not deployable\n } else if (((row.user_can_checkout == false)) && (row.available_actions.checkout == true) && (!row.assigned_to)) {\n return '<div data-toggle=\"tooltip\" title=\"This item has a status label that is undeployable and cannot be checked out at this time.\"><a class=\"btn btn-sm bg-maroon disabled\">{{ trans('general.checkout') }}</a></div>';", " // The user is allowed to check items in\n } else if (row.available_actions.checkin == true) {\n if (row.assigned_to) {\n return '<a href=\"{{ url('/') }}/' + destination + '/' + row.id + '/checkin\" class=\"btn btn-sm bg-purple\" data-toggle=\"tooltip\" title=\"Check this item in so it is available for re-imaging, re-issue, etc.\">{{ trans('general.checkin') }}</a>';\n } else if (row.assigned_pivot_id) {\n return '<a href=\"{{ url('/') }}/' + destination + '/' + row.assigned_pivot_id + '/checkin\" class=\"btn btn-sm bg-purple\" data-toggle=\"tooltip\" title=\"Check this item in so it is available for re-imaging, re-issue, etc.\">{{ trans('general.checkin') }}</a>';\n }", " }", " }", "\n }", "\n // This is only used by the requestable assets section\n function assetRequestActionsFormatter (row, value) {\n if (value.available_actions.cancel == true) {\n return '<form action=\"{{ url('/') }}/account/request-asset/'+ value.id + '\" method=\"GET\"><button class=\"btn btn-danger btn-sm\" data-toggle=\"tooltip\" title=\"Cancel this item request\">{{ trans('button.cancel') }}</button></form>';\n } else if (value.available_actions.request == true) {\n return '<form action=\"{{ url('/') }}/account/request-asset/'+ value.id + '\" method=\"GET\"><button class=\"btn btn-primary btn-sm\" data-toggle=\"tooltip\" title=\"Request this item\">{{ trans('button.request') }}</button></form>';\n }", " }", "", " var formatters = [\n 'hardware',\n 'accessories',\n 'consumables',\n 'components',\n 'locations',\n 'users',\n 'manufacturers',\n 'maintenances',\n 'statuslabels',\n 'models',\n 'licenses',\n 'categories',\n 'suppliers',\n 'departments',\n 'companies',\n 'depreciations',\n 'fieldsets',\n 'groups',\n 'kits'\n ];", " for (var i in formatters) {\n window[formatters[i] + 'LinkFormatter'] = genericRowLinkFormatter(formatters[i]);\n window[formatters[i] + 'LinkObjFormatter'] = genericColumnObjLinkFormatter(formatters[i]);\n window[formatters[i] + 'ActionsFormatter'] = genericActionsFormatter(formatters[i]);\n window[formatters[i] + 'InOutFormatter'] = genericCheckinCheckoutFormatter(formatters[i]);\n }", " var child_formatters = [\n ['kits', 'models'],\n ['kits', 'licenses'],\n ['kits', 'consumables'],\n ['kits', 'accessories'],\n ];", " for (var i in child_formatters) {\n var owner_name = child_formatters[i][0];\n var child_name = child_formatters[i][1];\n window[owner_name + '_' + child_name + 'ActionsFormatter'] = genericActionsFormatter(owner_name, child_name);\n }", "", " // This is gross, but necessary so that we can package the API response\n // for custom fields in a more useful way.\n function customFieldsFormatter(value, row) {", "\n if ((!this) || (!this.title)) {\n return '';\n }", " var field_column = this.title;", " // Pull out any HTMl that might be passed via the presenter\n // (for example, the locked icon for encrypted fields)\n var field_column_plain = field_column.replace(/<(?:.|\\n)*?> ?/gm, '');\n if ((row.custom_fields) && (row.custom_fields[field_column_plain])) {", " // If the field type needs special formatting, do that here\n if ((row.custom_fields[field_column_plain].field_format) && (row.custom_fields[field_column_plain].value)) {\n if (row.custom_fields[field_column_plain].field_format=='URL') {\n return '<a href=\"' + row.custom_fields[field_column_plain].value + '\" target=\"_blank\" rel=\"noopener\">' + row.custom_fields[field_column_plain].value + '</a>';\n } else if (row.custom_fields[field_column_plain].field_format=='EMAIL') {\n return '<a href=\"mailto:' + row.custom_fields[field_column_plain].value + '\">' + row.custom_fields[field_column_plain].value + '</a>';\n }\n }\n return row.custom_fields[field_column_plain].value;", " }", " }", "\n function createdAtFormatter(value) {\n if ((value) && (value.formatted)) {\n return value.formatted;\n }\n }", " function externalLinkFormatter(value) {\n if (value) {\n return '<a href=\"' + value + '\" target=\"_blank\">' + value + '</a>';\n }\n }", " function groupsFormatter(value) {", " if (value) {\n var groups = '';\n for (var index in value.rows) {\n groups += '<a href=\"{{ url('/') }}/admin/groups/' + value.rows[index].id + '\" class=\"label label-default\"> ' + value.rows[index].name + '</a> ';\n }\n return groups;\n }\n }", "", " function changeLogFormatter(value) {\n var result = '';\n for (var index in value) {\n result += index + ': <del>' + value[index].old + '</del> <i class=\"fa fa-long-arrow-right\" aria-hidden=\"true\"></i> ' + value[index].new + '<br>'\n }", " return result;", " }", "\n // Create a linked phone number in the table list\n function phoneFormatter(value) {\n if (value) {\n return '<a href=\"tel:' + value + '\">' + value + '</a>';\n }\n }", "\n function deployedLocationFormatter(row, value) {\n if ((row) && (row!=undefined)) {\n return '<a href=\"{{ url('/') }}/locations/' + row.id + '\"> ' + row.name + '</a>';\n } else if (value.rtd_location) {\n return '<a href=\"{{ url('/') }}/locations/' + value.rtd_location.id + '\" data-toggle=\"tooltip\" title=\"Default Location\"> ' + value.rtd_location.name + '</a>';\n }", " }", " function groupsAdminLinkFormatter(value, row) {\n return '<a href=\"{{ url('/') }}/admin/groups/' + row.id + '\"> ' + value + '</a>';\n }", " function assetTagLinkFormatter(value, row) {\n if ((row.asset) && (row.asset.id)) {\n return '<a href=\"{{ url('/') }}/hardware/' + row.asset.id + '\"> ' + row.asset.asset_tag + '</a>';\n }\n return '';", " }", " function departmentNameLinkFormatter(value, row) {\n if ((row.assigned_user) && (row.assigned_user.department) && (row.assigned_user.department.name)) {\n return '<a href=\"{{ url('/') }}/department/' + row.assigned_user.department.id + '\"> ' + row.assigned_user.department.name + '</a>';\n }", " }", " function assetNameLinkFormatter(value, row) {\n if ((row.asset) && (row.asset.name)) {\n return '<a href=\"{{ url('/') }}/hardware/' + row.asset.id + '\"> ' + row.asset.name + '</a>';\n }", " }", " function trueFalseFormatter(value) {\n if ((value) && ((value == 'true') || (value == '1'))) {\n return '<i class=\"fa fa-check text-success\"></i>';\n } else {\n return '<i class=\"fa fa-times text-danger\"></i>';\n }\n }", " function dateDisplayFormatter(value) {\n if (value) {\n return value.formatted;\n }\n }", " function iconFormatter(value) {\n if (value) {\n return '<i class=\"' + value + ' icon-med\"></i>';\n }\n }", " function emailFormatter(value) {\n if (value) {\n return '<a href=\"mailto:' + value + '\"> ' + value + '</a>';\n }\n }", " function linkFormatter(value) {\n if (value) {\n return '<a href=\"' + value + '\"> ' + value + '</a>';\n }\n }", " function assetCompanyFilterFormatter(value, row) {\n if (value) {\n return '<a href=\"{{ url('/') }}/hardware/?company_id=' + row.id + '\"> ' + value + '</a>';\n }\n }", " function assetCompanyObjFilterFormatter(value, row) {\n if ((row) && (row.company)) {\n return '<a href=\"{{ url('/') }}/hardware/?company_id=' + row.company.id + '\"> ' + row.company.name + '</a>';\n }\n }", " function usersCompanyObjFilterFormatter(value, row) {\n if (value) {\n return '<a href=\"{{ url('/') }}/users/?company_id=' + row.id + '\"> ' + value + '</a>';\n } else {\n return value;\n }\n }", " function employeeNumFormatter(value, row) {", " if ((row) && (row.assigned_to) && ((row.assigned_to.employee_number))) {\n return '<a href=\"{{ url('/') }}/users/' + row.assigned_to.id + '\"> ' + row.assigned_to.employee_number + '</a>';\n }\n }", " function orderNumberObjFilterFormatter(value, row) {\n if (value) {\n return '<a href=\"{{ url('/') }}/hardware/?order_number=' + row.order_number + '\"> ' + row.order_number + '</a>';\n }\n }", "\n function imageFormatter(value, row) {", "", " if (value) {", " if (row.name) {\n var altName = row.name;\n }\n else if ((row) && (row.model)) {\n var altName = row.model.name;\n }\n return '<a href=\"' + value + '\" data-toggle=\"lightbox\" data-type=\"image\"><img src=\"' + value + '\" style=\"max-height: {{ $snipeSettings->thumbnail_max_h }}px; width: auto;\" class=\"img-responsive\" alt=\"' + altName + '\"></a>';\n }\n }", " function fileUploadFormatter(value) {\n if ((value) && (value.url) && (value.inlineable)) {\n return '<a href=\"' + value.url + '\" data-toggle=\"lightbox\" data-type=\"image\"><img src=\"' + value.url + '\" style=\"max-height: {{ $snipeSettings->thumbnail_max_h }}px; width: auto;\" class=\"img-responsive\"></a>';\n } else if ((value) && (value.url)) {\n return '<a href=\"' + value.url + '\" class=\"btn btn-default\"><i class=\"fa fa-download\"></i></a>';\n }\n }", "\n function fileUploadNameFormatter(value) {\n console.dir(value);\n if ((value) && (value.filename) && (value.url)) {\n return '<a href=\"' + value.url + '\">' + value.filename + '</a>';\n }\n }", " function cleanFloat(number) {\n if(!number) { // in a JavaScript context, meaning, if it's null or zero or unset\n return 0.0;\n }\n if (\"{{$snipeSettings->digit_separator}}\" == \"1.234,56\") {\n // yank periods, change commas to periods\n periodless = number.toString().replace(/\\./g,\"\");\n decimalfixed = periodless.replace(/,/g,\".\");\n } else {\n // yank commas, that's it.\n decimalfixed = number.toString().replace(\",\",\"\");\n }\n return parseFloat(decimalfixed);\n }", " function sumFormatter(data) {\n if (Array.isArray(data)) {\n var field = this.field;\n var total_sum = data.reduce(function(sum, row) {\n return (sum) + (cleanFloat(row[field]) || 0);\n }, 0);\n return numberWithCommas(total_sum.toFixed(2));\n }\n return 'not an array';\n }", " function numberWithCommas(value) {\n if ((value) && (\"{{$snipeSettings->digit_separator}}\" == \"1.234,56\")){\n var parts = value.toString().split(\".\");\n parts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, \".\");\n return parts.join(\",\");\n } else {\n var parts = value.toString().split(\",\");\n parts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n return parts.join(\".\");\n }\n return value\n }", " $(function () {\n $('#bulkEdit').click(function () {\n var selectedIds = $('.snipe-table').bootstrapTable('getSelections');\n $.each(selectedIds, function(key,value) {\n $( \"#bulkForm\" ).append($('<input type=\"hidden\" name=\"ids[' + value.id + ']\" value=\"' + value.id + '\">' ));\n });", " });\n });", "", " $(function() {", " // This handles the search box highlighting on both ajax and client-side\n // bootstrap tables\n var searchboxHighlighter = function (event) {", " $('.search-input').each(function (index, element) {", " if ($(element).val() != '') {\n $(element).addClass('search-highlight');\n $(element).next().children().addClass('search-highlight');\n } else {\n $(element).removeClass('search-highlight');\n $(element).next().children().removeClass('search-highlight');\n }\n });\n };", " $('.search button[name=clearSearch]').click(searchboxHighlighter);\n searchboxHighlighter({ name:'pageload'});\n $('.search-input').keyup(searchboxHighlighter);", " // This is necessary to make the bootstrap tooltips work inside of the\n // wenzhixin/bootstrap-table formatters\n $('#table').on('post-body.bs.table', function () {\n $('[data-toggle=\"tooltip\"]').tooltip({\n container: 'body'\n });", "\n });\n });", "</script>\n \n@endpush" ]
[ 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, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [77], "buggy_code_start_loc": [77], "filenames": ["resources/views/partials/bootstrap-table.blade.php"], "fixing_code_end_loc": [82], "fixing_code_start_loc": [78], "message": "snipe-it is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:snipeitapp:snipe-it:*:*:*:*:*:*:*:*", "matchCriteriaId": "85B46A84-DED5-4BBA-B245-16C07FABC847", "versionEndExcluding": "5.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "snipe-it is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"}, {"lang": "es", "value": "snipe-it es vulnerable a una Neutralizaci\u00f3n Inapropiada de Entradas Durante la Generaci\u00f3n de P\u00e1ginas Web (\"Cross-site Scripting\")"}], "evaluatorComment": null, "id": "CVE-2021-3879", "lastModified": "2021-10-21T23:57:43.137", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:H/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-10-19T13:15:11.870", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/snipe/snipe-it/commit/bda23bb1e66fd7ce42c75c69cf5eea4e80865c1c"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/6dccc49e-3843-4a4a-b397-5c659e5f8bfe"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/snipe/snipe-it/commit/bda23bb1e66fd7ce42c75c69cf5eea4e80865c1c"}, "type": "CWE-79"}
185
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n *\t\t\tGPAC - Multimedia Framework C SDK\n *\n *\t\t\tAuthors: Jean Le Feuvre\n *\t\t\tCopyright (c) Telecom ParisTech 2000-2021\n *\t\t\t\t\tAll rights reserved\n *\n * This file is part of GPAC / mp4box application\n *\n * GPAC is free software; you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2, or (at your option)\n * any later version.\n *\n * GPAC is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; see the file COPYING. If not, write to\n * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.\n *\n */", "#include \"mp4box.h\"", "#if defined(GPAC_DISABLE_ISOM) || defined(GPAC_DISABLE_ISOM_WRITE)", "#error \"Cannot compile MP4Box if GPAC is not built with ISO File Format support\"", "#else", "#ifndef GPAC_DISABLE_X3D\n#include <gpac/nodes_x3d.h>\n#endif\n#ifndef GPAC_DISABLE_BIFS\n#include <gpac/internal/bifs_dev.h>\n#endif\n#ifndef GPAC_DISABLE_VRML\n#include <gpac/nodes_mpeg4.h>\n#endif\n#include <gpac/constants.h>\n#include <gpac/avparse.h>\n#include <gpac/internal/media_dev.h>\n/*ISO 639 languages*/\n#include <gpac/iso639.h>\n#include <gpac/mpegts.h>", "#ifndef GPAC_DISABLE_SMGR\n#include <gpac/scene_manager.h>\n#endif\n#include <gpac/internal/media_dev.h>\n#include <gpac/media_tools.h>\n/*for built-in box printing*/\n#include <gpac/internal/isomedia_dev.h>", "extern u32 swf_flags;\nextern Float swf_flatten_angle;\nextern GF_FileType get_file_type_by_ext(char *inName);\nextern u32 fs_dump_flags;", "void scene_coding_log(void *cbk, GF_LOG_Level log_level, GF_LOG_Tool log_tool, const char *fmt, va_list vlist);", "\n#ifdef GPAC_DISABLE_LOG\nvoid mp4box_log(const char *fmt, ...)\n{\n\tva_list vl;\n\tva_start(vl, fmt);\n\tvfprintf(stderr, fmt, vlist);\n\tfflush(stderr);\n\tva_end(vl);\n}\n#endif", "\nu32 PrintLanguages(char *val, u32 opt)\n{\n\tu32 i=0, count = gf_lang_get_count();\n\tfprintf(stderr, \"Supported ISO 639 languages and codes:\\n\\n\");\n\tfor (i=0; i<count; i++) {\n\t\tif (gf_lang_get_2cc(i)) {\n\t\t\tfprintf(stderr, \"%s (%s - %s)\\n\", gf_lang_get_name(i), gf_lang_get_3cc(i), gf_lang_get_2cc(i));\n\t\t}\n\t}\n\treturn 1;\n}", "static const char *GetLanguage(char *lcode)\n{\n\ts32 idx = gf_lang_find(lcode);\n\tif (idx>=0) return gf_lang_get_name(idx);\n\treturn lcode;\n}", "GF_Err dump_isom_cover_art(GF_ISOFile *file, char *inName, Bool is_final_name)\n{\n\tconst u8 *tag;\n\tFILE *t;\n\tu32 tag_len;\n\tGF_Err e = gf_isom_apple_get_tag(file, GF_ISOM_ITUNE_COVER_ART, &tag, &tag_len);\n\tif (e!=GF_OK) {\n\t\tif (e==GF_URL_ERROR) {\n\t\t\tM4_LOG(GF_LOG_WARNING, (\"No cover art found\\n\"));\n\t\t\treturn GF_OK;\n\t\t}\n\t\treturn e;\n\t}", "\tif (inName) {\n\t\tchar szName[1024];\n\t\tif (is_final_name) {\n\t\t\tstrcpy(szName, inName);\n\t\t} else {\n\t\t\tsprintf(szName, \"%s.%s\", inName, (tag_len>>31) ? \"png\" : \"jpg\");\n\t\t}\n\t\tt = gf_fopen(szName, \"wb\");\n\t\tif (!t) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s for dumping\\n\", szName));\n\t\t\treturn GF_IO_ERR;\n\t\t}\n\t} else {\n\t\tt = stdout;\n\t}\n\tgf_fwrite(tag, tag_len & 0x7FFFFFFF, t);", "\tif (inName) gf_fclose(t);\n\treturn GF_OK;\n}", "#ifndef GPAC_DISABLE_SCENE_DUMP", "GF_Err dump_isom_scene(char *file, char *inName, Bool is_final_name, GF_SceneDumpFormat dump_mode, Bool do_log, Bool no_odf_conv)\n{\n\tGF_Err e;\n\tGF_SceneManager *ctx;\n\tGF_SceneGraph *sg;\n\tGF_SceneLoader load;\n\tGF_FileType ftype;\n\tgf_log_cbk prev_logs = NULL;\n\tFILE *logs = NULL;", "\tsg = gf_sg_new();\n\tctx = gf_sm_new(sg);\n\tmemset(&load, 0, sizeof(GF_SceneLoader));\n\tload.fileName = file;\n\tload.ctx = ctx;\n\tload.swf_import_flags = swf_flags;\n\tif (dump_mode == GF_SM_DUMP_SVG) {\n\t\tload.swf_import_flags |= GF_SM_SWF_USE_SVG;\n\t\tload.svgOutFile = inName;\n\t}\n\tload.swf_flatten_limit = swf_flatten_angle;", "\tftype = get_file_type_by_ext(file);\n\tif (ftype == GF_FILE_TYPE_ISO_MEDIA) {\n\t\tload.isom = gf_isom_open(file, GF_ISOM_OPEN_READ, NULL);\n\t\tif (!load.isom) {\n\t\t\te = gf_isom_last_error(NULL);\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Error opening file: %s\\n\", gf_error_to_string(e)));\n\t\t\tgf_sm_del(ctx);\n\t\t\tgf_sg_del(sg);\n\t\t\treturn e;\n\t\t}\n\t\tif (no_odf_conv)\n\t\t\tgf_isom_disable_odf_conversion(load.isom, GF_TRUE);", "\t} else if (ftype==GF_FILE_TYPE_LSR_SAF) {\n\t\tload.isom = gf_isom_open(\"saf_conv\", GF_ISOM_WRITE_EDIT, NULL);\n#ifndef GPAC_DISABLE_MEDIA_IMPORT\n\t\tif (load.isom) {\n\t\t\tGF_Fraction _frac = {0,0};\n\t\t\te = import_file(load.isom, file, 0, _frac, 0, NULL, NULL, 0);\n\t\t} else\n#else\n\t\tM4_LOG(GF_LOG_WARNING, (\"Warning: GPAC was compiled without Media Import support\\n\"));\n#endif\n\t\t\te = gf_isom_last_error(NULL);", "\t\tif (e) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Error importing file: %s\\n\", gf_error_to_string(e)));\n\t\t\tgf_sm_del(ctx);\n\t\t\tgf_sg_del(sg);\n\t\t\tif (load.isom) gf_isom_delete(load.isom);\n\t\t\treturn e;\n\t\t}\n\t}", "\tif (do_log) {\n\t\tchar szLog[GF_MAX_PATH];\n\t\tsprintf(szLog, \"%s_dec.logs\", inName);\n\t\tlogs = gf_fopen(szLog, \"wt\");", "\t\tgf_log_set_tool_level(GF_LOG_CODING, GF_LOG_DEBUG);\n\t\tprev_logs = gf_log_set_callback(logs, scene_coding_log);\n\t}\n\te = gf_sm_load_init(&load);\n\tif (!e) e = gf_sm_load_run(&load);\n\tgf_sm_load_done(&load);\n\tif (logs) {\n\t\tgf_log_set_tool_level(GF_LOG_CODING, GF_LOG_ERROR);\n\t\tgf_log_set_callback(NULL, prev_logs);\n\t\tgf_fclose(logs);\n\t}\n\tif (!e && dump_mode != GF_SM_DUMP_SVG) {\n\t\tu32 count = gf_list_count(ctx->streams);\n\t\tif (count)\n\t\t\tfprintf(stderr, \"Scene loaded - dumping %d systems streams\\n\", count);\n\t\telse\n\t\t\tfprintf(stderr, \"Scene loaded - dumping root scene\\n\");", "\t\te = gf_sm_dump(ctx, inName, is_final_name, dump_mode);\n\t}", "\tgf_sm_del(ctx);\n\tgf_sg_del(sg);\n\tif (e) M4_LOG(GF_LOG_ERROR, (\"Error loading scene: %s\\n\", gf_error_to_string(e)));\n\tif (load.isom) gf_isom_delete(load.isom);\n\treturn e;\n}\n#endif", "#ifndef GPAC_DISABLE_SCENE_STATS", "static void dump_stats(FILE *dump, const GF_SceneStatistics *stats)\n{\n\tu32 i;\n\ts32 created, count, draw_created, draw_count, deleted, draw_deleted;\n\tcreated = count = draw_created = draw_count = deleted = draw_deleted = 0;", "\tfprintf(dump, \"<NodeStatistics>\\n\");\n\tfprintf(dump, \"<General NumberOfNodeTypes=\\\"%d\\\"/>\\n\", gf_list_count(stats->node_stats));\n\tfor (i=0; i<gf_list_count(stats->node_stats); i++) {\n\t\tGF_NodeStats *ptr = gf_list_get(stats->node_stats, i);\n\t\tfprintf(dump, \"<NodeStat NodeName=\\\"%s\\\">\\n\", ptr->name);", "\t\tswitch (ptr->tag) {\n#ifndef GPAC_DISABLE_VRML\n\t\tcase TAG_MPEG4_Bitmap:\n\t\tcase TAG_MPEG4_Background2D:\n\t\tcase TAG_MPEG4_Background:\n\t\tcase TAG_MPEG4_Box:\n\t\tcase TAG_MPEG4_Circle:\n\t\tcase TAG_MPEG4_CompositeTexture2D:\n\t\tcase TAG_MPEG4_CompositeTexture3D:\n\t\tcase TAG_MPEG4_Cylinder:\n\t\tcase TAG_MPEG4_Cone:\n\t\tcase TAG_MPEG4_Curve2D:\n\t\tcase TAG_MPEG4_Extrusion:\n\t\tcase TAG_MPEG4_ElevationGrid:\n\t\tcase TAG_MPEG4_IndexedFaceSet2D:\n\t\tcase TAG_MPEG4_IndexedFaceSet:\n\t\tcase TAG_MPEG4_IndexedLineSet2D:\n\t\tcase TAG_MPEG4_IndexedLineSet:\n\t\tcase TAG_MPEG4_PointSet2D:\n\t\tcase TAG_MPEG4_PointSet:\n\t\tcase TAG_MPEG4_Rectangle:\n\t\tcase TAG_MPEG4_Sphere:\n\t\tcase TAG_MPEG4_Text:\n\t\tcase TAG_MPEG4_Ellipse:\n\t\tcase TAG_MPEG4_XCurve2D:\n\t\t\tdraw_count += ptr->nb_created + ptr->nb_used - ptr->nb_del;\n\t\t\tdraw_deleted += ptr->nb_del;\n\t\t\tdraw_created += ptr->nb_created;\n\t\t\tbreak;\n#endif /*GPAC_DISABLE_VRML*/\n\t\t}\n\t\tfprintf(dump, \"<Instanciation NbObjects=\\\"%d\\\" NbUse=\\\"%d\\\" NbDestroy=\\\"%d\\\"/>\\n\", ptr->nb_created, ptr->nb_used, ptr->nb_del);\n\t\tcount += ptr->nb_created + ptr->nb_used;\n\t\tdeleted += ptr->nb_del;\n\t\tcreated += ptr->nb_created;\n\t\tfprintf(dump, \"</NodeStat>\\n\");\n\t}\n\tif (i) {\n\t\tfprintf(dump, \"<CumulatedStat TotalNumberOfNodes=\\\"%d\\\" ReallyAllocatedNodes=\\\"%d\\\" DeletedNodes=\\\"%d\\\" NumberOfAttributes=\\\"%d\\\"/>\\n\", count, created, deleted, stats->nb_svg_attributes);\n\t\tfprintf(dump, \"<DrawableNodesCumulatedStat TotalNumberOfNodes=\\\"%d\\\" ReallyAllocatedNodes=\\\"%d\\\" DeletedNodes=\\\"%d\\\"/>\\n\", draw_count, draw_created, draw_deleted);\n\t}\n\tfprintf(dump, \"</NodeStatistics>\\n\");", "\tcreated = count = deleted = 0;\n\tif (gf_list_count(stats->proto_stats)) {\n\t\tfprintf(dump, \"<ProtoStatistics NumberOfProtoUsed=\\\"%d\\\">\\n\", gf_list_count(stats->proto_stats));\n\t\tfor (i=0; i<gf_list_count(stats->proto_stats); i++) {\n\t\t\tGF_NodeStats *ptr = gf_list_get(stats->proto_stats, i);\n\t\t\tfprintf(dump, \"<ProtoStat ProtoName=\\\"%s\\\">\\n\", ptr->name);\n\t\t\tfprintf(dump, \"<Instanciation NbObjects=\\\"%d\\\" NbUse=\\\"%d\\\" NbDestroy=\\\"%d\\\"/>\\n\", ptr->nb_created, ptr->nb_used, ptr->nb_del);\n\t\t\tcount += ptr->nb_created + ptr->nb_used;\n\t\t\tdeleted += ptr->nb_del;\n\t\t\tcreated += ptr->nb_created;\n\t\t\tfprintf(dump, \"</ProtoStat>\\n\");\n\t\t}\n\t\tif (i) fprintf(dump, \"<CumulatedStat TotalNumberOfProtos=\\\"%d\\\" ReallyAllocatedProtos=\\\"%d\\\" DeletedProtos=\\\"%d\\\"/>\\n\", count, created, deleted);\n\t\tfprintf(dump, \"</ProtoStatistics>\\n\");\n\t}\n\tfprintf(dump, \"<FixedValues min=\\\"%f\\\" max=\\\"%f\\\">\\n\", FIX2FLT( stats->min_fixed) , FIX2FLT( stats->max_fixed ));\n\tfprintf(dump, \"<Resolutions scaleIntegerPart=\\\"%d\\\" scaleFracPart=\\\"%d\\\" coordIntegerPart=\\\"%d\\\" coordFracPart=\\\"%d\\\"/>\\n\", stats->scale_int_res_2d, stats->scale_frac_res_2d, stats->int_res_2d, stats->frac_res_2d);\n\tfprintf(dump, \"</FixedValues>\\n\");\n\tfprintf(dump, \"<FieldStatistic FieldType=\\\"MFVec2f\\\">\\n\");\n\tfprintf(dump, \"<ParsingInfo NumParsed=\\\"%d\\\" NumRemoved=\\\"%d\\\"/>\\n\", stats->count_2d, stats->rem_2d);\n\tif (stats->count_2d) {\n\t\tfprintf(dump, \"<ExtendInfo MinVec2f=\\\"%f %f\\\" MaxVec2f=\\\"%f %f\\\"/>\\n\", FIX2FLT( stats->min_2d.x) , FIX2FLT( stats->min_2d.y ), FIX2FLT( stats->max_2d.x ), FIX2FLT( stats->max_2d.y ) );\n\t}\n\tfprintf(dump, \"</FieldStatistic>\\n\");", "\tfprintf(dump, \"<FieldStatistic FieldType=\\\"MFVec3f\\\">\\n\");\n\tfprintf(dump, \"<ParsingInfo NumParsed=\\\"%d\\\" NumRemoved=\\\"%d\\\"/>\", stats->count_3d, stats->rem_3d);\n\tif (stats->count_3d) {\n\t\tfprintf(dump, \"<ExtendInfo MinVec3f=\\\"%f %f %f\\\" MaxVec3f=\\\"%f %f %f\\\"/>\\n\", FIX2FLT( stats->min_3d.x ), FIX2FLT( stats->min_3d.y ), FIX2FLT( stats->min_3d.z ), FIX2FLT( stats->max_3d.x ), FIX2FLT( stats->max_3d.y ), FIX2FLT( stats->max_3d.z ) );\n\t}\n\tfprintf(dump, \"</FieldStatistic>\\n\");", "\tfprintf(dump, \"<FieldStatistic FieldType=\\\"MF/SFColor\\\">\\n\");\n\tfprintf(dump, \"<ParsingInfo NumParsed=\\\"%d\\\" NumRemoved=\\\"%d\\\"/>\", stats->count_color, stats->rem_color);\n\tfprintf(dump, \"</FieldStatistic>\\n\");", "\tfprintf(dump, \"<FieldStatistic FieldType=\\\"MF/SFFloat\\\">\\n\");\n\tfprintf(dump, \"<ParsingInfo NumParsed=\\\"%d\\\" NumRemoved=\\\"%d\\\"/>\", stats->count_float, stats->rem_float);\n\tfprintf(dump, \"</FieldStatistic>\\n\");", "\tfprintf(dump, \"<FieldStatistic FieldType=\\\"SFVec2f\\\">\\n\");\n\tfprintf(dump, \"<ParsingInfo NumParsed=\\\"%d\\\"/>\", stats->count_2f);\n\tfprintf(dump, \"</FieldStatistic>\\n\");\n\tfprintf(dump, \"<FieldStatistic FieldType=\\\"SFVec3f\\\">\\n\");\n\tfprintf(dump, \"<ParsingInfo NumParsed=\\\"%d\\\"/>\", stats->count_3f);\n\tfprintf(dump, \"</FieldStatistic>\\n\");\n}", "\nstatic void ReorderAU(GF_List *sample_list, GF_AUContext *au)\n{\n\tu32 i;\n\tfor (i=0; i<gf_list_count(sample_list); i++) {\n\t\tGF_AUContext *ptr = gf_list_get(sample_list, i);\n\t\tif (\n\t\t /*time ordered*/\n\t\t (ptr->timing_sec > au->timing_sec)\n\t\t /*set bifs first*/\n\t\t || ((ptr->timing_sec == au->timing_sec) && (ptr->owner->streamType < au->owner->streamType))\n\t\t) {\n\t\t\tgf_list_insert(sample_list, au, i);\n\t\t\treturn;\n\t\t}\n\t}\n\tgf_list_add(sample_list, au);\n}", "void dump_isom_scene_stats(char *file, char *inName, Bool is_final_name, u32 stat_level)\n{\n\tGF_Err e;\n\tFILE *dump;\n\tBool close;\n\tu32 i, j, count;\n\tchar szBuf[1024];\n\tGF_SceneManager *ctx;\n\tGF_SceneLoader load;\n\tGF_StatManager *sm;\n\tGF_List *sample_list;\n\tGF_SceneGraph *scene_graph;", "\tdump = NULL;\n\tsm = NULL;\n\tsample_list = NULL;", "\tclose = 0;", "\tscene_graph = gf_sg_new();\n\tctx = gf_sm_new(scene_graph);\n\tmemset(&load, 0, sizeof(GF_SceneLoader));\n\tload.fileName = file;\n\tload.ctx = ctx;", "\tif (get_file_type_by_ext(file) == 1) {\n\t\tload.isom = gf_isom_open(file, GF_ISOM_OPEN_READ, NULL);\n\t\tif (!load.isom) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Cannot open file: %s\\n\", gf_error_to_string(gf_isom_last_error(NULL))));\n\t\t\tgf_sm_del(ctx);\n\t\t\tgf_sg_del(scene_graph);\n\t\t\treturn;\n\t\t}\n\t}", "\te = gf_sm_load_init(&load);\n\tif (!e) e = gf_sm_load_run(&load);\n\tgf_sm_load_done(&load);\n\tif (e<0) goto exit;", "\tif (inName) {\n\t\tstrcpy(szBuf, inName);\n\t\tif (!is_final_name) strcat(szBuf, \"_stat.xml\");\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s for dumping\\n\", szBuf));\n\t\t\treturn;\n\t\t}\n\t\tclose = 1;\n\t} else {\n\t\tdump = stdout;\n\t\tclose = 0;\n\t}", "\tfprintf(stderr, \"Analysing Scene\\n\");", "\tfprintf(dump, \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\\n\");\n\tfprintf(dump, \"<!-- Scene Graph Statistics Generated by MP4Box - GPAC \");\n\tif (! gf_sys_is_test_mode())\n\t\tfprintf(dump, \"%s \", gf_gpac_version());\n\tfprintf(dump, \"-->\\n\");", "\tfprintf(dump, \"<SceneStatistics file=\\\"%s\\\" DumpType=\\\"%s\\\">\\n\", gf_file_basename(file), (stat_level==1) ? \"full scene\" : ((stat_level==2) ? \"AccessUnit based\" : \"SceneGraph after each AU\"));", "\tsm = gf_sm_stats_new();", "\t/*stat level 1: complete scene stat*/\n\tif (stat_level == 1) {\n\t\te = gf_sm_stats_for_scene(sm, ctx);\n\t\tif (!e) dump_stats(dump, gf_sm_stats_get(sm) );\n\t\tgoto exit;\n\t}\n\t/*re_order all BIFS-AUs*/\n\tsample_list = gf_list_new();\n\t/*configure all systems streams we're dumping*/\n\tfor (i=0; i<gf_list_count(ctx->streams); i++) {\n\t\tGF_StreamContext *sc = gf_list_get(ctx->streams, i);\n\t\tif (sc->streamType != GF_STREAM_SCENE) continue;\n\t\tfor (j=0; j<gf_list_count(sc->AUs); j++) {\n\t\t\tGF_AUContext *au = gf_list_get(sc->AUs, j);\n\t\t\tReorderAU(sample_list, au);\n\t\t}\n\t}", "\tcount = gf_list_count(sample_list);\n\tfor (i=0; i<count; i++) {\n\t\tGF_AUContext *au = gf_list_get(sample_list, i);", "\t\tfor (j=0; j<gf_list_count(au->commands); j++) {\n\t\t\tGF_Command *com = gf_list_get(au->commands, j);\n\t\t\t/*stat level 2 - get command stats*/\n\t\t\tif (stat_level==2) {\n\t\t\t\te = gf_sm_stats_for_command(sm, com);\n\t\t\t\tif (e) goto exit;\n\t\t\t}\n\t\t\t/*stat level 3 - apply command*/\n\t\t\tif (stat_level==3) gf_sg_command_apply(scene_graph, com, 0);\n\t\t}\n\t\t/*stat level 3: get graph stat*/\n\t\tif (stat_level==3) {\n\t\t\te = gf_sm_stats_for_graph(sm, scene_graph);\n\t\t\tif (e) goto exit;\n\t\t}\n\t\tif (stat_level==2) {\n\t\t\tfprintf(dump, \"<AUStatistics StreamID=\\\"%d\\\" AUTime=\\\"\"LLD\"\\\">\\n\", au->owner->ESID, au->timing);\n\t\t} else {\n\t\t\tfprintf(dump, \"<GraphStatistics StreamID=\\\"%d\\\" AUTime=\\\"\"LLD\"\\\">\\n\", au->owner->ESID, au->timing);\n\t\t}\n\t\t/*dump stats*/\n\t\tdump_stats(dump, gf_sm_stats_get(sm) );\n\t\t/*reset stats*/\n\t\tgf_sm_stats_reset(sm);\n\t\tif (stat_level==2) {\n\t\t\tfprintf(dump, \"</AUStatistics>\\n\");\n\t\t} else {\n\t\t\tfprintf(dump, \"</GraphStatistics>\\n\");\n\t\t}", "\t\tgf_set_progress(\"Analysing AU\", i+1, count);\n\t}", "\nexit:\n\tif (sample_list) gf_list_del(sample_list);\n\tif (sm) gf_sm_stats_del(sm);\n\tgf_sm_del(ctx);\n\tgf_sg_del(scene_graph);\n\tif (load.isom) gf_isom_delete(load.isom);\n\tif (e) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Stats error: %s\\n\", gf_error_to_string(e)));\n\t} else {\n\t\tfprintf(dump, \"</SceneStatistics>\\n\");\n\t}\n\tif (dump && close) gf_fclose(dump);\n\tfprintf(stderr, \"done\\n\");\n}\n#endif /*GPAC_DISABLE_SCENE_STATS*/", "", "#ifndef GPAC_DISABLE_VRML", "static void PrintFixed(Fixed val, Bool add_space)\n{\n\tif (add_space) fprintf(stderr, \" \");\n\tif (val==FIX_MIN) fprintf(stderr, \"-I\");\n\telse if (val==FIX_MAX) fprintf(stderr, \"+I\");\n\telse fprintf(stderr, \"%g\", FIX2FLT(val));\n}", "static void PrintNodeSFField(u32 type, void *far_ptr)\n{\n\tif (!far_ptr) return;\n\tswitch (type) {\n\tcase GF_SG_VRML_SFBOOL:\n\t\tfprintf(stderr, \"%s\", (*(SFBool *)far_ptr) ? \"TRUE\" : \"FALSE\");\n\t\tbreak;\n\tcase GF_SG_VRML_SFINT32:\n\t\tfprintf(stderr, \"%d\", (*(SFInt32 *)far_ptr));\n\t\tbreak;\n\tcase GF_SG_VRML_SFFLOAT:\n\t\tPrintFixed((*(SFFloat *)far_ptr), 0);\n\t\tbreak;\n\tcase GF_SG_VRML_SFTIME:\n\t\tfprintf(stderr, \"%g\", (*(SFTime *)far_ptr));\n\t\tbreak;\n\tcase GF_SG_VRML_SFVEC2F:\n\t\tPrintFixed(((SFVec2f *)far_ptr)->x, 0);\n\t\tPrintFixed(((SFVec2f *)far_ptr)->y, 1);\n\t\tbreak;\n\tcase GF_SG_VRML_SFVEC3F:\n\t\tPrintFixed(((SFVec3f *)far_ptr)->x, 0);\n\t\tPrintFixed(((SFVec3f *)far_ptr)->y, 1);\n\t\tPrintFixed(((SFVec3f *)far_ptr)->z, 1);\n\t\tbreak;\n\tcase GF_SG_VRML_SFROTATION:\n\t\tPrintFixed(((SFRotation *)far_ptr)->x, 0);\n\t\tPrintFixed(((SFRotation *)far_ptr)->y, 1);\n\t\tPrintFixed(((SFRotation *)far_ptr)->z, 1);\n\t\tPrintFixed(((SFRotation *)far_ptr)->q, 1);\n\t\tbreak;\n\tcase GF_SG_VRML_SFCOLOR:\n\t\tPrintFixed(((SFColor *)far_ptr)->red, 0);\n\t\tPrintFixed(((SFColor *)far_ptr)->green, 1);\n\t\tPrintFixed(((SFColor *)far_ptr)->blue, 1);\n\t\tbreak;\n\tcase GF_SG_VRML_SFSTRING:\n\t\tif (((SFString*)far_ptr)->buffer)\n\t\t\tfprintf(stderr, \"\\\"%s\\\"\", ((SFString*)far_ptr)->buffer);\n\t\telse\n\t\t\tfprintf(stderr, \"NULL\");\n\t\tbreak;\n\t}\n}\n#endif", "#ifndef GPAC_DISABLE_VRML\nstatic void do_print_node(GF_Node *node, GF_SceneGraph *sg, const char *name, u32 graph_type, Bool is_nodefield, Bool do_cov)\n{\n\tu32 nbF, i;\n\tGF_FieldInfo f;\n#ifndef GPAC_DISABLE_BIFS\n\tu8 qt, at;\n\tFixed bmin, bmax;\n\tu32 nbBits;\n#endif /*GPAC_DISABLE_BIFS*/", "\tnbF = gf_node_get_field_count(node);", "\tif (is_nodefield) {\n\t\tchar szField[1024];\n\t\tu32 tfirst, tlast;\n\t\tif (gf_node_get_field_by_name(node, szField, &f) != GF_OK) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Field %s is not a member of node %s\\n\", szField, name));\n\t\t\treturn;\n\t\t}\n\t\tfprintf(stderr, \"Allowed nodes in %s.%s:\\n\", name, szField);\n\t\tif (graph_type==1) {\n\t\t\ttfirst = GF_NODE_RANGE_FIRST_X3D;\n\t\t\ttlast = GF_NODE_RANGE_LAST_X3D;\n\t\t} else {\n\t\t\ttfirst = GF_NODE_RANGE_FIRST_MPEG4;\n\t\t\ttlast = GF_NODE_RANGE_LAST_MPEG4;\n\t\t}\n\t\tfor (i=tfirst; i<tlast; i++) {\n\t\t\tGF_Node *tmp = gf_node_new(sg, i);\n\t\t\tgf_node_register(tmp, NULL);\n\t\t\tif (gf_node_in_table_by_tag(i, f.NDTtype)) {\n\t\t\t\tconst char *nname = gf_node_get_class_name(tmp);\n\t\t\t\tif (nname && strcmp(nname, \"Unknown Node\")) {\n\t\t\t\t\tfprintf(stderr, \"\\t%s\\n\", nname);\n\t\t\t\t}\n\t\t\t}\n\t\t\tgf_node_unregister(tmp, NULL);\n\t\t}\n\t\treturn;\n\t}\n\tif (do_cov) {\n\t\tu32 ndt;\n\t\tif (graph_type==0) {\n\t\t\tu32 all;\n\t\t\tgf_node_mpeg4_type_by_class_name(name);\n\t\t\tgf_bifs_get_child_table(node);\n\t\t\tall = gf_node_get_num_fields_in_mode(node, GF_SG_FIELD_CODING_ALL);\n\t\t\tfor (i=0; i<all; i++) {\n\t\t\t\tu32 res;\n\t\t\t\tgf_sg_script_get_field_index(node, i, GF_SG_FIELD_CODING_ALL, &res);\n\t\t\t}", "\t\t\tgf_node_get_num_fields_in_mode(node, GF_SG_FIELD_CODING_DEF);\n\t\t\tgf_node_get_num_fields_in_mode(node, GF_SG_FIELD_CODING_IN);\n\t\t\tgf_node_get_num_fields_in_mode(node, GF_SG_FIELD_CODING_OUT);\n\t\t\tgf_node_get_num_fields_in_mode(node, GF_SG_FIELD_CODING_DYN);\n\t\t}\n\t\telse if (graph_type==1) gf_node_x3d_type_by_class_name(name);\n\t\tfor (ndt=NDT_SFWorldNode; ndt<NDT_LAST; ndt++) {\n\t\t\tgf_node_in_table_by_tag(gf_node_get_tag(node), ndt);\n\t\t}\n\t}\n\tfprintf(stderr, \"%s {\\n\", name);", "\tfor (i=0; i<nbF; i++) {\n\t\tgf_node_get_field(node, i, &f);\n\t\tif (graph_type==2) {\n\t\t\tfprintf(stderr, \"\\t%s=\\\"...\\\"\\n\", f.name);\n\t\t\tcontinue;\n\t\t}", "\t\tfprintf(stderr, \"\\t%s %s %s\", gf_sg_vrml_get_event_type_name(f.eventType, 0), gf_sg_vrml_get_field_type_name(f.fieldType), f.name);\n\t\tif (f.fieldType==GF_SG_VRML_SFNODE) fprintf(stderr, \" NULL\");\n\t\telse if (f.fieldType==GF_SG_VRML_MFNODE) fprintf(stderr, \" []\");\n\t\telse if (gf_sg_vrml_is_sf_field(f.fieldType)) {\n\t\t\tfprintf(stderr, \" \");\n\t\t\tPrintNodeSFField(f.fieldType, f.far_ptr);\n\t\t} else {\n\t\t\tvoid *ptr;\n\t\t\tu32 j, sftype;\n\t\t\tGenMFField *mffield = (GenMFField *) f.far_ptr;\n\t\t\tfprintf(stderr, \" [\");\n\t\t\tsftype = gf_sg_vrml_get_sf_type(f.fieldType);\n\t\t\tfor (j=0; j<mffield->count; j++) {\n\t\t\t\tif (j) fprintf(stderr, \" \");\n\t\t\t\tgf_sg_vrml_mf_get_item(f.far_ptr, f.fieldType, &ptr, j);\n\t\t\t\tPrintNodeSFField(sftype, ptr);\n\t\t\t}\n\t\t\tfprintf(stderr, \"]\");\n\t\t}\n#ifndef GPAC_DISABLE_BIFS\n\t\tif (gf_bifs_get_aq_info(node, i, &qt, &at, &bmin, &bmax, &nbBits)) {\n\t\t\tif (qt) {\n\t\t\t\tfprintf(stderr, \" #QP=%d\", qt);\n\t\t\t\tif (qt==13) fprintf(stderr, \" NbBits=%d\", nbBits);\n\t\t\t\tif (bmin && bmax) {\n\t\t\t\t\tfprintf(stderr, \" Bounds=[\");\n\t\t\t\t\tPrintFixed(bmin, 0);\n\t\t\t\t\tfprintf(stderr, \",\");\n\t\t\t\t\tPrintFixed(bmax, 0);\n\t\t\t\t\tfprintf(stderr, \"]\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n#endif /*GPAC_DISABLE_BIFS*/\n\t\tfprintf(stderr, \"\\n\");", "\t\tif (do_cov) {\n\t\t\tgf_node_get_field_by_name(node, (char *) f.name, &f);\n\t\t}\n\t}\n\tfprintf(stderr, \"}\\n\\n\");", "}\n#endif", "\nu32 PrintNode(const char *name, u32 graph_type)\n{\n#ifdef GPAC_DISABLE_VRML\n\tM4_LOG(GF_LOG_ERROR, (\"VRML/MPEG-4/X3D scene graph is disabled in this build of GPAC\\n\"));\n\treturn 2;\n#else\n\tconst char *std_name;\n\tGF_Node *node;\n\tGF_SceneGraph *sg;\n\tu32 tag;\n#ifndef GPAC_DISABLE_BIFS\n#endif /*GPAC_DISABLE_BIFS*/\n\tBool is_nodefield = 0;", "\tchar *sep = strchr(name, '.');\n\tif (sep) {\n\t\tsep[0] = 0;\n\t\tis_nodefield = 1;\n\t}", "\tif (graph_type==1) {\n#ifndef GPAC_DISABLE_X3D\n\t\ttag = gf_node_x3d_type_by_class_name(name);\n\t\tstd_name = \"X3D\";\n#else\n\t\tM4_LOG(GF_LOG_ERROR, (\"X3D node printing is not supported (X3D support disabled)\\n\"));\n\t\treturn 2;\n#endif\n\t} else {\n\t\ttag = gf_node_mpeg4_type_by_class_name(name);\n\t\tstd_name = \"MPEG4\";\n\t}\n\tif (!tag) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Unknown %s node %s\\n\", std_name, name));\n\t\treturn 2;\n\t}", "\tsg = gf_sg_new();\n\tnode = gf_node_new(sg, tag);\n\tgf_node_register(node, NULL);\n\tname = gf_node_get_class_name(node);\n\tif (!node) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Node %s not supported in current built\\n\", name));\n\t\treturn 2;\n\t}\n\tdo_print_node(node, sg, name, graph_type, is_nodefield, GF_FALSE);", "\tgf_node_unregister(node, NULL);\n\tgf_sg_del(sg);\n#endif /*GPAC_DISABLE_VRML*/\n\treturn 1;\n}", "u32 PrintBuiltInNodes(char *arg_val, u32 dump_type)\n{\n#if !defined(GPAC_DISABLE_VRML) && !defined(GPAC_DISABLE_X3D) && !defined(GPAC_DISABLE_SVG)\n\tGF_SceneGraph *sg;\n\tu32 i, nb_in, nb_not_in, start_tag, end_tag;\n\tu32 graph_type;\n\tBool dump_nodes = ((dump_type==1) || (dump_type==3)) ? 1 : 0;", "\tif (dump_type==4) graph_type = 2;\n\telse if ((dump_type==2) || (dump_type==3)) graph_type = 1;\n\telse graph_type = 0;", "\tif (graph_type==1) {\n#if !defined(GPAC_DISABLE_VRML) && !defined(GPAC_DISABLE_X3D)\n\t\tstart_tag = GF_NODE_RANGE_FIRST_X3D;\n\t\tend_tag = TAG_LastImplementedX3D;\n#else\n\t\tM4_LOG(GF_LOG_ERROR, (\"X3D scene graph disabled in this build of GPAC\\n\"));\n\t\treturn 2;\n#endif\n\t} else if (graph_type==2) {\n#ifdef GPAC_DISABLE_SVG\n\t\tM4_LOG(GF_LOG_ERROR, (\"SVG scene graph disabled in this build of GPAC\\n\"));\n\t\treturn 2;\n#else\n\t\tstart_tag = GF_NODE_RANGE_FIRST_SVG;\n\t\tend_tag = GF_NODE_RANGE_LAST_SVG;\n#endif\n\t} else {\n#ifdef GPAC_DISABLE_VRML\n\t\tM4_LOG(GF_LOG_ERROR, (\"VRML/MPEG-4 scene graph disabled in this build of GPAC\\n\"));\n\t\treturn 2;\n#else\n\t\tstart_tag = GF_NODE_RANGE_FIRST_MPEG4;\n\t\tend_tag = TAG_LastImplementedMPEG4;\n#endif\n\t}\n\tnb_in = nb_not_in = 0;\n\tsg = gf_sg_new();", "\tif (graph_type==1) {\n\t\tfprintf(stderr, \"Available X3D nodes in this build (dumping):\\n\");\n\t} else if (graph_type==2) {\n\t\tfprintf(stderr, \"Available SVG nodes in this build (dumping and LASeR coding):\\n\");\n\t} else {\n\t\tfprintf(stderr, \"Available MPEG-4 nodes in this build (encoding/decoding/dumping):\\n\");\n\t}\n\tfor (i=start_tag; i<end_tag; i++) {\n\t\tGF_Node *node = gf_node_new(sg, i);\n\t\tif (node) {\n\t\t\tgf_node_register(node, NULL);\n\t\t\tif (dump_nodes) {\n\t\t\t\tdo_print_node(node, sg, gf_node_get_class_name(node), graph_type, GF_FALSE, GF_TRUE);\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \" %s\\n\", gf_node_get_class_name(node));\n\t\t\t}\n\t\t\tgf_node_unregister(node, NULL);\n\t\t\tnb_in++;\n\t\t} else {\n\t\t\tif (graph_type==2)\n\t\t\t\tbreak;\n\t\t\tnb_not_in++;\n\t\t}\n\t}\n\tgf_sg_del(sg);\n\tif (graph_type==2) {\n\t\tfprintf(stderr, \"\\n%d nodes supported\\n\", nb_in);\n\t} else {\n\t\tfprintf(stderr, \"\\n%d nodes supported - %d nodes not supported\\n\", nb_in, nb_not_in);\n\t}\n\t//coverage\n\tif (dump_nodes) {\n\t\tfor (i=GF_SG_VRML_SFBOOL; i<GF_SG_VRML_SCRIPT_FUNCTION; i++) {\n\t\t\tvoid *fp = gf_sg_vrml_field_pointer_new(i);\n\t\t\tif (fp) {\n\t\t\t\tif (i==GF_SG_VRML_SFSCRIPT) gf_free(fp);\n\t\t\t\telse gf_sg_vrml_field_pointer_del(fp, i);\n\t\t\t}\n\t\t}", "\t}\n#else\n\tM4_LOG(GF_LOG_ERROR, (\"No scene graph enabled in this MP4Box build\\n\"));\n#endif\n\treturn 1;\n}", "\nu32 PrintBuiltInBoxes(char *argval, u32 do_cov)\n{\n\tu32 i, count=gf_isom_get_num_supported_boxes();\n\t\n\tfprintf(stdout, \"<Boxes>\\n\");\n\t//index 0 is our internal unknown box handler\n\tfor (i=1; i<count; i++) {\n\t\tgf_isom_dump_supported_box(i, stdout);\n if (do_cov) {\n\t\t\tu32 btype = gf_isom_get_supported_box_type(i);\n GF_Box *b=gf_isom_box_new(btype);\n if (b) {\n GF_Box *c=NULL;\n gf_isom_clone_box(b, &c);\n if (c) gf_isom_box_del(c);\n gf_isom_box_del(b);\n }\n }\n\t}\n\tfprintf(stdout, \"</Boxes>\\n\");\n\treturn 1;\n}", "#if !defined(GPAC_DISABLE_ISOM_HINTING) && !defined(GPAC_DISABLE_ISOM_DUMP)", "void dump_isom_rtp(GF_ISOFile *file, char *inName, Bool is_final_name)\n{\n\tu32 i, j, size;\n\tFILE *dump;\n\tconst char *sdp;", "\tif (inName) {\n\t\tchar szBuf[1024];\n\t\tstrcpy(szBuf, inName);\n\t\tif (!is_final_name) strcat(szBuf, \"_rtp.xml\");\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s\\n\", szBuf));\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t}", "\tfprintf(dump, \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\\n\");\n\tfprintf(dump, \"<!-- MP4Box RTP trace -->\\n\");\n\tfprintf(dump, \"<RTPFile>\\n\");", "\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\tif (gf_isom_get_media_type(file, i+1) != GF_ISOM_MEDIA_HINT) continue;", "\t\tfprintf(dump, \"<RTPHintTrack trackID=\\\"%d\\\">\\n\", gf_isom_get_track_id(file, i+1));\n\t\tgf_isom_sdp_track_get(file, i+1, &sdp, &size);\n\t\tfprintf(dump, \"<SDPInfo>%s</SDPInfo>\", sdp);", "#ifndef GPAC_DISABLE_ISOM_HINTING\n\t\tfor (j=0; j<gf_isom_get_sample_count(file, i+1); j++) {\n\t\t\tgf_isom_dump_hint_sample(file, i+1, j+1, dump);\n\t\t}\n#endif\n\t\tfprintf(dump, \"</RTPHintTrack>\\n\");\n\t}\n\tfprintf(dump, \"</RTPFile>\\n\");\n\tif (inName) gf_fclose(dump);\n}\n#endif", "\nvoid dump_isom_timestamps(GF_ISOFile *file, char *inName, Bool is_final_name, u32 dump_mode)\n{\n\tu32 i, j, k, count;\n\tBool has_ctts_error, is_fragmented=GF_FALSE;\n\tFILE *dump;\n\tBool skip_offset = ((dump_mode==2) || (dump_mode==4)) ? GF_TRUE : GF_FALSE;\n\tBool check_ts = ((dump_mode==3) || (dump_mode==4)) ? GF_TRUE : GF_FALSE;\n\tstruct _ts_info {\n\t\tu64 dts;\n\t\ts64 cts;\n\t};\n\tstruct _ts_info *timings = NULL;\n\tu32 nb_timings=0, nb_timings_alloc = 0;", "\n\tif (inName) {\n\t\tchar szBuf[1024];\n\t\tstrcpy(szBuf, inName);\n\t\tif (!is_final_name) strcat(szBuf, \"_ts.txt\");\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s\\n\", szBuf));\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t}\n\tif (gf_isom_is_fragmented(file))\n\t\tis_fragmented = GF_TRUE;", "\thas_ctts_error = GF_FALSE;\n\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\ts64 cts_dts_shift = gf_isom_get_cts_to_dts_shift(file, i+1);\n\t\tu32 has_cts_offset = gf_isom_has_time_offset(file, i+1);", "\t\tfprintf(dump, \"#dumping track ID %d timing:\\n\", gf_isom_get_track_id(file, i + 1));\n\t\tfprintf(dump, \"Num\\tDTS\\tCTS\\tSize\\tRAP%s\\tisLeading\\tDependsOn\\tDependedOn\\tRedundant\\tRAP-SampleGroup\\tRoll-SampleGroup\\tRoll-Distance\", skip_offset ? \"\" : \"\\tOffset\");\n\t\tif (is_fragmented) {\n\t\t\tfprintf(dump, \"\\tfrag_start\");\n\t\t}\n\t\tfprintf(dump, \"\\n\");", "\n\t\tcount = gf_isom_get_sample_count(file, i+1);\n\t\tif (has_cts_offset && check_ts) {\n\t\t\tif (nb_timings_alloc<count) {\n\t\t\t\tnb_timings_alloc = count;\n\t\t\t\ttimings = gf_realloc(timings, sizeof (struct _ts_info) * count);\n\t\t\t}\n\t\t\tnb_timings = 0;\n\t\t}", "\t\tfor (j=0; j<count; j++) {\n\t\t\ts64 cts;\n\t\t\tu64 dts, offset;\n\t\t\tu32 isLeading, dependsOn, dependedOn, redundant;\n\t\t\tBool is_rap;\n\t\t\tGF_ISOSampleRollType roll_type;\n\t\t\ts32 roll_distance;\n\t\t\tu32 index;\n\t\t\tGF_ISOSample *samp = gf_isom_get_sample_info(file, i+1, j+1, &index, &offset);\n\t\t\tif (!samp) {\n\t\t\t\tfprintf(dump, \" SAMPLE #%d IN TRACK #%d NOT THERE !!!\\n\", j+1, i+1);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tgf_isom_get_sample_flags(file, i+1, j+1, &isLeading, &dependsOn, &dependedOn, &redundant);\n\t\t\tgf_isom_get_sample_rap_roll_info(file, i+1, j+1, &is_rap, &roll_type, &roll_distance);\n\t\t\tdts = samp->DTS;\n\t\t\tcts = dts + (s32) samp->CTS_Offset;\n\t\t\tfprintf(dump, \"Sample %d\\tDTS \"LLU\"\\tCTS \"LLD\"\\t%d\\t%d\", j+1, dts, cts, samp->dataLength, samp->IsRAP);", "\t\t\tif (!skip_offset)\n\t\t\t\tfprintf(dump, \"\\t\"LLU, offset);", "\t\t\tfprintf(dump, \"\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\", isLeading, dependsOn, dependedOn, redundant, is_rap, roll_type, roll_distance);", "\t\t\tif (cts< (s64) dts) {\n\t\t\t\tif (has_cts_offset==2) {\n\t\t\t\t\tif (cts_dts_shift && (cts+cts_dts_shift < (s64) dts)) {\n\t\t\t\t\t\tfprintf(dump, \" #NEGATIVE CTS OFFSET!!!\");\n\t\t\t\t\t\thas_ctts_error = 1;\n\t\t\t\t\t} else if (!cts_dts_shift) {\n\t\t\t\t\t\tfprintf(dump, \" #possible negative CTS offset (no cslg in file)\");\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(dump, \" #NEGATIVE CTS OFFSET!!!\");\n\t\t\t\t\thas_ctts_error = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (has_cts_offset && check_ts) {\n\t\t\t\tfor (k=0; k<nb_timings; k++) {", "\t\t\t\t\tif (timings[k].dts==dts) {\n\t\t\t\t\t\tfprintf(dump, \" #SAME DTS USED!!!\");\n\t\t\t\t\t\thas_ctts_error = 1;\n\t\t\t\t\t}\n\t\t\t\t\tif (timings[k].cts==cts) {\n\t\t\t\t\t\tfprintf(dump, \" #SAME CTS USED!!! \");\n\t\t\t\t\t\thas_ctts_error = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ttimings[nb_timings].dts = dts;\n\t\t\t\ttimings[nb_timings].cts = cts;\n\t\t\t\tnb_timings++;\n\t\t\t}", "\t\t\tgf_isom_sample_del(&samp);", "\t\t\tif (is_fragmented) {\n\t\t\t\tfprintf(dump, \"\\t%d\", gf_isom_sample_is_fragment_start(file, i+1, j+1, NULL) );\n\t\t\t}\n\t\t\tfprintf(dump, \"\\n\");\n\t\t\tgf_set_progress(\"Dumping track timing\", j+1, count);\n\t\t}\n\t\tfprintf(dump, \"\\n\\n\");\n\t\tgf_set_progress(\"Dumping track timing\", count, count);\n\t}\n\tif (timings) gf_free(timings);", "\tif (inName) gf_fclose(dump);\n\tif (has_ctts_error) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"\\tFile has CTTS table errors\\n\"));\n\t}\n}", "", "static u32 read_nal_size_hdr(u8 *ptr, u32 nalh_size)\n{\n\tu32 nal_size=0;\n\tu32 v = nalh_size;\n\twhile (v) {\n\t\tnal_size |= (u8) *ptr;\n\t\tptr++;\n\t\tv-=1;\n\t\tif (v) nal_size <<= 8;\n\t}\n\treturn nal_size;\n}", "#ifndef GPAC_DISABLE_AV_PARSERS\nvoid gf_inspect_dump_nalu(FILE *dump, u8 *ptr, u32 ptr_size, Bool is_svc, HEVCState *hevc, AVCState *avc, VVCState *vvc, u32 nalh_size, Bool dump_crc, Bool is_encrypted);\n#endif", "\nstatic void dump_isom_nal_ex(GF_ISOFile *file, GF_ISOTrackID trackID, FILE *dump, u32 dump_flags)\n{\n\tu32 i, j, count, nb_descs, track, nalh_size, timescale, cur_extract_mode;\n\ts32 countRef;\n\tBool is_adobe_protected = GF_FALSE;\n\tBool is_cenc_protected = GF_FALSE;\n\tBool is_hevc = GF_FALSE;\n\tBool is_vvc = GF_FALSE;\n#ifndef GPAC_DISABLE_AV_PARSERS\n\tAVCState *avc_state = NULL;\n\tHEVCState *hevc_state = NULL;\n\tVVCState *vvc_state = NULL;\n#endif\n\tGF_AVCConfig *avccfg, *svccfg;\n\tGF_HEVCConfig *hevccfg, *lhvccfg;\n\tGF_VVCConfig *vvccfg;\n\tGF_NALUFFParam *slc;\n\tBool has_svcc = GF_FALSE;", "\ttrack = gf_isom_get_track_by_id(file, trackID);", "\tcount = gf_isom_get_sample_count(file, track);", "\ttimescale = gf_isom_get_media_timescale(file, track);", "\tcur_extract_mode = gf_isom_get_nalu_extract_mode(file, track);", "\tnb_descs = gf_isom_get_sample_description_count(file, track);\n\tif (!nb_descs) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Error: Track #%d has no sample description so is likely not NALU-based!\\n\", trackID));\n\t\treturn;\n\t}", "\tfprintf(dump, \"<NALUTrack trackID=\\\"%d\\\" SampleCount=\\\"%d\\\" TimeScale=\\\"%d\\\">\\n\", trackID, count, timescale);", "#ifndef GPAC_DISABLE_AV_PARSERS", "#define DUMP_ARRAY(arr, name, loc, _is_svc)\\\n\tif (arr) {\\\n\t\tfprintf(dump, \" <%sArray location=\\\"%s\\\">\\n\", name, loc);\\\n\t\tfor (i=0; i<gf_list_count(arr); i++) {\\\n\t\t\tslc = gf_list_get(arr, i);\\\n\t\t\tfprintf(dump, \" <NALU size=\\\"%d\\\" \", slc->size);\\\n\t\t\tgf_inspect_dump_nalu(dump, (u8 *) slc->data, slc->size, _is_svc, is_hevc ? hevc_state : NULL, avc_state, is_vvc ? vvc_state : NULL, nalh_size, (dump_flags&1) ? GF_TRUE : GF_FALSE, GF_FALSE);\\\n\t\t}\\\n\t\tfprintf(dump, \" </%sArray>\\n\", name);\\\n\t}\\", "#else", "#define DUMP_ARRAY(arr, name, loc, _is_svc)\\\n\tif (arr) {\\\n\t\tfprintf(dump, \" <%sArray location=\\\"%s\\\">\\n\", name, loc);\\\n\t\tfor (i=0; i<gf_list_count(arr); i++) {\\\n\t\t\tslc = gf_list_get(arr, i);\\\n\t\t\tfprintf(dump, \" <NALU size=\\\"%d\\\" \", slc->size);\\\n\t\t\tfprintf(dump, \"/>\\n\");\\\n\t\t}\\\n\t\tfprintf(dump, \" </%sArray>\\n\", name);\\\n\t}\\", "#endif", "\tnalh_size = 0;", "\tfor (j=0; j<nb_descs; j++) {\n\t\tGF_AVCConfig *mvccfg;\n\t\tBool is_svc;", "\t\tavccfg = gf_isom_avc_config_get(file, track, j+1);\n\t\tsvccfg = gf_isom_svc_config_get(file, track, j+1);\n\t\tmvccfg = gf_isom_mvc_config_get(file, track, j+1);\n\t\thevccfg = gf_isom_hevc_config_get(file, track, j+1);\n\t\tlhvccfg = gf_isom_lhvc_config_get(file, track, j+1);\n\t\tvvccfg = gf_isom_vvc_config_get(file, track, j+1);", "\t\tis_svc = (svccfg!=NULL) ? 1:0;", "\t\tif (hevccfg || lhvccfg) {\n\t\t\tis_hevc = 1;\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\tGF_SAFEALLOC(hevc_state, HEVCState)\n#endif\n\t\t} else if (vvccfg) {\n\t\t\tis_vvc = 1;\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\tGF_SAFEALLOC(vvc_state, VVCState)\n#endif\n\t\t} else if (avccfg || svccfg || mvccfg) {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\tGF_SAFEALLOC(avc_state, AVCState)\n#endif\n\t\t}", "\n\t\t//for tile tracks the hvcC is stored in the 'tbas' track\n\t\tif (!hevccfg && gf_isom_get_reference_count(file, track, GF_ISOM_REF_TBAS)) {\n\t\t\tu32 tk = 0;\n\t\t\tgf_isom_get_reference(file, track, GF_ISOM_REF_TBAS, 1, &tk);\n\t\t\thevccfg = gf_isom_hevc_config_get(file, tk, 1);\n\t\t}", "\t\tfprintf(dump, \" <NALUConfig>\\n\");", "\t\tif (!avccfg && !svccfg && !hevccfg && !lhvccfg && !vvccfg) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Error: Track #%d is not NALU or OBU based!\\n\", trackID));\n\t\t\treturn;\n\t\t}", "\t\tif (avccfg) {\n\t\t\tnalh_size = avccfg->nal_unit_size;", "\t\t\tDUMP_ARRAY(avccfg->sequenceParameterSets, \"AVCSPS\", \"avcC\", is_svc);\n\t\t\tDUMP_ARRAY(avccfg->pictureParameterSets, \"AVCPPS\", \"avcC\", is_svc)\n\t\t\tDUMP_ARRAY(avccfg->sequenceParameterSetExtensions, \"AVCSPSEx\", \"avcC\", is_svc)\n\t\t}\n\t\tif (is_svc) {\n\t\t\tif (!nalh_size) nalh_size = svccfg->nal_unit_size;\n\t\t\tDUMP_ARRAY(svccfg->sequenceParameterSets, \"SVCSPS\", \"svcC\", is_svc)\n\t\t\tDUMP_ARRAY(svccfg->pictureParameterSets, \"SVCPPS\", \"svcC\", is_svc)\n\t\t}\n\t\tif (mvccfg) {\n\t\t\tif (!nalh_size) nalh_size = mvccfg->nal_unit_size;\n\t\t\tDUMP_ARRAY(mvccfg->sequenceParameterSets, \"SVCSPS\", \"mvcC\", is_svc)\n\t\t\tDUMP_ARRAY(mvccfg->pictureParameterSets, \"SVCPPS\", \"mvcC\", is_svc)\n\t\t}\n\t\tif (hevccfg) {\n\t\t\tu32 idx;\n\t\t\tnalh_size = hevccfg->nal_unit_size;\n\t\t\tfor (idx=0; idx<gf_list_count(hevccfg->param_array); idx++) {\n\t\t\t\tGF_NALUFFParamArray *ar = gf_list_get(hevccfg->param_array, idx);\n\t\t\t\tif (ar->type==GF_HEVC_NALU_SEQ_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"HEVCSPS\", \"hvcC\", 0)\n\t\t\t\t} else if (ar->type==GF_HEVC_NALU_PIC_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"HEVCPPS\", \"hvcC\", 0)\n\t\t\t\t} else if (ar->type==GF_HEVC_NALU_VID_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"HEVCVPS\", \"hvcC\", 0)\n\t\t\t\t} else {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"HEVCUnknownPS\", \"hvcC\", 0)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (vvccfg) {\n\t\t\tu32 idx;\n\t\t\tnalh_size = vvccfg->nal_unit_size;\n\t\t\tfor (idx=0; idx<gf_list_count(vvccfg->param_array); idx++) {\n\t\t\t\tGF_NALUFFParamArray *ar = gf_list_get(vvccfg->param_array, idx);\n\t\t\t\tif (ar->type==GF_VVC_NALU_SEQ_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"VVCSPS\", \"vvcC\", 0)\n\t\t\t\t} else if (ar->type==GF_VVC_NALU_PIC_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"VVCPPS\", \"vvcC\", 0)\n\t\t\t\t} else if (ar->type==GF_VVC_NALU_VID_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"VVCVPS\", \"vvcC\", 0)\n\t\t\t\t} else {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"VVCUnknownPS\", \"vvcC\", 0)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (lhvccfg) {\n\t\t\tu32 idx;\n\t\t\tnalh_size = lhvccfg->nal_unit_size;\n\t\t\tfor (idx=0; idx<gf_list_count(lhvccfg->param_array); idx++) {\n\t\t\t\tGF_NALUFFParamArray *ar = gf_list_get(lhvccfg->param_array, idx);\n\t\t\t\tif (ar->type==GF_HEVC_NALU_SEQ_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"HEVCSPS\", \"lhcC\", 0)\n\t\t\t\t} else if (ar->type==GF_HEVC_NALU_PIC_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"HEVCPPS\", \"lhcC\", 0)\n\t\t\t\t} else if (ar->type==GF_HEVC_NALU_VID_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"HEVCVPS\", \"lhcC\", 0)\n\t\t\t\t} else {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"HEVCUnknownPS\", \"lhcC\", 0)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfprintf(dump, \" </NALUConfig>\\n\");", "\t\tif (avccfg) gf_odf_avc_cfg_del(avccfg);\n\t\tif (svccfg) {\n\t\t\tgf_odf_avc_cfg_del(svccfg);\n\t\t\thas_svcc = GF_TRUE;\n\t\t}\n\t\tif (hevccfg) gf_odf_hevc_cfg_del(hevccfg);\n\t\tif (vvccfg) gf_odf_vvc_cfg_del(vvccfg);\n\t\tif (lhvccfg) gf_odf_hevc_cfg_del(lhvccfg);\n\t}", "\t/*fixme: for dumping encrypted track: we don't have neither avccfg nor svccfg*/\n\tif (!nalh_size) nalh_size = 4;", "\t/*for testing dependency*/\n\tcountRef = gf_isom_get_reference_count(file, track, GF_ISOM_REF_SCAL);\n\tif (countRef > 0)\n\t{\n\t\tGF_ISOTrackID refTrackID;\n\t\tfprintf(dump, \" <SCALReferences>\\n\");\n\t\tfor (i = 1; i <= (u32) countRef; i++)\n\t\t{\n\t\t\tgf_isom_get_reference_ID(file, track, GF_ISOM_REF_SCAL, i, &refTrackID);\n\t\t\tfprintf(dump, \" <SCALReference number=\\\"%d\\\" refTrackID=\\\"%d\\\"/>\\n\", i, refTrackID);\n\t\t}", "\t\tfprintf(dump, \" </SCALReferences>\\n\");\n\t}", "\tfprintf(dump, \" <NALUSamples>\\n\");\n\tgf_isom_set_nalu_extract_mode(file, track, GF_ISOM_NALU_EXTRACT_INSPECT);\n\tis_adobe_protected = gf_isom_is_adobe_protection_media(file, track, 1);\n\tis_cenc_protected = gf_isom_is_cenc_media(file, track, 1);\n\tfor (i=0; i<count; i++) {\n\t\tu64 dts, cts;\n\t\tBool is_rap;\n\t\tu32 size, nal_size, idx, di;\n\t\tu8 *ptr;\n\t\tGF_ISOSample *samp = gf_isom_get_sample(file, track, i+1, &di);\n\t\tif (!samp) {\n\t\t\tfprintf(dump, \"<!-- Unable to fetch sample %d -->\\n\", i+1);\n\t\t\tcontinue;\n\t\t}\n\t\tdts = samp->DTS;\n\t\tcts = dts + (s32) samp->CTS_Offset;\n\t\tis_rap = samp->IsRAP;\n\t\tif (!is_rap) gf_isom_get_sample_rap_roll_info(file, track, i+1, &is_rap, NULL, NULL);", "\t\tif (dump_flags&2) {\n\t\t\tfprintf(dump, \" <Sample size=\\\"%d\\\" RAP=\\\"%d\\\"\", samp->dataLength, is_rap);\n\t\t} else {\n\t\t\tfprintf(dump, \" <Sample DTS=\\\"\"LLD\"\\\" CTS=\\\"\"LLD\"\\\" size=\\\"%d\\\" RAP=\\\"%d\\\"\", dts, cts, samp->dataLength, is_rap);\n\t\t}\n\t\tif (nb_descs>1)\n\t\t\tfprintf(dump, \" sample_description=\\\"%d\\\"\", di);\n\t\tfprintf(dump, \" >\\n\");", "\t\tif (cts<dts) fprintf(dump, \"<!-- NEGATIVE CTS OFFSET! -->\\n\");", "\t\tidx = 1;\n\t\tptr = samp->data;\n\t\tsize = samp->dataLength;\n\t\tif (is_adobe_protected) {\n\t\t\tu8 encrypted_au = ptr[0];\n\t\t\tif (encrypted_au) {\n\t\t\t\tfprintf(dump, \" <!-- Sample number %d is an Adobe's protected sample: can not be dumped -->\\n\", i+1);\n\t\t\t\tfprintf(dump, \" </Sample>\\n\\n\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tptr++;\n\t\t\t\tsize--;\n\t\t\t}\n\t\t}\n\t\twhile (size) {\n\t\t\tnal_size = read_nal_size_hdr(ptr, nalh_size);\n\t\t\tptr += nalh_size;", "\t\t\tif (nal_size >= UINT_MAX-nalh_size || nalh_size + nal_size > size) {\n\t\t\t\tfprintf(dump, \" <!-- NALU number %d is corrupted: size is %d but only %d remains -->\\n\", idx, nal_size, size);\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\tfprintf(dump, \" <NALU size=\\\"%d\\\" \", nal_size);\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\tBool is_encrypted = 0;\n\t\t\t\tif (is_cenc_protected) {\n\t\t\t\t\tGF_Err e = gf_isom_get_sample_cenc_info(file, track, i + 1, &is_encrypted, NULL, NULL, NULL, NULL);\n\t\t\t\t\tif (e != GF_OK) {\n\t\t\t\t\t\tfprintf(dump, \"dump_msg=\\\"Error %s while fetching encryption info for sample, assuming sample is encrypted\\\" \", gf_error_to_string(e) );\n\t\t\t\t\t\tis_encrypted = GF_TRUE;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgf_inspect_dump_nalu(dump, ptr, nal_size, has_svcc ? 1 : 0, hevc_state, avc_state, vvc_state, nalh_size, dump_flags, is_encrypted);\n#else\n\t\t\t\tfprintf(dump, \"/>\\n\");\n#endif\n\t\t\t}\n\t\t\tidx++;\n\t\t\tptr+=nal_size;\n\t\t\tsize -= nal_size + nalh_size;\n\t\t}\n\t\tfprintf(dump, \" </Sample>\\n\");\n\t\tgf_isom_sample_del(&samp);", "\t\tfprintf(dump, \"\\n\");\n\t\tgf_set_progress(\"Analysing Track NALUs\", i+1, count);\n\t}\n\tfprintf(dump, \" </NALUSamples>\\n\");\n\tfprintf(dump, \"</NALUTrack>\\n\");", "\tgf_isom_set_nalu_extract_mode(file, track, cur_extract_mode);", "#ifndef GPAC_DISABLE_AV_PARSERS\n\tif (hevc_state) gf_free(hevc_state);\n\tif (vvc_state) gf_free(vvc_state);\n\tif (avc_state) gf_free(avc_state);\n#endif\n}", "static void dump_isom_obu(GF_ISOFile *file, GF_ISOTrackID trackID, FILE *dump, Bool dump_crc);\nstatic void dump_qt_prores(GF_ISOFile *file, GF_ISOTrackID trackID, FILE *dump, Bool dump_crc);", "void dump_isom_nal(GF_ISOFile *file, GF_ISOTrackID trackID, char *inName, Bool is_final_name, u32 dump_flags)\n{\n\tBool is_av1 = GF_FALSE;\n\tBool is_prores = GF_FALSE;", "\tFILE *dump;\n\tif (inName) {\n\t\tGF_ESD* esd;\n\t\tchar szBuf[GF_MAX_PATH];", "\t\tstrcpy(szBuf, inName);", "\t\tu32 track = gf_isom_get_track_by_id(file, trackID);\n\t\tesd = gf_isom_get_esd(file, track, 1);", "\t\tif (!esd || !esd->decoderConfig) {\n\t\t\tswitch (gf_isom_get_media_subtype(file, track, 1)) {\n\t\t\tcase GF_ISOM_SUBTYPE_AV01:\n\t\t\t\tis_av1 = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tcase GF_QT_SUBTYPE_APCH:\n\t\t\tcase GF_QT_SUBTYPE_APCO:\n\t\t\tcase GF_QT_SUBTYPE_APCN:\n\t\t\tcase GF_QT_SUBTYPE_APCS:\n\t\t\tcase GF_QT_SUBTYPE_AP4X:\n\t\t\tcase GF_QT_SUBTYPE_AP4H:\n\t\t\t\tis_prores = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse if (esd->decoderConfig->objectTypeIndication == GF_CODECID_AV1) {\n\t\t\tis_av1 = GF_TRUE;\n\t\t}\n\t\tif (esd) gf_odf_desc_del((GF_Descriptor*)esd);", "\t\tif (!is_final_name) sprintf(szBuf, \"%s_%d_%s.xml\", inName, trackID, is_av1 ? \"obu\" : \"nalu\");\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s for dumping\\n\", szBuf));\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t}", "\tif (is_av1)\n\t\tdump_isom_obu(file, trackID, dump, dump_flags);\n\telse if (is_prores)\n\t\tdump_qt_prores(file, trackID, dump, dump_flags);\n\telse\n\t\tdump_isom_nal_ex(file, trackID, dump, dump_flags);", "\tif (inName) gf_fclose(dump);\n}", "#ifndef GPAC_DISABLE_AV_PARSERS\nvoid gf_inspect_dump_obu(FILE *dump, AV1State *av1, u8 *obu, u64 obu_length, ObuType obu_type, u64 obu_size, u32 hdr_size, Bool dump_crc);\n#endif", "static void dump_isom_obu(GF_ISOFile *file, GF_ISOTrackID trackID, FILE *dump, Bool dump_crc)\n{\n#ifndef GPAC_DISABLE_AV_PARSERS\n\tu32 i, count, track, timescale;\n\tAV1State av1;\n\tObuType obu_type;\n\tu64 obu_size;\n\tu32 hdr_size;\n\tGF_BitStream *bs;\n\tu32 idx;", "\ttrack = gf_isom_get_track_by_id(file, trackID);", "\tgf_av1_init_state(&av1);\n\tav1.config = gf_isom_av1_config_get(file, track, 1);\n\tif (!av1.config) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Error: Track #%d is not AV1!\\n\", trackID));\n\t\treturn;\n\t}", "\tcount = gf_isom_get_sample_count(file, track);\n\ttimescale = gf_isom_get_media_timescale(file, track);", "\tfprintf(dump, \"<OBUTrack trackID=\\\"%d\\\" SampleCount=\\\"%d\\\" TimeScale=\\\"%d\\\">\\n\", trackID, count, timescale);", "\tfprintf(dump, \" <OBUConfig>\\n\");", "\tfor (i=0; i<gf_list_count(av1.config->obu_array); i++) {\n\t\tGF_AV1_OBUArrayEntry *obu = gf_list_get(av1.config->obu_array, i);\n\t\tbs = gf_bs_new(obu->obu, (u32) obu->obu_length, GF_BITSTREAM_READ);\n\t\tgf_av1_parse_obu(bs, &obu_type, &obu_size, &hdr_size, &av1);\n\t\tgf_inspect_dump_obu(dump, &av1, obu->obu, obu->obu_length, obu_type, obu_size, hdr_size, dump_crc);\n\t\tgf_bs_del(bs);\n\t}\n\tfprintf(dump, \" </OBUConfig>\\n\");", "\tfprintf(dump, \" <OBUSamples>\\n\");", "\tfor (i=0; i<count; i++) {\n\t\tu64 dts, cts;\n\t\tu32 size;\n\t\tu8 *ptr;\n\t\tGF_ISOSample *samp = gf_isom_get_sample(file, track, i+1, NULL);\n\t\tif (!samp) {\n\t\t\tfprintf(dump, \"<!-- Unable to fetch sample %d -->\\n\", i+1);\n\t\t\tcontinue;\n\t\t}\n\t\tdts = samp->DTS;\n\t\tcts = dts + (s32) samp->CTS_Offset;", "\t\tfprintf(dump, \" <Sample number=\\\"%d\\\" DTS=\\\"\"LLD\"\\\" CTS=\\\"\"LLD\"\\\" size=\\\"%d\\\" RAP=\\\"%d\\\" >\\n\", i+1, dts, cts, samp->dataLength, samp->IsRAP);\n\t\tif (cts<dts) fprintf(dump, \"<!-- NEGATIVE CTS OFFSET! -->\\n\");", "\t\tidx = 1;\n\t\tptr = samp->data;\n\t\tsize = samp->dataLength;", "\t\tbs = gf_bs_new(ptr, size, GF_BITSTREAM_READ);\n\t\twhile (size) {\n\t\t\tgf_av1_parse_obu(bs, &obu_type, &obu_size, &hdr_size, &av1);\n\t\t\tif (obu_size > size) {\n\t\t\t\tfprintf(dump, \" <!-- OBU number %d is corrupted: size is %d but only %d remains -->\\n\", idx, (u32) obu_size, size);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tgf_inspect_dump_obu(dump, &av1, ptr, obu_size, obu_type, obu_size, hdr_size, dump_crc);\n\t\t\tptr += obu_size;\n\t\t\tsize -= (u32)obu_size;\n\t\t\tidx++;\n\t\t}\n\t\tgf_bs_del(bs);\n\t\tfprintf(dump, \" </Sample>\\n\");\n\t\tgf_isom_sample_del(&samp);", "\t\tfprintf(dump, \"\\n\");\n\t\tgf_set_progress(\"Analysing Track OBUs\", i+1, count);\n\t}\n\tfprintf(dump, \" </OBUSamples>\\n\");\n\tfprintf(dump, \"</OBUTrack>\\n\");", "\tif (av1.config) gf_odf_av1_cfg_del(av1.config);\n\tgf_av1_reset_state(&av1, GF_TRUE);\n#endif\n}", "static void dump_qt_prores(GF_ISOFile *file, u32 trackID, FILE *dump, Bool dump_crc)\n{\n#ifndef GPAC_DISABLE_AV_PARSERS\n\tu32 i, count, track, timescale;", "\ttrack = gf_isom_get_track_by_id(file, trackID);", "\tcount = gf_isom_get_sample_count(file, track);\n\ttimescale = gf_isom_get_media_timescale(file, track);", "\tfprintf(dump, \"<ProResTrack trackID=\\\"%d\\\" SampleCount=\\\"%d\\\" TimeScale=\\\"%d\\\">\\n\", trackID, count, timescale);", "\tfor (i=0; i<count; i++) {\n\t\tvoid gf_inspect_dump_prores(FILE *dump, u8 *ptr, u64 frame_size, Bool dump_crc);\n\t\tu64 dts, cts;\n\t\tGF_ISOSample *samp = gf_isom_get_sample(file, track, i+1, NULL);\n\t\tif (!samp) {\n\t\t\tfprintf(dump, \"<!-- Unable to fetch sample %d -->\\n\", i+1);\n\t\t\tcontinue;\n\t\t}\n\t\tdts = samp->DTS;\n\t\tcts = dts + (s32) samp->CTS_Offset;", "\t\tif (cts!=dts) fprintf(dump, \"<!-- Wrong timing info (CTS \"LLD\" vs DTS \"LLD\") ! -->\\n\", cts, dts);\n\t\tif (!samp->IsRAP) fprintf(dump, \"<!-- Wrong sync sample info, sample is not SAP1 ! -->\\n\");", "\t\tfprintf(dump, \" <Sample number=\\\"%d\\\" CTS=\\\"\"LLD\"\\\" size=\\\"%d\\\">\\n\", i+1, cts, samp->dataLength);", "\t\tgf_inspect_dump_prores(dump, samp->data, samp->dataLength, dump_crc);\n\t\tfprintf(dump, \" </Sample>\\n\");", "\t\tgf_isom_sample_del(&samp);", "\t\tfprintf(dump, \"\\n\");\n\t\tgf_set_progress(\"Analysing ProRes Track\", i+1, count);\n\t}\n\tfprintf(dump, \"</ProResTrack>\\n\");\n#endif\n}", "void dump_isom_saps(GF_ISOFile *file, GF_ISOTrackID trackID, u32 dump_saps_mode, char *inName, Bool is_final_name)\n{\n\tFILE *dump;\n\tu32 i, count;\n\ts64 media_offset=0;\n\tu32 track = gf_isom_get_track_by_id(file, trackID);\n\tif (inName) {\n\t\tchar szBuf[GF_MAX_PATH];\n\t\tstrcpy(szBuf, inName);", "\t\tif (!is_final_name) sprintf(szBuf, \"%s_%d_cues.xml\", inName, trackID);\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s for dumping\\n\", szBuf));\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t}", "\tfprintf(dump, \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n\tfprintf(dump, \"<DASHCues xmlns=\\\"urn:gpac:dash:schema:cues:2018\\\">\\n\");\n\tfprintf(dump, \"<Stream id=\\\"%d\\\" timescale=\\\"%d\\\"\", trackID, gf_isom_get_media_timescale(file, track) );\n\tif (dump_saps_mode==4) {\n\t\tfprintf(dump, \" mode=\\\"edit\\\"\");\n\t\tgf_isom_get_edit_list_type(file, track, &media_offset);\n\t}\n\tfprintf(dump, \">\\n\");", "\tcount = gf_isom_get_sample_count(file, track);\n\tfor (i=0; i<count; i++) {\n\t\ts64 cts, dts;\n\t\tu32 di;\n\t\tBool traf_start = 0;\n\t\tu32 sap_type = 0;\n\t\tu64 doffset;\n\t\t\n\t\tGF_ISOSample *samp = gf_isom_get_sample_info(file, track, i+1, &di, &doffset);", "\t\ttraf_start = gf_isom_sample_is_fragment_start(file, track, i+1, NULL);", "\t\tsap_type = samp->IsRAP;\n\t\tif (!sap_type) {\n\t\t\tBool is_rap;\n\t\t\tGF_ISOSampleRollType roll_type;\n\t\t\ts32 roll_dist;\n\t\t\tgf_isom_get_sample_rap_roll_info(file, track, i+1, &is_rap, &roll_type, &roll_dist);\n\t\t\tif (roll_type) sap_type = SAP_TYPE_4;\n\t\t\telse if (is_rap) sap_type = SAP_TYPE_3;\n\t\t}", "\t\tif (!sap_type) {\n\t\t\tgf_isom_sample_del(&samp);\n\t\t\tcontinue;\n\t\t}", "\t\tdts = cts = samp->DTS;\n\t\tcts += samp->CTS_Offset;\n\t\tfprintf(dump, \"<Cue sap=\\\"%d\\\"\", sap_type);\n\t\tif (dump_saps_mode==4) {\n\t\t\tcts += media_offset;\n\t\t\tfprintf(dump, \" cts=\\\"\"LLD\"\\\"\", cts);\n\t\t} else {\n\t\t\tif (!dump_saps_mode || (dump_saps_mode==1)) fprintf(dump, \" sample=\\\"%d\\\"\", i+1);\n\t\t\tif (!dump_saps_mode || (dump_saps_mode==2)) fprintf(dump, \" cts=\\\"\"LLD\"\\\"\", cts);\n\t\t\tif (!dump_saps_mode || (dump_saps_mode==3)) fprintf(dump, \" dts=\\\"\"LLD\"\\\"\", dts);\n\t\t}", "\t\tif (traf_start)\n\t\t\tfprintf(dump, \" wasFragStart=\\\"yes\\\"\");", "\t\tfprintf(dump, \"/>\\n\");", "\t\tgf_isom_sample_del(&samp);\n\t}\n\tfprintf(dump, \"</Stream>\\n\");\n\tfprintf(dump, \"</DASHCues>\\n\");\n\tif (inName) gf_fclose(dump);\n}", "#ifndef GPAC_DISABLE_ISOM_DUMP", "void dump_isom_ismacryp(GF_ISOFile *file, char *inName, Bool is_final_name)\n{\n\tu32 i, j;\n\tFILE *dump;", "\tif (inName) {\n\t\tchar szBuf[1024];\n\t\tstrcpy(szBuf, inName);\n\t\tif (!is_final_name) strcat(szBuf, \"_ismacryp.xml\");\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s for dumping\\n\", szBuf));\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t}", "\tfprintf(dump, \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\\n\");\n\tfprintf(dump, \"<!-- MP4Box ISMACryp trace -->\\n\");\n\tfprintf(dump, \"<ISMACrypFile>\\n\");", "\n\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\tif (gf_isom_get_media_subtype(file, i+1, 1) != GF_ISOM_SUBTYPE_MPEG4_CRYP) continue;", "\t\tgf_isom_dump_ismacryp_protection(file, i+1, dump);", "\t\tfprintf(dump, \"<ISMACrypTrack trackID=\\\"%d\\\">\\n\", gf_isom_get_track_id(file, i+1));\n\t\tfor (j=0; j<gf_isom_get_sample_count(file, i+1); j++) {\n\t\t\tgf_isom_dump_ismacryp_sample(file, i+1, j+1, dump);\n\t\t}\n\t\tfprintf(dump, \"</ISMACrypTrack >\\n\");\n\t}\n\tfprintf(dump, \"</ISMACrypFile>\\n\");\n\tif (inName) gf_fclose(dump);\n}", "\nvoid dump_isom_timed_text(GF_ISOFile *file, GF_ISOTrackID trackID, char *inName, Bool is_final_name, Bool is_convert, GF_TextDumpType dump_type)\n{\n\tFILE *dump;\n\tGF_Err e;\n\tu32 track;", "\ttrack = gf_isom_get_track_by_id(file, trackID);\n\tif (!track) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Cannot find track ID %d\\n\", trackID));\n\t\treturn;\n\t}", "\tswitch (gf_isom_get_media_type(file, track)) {\n\tcase GF_ISOM_MEDIA_TEXT:\n\tcase GF_ISOM_MEDIA_SUBT:\n\t\tbreak;\n\tdefault:\n\t\tM4_LOG(GF_LOG_ERROR, (\"Track ID %d is not a 3GPP text track\\n\", trackID));\n\t\treturn;\n\t}", "\tif (inName) {\n\t\tchar szBuf[1024];\n\t\tchar *ext;\n\t\text = ((dump_type==GF_TEXTDUMPTYPE_SVG) ? \"svg\" : ((dump_type==GF_TEXTDUMPTYPE_SRT) ? \"srt\" : \"ttxt\"));\n\t\tif (is_final_name) {\n\t\t\tstrcpy(szBuf, inName) ;\n\t\t} else if (is_convert)\n\t\t\tsprintf(szBuf, \"%s.%s\", inName, ext) ;\n\t\telse\n\t\t\tsprintf(szBuf, \"%s_%d_text.%s\", inName, trackID, ext);", "\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s for dumping\\n\", szBuf));\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t}\n\te = gf_isom_text_dump(file, track, dump, dump_type);\n\tif (inName) gf_fclose(dump);", "\tif (e) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Conversion failed (%s)\\n\", gf_error_to_string(e)));\n\t} else {\n\t\tfprintf(stderr, \"Conversion done\\n\");\n\t}\n}", "#endif /*GPAC_DISABLE_ISOM_DUMP*/", "#ifndef GPAC_DISABLE_ISOM_HINTING", "void dump_isom_sdp(GF_ISOFile *file, char *inName, Bool is_final_name)\n{\n\tconst char *sdp;\n\tu32 size, i;\n\tFILE *dump;", "\tif (inName) {\n\t\tchar szBuf[1024];\n\t\tstrcpy(szBuf, inName);\n\t\tif (!is_final_name) {\n\t\t\tchar *ext = strchr(szBuf, '.');\n\t\t\tif (ext) ext[0] = 0;\n\t\t\tstrcat(szBuf, \"_sdp.txt\");\n\t\t}\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s for dumping\\n\", szBuf));\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t\tfprintf(dump, \"# File SDP content \\n\\n\");\n\t}\n\t//get the movie SDP\n\tgf_isom_sdp_get(file, &sdp, &size);\n\tif (sdp && size)\n\t\tfprintf(dump, \"%s\", sdp);\n\tfprintf(dump, \"\\r\\n\");", "\t//then tracks\n\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\tif (gf_isom_get_media_type(file, i+1) != GF_ISOM_MEDIA_HINT) continue;\n\t\tgf_isom_sdp_track_get(file, i+1, &sdp, &size);\n\t\tfprintf(dump, \"%s\", sdp);\n\t}\n\tfprintf(dump, \"\\n\\n\");\n\tif (inName) gf_fclose(dump);\n}", "#endif", "\n#ifndef GPAC_DISABLE_ISOM_DUMP", "GF_Err dump_isom_xml(GF_ISOFile *file, char *inName, Bool is_final_name, Bool do_track_dump, Bool merge_vtt_cues, Bool skip_init, Bool skip_samples)\n{\n\tGF_Err e;\n\tFILE *dump = stdout;\n\tBool do_close=GF_FALSE;\n\tif (!file) return GF_ISOM_INVALID_FILE;", "\tif (inName) {\n\t\tchar szBuf[1024];\n\t\tstrcpy(szBuf, inName);\n\t\tif (!is_final_name) {\n\t\t\tstrcat(szBuf, do_track_dump ? \"_dump.xml\" : \"_info.xml\");\n\t\t}\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s\\n\", szBuf));\n\t\t\treturn GF_IO_ERR;\n\t\t}\n\t\tdo_close=GF_TRUE;\n\t}", "\tfprintf(dump, \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n\tif (do_track_dump) {\n\t\tfprintf(dump, \"<ISOBaseMediaFileTrace>\\n\");\n\t}\n\te = gf_isom_dump(file, dump, skip_init, skip_samples);\n\tif (e) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Error dumping ISO structure\\n\"));\n\t}", "\tif (do_track_dump) {\n#ifndef GPAC_DISABLE_MEDIA_EXPORT\n\t\tu32 i;\n\t\t//because of dump mode we need to reopen in regular read mode to avoid mem leaks\n\t\tGF_ISOFile *the_file = gf_isom_open(gf_isom_get_filename(file), GF_ISOM_OPEN_READ, NULL);\n\t\tu32 tcount = gf_isom_get_track_count(the_file);\n\t\tfprintf(dump, \"<Tracks>\\n\");", "\t\tfor (i=0; i<tcount; i++) {\n\t\t\tGF_MediaExporter dumper;\n\t\t\tGF_ISOTrackID trackID = gf_isom_get_track_id(the_file, i+1);\n\t\t\tu32 mtype = gf_isom_get_media_type(the_file, i+1);\n\t\t\tu32 msubtype = gf_isom_get_media_subtype(the_file, i+1, 1);\n\t\t\tBool fmt_handled = GF_FALSE;\n\t\t\tmemset(&dumper, 0, sizeof(GF_MediaExporter));\n\t\t\tdumper.file = the_file;\n\t\t\tdumper.trackID = trackID;\n\t\t\tdumper.dump_file = dump;", "\t\t\tif (mtype == GF_ISOM_MEDIA_HINT) {\n#ifndef GPAC_DISABLE_ISOM_HINTING\n\t\t\t\tchar *name=NULL;\n\t\t\t\tif (msubtype==GF_ISOM_SUBTYPE_RTP) name = \"RTPHintTrack\";\n\t\t\t\telse if (msubtype==GF_ISOM_SUBTYPE_SRTP) name = \"SRTPHintTrack\";\n\t\t\t\telse if (msubtype==GF_ISOM_SUBTYPE_RRTP) name = \"RTPReceptionHintTrack\";\n\t\t\t\telse if (msubtype==GF_ISOM_SUBTYPE_RTCP) name = \"RTCPReceptionHintTrack\";\n\t\t\t\telse if (msubtype==GF_ISOM_SUBTYPE_FLUTE) name = \"FLUTEReceptionHintTrack\";\n\t\t\t\telse name = \"UnknownHintTrack\";", "\t\t\t\tfprintf(dump, \"<%s trackID=\\\"%d\\\">\\n\", name, trackID);", "#ifndef GPAC_DISABLE_ISOM_HINTING\n\t\t\t\tu32 j, scount=gf_isom_get_sample_count(the_file, i+1);\n\t\t\t\tfor (j=0; j<scount; j++) {\n\t\t\t\t\tgf_isom_dump_hint_sample(the_file, i+1, j+1, dump);\n\t\t\t\t}\n#endif\n\t\t\t\tfprintf(dump, \"</%s>\\n\", name);\n\t\t\t\tfmt_handled = GF_TRUE;\n#endif /*GPAC_DISABLE_ISOM_HINTING*/\n\t\t\t}\n\t\t\telse if (gf_isom_get_avc_svc_type(the_file, i+1, 1) || gf_isom_get_hevc_lhvc_type(the_file, i+1, 1)) {\n\t\t\t\tdump_isom_nal_ex(the_file, trackID, dump, GF_FALSE);\n\t\t\t\tfmt_handled = GF_TRUE;\n\t\t\t} else if ((mtype==GF_ISOM_MEDIA_TEXT) || (mtype==GF_ISOM_MEDIA_SUBT) ) {", "\t\t\t\tif (msubtype==GF_ISOM_SUBTYPE_WVTT) {\n\t\t\t\t\tgf_webvtt_dump_iso_track(&dumper, i+1, merge_vtt_cues, GF_TRUE);\n\t\t\t\t\tfmt_handled = GF_TRUE;\n\t\t\t\t} else if ((msubtype==GF_ISOM_SUBTYPE_TX3G) || (msubtype==GF_ISOM_SUBTYPE_TEXT)) {\n\t\t\t\t\tgf_isom_text_dump(the_file, i+1, dump, GF_TEXTDUMPTYPE_TTXT_BOXES);\n\t\t\t\t\tfmt_handled = GF_TRUE;\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (!fmt_handled) {\n\t\t\t\tdumper.flags = GF_EXPORT_NHML | GF_EXPORT_NHML_FULL;\n\t\t\t\tdumper.print_stats_graph = fs_dump_flags;\n\t\t\t\tgf_media_export(&dumper);\n\t\t\t}\n\t\t}\n#else\n\t\treturn GF_NOT_SUPPORTED;\n#endif /*GPAC_DISABLE_MEDIA_EXPORT*/\n\t\tgf_isom_delete(the_file);\n\t\tfprintf(dump, \"</Tracks>\\n\");\n\t\tfprintf(dump, \"</ISOBaseMediaFileTrace>\\n\");\n\t}\n\tif (do_close) gf_fclose(dump);\n\treturn e;\n}\n#endif", "\nstatic char *format_duration(u64 dur, u32 timescale, char *szDur)\n{\n\tu32 h, m, s, ms;\n\tif ((dur==(u64) -1) || (dur==(u32) -1)) {\n\t\tstrcpy(szDur, \"Unknown\");\n\t\treturn szDur;\n\t}\n\tdur = (u64) (( ((Double) (s64) dur)/timescale)*1000);\n\th = (u32) (dur / 3600000);\n\tm = (u32) (dur/ 60000) - h*60;\n\ts = (u32) (dur/1000) - h*3600 - m*60;\n\tms = (u32) (dur) - h*3600000 - m*60000 - s*1000;\n\tif (h<=24) {\n\t\tsprintf(szDur, \"%02d:%02d:%02d.%03d\", h, m, s, ms);\n\t} else {\n\t\tu32 d = (u32) (dur / 3600000 / 24);\n\t\th = (u32) (dur/3600000)-24*d;\n\t\tif (d<=365) {\n\t\t\tsprintf(szDur, \"%d Days, %02d:%02d:%02d.%03d\", d, h, m, s, ms);\n\t\t} else {\n\t\t\tu32 y=0;\n\t\t\twhile (d>365) {\n\t\t\t\ty++;\n\t\t\t\td-=365;\n\t\t\t\tif (y%4) d--;\n\t\t\t}\n\t\t\tsprintf(szDur, \"%d Years %d Days, %02d:%02d:%02d.%03d\", y, d, h, m, s, ms);\n\t\t}", "\t}\n\treturn szDur;\n}", "static char *format_date(u64 time, char *szTime)\n{\n\ttime_t now;\n\tif (!time) {\n\t\tstrcpy(szTime, \"UNKNOWN DATE\");\n\t} else {\n\t\ttime -= 2082844800;\n\t\tnow = (u32) time;\n\t\tsprintf(szTime, \"GMT %s\", asctime(gf_gmtime(&now)) );\n\t}\n\treturn szTime;\n}", "void print_udta(GF_ISOFile *file, u32 track_number, Bool has_itags)\n{\n\tu32 i, count;", "\tcount = gf_isom_get_udta_count(file, track_number);\n\tif (!count) return;", "\tif (has_itags) {\n\t\tfor (i=0; i<count; i++) {\n\t\t\tu32 type;\n\t\t\tbin128 uuid;\n\t\t\tgf_isom_get_udta_type(file, track_number, i+1, &type, &uuid);\n\t\t\tif (type == GF_ISOM_BOX_TYPE_META) {\n\t\t\t\tcount--;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!count) return;\n\t}", "\tfprintf(stderr, \"%d UDTA types: \", count);", "\tfor (i=0; i<count; i++) {\n\t\tu32 j, type, nb_items, first=GF_TRUE;\n\t\tbin128 uuid;\n\t\tgf_isom_get_udta_type(file, track_number, i+1, &type, &uuid);\n\t\tnb_items = gf_isom_get_user_data_count(file, track_number, type, uuid);\n\t\tfprintf(stderr, \"%s (%d) \", gf_4cc_to_str(type), nb_items);\n\t\tfor (j=0; j<nb_items; j++) {\n\t\t\tu8 *udta=NULL;\n\t\t\tu32 udta_size;\n\t\t\tgf_isom_get_user_data(file, track_number, type, uuid, j+1, &udta, &udta_size);\n\t\t\tif (!udta) continue;\n\t\t\tif (udta_size && gf_utf8_is_legal(udta, udta_size)) {\n\t\t\t\tu32 idx;\n\t\t\t\tif (first) {\n\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\tfirst = GF_FALSE;\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \"\\t\");\n\t\t\t\tfor (idx=0; idx<udta_size; idx++) {\n\t\t\t\t\tif (!udta[idx]) break;\n\t\t\t\t\tfprintf(stderr, \"%c\", udta[idx]);\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t}\n\t\t\tgf_free(udta);\n\t\t}\n\t}\n\tfprintf(stderr, \"\\n\");\n}", "GF_Err dump_isom_udta(GF_ISOFile *file, char *inName, Bool is_final_name, u32 dump_udta_type, u32 dump_udta_track)\n{\n\tu8 *data;\n\tFILE *t;\n\tbin128 uuid;\n\tu32 count, res;\n\tGF_Err e;", "\tmemset(uuid, 0, 16);\n\tcount = gf_isom_get_user_data_count(file, dump_udta_track, dump_udta_type, uuid);\n\tif (!count) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"No UDTA for type %s found\\n\", gf_4cc_to_str(dump_udta_type) ));\n\t\treturn GF_NOT_FOUND;\n\t}", "\tdata = NULL;\n\tcount = 0;\n\te = gf_isom_get_user_data(file, dump_udta_track, dump_udta_type, uuid, 0, &data, &count);\n\tif (e) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Error dumping UDTA %s: %s\\n\", gf_4cc_to_str(dump_udta_type), gf_error_to_string(e) ));\n\t\treturn e;\n\t}\n\tif (inName) {\n\t\tchar szName[1024];\n\t\tif (is_final_name)\n\t\t\tstrcpy(szName, inName);\n\t\telse\n\t\t\tsprintf(szName, \"%s_%s.udta\", inName, gf_4cc_to_str(dump_udta_type) );", "\t\tt = gf_fopen(szName, \"wb\");\n\t\tif (!t) {\n\t\t\tgf_free(data);\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Cannot open file %s\\n\", szName ));\n\t\t\treturn GF_IO_ERR;\n\t\t}\n\t} else {\n\t\tt = stdout;\n\t}\n\tres = (u32) gf_fwrite(data+8, count-8, t);\n\tif (inName) gf_fclose(t);\n\tgf_free(data);\n\tif (count-8 != res) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Error writing udta to file\\n\"));\n\t\treturn GF_IO_ERR;\n\t}\n\treturn GF_OK;\n}", "\nGF_Err dump_isom_chapters(GF_ISOFile *file, char *inName, Bool is_final_name, u32 dump_mode)\n{\n\tFILE *t;\n\tu32 i, count;\n\tu32 chap_tk = 0;\n\tcount = gf_isom_get_chapter_count(file, 0);", "\tif (dump_mode==2) dump_mode = GF_TEXTDUMPTYPE_OGG_CHAP;\n\telse if (dump_mode==3) dump_mode = GF_TEXTDUMPTYPE_ZOOM_CHAP;\n\telse dump_mode = GF_TEXTDUMPTYPE_TTXT_CHAP;", "\tif (!count) {\n\t\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\t\tif (gf_isom_get_reference_count(file, i+1, GF_ISOM_REF_CHAP)) {\n\t\t\t\tGF_Err e = gf_isom_get_reference(file, i+1, GF_ISOM_REF_CHAP, 1, &chap_tk);\n\t\t\t\tif (!e) break;\n\t\t\t}\n\t\t}\n\t\tif (!chap_tk) {\n\t\t\tM4_LOG(GF_LOG_WARNING, (\"No chapters or chapters track found in file\\n\"));\n\t\t\treturn GF_OK;\n\t\t}", "\t\tfprintf(stderr, \"Dumping chapter track %d\\n\", chap_tk);\n\t\tdump_isom_timed_text(file, gf_isom_get_track_id(file, chap_tk), inName, is_final_name, GF_FALSE, dump_mode);\n\t\treturn GF_OK;", "\t}\n\tif (inName) {\n\t\tchar szName[1024];\n\t\tstrcpy(szName, inName);\n\t\tif (!is_final_name) {\n\t\t\tif (dump_mode==GF_TEXTDUMPTYPE_OGG_CHAP) {\n\t\t\t\tstrcat(szName, \".txt\");\n\t\t\t} else if (dump_mode==GF_TEXTDUMPTYPE_ZOOM_CHAP) {\n\t\t\t\tstrcat(szName, \".txt\");\n\t\t\t} else {\n\t\t\t\tstrcat(szName, \".ttxt\");\n\t\t\t}\n\t\t}\n\t\tt = gf_fopen(szName, \"wt\");\n\t\tif (!t) return GF_IO_ERR;\n\t} else {\n\t\tt = stdout;\n\t}", "\tif (dump_mode==GF_TEXTDUMPTYPE_TTXT_CHAP) {\n\t\tfprintf(t, \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\\n\");\n\t\tfprintf(t, \"<TextStream version=\\\"1.1\\\">\\n\");\n\t\tfprintf(t, \"<TextStreamHeader width=\\\"0\\\" height=\\\"0\\\" layer=\\\"0\\\" translation_x=\\\"0\\\" translation_y=\\\"0\\\">\\n\");\n\t\tfprintf(t, \"<TextSampleDescription horizontalJustification=\\\"left\\\" backColor=\\\"0 0 0\\\" scroll=\\\"None\\\"/>\\n\");\n\t\tfprintf(t, \"</TextStreamHeader>\\n\");\n\t}", "\tfor (i=0; i<count; i++) {\n\t\tchar szDur[20];\n\t\tu64 chapter_time;\n\t\tconst char *name;\n\t\tgf_isom_get_chapter(file, 0, i+1, &chapter_time, &name);\n\t\tif (dump_mode==GF_TEXTDUMPTYPE_OGG_CHAP) {\n\t\t\tfprintf(t, \"CHAPTER%02d=%s\\n\", i+1, format_duration(chapter_time, 1000, szDur));\n\t\t\tfprintf(t, \"CHAPTER%02dNAME=%s\\n\", i+1, name);\n\t\t} else if (dump_mode==GF_TEXTDUMPTYPE_ZOOM_CHAP) {\n\t\t\tchapter_time /= 1000;\n\t\t\tfprintf(t, \"AddChapterBySecond(\"LLD\",%s)\\n\", chapter_time, name);\n\t\t} else {\n\t\t\tfprintf(t, \"<TextSample sampleTime=\\\"%s\\\" sampleDescriptionIndex=\\\"1\\\" xml:space=\\\"preserve\\\">%s</TextSample>\\n\"\n\t\t\t\t, format_duration(chapter_time, 1000, szDur), name);\n\t\t}\n\t}\n\tif (dump_mode==GF_TEXTDUMPTYPE_TTXT_CHAP) {\n\t\tfprintf(t, \"</TextStream>\\n\");\n\t}\n\tif (inName) gf_fclose(t);\n\treturn GF_OK;\n}", "\nstatic void dump_key_info(const u8 *key_info, u32 key_info_size, Bool is_protected)\n{\n\tif (!key_info) return;\n\tu32 j, k, kpos=3;\n\tu32 nb_keys = 1;\n\tif (key_info[0]) {\n\t\tnb_keys = key_info[1];\n\t\tnb_keys <<= 8;\n\t\tnb_keys |= key_info[2];\n\t}\n\tfor (k=0; k<nb_keys; k++) {\n\t\tu8 constant_iv_size=0;\n\t\tu8 iv_size=key_info[kpos+1];\n\t\tfprintf(stderr, \"\\t\\tKID\");\n\t\tif (nb_keys>1)\n\t\t\tfprintf(stderr, \"%d\", k+1);\n\t\tfprintf(stderr, \" \");\n\t\tfor (j=0; j<16; j++) fprintf(stderr, \"%02X\", key_info[kpos+1+j]);\n\t\tkpos+=17;\n\t\tif (!iv_size && is_protected) {\n\t\t\tconstant_iv_size = key_info[1];\n\t\t\tkpos += 1 + constant_iv_size;\n\t\t}\n\t\tfprintf(stderr, \" - %sIV size %d \\n\", constant_iv_size ? \"const \" : \"\", constant_iv_size ? constant_iv_size : iv_size);\n\t}\n}", "static void DumpMetaItem(GF_ISOFile *file, Bool root_meta, u32 tk_num, char *name)\n{\n\tchar szInd[2];\n\tu32 i, count, primary_id;\n\tu32 meta_type = gf_isom_get_meta_type(file, root_meta, tk_num);\n\tif (name[0]=='\\t') {\n\t\tszInd[0] = '\\t';\n\t\tszInd[1] = 0;\n\t} else {\n\t\tszInd[0] = 0;\n\t}", "\tcount = gf_isom_get_meta_item_count(file, root_meta, tk_num);\n\tprimary_id = gf_isom_get_meta_primary_item_id(file, root_meta, tk_num);\n\tfprintf(stderr, \"%s type: \\\"%s\\\" - %d resource item(s)\\n\", name, meta_type ? gf_4cc_to_str(meta_type) : \"undefined\", (count+(primary_id>0)));\n\tswitch (gf_isom_has_meta_xml(file, root_meta, tk_num)) {\n\tcase 1:\n\t\tfprintf(stderr, \"%sMeta has XML resource\\n\", szInd);\n\t\tbreak;\n\tcase 2:\n\t\tfprintf(stderr, \"%sMeta has BinaryXML resource\\n\", szInd);\n\t\tbreak;\n\t}\n\tif (primary_id) {\n\t\tfprintf(stderr, \"%sPrimary Item - ID %d\\n\", szInd, primary_id);\n\t}\n\tfor (i=0; i<count; i++) {\n\t\tconst char *it_name, *mime, *enc, *url, *urn;\n\t\tBool self_ref;\n\t\tu32 ID;\n\t\tu32 it_type, cenc_scheme, cenc_version;\n\t\tGF_Err e = gf_isom_get_meta_item_info(file, root_meta, tk_num, i+1, &ID, &it_type, &cenc_scheme, &cenc_version, &self_ref, &it_name, &mime, &enc, &url, &urn);\n\t\tif (e) {\n\t\t\tfprintf(stderr, \"%sItem #%d fetch info error: %s\\n\", szInd, i+1, gf_error_to_string(e) );\n\t\t\tcontinue;\n\t\t}\n\t\tfprintf(stderr, \"%sItem #%d: ID %d type %s\", szInd, i+1, ID, gf_4cc_to_str(it_type));\n\t\tif (self_ref) fprintf(stderr, \" Self-Reference\");\n\t\telse if (it_name && it_name[0]) fprintf(stderr, \" Name \\\"%s\\\"\", it_name);\n\t\tif (mime) fprintf(stderr, \" MIME: \\\"%s\\\"\", mime);\n\t\tif (enc) fprintf(stderr, \" ContentEncoding: \\\"%s\\\"\", enc);", "\t\tif (meta_type == GF_META_ITEM_TYPE_PICT) {\n\t\t\tGF_ImageItemProperties img_props;\n\t\t\te = gf_isom_get_meta_image_props(file, root_meta, tk_num, ID, &img_props);\n\t\t\tif (e) {\n\t\t\t\tfprintf(stderr, \" invalid image properties !\");\n\t\t\t} else {\n\t\t\t\tu32 j;\n\t\t\t\tBool chan_diff = 0;\n\t\t\t\tif (img_props.width && img_props.height) {\n\t\t\t\t\tfprintf(stderr, \" size %ux%u\", img_props.width, img_props.height);\n\t\t\t\t}\n\t\t\t\tif (img_props.hSpacing && img_props.vSpacing) {\n\t\t\t\t\tfprintf(stderr, \" SAR %u/%u\", img_props.hSpacing, img_props.vSpacing);\n\t\t\t\t}\n\t\t\t\tif (img_props.num_channels) {\n\t\t\t\t\tfprintf(stderr, \" %d channel%s (\", img_props.num_channels, (img_props.num_channels>1) ? \"s\" : \"\");\n\t\t\t\t\tfor (j=1; j<img_props.num_channels; j++) {\n\t\t\t\t\t\tif (img_props.bits_per_channel[0] != img_props.bits_per_channel[j])\n\t\t\t\t\t\t\tchan_diff = 1;\n\t\t\t\t\t}\n\t\t\t\t\tif (chan_diff) {\n\t\t\t\t\t\tfor (j=0; j<img_props.num_channels; j++) {\n\t\t\t\t\t\t\tif (j) fprintf(stderr, \",\");\n\t\t\t\t\t\t\tfprintf(stderr, \"%d\", img_props.bits_per_channel[j]);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfprintf(stderr, \"%d\", img_props.bits_per_channel[0]);\n\t\t\t\t\t}\n\t\t\t\t\tfprintf(stderr, \" bpc)\");\n\t\t\t\t}\n\t\t\t\tif (img_props.hOffset || img_props.vOffset)\n\t\t\t\t\tfprintf(stderr, \" Offset %ux%u\", img_props.hOffset, img_props.vOffset);\n\t\t\t\tif (img_props.alpha) fprintf(stderr, \" Alpha\");\n\t\t\t\tif (img_props.hidden) fprintf(stderr, \" Hidden\");\n\t\t\t\tif (img_props.angle) fprintf(stderr, \" Rotate %d\", img_props.angle);\n\t\t\t\tif (img_props.mirror) fprintf(stderr, \" Mirror %d\", img_props.mirror);\n\t\t\t\tif (img_props.clap_hden || img_props.clap_wden)\n\t\t\t\t\tfprintf(stderr, \" Clap %d/%d,%d/%d,%d/%d,%d/%d\", img_props.clap_wnum, img_props.clap_wden, img_props.clap_hnum, img_props.clap_hden, img_props.clap_honum, img_props.clap_hoden, img_props.clap_vonum, img_props.clap_voden);\n\t\t\t}\n\t\t}", "\t\tif (cenc_scheme) {\n\t\t\tBool is_protected;\n\t\t\tu8 skip_byte_block, crypt_byte_block;\n\t\t\tconst u8 *key_info;\n\t\t\tu32 key_info_size;\n\t\t\tfprintf(stderr, \" - Protection scheme: %s v0x%08X\", gf_4cc_to_str(cenc_scheme), cenc_version);", "\t\t\tgf_isom_extract_meta_item_get_cenc_info(file, root_meta, tk_num, ID, &is_protected, &skip_byte_block, &crypt_byte_block, &key_info, &key_info_size, NULL, NULL, NULL, NULL);\n\t\t\tif (skip_byte_block && crypt_byte_block)\n\t\t\t\tfprintf(stderr, \" - Pattern %d:%d\", skip_byte_block, crypt_byte_block);\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t\tdump_key_info(key_info, key_info_size, is_protected);\n\t\t}\n\t\tfprintf(stderr, \"\\n\");\n\t\tif (url) fprintf(stderr, \"%sURL: %s\\n\", szInd, url);\n\t\tif (urn) fprintf(stderr, \"%sURN: %s\\n\", szInd, urn);", "\t}\n}", "\nstatic void print_config_hash(GF_List *xps_array, char *szName)\n{\n\tu32 i, j;\n\tu8 hash[20];\n\tfor (i=0; i<gf_list_count(xps_array); i++) {\n\t\tGF_NALUFFParam *slc = gf_list_get(xps_array, i);\n\t\tgf_sha1_csum((u8 *) slc->data, slc->size, hash);\n\t\tfprintf(stderr, \"\\t%s#%d hash: \", szName, i+1);\n\t\tfor (j=0; j<20; j++) fprintf(stderr, \"%02X\", hash[j]);\n\t\tfprintf(stderr, \"\\n\");\n\t}\n}", "void dump_hevc_track_info(GF_ISOFile *file, u32 trackNum, GF_HEVCConfig *hevccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t, HEVCState *hevc_state\n#endif /*GPAC_DISABLE_AV_PARSERS && defined(GPAC_DISABLE_HEVC)*/\n\t)\n{\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\tu32 idx;\n#endif\n\tu32 k;\n\tBool non_hevc_base_layer=GF_FALSE;\n\tfprintf(stderr, \"\\t%s Info:\", hevccfg->is_lhvc ? \"LHVC\" : \"HEVC\");\n\tif (!hevccfg->is_lhvc)\n\t\tfprintf(stderr, \" Profile %s @ Level %g - Chroma Format %s\\n\", gf_hevc_get_profile_name(hevccfg->profile_idc), ((Double)hevccfg->level_idc) / 30.0, gf_avc_hevc_get_chroma_format_name(hevccfg->chromaFormat));\n\tfprintf(stderr, \"\\n\");\n\tfprintf(stderr, \"\\tNAL Unit length bits: %d\", 8*hevccfg->nal_unit_size);\n\tif (!hevccfg->is_lhvc)\n\t\tfprintf(stderr, \" - general profile compatibility 0x%08X\\n\", hevccfg->general_profile_compatibility_flags);\n\tfprintf(stderr, \"\\n\");\n\tfprintf(stderr, \"\\tParameter Sets: \");\n\tfor (k=0; k<gf_list_count(hevccfg->param_array); k++) {\n\t\tGF_NALUFFParamArray *ar=gf_list_get(hevccfg->param_array, k);\n\t\tif (ar->type==GF_HEVC_NALU_SEQ_PARAM) {\n\t\t\tfprintf(stderr, \"%d SPS \", gf_list_count(ar->nalus));\n\t\t}\n\t\tif (ar->type==GF_HEVC_NALU_PIC_PARAM) {\n\t\t\tfprintf(stderr, \"%d PPS \", gf_list_count(ar->nalus));\n\t\t}\n\t\tif (ar->type==GF_HEVC_NALU_VID_PARAM) {\n\t\t\tfprintf(stderr, \"%d VPS \", gf_list_count(ar->nalus));", "#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\tfor (idx=0; idx<gf_list_count(ar->nalus); idx++) {\n\t\t\t\tGF_NALUFFParam *vps = gf_list_get(ar->nalus, idx);\n\t\t\t\ts32 ps_idx=gf_hevc_read_vps(vps->data, vps->size, hevc_state);\n\t\t\t\tif (hevccfg->is_lhvc && (ps_idx>=0)) {\n\t\t\t\t\tnon_hevc_base_layer = ! hevc_state->vps[ps_idx].base_layer_internal_flag;\n\t\t\t\t}\n\t\t\t}\n#endif", "\t\t}\n\t}", "\tfprintf(stderr, \"\\n\");\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\tfor (k=0; k<gf_list_count(hevccfg->param_array); k++) {\n\t\tGF_NALUFFParamArray *ar=gf_list_get(hevccfg->param_array, k);\n\t\tu32 width, height;\n\t\ts32 par_n, par_d;", "\t\tif (ar->type !=GF_HEVC_NALU_SEQ_PARAM) continue;\n\t\tfor (idx=0; idx<gf_list_count(ar->nalus); idx++) {\n\t\t\tGF_Err e;\n\t\t\tGF_NALUFFParam *sps = gf_list_get(ar->nalus, idx);\n\t\t\tpar_n = par_d = -1;\n\t\t\te = gf_hevc_get_sps_info_with_state(hevc_state, sps->data, sps->size, NULL, &width, &height, &par_n, &par_d);\n\t\t\tif (e==GF_OK) {\n\t\t\t\tfprintf(stderr, \"\\tSPS resolution %dx%d\", width, height);\n\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\tu32 tw, th;\n\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\tfprintf(stderr, \" - Pixel Aspect Ratio %d:%d - Indicated track size %d x %d\", par_n, par_d, tw, th);\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t} else {\n\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to read SPS: %s\\n\\n\", gf_error_to_string(e) ));\n\t\t\t}\n\t\t}\n\t}\n#endif\n\tif (!hevccfg->is_lhvc)\n\t\tfprintf(stderr, \"\\tBit Depth luma %d - Chroma %d - %d temporal layers\\n\", hevccfg->luma_bit_depth, hevccfg->chroma_bit_depth, hevccfg->numTemporalLayers);\n\telse\n\t\tfprintf(stderr, \"\\t%d temporal layers\\n\", hevccfg->numTemporalLayers);\n\tif (hevccfg->is_lhvc) {\n\t\tfprintf(stderr, \"\\t%sHEVC base layer - Complete representation %d\\n\", non_hevc_base_layer ? \"Non-\" : \"\", hevccfg->complete_representation);\n\t}", "\tfor (k=0; k<gf_list_count(hevccfg->param_array); k++) {\n\t\tGF_NALUFFParamArray *ar=gf_list_get(hevccfg->param_array, k);\n\t\tif (ar->type==GF_HEVC_NALU_SEQ_PARAM) print_config_hash(ar->nalus, \"SPS\");\n\t\telse if (ar->type==GF_HEVC_NALU_PIC_PARAM) print_config_hash(ar->nalus, \"PPS\");\n\t\telse if (ar->type==GF_HEVC_NALU_VID_PARAM) print_config_hash(ar->nalus, \"VPS\");\n\t}\n}", "void dump_vvc_track_info(GF_ISOFile *file, u32 trackNum, GF_VVCConfig *vvccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t, VVCState *vvc_state\n#endif /*GPAC_DISABLE_AV_PARSERS && defined(GPAC_DISABLE_HEVC)*/\n\t)\n{\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\tu32 idx;\n#endif\n\tu32 k;\n\tfprintf(stderr, \"\\tVVC Info:\");", "\tfprintf(stderr, \" Profile %d @ Level %d - Chroma Format %s\\n\", vvccfg->general_profile_idc, vvccfg->general_level_idc, vvccfg->chromaformat_plus_one ? gf_avc_hevc_get_chroma_format_name(vvccfg->chromaformat_plus_one-1) : \"n/a\");\n\tfprintf(stderr, \"\\n\");\n\tfprintf(stderr, \"\\tNAL Unit length bits: %d\", 8*vvccfg->nal_unit_size);\n\tif (vvccfg->general_constraint_info && vvccfg->num_constraint_info && vvccfg->general_constraint_info[0]) {\n\t\tfprintf(stderr, \" - general constraint info 0x\");\n\t\tfor (idx=0; idx<vvccfg->num_constraint_info; idx++) {\n\t\t\tfprintf(stderr, \"%02X\", vvccfg->general_constraint_info[idx]);\n\t\t}\n\t}\n\tfprintf(stderr, \"\\n\");\n\tfprintf(stderr, \"\\tParameter Sets: \");\n\tfor (k=0; k<gf_list_count(vvccfg->param_array); k++) {\n\t\tGF_NALUFFParamArray *ar=gf_list_get(vvccfg->param_array, k);\n\t\tif (ar->type==GF_VVC_NALU_SEQ_PARAM) {\n\t\t\tfprintf(stderr, \"%d SPS \", gf_list_count(ar->nalus));\n\t\t}\n\t\tif (ar->type==GF_VVC_NALU_PIC_PARAM) {\n\t\t\tfprintf(stderr, \"%d PPS \", gf_list_count(ar->nalus));\n\t\t}\n\t\tif (ar->type==GF_VVC_NALU_VID_PARAM) {\n\t\t\tfprintf(stderr, \"%d VPS \", gf_list_count(ar->nalus));", "#if !defined(GPAC_DISABLE_AV_PARSERS) && 0 //TODO\n\t\t\tfor (idx=0; idx<gf_list_count(ar->nalus); idx++) {\n\t\t\t\tGF_NALUFFParam *vps = gf_list_get(ar->nalus, idx);\n\t\t\t\ts32 ps_idx=gf_hevc_read_vps(vps->data, vps->size, hevc_state);\n\t\t\t\tif (hevccfg->is_lhvc && (ps_idx>=0)) {\n\t\t\t\t\tnon_hevc_base_layer = ! hevc_state->vps[ps_idx].base_layer_internal_flag;\n\t\t\t\t}\n\t\t\t}\n#endif", "\t\t}\n\t}", "\tfprintf(stderr, \"\\n\");\n#if !defined(GPAC_DISABLE_AV_PARSERS) && 0 //TODO\n\tfor (k=0; k<gf_list_count(vvccfg->param_array); k++) {\n\t\tGF_NALUFFParamArray *ar=gf_list_get(vvccfg->param_array, k);\n\t\tu32 width, height;\n\t\ts32 par_n, par_d;", "\t\tif (ar->type !=GF_VVC_NALU_SEQ_PARAM) continue;\n\t\tfor (idx=0; idx<gf_list_count(ar->nalus); idx++) {\n\t\t\tGF_Err e;\n\t\t\tGF_NALUFFParam *sps = gf_list_get(ar->nalus, idx);\n\t\t\tpar_n = par_d = -1;\n\t\t\te = gf_vvc_get_sps_info_with_state(vvc_state, sps->data, sps->size, NULL, &width, &height, &par_n, &par_d);\n\t\t\tif (e==GF_OK) {\n\t\t\t\tfprintf(stderr, \"\\tSPS resolution %dx%d\", width, height);\n\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\tu32 tw, th;\n\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\tfprintf(stderr, \" - Pixel Aspect Ratio %d:%d - Indicated track size %d x %d\", par_n, par_d, tw, th);\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t} else {\n\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"\\nFailed to read SPS: %s\\n\\n\", gf_error_to_string(e) ));\n\t\t\t}\n\t\t}\n\t}\n#endif\n\tfprintf(stderr, \"\\tBit Depth %d - %d temporal layers\\n\", vvccfg->bit_depth_plus_one-1, vvccfg->numTemporalLayers);", "\tfor (k=0; k<gf_list_count(vvccfg->param_array); k++) {\n\t\tGF_NALUFFParamArray *ar=gf_list_get(vvccfg->param_array, k);\n\t\tif (ar->type==GF_VVC_NALU_SEQ_PARAM) print_config_hash(ar->nalus, \"SPS\");\n\t\telse if (ar->type==GF_VVC_NALU_PIC_PARAM) print_config_hash(ar->nalus, \"PPS\");\n\t\telse if (ar->type==GF_VVC_NALU_VID_PARAM) print_config_hash(ar->nalus, \"VPS\");\n\t}\n}", "void gf_inspect_format_timecode(const u8 *data, u32 size, u32 tmcd_flags, u32 tc_num, u32 tc_den, u32 tmcd_fpt, char szFmt[100]);", "void DumpTrackInfo(GF_ISOFile *file, GF_ISOTrackID trackID, Bool full_dump, Bool is_track_num, Bool dump_m4sys)\n{\n\tchar szCodec[RFC6381_CODEC_NAME_SIZE_MAX];\n\tDouble scale, max_rate, rate;\n\tBool is_od_track = 0;\n\tu32 trackNum, i, j, ts, mtype, msub_type, timescale, sr, nb_ch, count, alt_group, nb_groups, nb_edits, cdur, csize, bps, pfmt, codecid;\n\tu64 time_slice, dur, size;\n\ts32 cts_shift;\n\tGF_ESD *esd;\n\tchar szDur[50];\n\tchar *lang;", "\tif (!is_track_num) {\n\t\ttrackNum = gf_isom_get_track_by_id(file, trackID);\n\t} else {\n\t\ttrackNum = trackID;\n\t\ttrackID = gf_isom_get_track_id(file, trackNum);\n\t}\n\tif (!trackNum) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"No track with ID %d found\\n\", trackID));\n\t\treturn;\n\t}", "\ttimescale = gf_isom_get_media_timescale(file, trackNum);\n\tfprintf(stderr, \"# Track %d Info - ID %d - TimeScale %d\\n\", trackNum, trackID, timescale);", "\tdur = gf_isom_get_media_original_duration(file, trackNum);\n\tsize = gf_isom_get_media_duration(file, trackNum);\n\tfprintf(stderr, \"Media Duration %s \", format_duration(dur, timescale, szDur));\n\tif (dur != size)\n\t\tfprintf(stderr, \" (recomputed %s)\", format_duration(size, timescale, szDur));\n\tfprintf(stderr, \"\\n\");", "\tif (gf_isom_check_data_reference(file, trackNum, 1) != GF_OK) {\n\t\tM4_LOG(GF_LOG_WARNING, (\"Track uses external data reference not supported by GPAC!\\n\"));\n\t}", "\tnb_edits = gf_isom_get_edits_count(file, trackNum);\n\tif (nb_edits)\n\t\tfprintf(stderr, \"Track has %d edits: track duration is %s\\n\", nb_edits, format_duration(gf_isom_get_track_duration(file, trackNum), gf_isom_get_timescale(file), szDur));", "\tcts_shift = gf_isom_get_composition_offset_shift(file, trackNum);\n\tif (cts_shift)\n\t\tfprintf(stderr, \"Track composition offset shift (negative CTS offset): %d\\n\", cts_shift);", "\tif (gf_isom_is_track_in_root_od(file, trackNum) ) fprintf(stderr, \"Track is present in Root OD\\n\");\n\tif (!gf_isom_is_track_enabled(file, trackNum)) fprintf(stderr, \"Track is disabled\\n\");\n\tgf_isom_get_media_language(file, trackNum, &lang);\n\tfprintf(stderr, \"Media Info: Language \\\"%s (%s)\\\" - \", GetLanguage(lang), lang );\n\tgf_free(lang);\n\tmtype = gf_isom_get_media_type(file, trackNum);\n\tfprintf(stderr, \"Type \\\"%s:\", gf_4cc_to_str(mtype));\n\tmsub_type = gf_isom_get_mpeg4_subtype(file, trackNum, 1);\n\tif (!msub_type) msub_type = gf_isom_get_media_subtype(file, trackNum, 1);\n\tfprintf(stderr, \"%s\\\" - %d samples\\n\", gf_4cc_to_str(msub_type), gf_isom_get_sample_count(file, trackNum));", "\tpfmt = gf_pixel_fmt_from_qt_type(msub_type);\n\tcodecid = gf_codec_id_from_isobmf(msub_type);", "\tcount = gf_isom_get_track_kind_count(file, trackNum);\n\tfor (i = 0; i < count; i++) {\n\t\tchar *kind_scheme, *kind_value;\n\t\tgf_isom_get_track_kind(file, trackNum, i, &kind_scheme, &kind_value);\n\t\tfprintf(stderr, \"Kind: %s - %s\\n\", kind_scheme ? kind_scheme : \"null\", kind_value ? kind_value : \"null\");\n\t\tif (kind_scheme) gf_free(kind_scheme);\n\t\tif (kind_value) gf_free(kind_value);\n\t}", "\tif (gf_isom_is_track_fragmented(file, trackID) ) {\n\t\tu32 defaultDuration, defaultSize, defaultDescriptionIndex, defaultRandomAccess;\n\t\tu8 defaultPadding;\n\t\tu16 defaultDegradationPriority;\n\t\tu32 frag_samples;\n\t\tu64 frag_duration;\n\t\tgf_isom_get_fragmented_samples_info(file, trackID, &frag_samples, &frag_duration);\n\t\tfprintf(stderr, \"Fragmented track: %d samples - Media Duration %s\\n\", frag_samples, format_duration(frag_duration, timescale, szDur));", "\t\tgf_isom_get_fragment_defaults(file, trackNum, &defaultDuration, &defaultSize, &defaultDescriptionIndex, &defaultRandomAccess, &defaultPadding, &defaultDegradationPriority);", "\t\tfprintf(stderr, \"Fragment sample defaults: duration %d size %d stsd %d sync %d padding %d degradation_priority %d\\n\",\n\t\t\t\tdefaultDuration, defaultSize, defaultDescriptionIndex, defaultRandomAccess,\n\t\t\t\t(u32) defaultPadding, (u32) defaultDegradationPriority\n\t\t);\n\t}", "\tif (!gf_isom_is_self_contained(file, trackNum, 1)) {\n\t\tconst char *url, *urn;\n\t\tgf_isom_get_data_reference(file, trackNum, 1, &url, &urn);\n\t\tfprintf(stderr, \"Media Data Location: %s\\n\", url ? url : urn);\n\t}", "\tif (full_dump) {\n\t\tconst char *handler_name;\n\t\tgf_isom_get_handler_name(file, trackNum, &handler_name);\n\t\tfprintf(stderr, \"Handler name: %s\\n\", handler_name);\n\t}", "\tprint_udta(file, trackNum, GF_FALSE);", "\tif (gf_isom_is_video_handler_type(mtype) ) {\n\t\ts32 tx, ty;\n\t\tu32 w, h;\n\t\tu16 bit_depth;", "\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tgf_isom_get_visual_bit_depth(file, trackNum, 1, &bit_depth);\n\t\tfprintf(stderr, \"Visual Sample Entry Info: width=%d height=%d (depth=%d bits)\\n\", w, h, (int)bit_depth);", "\t\tgf_isom_get_track_layout_info(file, trackNum, &w, &h, &tx, &ty, NULL);\n\t\tfprintf(stderr, \"Visual Track layout: x=%d y=%d width=%d height=%d\\n\", tx, ty, w, h);\n\t}", "\tgf_isom_get_audio_info(file, trackNum, 1, &sr, &nb_ch, &bps);\n\tgf_isom_set_nalu_extract_mode(file, trackNum, GF_ISOM_NALU_EXTRACT_INSPECT);", "\tmsub_type = gf_isom_get_media_subtype(file, trackNum, 1);\n\tif (msub_type==GF_ISOM_SUBTYPE_MPEG4_CRYP)\n\t\tgf_isom_get_original_format_type(file, trackNum, 1, &msub_type);", "\tif ((msub_type==GF_ISOM_SUBTYPE_MPEG4)\n\t || (msub_type==GF_ISOM_SUBTYPE_AVC_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_AVC2_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_AVC3_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_AVC4_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_SVC_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_MVC_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_LSR1)\n\t || (msub_type==GF_ISOM_SUBTYPE_HVC1)\n\t || (msub_type==GF_ISOM_SUBTYPE_HEV1)\n\t || (msub_type==GF_ISOM_SUBTYPE_HVC2)\n\t || (msub_type==GF_ISOM_SUBTYPE_HEV2)\n\t || (msub_type==GF_ISOM_SUBTYPE_LHV1)\n\t || (msub_type==GF_ISOM_SUBTYPE_LHE1)\n\t || (msub_type==GF_ISOM_SUBTYPE_HVT1)\n\t ) {\n\t\tesd = gf_isom_get_esd(file, trackNum, 1);\n\t\tif (!esd || !esd->decoderConfig) {\n\t\t\tM4_LOG(GF_LOG_WARNING, (\"WARNING: Broken MPEG-4 Track\\n\"));\n\t\t\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);\n\t\t} else {\n\t\t\tconst char *st = gf_stream_type_name(esd->decoderConfig->streamType);\n\t\t\tif (dump_m4sys) {\n\t\t\t\tif (st) {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Config%s%s Stream - ObjectTypeIndication 0x%02x\\n\",\n\t\t\t\t\t\t\tfull_dump ? \"\\n\\t\" : \": \", st, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Config%sStream Type 0x%02x - ObjectTypeIndication 0x%02x\\n\",\n\t\t\t\t\t\t\tfull_dump ? \"\\n\\t\" : \": \", esd->decoderConfig->streamType, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (esd->decoderConfig->streamType==GF_STREAM_OD)\n\t\t\t\tis_od_track=1;", "\t\t\tif (esd->decoderConfig->streamType==GF_STREAM_VISUAL) {\n\t\t\t\tu32 w, h;\n\t\t\t\tu16 rvc_predef;\n\t\t\t\tw = h = 0;\n\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\tif (!esd->decoderConfig->decoderSpecificInfo) {\n#else\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Visual Size %d x %d\\n\", w, h);\n#endif\n\t\t\t\t\t\tM4_LOG(GF_LOG_WARNING, (\"Non-compliant MPEG-4 Visual track: video_object_layer infos not found in sample description\\n\"));\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t} else {\n\t\t\t\t\t\tGF_M4VDecSpecInfo dsi;\n\t\t\t\t\t\tgf_m4v_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &dsi);\n\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\tw = dsi.width;\n\t\t\t\t\t\th = dsi.height;\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-4 Visual Size %d x %d - %s\\n\", w, h, gf_m4v_get_profile_name(dsi.VideoPL));\n\t\t\t\t\t\tif (dsi.par_den && dsi.par_num) {\n\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\tfprintf(stderr, \"Pixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", dsi.par_num, dsi.par_den, tw, th);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#endif\n\t\t\t\t} else if (gf_isom_get_avc_svc_type(file, trackNum, 1) != GF_ISOM_AVCTYPE_NONE) {\n\t\t\t\t\tGF_AVCConfig *avccfg, *svccfg, *mvccfg;", "\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"AVC/H264 Video - Visual Size %d x %d\\n\", w, h);", "\t\t\t\t\tavccfg = gf_isom_avc_config_get(file, trackNum, 1);\n\t\t\t\t\tsvccfg = gf_isom_svc_config_get(file, trackNum, 1);\n\t\t\t\t\tmvccfg = gf_isom_mvc_config_get(file, trackNum, 1);\n\t\t\t\t\tif (!avccfg && !svccfg && !mvccfg) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"\\tNon-compliant AVC track: SPS/PPS not found in sample description\\n\"));\n\t\t\t\t\t} else if (avccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tAVC Info: %d SPS - %d PPS\", gf_list_count(avccfg->sequenceParameterSets) , gf_list_count(avccfg->pictureParameterSets) );\n\t\t\t\t\t\tfprintf(stderr, \" - Profile %s @ Level %g\\n\", gf_avc_get_profile_name(avccfg->AVCProfileIndication), ((Double)avccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tNAL Unit length bits: %d\\n\", 8*avccfg->nal_unit_size);", "#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; i<gf_list_count(avccfg->sequenceParameterSets); i++) {\n\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(avccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, NULL, NULL, NULL, &par_n, &par_d);\n\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!full_dump) break;\n\t\t\t\t\t\t}\n#endif", "\t\t\t\t\t\tif (avccfg->chroma_bit_depth) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tChroma format %s - Luma bit depth %d - chroma bit depth %d\\n\", gf_avc_hevc_get_chroma_format_name(avccfg->chroma_format), avccfg->luma_bit_depth, avccfg->chroma_bit_depth);\n\t\t\t\t\t\t}", "\t\t\t\t\t\tprint_config_hash(avccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(avccfg->pictureParameterSets, \"PPS\");", "\t\t\t\t\t\tgf_odf_avc_cfg_del(avccfg);\n\t\t\t\t\t}\n\t\t\t\t\tif (svccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tSVC Info: %d SPS - %d PPS - Profile %s @ Level %g\\n\", gf_list_count(svccfg->sequenceParameterSets) , gf_list_count(svccfg->pictureParameterSets), gf_avc_get_profile_name(svccfg->AVCProfileIndication), ((Double)svccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tSVC NAL Unit length bits: %d\\n\", 8*svccfg->nal_unit_size);\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; i<gf_list_count(svccfg->sequenceParameterSets); i++) {\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(svccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tif (slc) {\n\t\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\t\tu32 s_w, s_h, sps_id;\n\t\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, &sps_id, &s_w, &s_h, &par_n, &par_d);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\t\\tSPS ID %d - Visual Size %d x %d\\n\", sps_id, s_w, s_h);\n\t\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\tprint_config_hash(svccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(svccfg->pictureParameterSets, \"PPS\");\n\t\t\t\t\t\tprint_config_hash(svccfg->sequenceParameterSetExtensions, \"SPSEx\");", "\t\t\t\t\t\tgf_odf_avc_cfg_del(svccfg);\n\t\t\t\t\t}", "\t\t\t\t\tif (mvccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tMVC Info: %d SPS - %d PPS - Profile %s @ Level %g\\n\", gf_list_count(mvccfg->sequenceParameterSets) , gf_list_count(mvccfg->pictureParameterSets), gf_avc_get_profile_name(mvccfg->AVCProfileIndication), ((Double)mvccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tMVC NAL Unit length bits: %d\\n\", 8*mvccfg->nal_unit_size);\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; i<gf_list_count(mvccfg->sequenceParameterSets); i++) {\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(mvccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tif (slc) {\n\t\t\t\t\t\t\t\tu32 s_w, s_h, sps_id;\n\t\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, &sps_id, &s_w, &s_h, &par_n, &par_d);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\t\\tSPS ID %d - Visual Size %d x %d\\n\", sps_id, s_w, s_h);\n\t\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\tprint_config_hash(mvccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(mvccfg->pictureParameterSets, \"PPS\");\n\t\t\t\t\t\tgf_odf_avc_cfg_del(mvccfg);\n\t\t\t\t\t}", "\t\t\t\t} else if ((esd->decoderConfig->objectTypeIndication==GF_CODECID_HEVC)\n\t\t\t\t || (esd->decoderConfig->objectTypeIndication==GF_CODECID_LHVC)\n\t\t\t\t ) {\n\t\t\t\t\tGF_HEVCConfig *hevccfg, *lhvccfg;\n\t\t\t\t\tGF_OperatingPointsInformation *oinf;\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\tHEVCState hevc_state;\n\t\t\t\t\tmemset(&hevc_state, 0, sizeof(HEVCState));\n\t\t\t\t\thevc_state.sps_active_idx = -1;\n#endif", "\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"HEVC Video - Visual Size %d x %d\\n\", w, h);\n\t\t\t\t\thevccfg = gf_isom_hevc_config_get(file, trackNum, 1);\n\t\t\t\t\tlhvccfg = gf_isom_lhvc_config_get(file, trackNum, 1);", "\t\t\t\t\tif (msub_type==GF_ISOM_SUBTYPE_HVT1) {\n\t\t\t\t\t\tconst u8 *data;\n\t\t\t\t\t\tu32 tsize;\n\t\t\t\t\t\tu32 is_default, tx,ty,tw,th, id, independent;\n\t\t\t\t\t\tBool full_frame;\n\t\t\t\t\t\tif (gf_isom_get_tile_info(file, trackNum, 1, &is_default, &id, &independent, &full_frame, &tx, &ty, &tw, &th)) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile - ID %d independent %d (x,y,w,h)=%d,%d,%d,%d \\n\", id, independent, tx, ty, tw, th);\n\t\t\t\t\t\t} else if (gf_isom_get_sample_group_info(file, trackNum, 1, GF_ISOM_SAMPLE_GROUP_TRIF, &is_default, &data, &tsize)) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile track containing a tile set\\n\");\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile track without tiling info\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (!hevccfg && !lhvccfg) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"\\tNon-compliant HEVC track: No hvcC or shcC found in sample description\\n\"));\n\t\t\t\t\t}", "\t\t\t\t\tif (gf_isom_get_reference_count(file, trackNum, GF_ISOM_REF_SABT)) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile base track\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif (hevccfg) {\n\t\t\t\t\t\tdump_hevc_track_info(file, trackNum, hevccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\t\t\t, &hevc_state\n#endif\n\t\t\t\t\t\t);\n\t\t\t\t\t\tgf_odf_hevc_cfg_del(hevccfg);\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif (lhvccfg) {\n\t\t\t\t\t\tdump_hevc_track_info(file, trackNum, lhvccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\t\t\t, &hevc_state\n#endif\n\t\t\t\t\t\t);\n\t\t\t\t\t\tgf_odf_hevc_cfg_del(lhvccfg);\n\t\t\t\t\t}", "\t\t\t\t\tif (gf_isom_get_oinf_info(file, trackNum, &oinf)) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tOperating Points Information -\");\n\t\t\t\t\t\tfprintf(stderr, \" scalability_mask %d (\", oinf->scalability_mask);\n\t\t\t\t\t\tswitch (oinf->scalability_mask) {\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\tfprintf(stderr, \"Multiview\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 4:\n\t\t\t\t\t\t\tfprintf(stderr, \"Spatial scalability\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 8:\n\t\t\t\t\t\t\tfprintf(stderr, \"Auxilary\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tfprintf(stderr, \"unknown\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//TODO: need to dump more info ?\n\t\t\t\t\t\tfprintf(stderr, \") num_profile_tier_level %d \", gf_list_count(oinf->profile_tier_levels) );\n\t\t\t\t\t\tfprintf(stderr, \" num_operating_points %d dependency layers %d \\n\", gf_list_count(oinf->operating_points), gf_list_count(oinf->dependency_layers) );\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\t/*OGG media*/\n\t\t\t\telse if (esd->decoderConfig->objectTypeIndication==GF_CODECID_THEORA) {\n\t\t\t\t\tchar *szName;\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tif (!strnicmp((char *) &esd->decoderConfig->decoderSpecificInfo->data[3], \"theora\", 6)) szName = \"Theora\";\n\t\t\t\t\telse szName = \"Unknown\";\n\t\t\t\t\tfprintf(stderr, \"Ogg/%s video / GPAC Mux - Visual Size %d x %d\\n\", szName, w, h);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t//check if we know this codec from its OTI\n\t\t\t\t\tu32 codec_id = gf_codecid_from_oti(GF_STREAM_VISUAL, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tif (codec_id) {\n\t\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\t\tfprintf(stderr, \"%s - Visual Size %d x %d\\n\", gf_codecid_name(codec_id), w, h);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!w || !h) {\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"Visual Size %d x %d\\n\", w, h);\n\t\t\t\t}\n\t\t\t\tif (gf_isom_get_rvc_config(file, trackNum, 1, &rvc_predef, NULL, NULL, NULL)==GF_OK) {\n\t\t\t\t\tfprintf(stderr, \"Has RVC signaled - Predefined configuration %d\\n\", rvc_predef);\n\t\t\t\t}", "\t\t\t} else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\tGF_M4ADecSpecInfo a_cfg;\n\t\t\t\tGF_Err e;\n\t\t\t\tu32 oti;\n#endif\n\t\t\t\tu32 codec_id;\n\t\t\t\tBool is_mp2 = GF_FALSE;\n\t\t\t\tswitch (esd->decoderConfig->objectTypeIndication) {\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_MP:\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_LCP:\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_SSRP:\n\t\t\t\t\tis_mp2 = GF_TRUE;\n\t\t\t\tcase GF_CODECID_AAC_MPEG4:\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\tif (!esd->decoderConfig->decoderSpecificInfo)\n\t\t\t\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t\t\telse\n\t\t\t\t\t\te = gf_m4a_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &a_cfg);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Corrupted AAC Config\\n\"));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchar *signaling = \"implicit\";\n\t\t\t\t\t\tchar *heaac = \"\";\n\t\t\t\t\t\tif (!is_mp2 && a_cfg.has_sbr) {\n\t\t\t\t\t\t\tif (a_cfg.has_ps) heaac = \"(HE-AAC v2) \";\n\t\t\t\t\t\t\telse heaac = \"(HE-AAC v1) \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (a_cfg.base_object_type==2) {\n\t\t\t\t\t\t\tif (a_cfg.has_ps || a_cfg.has_sbr)\n\t\t\t\t\t\t\t\tsignaling = \"backward compatible\";\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsignaling = \"hierarchical\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfprintf(stderr, \"%s (AOT=%d %s) %s- %d Channel(s) - SampleRate %d\", gf_m4a_object_type_name(a_cfg.base_object_type), a_cfg.base_object_type, signaling, heaac, a_cfg.nb_chan, a_cfg.base_sr);\n\t\t\t\t\t\tif (is_mp2) fprintf(stderr, \" (MPEG-2 Signaling)\");\n\t\t\t\t\t\tif (a_cfg.has_sbr) fprintf(stderr, \" - SBR: SampleRate %d Type %s\", a_cfg.sbr_sr, gf_m4a_object_type_name(a_cfg.sbr_object_type));\n\t\t\t\t\t\tif (a_cfg.has_ps) fprintf(stderr, \" - PS\");\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n#else\n\t\t\t\t\tfprintf(stderr, \"MPEG-2/4 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n#endif\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_MPEG2_PART3:\n\t\t\t\tcase GF_CODECID_MPEG_AUDIO:\n\t\t\t\t\tif (msub_type == GF_ISOM_SUBTYPE_MPEG4_CRYP) {\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-1/2 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n\t\t\t\t\t} else {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tGF_ISOSample *samp = gf_isom_get_sample(file, trackNum, 1, &oti);\n\t\t\t\t\t\tif (samp) {\n\t\t\t\t\t\t\tu32 mhdr = GF_4CC((u8)samp->data[0], (u8)samp->data[1], (u8)samp->data[2], (u8)samp->data[3]);\n\t\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\t\tfprintf(stderr, \"%s Audio - %d Channel(s) - SampleRate %d - Layer %d\\n\",\n\t\t\t\t\t\t\t gf_mp3_version_name(mhdr),\n\t\t\t\t\t\t\t gf_mp3_num_channels(mhdr),\n\t\t\t\t\t\t\t gf_mp3_sampling_rate(mhdr),\n\t\t\t\t\t\t\t gf_mp3_layer(mhdr)\n\t\t\t\t\t\t\t );\n\t\t\t\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Error fetching sample: %s\\n\", gf_error_to_string(gf_isom_last_error(file)) ));\n\t\t\t\t\t\t}\n#else\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-1/2 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n#endif\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_EVRC:\n\t\t\t\t\tfprintf(stderr, \"EVRC Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_SMV:\n\t\t\t\t\tfprintf(stderr, \"SMV Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_QCELP:\n\t\t\t\t\tfprintf(stderr, \"QCELP Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\t/*packetVideo hack for EVRC...*/\n\t\t\t\tcase GF_CODECID_EVRC_PV:\n\t\t\t\t\tif (esd->decoderConfig->decoderSpecificInfo && (esd->decoderConfig->decoderSpecificInfo->dataLength==8)\n\t\t\t\t\t && !strnicmp((char *)esd->decoderConfig->decoderSpecificInfo->data, \"pvmm\", 4)) {\n\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\tfprintf(stderr, \"EVRC Audio (PacketVideo Mux) - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tcodec_id = gf_codecid_from_oti(GF_STREAM_AUDIO, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tif (codec_id) {\n\t\t\t\t\t\tfprintf(stderr, \"%s - Sample Rate %d - %d channel(s)\\n\", gf_codecid_name(codec_id), sr, nb_ch);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (esd->decoderConfig->streamType==GF_STREAM_SCENE) {\n\t\t\t\tif (esd->decoderConfig->objectTypeIndication<=4) {\n\t\t\t\t\tGF_BIFSConfig *b_cfg = gf_odf_get_bifs_config(esd->decoderConfig->decoderSpecificInfo, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tfprintf(stderr, \"BIFS Scene description - %s stream\\n\", b_cfg->elementaryMasks ? \"Animation\" : \"Command\");\n\t\t\t\t\tif (full_dump && !b_cfg->elementaryMasks) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tWidth %d Height %d Pixel Metrics %s\\n\", b_cfg->pixelWidth, b_cfg->pixelHeight, b_cfg->pixelMetrics ? \"yes\" : \"no\");\n\t\t\t\t\t}\n\t\t\t\t\tgf_odf_desc_del((GF_Descriptor *)b_cfg);\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_AFX) {\n\t\t\t\t\tu8 tag = esd->decoderConfig->decoderSpecificInfo ? esd->decoderConfig->decoderSpecificInfo->data[0] : 0xFF;\n\t\t\t\t\tconst char *afxtype = gf_stream_type_afx_name(tag);\n\t\t\t\t\tfprintf(stderr, \"AFX Stream - type %s (%d)\\n\", afxtype, tag);\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_FONT) {\n\t\t\t\t\tfprintf(stderr, \"Font Data stream\\n\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_LASER) {\n\t\t\t\t\tGF_LASERConfig l_cfg;\n\t\t\t\t\tgf_odf_get_laser_config(esd->decoderConfig->decoderSpecificInfo, &l_cfg);\n\t\t\t\t\tfprintf(stderr, \"LASER Stream - %s\\n\", l_cfg.newSceneIndicator ? \"Full Scene\" : \"Scene Segment\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_TEXT_MPEG4) {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Streaming Text stream\\n\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_SYNTHESIZED_TEXTURE) {\n\t\t\t\t\tfprintf(stderr, \"Synthetized Texture stream stream\\n\");\n\t\t\t\t} else {\n\t\t\t\t\tM4_LOG(GF_LOG_WARNING, (\"Unknown Systems stream OTI %d\\n\", esd->decoderConfig->objectTypeIndication));\n\t\t\t\t}\n\t\t\t}", "\t\t\t/*sync is only valid if we open all tracks to take care of default MP4 sync..*/\n\t\t\tif (!full_dump) {\n\t\t\t\tif (dump_m4sys) {\n\t\t\t\t\tif (!esd->OCRESID || (esd->OCRESID == esd->ESID))\n\t\t\t\t\t\tfprintf(stderr, \"Self-synchronized\\n\");\n\t\t\t\t\telse\n\t\t\t\t\t\tfprintf(stderr, \"Synchronized on stream %d\\n\", esd->OCRESID);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"\\tDecoding Buffer size %d - Bitrate: avg %d - max %d kbps\\n\", esd->decoderConfig->bufferSizeDB, esd->decoderConfig->avgBitrate/1000, esd->decoderConfig->maxBitrate/1000);\n\t\t\t\tif (esd->dependsOnESID)\n\t\t\t\t\tfprintf(stderr, \"\\tDepends on stream %d for decoding\\n\", esd->dependsOnESID);\n\t\t\t\telse\n\t\t\t\t\tfprintf(stderr, \"\\tNo stream dependencies for decoding\\n\");", "\t\t\t\tfprintf(stderr, \"\\tStreamPriority %d\\n\", esd->streamPriority);\n\t\t\t\tif (esd->URLString) fprintf(stderr, \"\\tRemote Data Source %s\\n\", esd->URLString);\n\t\t\t}\n\t\t\tgf_odf_desc_del((GF_Descriptor *) esd);\n\t\t}\n\t} else if (msub_type == GF_ISOM_SUBTYPE_AV01) {\n\t\tGF_AV1Config *av1c;\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\tAOM AV1 stream - Resolution %d x %d\\n\", w, h);", "\t\tav1c = gf_isom_av1_config_get(file, trackNum, 1);", "\t\tfprintf(stderr, \"\\tversion=%u, profile=%u, level_idx0=%u, tier=%u\\n\", (u32)av1c->version, (u32)av1c->seq_profile, (u32)av1c->seq_level_idx_0, (u32)av1c->seq_tier_0);\n\t\tfprintf(stderr, \"\\thigh_bitdepth=%u, twelve_bit=%u, monochrome=%u\\n\", (u32)av1c->high_bitdepth, (u32)av1c->twelve_bit, (u32)av1c->monochrome);\n\t\tfprintf(stderr, \"\\tchroma: subsampling_x=%u, subsampling_y=%u, sample_position=%u\\n\", (u32)av1c->chroma_subsampling_x, (u32)av1c->chroma_subsampling_y, (u32)av1c->chroma_sample_position);", "\t\tif (av1c->initial_presentation_delay_present)\n\t\t\tfprintf(stderr, \"\\tInitial presentation delay %u\\n\", (u32) av1c->initial_presentation_delay_minus_one+1);", "\t\tcount = gf_list_count(av1c->obu_array);\n\t\tfor (i=0; i<count; i++) {\n\t\t\tu8 hash[20];\n\t\t\tGF_AV1_OBUArrayEntry *obu = gf_list_get(av1c->obu_array, i);\n\t\t\tgf_sha1_csum((u8*)obu->obu, (u32)obu->obu_length, hash);\n\t\t\tfprintf(stderr, \"\\tOBU#%d %s hash: \", i+1, gf_av1_get_obu_name(obu->obu_type) );\n\t\t\tfor (j=0; j<20; j++) fprintf(stderr, \"%02X\", hash[j]);\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t}\n\t\tgf_odf_av1_cfg_del(av1c);", "\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_H263) {\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\t3GPP H263 stream - Resolution %d x %d\\n\", w, h);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_MJP2) {\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\tMotionJPEG2000 stream - Resolution %d x %d\\n\", w, h);\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_3GP_AMR) || (msub_type == GF_ISOM_SUBTYPE_3GP_AMR_WB)) {\n\t\tfprintf(stderr, \"\\t3GPP AMR%s stream - Sample Rate %d - %d channel(s) %d bps\\n\", (msub_type == GF_ISOM_SUBTYPE_3GP_AMR_WB) ? \" Wide Band\" : \"\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_EVRC) {\n\t\tfprintf(stderr, \"\\t3GPP EVRC stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_QCELP) {\n\t\tfprintf(stderr, \"\\t3GPP QCELP stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_MP3) {\n\t\tfprintf(stderr, \"\\tMPEG 1/2 Audio stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_AC3) || (msub_type == GF_ISOM_SUBTYPE_EC3)) {\n\t\tu32 br = 0;\n\t\tconst char *lfe = \"\";\n\t\tBool is_ec3 = (msub_type == GF_ISOM_SUBTYPE_EC3) ? GF_TRUE : GF_FALSE;\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\tGF_AC3Config *ac3 = gf_isom_ac3_config_get(file, trackNum, 1);\n\t\tif (ac3) {\n\t\t\tnb_ch = gf_ac3_get_channels(ac3->streams[0].acmod);\n\t\t\tfor (i=0; i<ac3->streams[0].nb_dep_sub; ++i) {\n\t\t\t\tassert(ac3->streams[0].nb_dep_sub == 1);\n\t\t\t\tnb_ch += gf_ac3_get_channels(ac3->streams[0].chan_loc);\n\t\t\t}\n\t\t\tif (ac3->streams[0].lfon) lfe = \".1\";\n\t\t\tbr = ac3->is_ec3 ? ac3->brcode : gf_ac3_get_bitrate(ac3->brcode);\n\t\t\tis_ec3 = ac3->is_ec3;\n\t\t\tgf_free(ac3);\n\t\t}\n#endif\n\t\tfprintf(stderr, \"\\t%s stream - Sample Rate %d - %d%s channel(s) - bitrate %d\\n\", is_ec3 ? \"EC-3\" : \"AC-3\", sr, nb_ch, lfe, br);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_SMV) {\n\t\tfprintf(stderr, \"\\t3GPP SMV stream - Sample Rate %d - %d channel(s) %d bits per samples\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_DIMS) {\n\t\tu32 w, h;\n\t\tGF_DIMSDescription dims;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);", "\t\tgf_isom_get_dims_description(file, trackNum, 1, &dims);\n\t\tfprintf(stderr, \"\\t3GPP DIMS stream - size %d x %d - Profile %d - Level %d\\n\", w, h, dims.profile, dims.level);\n\t\tfprintf(stderr, \"\\tpathComponents: %d - useFullRequestHost: %s\\n\", dims.pathComponents, dims.fullRequestHost ? \"yes\" : \"no\");\n\t\tfprintf(stderr, \"\\tstream type: %s - redundant: %s\\n\", dims.streamType ? \"primary\" : \"secondary\", (dims.containsRedundant==1) ? \"main\" : ((dims.containsRedundant==2) ? \"redundant\" : \"main+redundant\") );\n\t\tif (dims.textEncoding[0]) fprintf(stderr, \"\\ttext encoding %s\\n\", dims.textEncoding);\n\t\tif (dims.contentEncoding[0]) fprintf(stderr, \"\\tcontent encoding %s\\n\", dims.contentEncoding);\n\t\tif (dims.content_script_types) fprintf(stderr, \"\\tscript languages %s\\n\", dims.content_script_types);\n\t} else if (mtype==GF_ISOM_MEDIA_HINT) {\n\t\tu32 refTrack;\n\t\ts32 refCount = gf_isom_get_reference_count(file, trackNum, GF_ISOM_REF_HINT);\n\t\tif (refCount>0) {\n\t\t\tfprintf(stderr, \"Streaming Hint Track for track%s \", (refCount>1) ? \"s\" :\"\");\n\t\t\tfor (i=0; i<(u32) refCount; i++) {\n\t\t\t\tgf_isom_get_reference(file, trackNum, GF_ISOM_REF_HINT, i+1, &refTrack);\n\t\t\t\tif (i) fprintf(stderr, \" - \");\n\t\t\t\tfprintf(stderr, \"ID %d\", gf_isom_get_track_id(file, refTrack));\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"Streaming Hint Track (no refs)\\n\");\n\t\t}\n#ifndef GPAC_DISABLE_ISOM_HINTING\n\t\trefCount = gf_isom_get_payt_count(file, trackNum);\n\t\tif (refCount>0) {\n\t\t\tfor (i=0; i<(u32) refCount; i++) {\n\t\t\t\tconst char *name = gf_isom_get_payt_info(file, trackNum, i+1, &refTrack);\n\t\t\t\tfprintf(stderr, \"\\tPayload ID %d: type %s\\n\", refTrack, name);\n\t\t\t}\n\t\t}\n#endif\n\t} else if (mtype==GF_ISOM_MEDIA_FLASH) {\n\t\tfprintf(stderr, \"Macromedia Flash Movie\\n\");\n\t} else if ((mtype==GF_ISOM_MEDIA_TEXT) || (mtype==GF_ISOM_MEDIA_SUBT) || (mtype==GF_ISOM_MEDIA_MPEG_SUBT)) {\n\t\tu32 w, h;\n\t\ts16 l;\n\t\ts32 tx, ty;\n\t\tconst char *content_encoding = NULL;\n\t\tconst char *mime = NULL;\n\t\tconst char *config = NULL;\n\t\tconst char *_namespace = NULL;\n\t\tconst char *schema_loc = NULL;\n\t\tconst char *auxiliary_mimes = NULL;\n\t\tgf_isom_get_track_layout_info(file, trackNum, &w, &h, &tx, &ty, &l);\n\t\tif (msub_type == GF_ISOM_SUBTYPE_SBTT) {\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Textual Subtitle Stream \");\n\t\t\tfprintf(stderr, \"- mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_STXT) {\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Simple Timed Text Stream \");\n\t\t\tfprintf(stderr, \"- mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_STPP) {\n\t\t\tgf_isom_xml_subtitle_get_description(file, trackNum, 1, &_namespace, &schema_loc, &auxiliary_mimes);\n\t\t\tfprintf(stderr, \"XML Subtitle Stream \");\n\t\t\tfprintf(stderr, \"- namespace %s\", _namespace);\n\t\t\tif (schema_loc != NULL) {\n\t\t\t\tfprintf(stderr, \" - schema-location %s\", schema_loc);\n\t\t\t}\n\t\t\tif (auxiliary_mimes != NULL) {\n\t\t\t\tfprintf(stderr, \" - auxiliary-mime-types %s\", auxiliary_mimes);\n\t\t\t}\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown Text Stream\");\n\t\t}\n\t\tfprintf(stderr, \"\\n Size %d x %d - Translation X=%d Y=%d - Layer %d\\n\", w, h, tx, ty, l);\n\t} else if (mtype == GF_ISOM_MEDIA_META) {\n\t\tconst char *content_encoding = NULL;\n\t\tif (msub_type == GF_ISOM_SUBTYPE_METT) {\n\t\t\tconst char *mime = NULL;\n\t\t\tconst char *config = NULL;\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Textual Metadata Stream - mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_METX) {\n\t\t\tconst char *_namespace = NULL;\n\t\t\tconst char *schema_loc = NULL;\n\t\t\tgf_isom_get_xml_metadata_description(file, trackNum, 1, &_namespace, &schema_loc, &content_encoding);\n\t\t\tfprintf(stderr, \"XML Metadata Stream - namespace %s\", _namespace);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (schema_loc != NULL) {\n\t\t\t\tfprintf(stderr, \" - schema-location %s\", schema_loc);\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown Metadata Stream\\n\");\n\t\t}\n\t} else if ((msub_type==GF_ISOM_SUBTYPE_VVC1) || (msub_type==GF_ISOM_SUBTYPE_VVI1)) {\n\t\tGF_VVCConfig *vvccfg;\n\t\tu32 w, h;\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\tVVCState *vvc_state;\n\t\tGF_SAFEALLOC(vvc_state, VVCState);\n\t\tif (vvc_state) vvc_state->sps_active_idx = -1;\n#endif", "\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\tfprintf(stderr, \"VVC Video - Visual Size %d x %d\\n\", w, h);\n\t\tvvccfg = gf_isom_vvc_config_get(file, trackNum, 1);", "\t\tif (!vvccfg) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Non-compliant VVC track: No vvcC found in sample description\\n\"));\n\t\t} else {\n\t\t\tdump_vvc_track_info(file, trackNum, vvccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\t\t\t, vvc_state\n#endif\n\t\t\t);\n\t\t\tgf_odf_vvc_cfg_del(vvccfg);\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t}\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\tif (vvc_state) gf_free(vvc_state);\n#endif\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_MH3D_MHA1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHA2)\n\t\t\t|| (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM2)\n\t) {\n\t\tconst u8 *compat_profiles;\n\t\tu32 nb_compat_profiles;\n\t\tBool valid = GF_FALSE;\n\t\tBool allow_inband = GF_FALSE;\n\t\tif ( (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM2))\n\t\t\tallow_inband = GF_TRUE;", "\t\tfprintf(stderr, \"\\tMPEG-H Audio stream - Sample Rate %d\\n\", sr);", "\t\tesd = gf_media_map_esd(file, trackNum, 1);\n\t\tif (!esd || !esd->decoderConfig || !esd->decoderConfig->decoderSpecificInfo\n\t\t\t|| !esd->decoderConfig->decoderSpecificInfo->data\n\t\t) {\n\t\t\tif (allow_inband) {\n\t\t\t\tGF_ISOSample *samp = gf_isom_get_sample(file, trackNum, 1, NULL);\n\t\t\t\tif (samp) {\n\t\t\t\t\tu64 ch_layout=0;\n\t\t\t\t\ts32 PL = gf_mpegh_get_mhas_pl(samp->data, samp->dataLength, &ch_layout);\n\t\t\t\t\tif (PL>=0) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tProfileLevelIndication: 0x%02X\", PL);\n\t\t\t\t\t\tif (ch_layout)\n\t\t\t\t\t\t\tfprintf(stderr, \" - Reference Channel Layout %s\", gf_audio_fmt_get_layout_name(ch_layout) );\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t\t}\n\t\t\t\tvalid = GF_TRUE;\n\t\t\t}\n\t\t} else if (esd->decoderConfig->decoderSpecificInfo->dataLength>=5) {\n\t\t\tfprintf(stderr, \"\\tProfileLevelIndication: 0x%02X - Reference Channel Layout %s\\n\", esd->decoderConfig->decoderSpecificInfo->data[1]\n\t\t\t\t, gf_audio_fmt_get_layout_name_from_cicp(esd->decoderConfig->decoderSpecificInfo->data[2])\n\t\t\t);\n\t\t\tvalid = GF_TRUE;\n\t\t}\n\t\tif (!valid) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Invalid MPEG-H audio config\\n\"));\n\t\t}\n\t\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);\n\t\tcompat_profiles = gf_isom_get_mpegh_compatible_profiles(file, trackNum, 1, &nb_compat_profiles);\n\t\tfor (i=0; i<nb_compat_profiles; i++) {\n\t\t\tif (!i)\n\t\t\t\tfprintf(stderr, \"\\tCompatible profiles:\");\n\t\t\tfprintf(stderr, \" 0x%02X\", compat_profiles[i]);\n\t\t}\n\t\tif (i) fprintf(stderr, \"\\n\");\n\t} else if (msub_type==GF_ISOM_SUBTYPE_MLPA) {\n\t\tu32 fmt, prate;\n\t\tif (gf_isom_truehd_config_get(file, trackNum, 1, &fmt, &prate) != GF_OK) {\n\t\t\tfprintf(stderr, \"\\tInvalid TrueHD audio config\\n\");\n\t\t}\n\t\tfprintf(stderr, \"TrueHD Audio stream - Sample Rate %u - channels %u - format %u peak rate %u\\n\", sr, nb_ch, fmt, prate);\n\t} else if (codecid) {\n\t\tif (gf_isom_is_video_handler_type(mtype) ) {\n\t\t\tu32 w, h;\n\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\tfprintf(stderr, \"%s - Resolution %d x %d\\n\", gf_codecid_name(codecid), w, h);\n\t\t} else if (mtype==GF_ISOM_MEDIA_AUDIO) {\n\t\t\tgf_isom_get_audio_info(file, trackNum, 1, &sr, &nb_ch, NULL);\n\t\t\tfprintf(stderr, \"%s - Sample Rate %d - %d channel(s)\\n\", gf_codecid_name(codecid), sr, nb_ch);\n\t\t} else {\n\t\t\tfprintf(stderr, \"%s\\n\", gf_codecid_name(codecid) );\n\t\t}\n\t} else if (pfmt) {\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"Raw video %s - Resolution %d x %d\\n\", gf_pixel_fmt_name(pfmt), w, h);\n\t} else if (msub_type==GF_QT_SUBTYPE_TMCD) {\n\t\tu32 stsd_idx;\n\t\tGF_ISOSample *sample = gf_isom_get_sample(file, trackNum, 1, &stsd_idx);\n\t\tfprintf(stderr, \"Time Code stream\\n\");\n\t\tif (sample) {\n\t\t\tchar szTimecode[100];\n\t\t\tu32 tmcd_flags, tmcd_num, tmcd_den, tmcd_fpt;", "\t\t\tgf_isom_get_tmcd_config(file, trackNum, stsd_idx, &tmcd_flags, &tmcd_num, &tmcd_den, &tmcd_fpt);", "\t\t\tgf_inspect_format_timecode(sample->data, sample->dataLength, tmcd_flags, tmcd_num, tmcd_den, tmcd_fpt, szTimecode);", "\t\t\tgf_isom_sample_del(&sample);\n\t\t\tfprintf(stderr, \"\\tFirst timecode: %s\\n\", szTimecode);\n\t\t}\n\t} else {\n\t\tGF_GenericSampleDescription *udesc;", "\t\tudesc = gf_isom_get_generic_sample_description(file, trackNum, 1);\n\t\tif (udesc) {\n\t\t\tif (gf_isom_is_video_handler_type(mtype) ) {\n fprintf(stderr, \"%s - Compressor \\\"%s\\\" - Resolution %d x %d\\n\",\n\t\t\t\t\t\t( (mtype == GF_ISOM_MEDIA_VISUAL ? \"Visual\" : \"Auxiliary Video\") ),\n udesc->compressor_name, udesc->width, udesc->height);\n\t\t\t} else if (mtype==GF_ISOM_MEDIA_AUDIO) {\n\t\t\t\tfprintf(stderr, \"Audio - Sample Rate %d - %d channel(s)\\n\", udesc->samplerate, udesc->nb_channels);\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"Unknown media type\\n\");\n\t\t\t}\n\t\t\tif (udesc->vendor_code)\n\t\t\t\tfprintf(stderr, \"\\tVendor code \\\"%s\\\" - Version %d - revision %d\\n\", gf_4cc_to_str(udesc->vendor_code), udesc->version, udesc->revision);", "\t\t\tif (udesc->extension_buf) {\n\t\t\t\tfprintf(stderr, \"\\tCodec configuration data size: %d bytes\\n\", udesc->extension_buf_size);\n\t\t\t\tgf_free(udesc->extension_buf);\n\t\t\t}\n\t\t\tgf_free(udesc);\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown track type\\n\");\n\t\t}\n\t}", "\n\t/*Crypto info*/\n\tif (gf_isom_is_track_encrypted(file, trackNum)) {\n\t\tconst char *scheme_URI, *KMS_URI;\n\t\tu32 scheme_type, version;\n\t\tu32 IV_size;\n\t\tBool use_sel_enc;", "\t\tif (gf_isom_is_ismacryp_media(file, trackNum, 1)) {\n\t\t\tgf_isom_get_ismacryp_info(file, trackNum, 1, NULL, &scheme_type, &version, &scheme_URI, &KMS_URI, &use_sel_enc, &IV_size, NULL);\n\t\t\tfprintf(stderr, \"\\n\\tProtected by ISMA E&A scheme %s (version %d)\\n\", gf_4cc_to_str(scheme_type), version);\n\t\t\tif (scheme_URI) fprintf(stderr, \"scheme location: %s\\n\", scheme_URI);\n\t\t\tif (KMS_URI) {\n\t\t\t\tif (!strnicmp(KMS_URI, \"(key)\", 5)) fprintf(stderr, \"\\tKMS location: key in file\\n\");\n\t\t\t\telse fprintf(stderr, \"\\tKMS location: %s\\n\", KMS_URI);\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\tSelective Encryption: %s\\n\", use_sel_enc ? \"Yes\" : \"No\");\n\t\t\tif (IV_size) fprintf(stderr, \"\\tInitialization Vector size: %d bits\\n\", IV_size*8);\n\t\t} else if (gf_isom_is_omadrm_media(file, trackNum, 1)) {\n\t\t\tconst char *textHdrs;\n\t\t\tu32 enc_type, hdr_len;\n\t\t\tu64 orig_len;\n\t\t\tgf_isom_get_omadrm_info(file, trackNum, 1, NULL, &scheme_type, &version, &scheme_URI, &KMS_URI, &textHdrs, &hdr_len, &orig_len, &enc_type, &use_sel_enc, &IV_size, NULL);\n\t\t\tfprintf(stderr, \"\\n\\tProtected by OMA DRM scheme %s (version %d)\\n\", gf_4cc_to_str(scheme_type), version);\n\t\t\tfprintf(stderr, \"\\tRights Issuer: %s\\n\", KMS_URI);\n\t\t\tfprintf(stderr, \"\\tContent ID: %s\\n\", scheme_URI);\n\t\t\tif (textHdrs) {\n\t\t\t\tu32 offset;\n\t\t\t\tconst char *start = textHdrs;\n\t\t\t\tfprintf(stderr, \"\\tOMA Textual Headers:\\n\");\n\t\t\t\ti=0;\n\t\t\t\toffset=0;\n\t\t\t\twhile (i<hdr_len) {\n\t\t\t\t\tif (start[i]==0) {\n\t\t\t\t\t\tfprintf(stderr, \"\\t\\t%s\\n\", start+offset);\n\t\t\t\t\t\toffset=i+1;\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \"\\\\tt%s\\n\", start+offset);\n\t\t\t}\n\t\t\tif (orig_len) fprintf(stderr, \"\\tOriginal media size \"LLD\"\\n\", orig_len);\n\t\t\tfprintf(stderr, \"\\tEncryption algorithm %s\\n\", (enc_type==1) ? \"AEA 128 CBC\" : (enc_type ? \"AEA 128 CTR\" : \"None\"));\n\t\t\tfprintf(stderr, \"\\tSelective Encryption: %s\\n\", use_sel_enc ? \"Yes\" : \"No\");\n\t\t\tif (IV_size) fprintf(stderr, \"\\tInitialization Vector size: %d bits\\n\", IV_size*8);\n\t\t} else if(gf_isom_is_cenc_media(file, trackNum, 1)) {\n\t\t\tconst u8 *def_key;\n\t\t\tu32 def_key_size;\n\t\t\tBool IsEncrypted;\n\t\t\tu8 crypt_byte_block, skip_byte_block;\n\t\t\tIV_size = 0;\n\t\t\tgf_isom_get_cenc_info(file, trackNum, 1, NULL, &scheme_type, &version);", "\t\t\tgf_isom_cenc_get_default_info(file, trackNum, 1, NULL, &IsEncrypted, &crypt_byte_block, &skip_byte_block, &def_key, &def_key_size);", "\t\t\tfprintf(stderr, \"\\n\\tProtected by CENC scheme %s version 0x%08X\", gf_4cc_to_str(scheme_type), version);", "\t\t\tif (crypt_byte_block && skip_byte_block)\n\t\t\t\tfprintf(stderr, \" - Pattern %d:%d\", (u32) skip_byte_block, (u32) crypt_byte_block);\n\t\t\tif (def_key && def_key[0])\n\t\t\t\tfprintf(stderr, \" - MultiKey\");", "\t\t\tfprintf(stderr, \"\\n\");\n\t\t\tdump_key_info(def_key, def_key_size, IsEncrypted);", "\t\t} else if(gf_isom_is_adobe_protection_media(file, trackNum, 1)) {\n\t\t\tgf_isom_get_adobe_protection_info(file, trackNum, 1, NULL, &scheme_type, &version, NULL);\n\t\t\tfprintf(stderr, \"\\nProtected by Adobe scheme %s (version %d)\\n\", gf_4cc_to_str(scheme_type), version);\n\t\t} else {\n\t\t\tfprintf(stderr, \"\\nProtected by unknown scheme %s\\n\", gf_4cc_to_str(gf_isom_is_media_encrypted(file, trackNum, 0) ));\n\t\t}\n\t\tfprintf(stderr, \"\\n\");\n\t}", "\tif ( gf_media_get_rfc_6381_codec_name(file, trackNum, szCodec, GF_FALSE, GF_FALSE) == GF_OK) {\n\t\tfprintf(stderr, \"\\tRFC6381 Codec Parameters: %s\\n\", szCodec);\n\t}", "\n\tDumpMetaItem(file, 0, trackNum, \"\\tTrack Meta\");", "\tgf_isom_get_track_switch_group_count(file, trackNum, &alt_group, &nb_groups);\n\tif (alt_group) {\n\t\tfprintf(stderr, \"Alternate Group ID %d\\n\", alt_group);\n\t\tfor (i=0; i<nb_groups; i++) {\n\t\t\tu32 nb_crit, switchGroupID;\n\t\t\tconst u32 *criterias = gf_isom_get_track_switch_parameter(file, trackNum, i+1, &switchGroupID, &nb_crit);\n\t\t\tif (!nb_crit) {\n\t\t\t\tfprintf(stderr, \"\\tNo criteria in %s group\\n\", switchGroupID ? \"switch\" : \"alternate\");\n\t\t\t} else {\n\t\t\t\tif (switchGroupID) {\n\t\t\t\t\tfprintf(stderr, \"\\tSwitchGroup ID %d criterias: \", switchGroupID);\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(stderr, \"\\tAlternate Group criterias: \");\n\t\t\t\t}\n\t\t\t\tfor (j=0; j<nb_crit; j++) {\n\t\t\t\t\tif (j) fprintf(stderr, \" \");\n\t\t\t\t\tfprintf(stderr, \"%s\", gf_4cc_to_str(criterias[j]) );\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t}\n\t\t}\n\t}", "\tswitch (gf_isom_has_sync_points(file, trackNum)) {\n\tcase 0:\n\t\tfprintf(stderr, \"\\tAll samples are sync\\n\");\n\t\tbreak;\n\tcase 1:\n\t{\n\t\tu32 nb_sync = gf_isom_get_sync_point_count(file, trackNum) - 1;\n\t\tif (! nb_sync) {\n\t\t\tfprintf(stderr, \"\\tOnly one sync sample\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"\\tAverage GOP length: %d samples\\n\", gf_isom_get_sample_count(file, trackNum) / nb_sync);\n\t\t}\n\t}\n\tbreak;\n\tcase 2:\n\t\tfprintf(stderr, \"\\tNo sync sample found\\n\");\n\t\tbreak;\n\t}\n\tfprintf(stderr, \"\\tMax sample duration: %d / %d\\n\", gf_isom_get_max_sample_delta(file, trackNum), timescale);", "\tif (!full_dump) {\n\t\tfprintf(stderr, \"\\n\");\n\t\treturn;\n\t}", "\tdur = size = 0;\n\tmax_rate = rate = 0;\n\ttime_slice = 0;\n\tts = gf_isom_get_media_timescale(file, trackNum);\n\tcsize = gf_isom_get_constant_sample_size(file, trackNum);\n\tcdur = gf_isom_get_constant_sample_duration(file, trackNum);\n\tcount = gf_isom_get_sample_count(file, trackNum);\n\tif (csize && cdur) {\n\t\tsize = count * csize;\n\t\tdur = cdur * count;\n\t} else {", "\t\tfor (j=0; j<count; j++) {\n\t\t\tGF_ISOSample *samp;\n\t\t\tif (is_od_track) {\n\t\t\t\tsamp = gf_isom_get_sample(file, trackNum, j+1, NULL);\n\t\t\t} else {\n\t\t\t\tsamp = gf_isom_get_sample_info(file, trackNum, j+1, NULL, NULL);\n\t\t\t}\n\t\t\tif (!samp) {\n\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to fetch sample %d\\n\", j+1));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdur = samp->DTS+samp->CTS_Offset;\n\t\t\tsize += samp->dataLength;\n\t\t\trate += samp->dataLength;\n\t\t\tif (samp->DTS - time_slice > ts) {\n\t\t\t\tDouble max_tmp = rate * ts / (samp->DTS - time_slice);\n\t\t\t\tif (max_rate < max_tmp )\n\t\t\t\t\tmax_rate = max_tmp;", "\t\t\t\trate = 0;\n\t\t\t\ttime_slice = samp->DTS;\n\t\t\t}\n\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t}\n\tfprintf(stderr, \"\\nComputed info from media:\\n\");\n\tif (csize && cdur) {\n\t\tfprintf(stderr, \"\\tConstant sample size %d bytes and dur %d / %d\\n\", csize, cdur, ts);\n\t}\n\tscale = 1000.0 / ts;\n\tdur = (u64) (scale * dur);\n\tfprintf(stderr, \"\\tTotal size \"LLU\" bytes - Total samples duration \"LLU\" ms\\n\", size, dur);\n\tif (!dur) {\n\t\tfprintf(stderr, \"\\n\");\n\t\treturn;\n\t}\n\t/*rate in byte, dur is in ms*/\n\trate = 8000.0 * size / dur;", "\tif (!max_rate)\n\t\tmax_rate = rate;\n\telse\n\t\tmax_rate *= 8.0;", "\tif (rate >= 1500) {\n\t\tfprintf(stderr, \"\\tAverage rate %.2f kbps - Max Rate %.2f kbps\\n\", rate/1000, max_rate/1000);\n\t} else {\n\t\tfprintf(stderr, \"\\tAverage rate %.2f bps - Max Rate %.2f bps\\n\", rate, max_rate);\n\t}", "\t{\n\t\tu32 dmin, dmax, davg, smin, smax, savg;\n\t\tgf_isom_get_chunks_infos(file, trackNum, &dmin, &davg, &dmax, &smin, &savg, &smax);\n\t\tfprintf(stderr, \"\\tChunk durations: min %d ms - max %d ms - average %d ms\\n\", (1000*dmin)/ts, (1000*dmax)/ts, (1000*davg)/ts);\n\t\tfprintf(stderr, \"\\tChunk sizes (bytes): min %d - max %d - average %d\\n\", smin, smax, savg);\n\t}\n\tfprintf(stderr, \"\\n\");", "\tcount = gf_isom_get_chapter_count(file, trackNum);\n\tif (count) {\n\t\tconst char *name;\n\t\tu64 time;\n\t\tfprintf(stderr, \"\\nChapters:\\n\");\n\t\tfor (j=0; j<count; j++) {\n\t\t\tgf_isom_get_chapter(file, trackNum, j+1, &time, &name);\n\t\t\tfprintf(stderr, \"\\tChapter #%d - %s - \\\"%s\\\"\\n\", j+1, format_duration(time, 1000, szDur), name);\n\t\t}\n\t}\n}", "void DumpMovieInfo(GF_ISOFile *file)\n{\n\tGF_InitialObjectDescriptor *iod;\n\tBool dump_m4sys = GF_FALSE;\n\tu32 i, brand, min, timescale, count, data_len;\n\tconst u8 *data;\n\tu64 create, modif;\n\tBool has_itags = GF_FALSE;\n\tchar szDur[50];", "\tDumpMetaItem(file, 1, 0, \"# File Meta\");\n\tif (!gf_isom_has_movie(file)) {\n\t\tif (gf_isom_has_segment(file, &brand, &min)) {\n\t\t\tcount = gf_isom_segment_get_fragment_count(file);\n\t\t\tfprintf(stderr, \"File is a segment - %d movie fragments - Brand %s (version %d):\\n\", count, gf_4cc_to_str(brand), min);\n\t\t\tfor (i=0; i<count; i++) {\n\t\t\t\tu32 j, traf_count = gf_isom_segment_get_track_fragment_count(file, i+1);\n\t\t\t\tfor (j=0; j<traf_count; j++) {\n\t\t\t\t\tu32 ID;\n\t\t\t\t\tu64 tfdt;\n\t\t\t\t\tID = gf_isom_segment_get_track_fragment_decode_time(file, i+1, j+1, &tfdt);\n\t\t\t\t\tfprintf(stderr, \"\\tFragment #%d Track ID %d - TFDT \"LLU\"\\n\", i+1, ID, tfdt);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfprintf(stderr, \"File has no movie (moov) - static data container\\n\");\n\t\t}\n\t\treturn;\n\t}", "\ttimescale = gf_isom_get_timescale(file);\n\ti=gf_isom_get_track_count(file);\n\tfprintf(stderr, \"# Movie Info - %d track%s - TimeScale %d\\n\", i, i>1 ? \"s\" : \"\", timescale);", "\tmodif = gf_isom_get_duration(file);\n\tcreate = gf_isom_get_original_duration(file);\n\tfprintf(stderr, \"Duration %s\", format_duration(create, timescale, szDur));\n\tif (create!=modif) {\n\t\tfprintf(stderr, \" (recomputed %s)\", format_duration(modif, timescale, szDur));\n\t}\n\tfprintf(stderr, \"\\n\");", "#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\tif (gf_isom_is_fragmented(file)) {\n\t\tfprintf(stderr, \"Fragmented: yes - duration %s\\n%d fragments - %d SegmentIndexes\\n\", format_duration(gf_isom_get_fragmented_duration(file), timescale, szDur), gf_isom_get_fragments_count(file, 0) , gf_isom_get_fragments_count(file, 1) );\n\t} else {\n\t\tfprintf(stderr, \"Fragmented: no\\n\");\n\t}\n#endif", "\tif (gf_isom_moov_first(file))\n\t\tfprintf(stderr, \"Progressive (moov before mdat)\\n\");", "\tif (gf_isom_get_brand_info(file, &brand, &min, &count) == GF_OK) {\n\t\tfprintf(stderr, \"Major Brand %s - version %d - compatible brands:\", gf_4cc_to_str(brand), min);\n\t\tfor (i=0; i<count;i++) {\n\t\t\tif (gf_isom_get_alternate_brand(file, i+1, &brand)==GF_OK)\n\t\t\t\tfprintf(stderr, \" %s\", gf_4cc_to_str(brand) );\n\t\t}\n\t\tfprintf(stderr, \"\\n\");\n\t}\n\tgf_isom_get_creation_time(file, &create, &modif);\n\tfprintf(stderr, \"Created: %s\", format_date(create, szDur));\n\tif (create != modif)\n\t\tfprintf(stderr, \"Modified: %s\", format_date(modif, szDur));\n\tfprintf(stderr, \"\\n\");", "\tDumpMetaItem(file, 0, 0, \"# Movie Meta\");", "\tiod = (GF_InitialObjectDescriptor *) gf_isom_get_root_od(file);\n\tif (iod) {\n\t\tu32 desc_size = gf_odf_desc_size((GF_Descriptor *)iod);\n\t\tif (iod->tag == GF_ODF_IOD_TAG) {\n\t\t\tfprintf(stderr, \"File has root IOD (%d bytes)\\n\", desc_size);\n\t\t\tfprintf(stderr, \"Scene PL 0x%02x - Graphics PL 0x%02x - OD PL 0x%02x\\n\", iod->scene_profileAndLevel, iod->graphics_profileAndLevel, iod->OD_profileAndLevel);\n\t\t\tfprintf(stderr, \"Visual PL: %s (0x%02x)\\n\", gf_m4v_get_profile_name(iod->visual_profileAndLevel), iod->visual_profileAndLevel);\n\t\t\tfprintf(stderr, \"Audio PL: %s (0x%02x)\\n\", gf_m4a_get_profile_name(iod->audio_profileAndLevel), iod->audio_profileAndLevel);\n\t\t\t//fprintf(stderr, \"inline profiles included %s\\n\", iod->inlineProfileFlag ? \"yes\" : \"no\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"File has root OD (%d bytes)\\n\", desc_size);\n\t\t}\n\t\tif (!gf_list_count(iod->ESDescriptors))\n\t\t\tfprintf(stderr, \"No streams included in root OD\\n\");\n\t\telse\n\t\t\tdump_m4sys = GF_TRUE;", "\t\tgf_odf_desc_del((GF_Descriptor *) iod);\n\t}\n\tif (gf_isom_is_JPEG2000(file)) fprintf(stderr, \"File is JPEG 2000\\n\");", "\tcount = gf_isom_get_copyright_count(file);\n\tif (count) {\n\t\tconst char *lang, *note;\n\t\tfprintf(stderr, \"\\nCopyrights:\\n\");\n\t\tfor (i=0; i<count; i++) {\n\t\t\tgf_isom_get_copyright(file, i+1, &lang, &note);\n\t\t\tfprintf(stderr, \"\\t(%s) %s\\n\", lang, note);\n\t\t}\n\t}", "\tcount = gf_isom_get_chapter_count(file, 0);\n\tif (count) {\n\t\tconst char *name;\n\t\tu64 time;\n\t\tfprintf(stderr, \"\\nChapters:\\n\");\n\t\tfor (i=0; i<count; i++) {\n\t\t\tgf_isom_get_chapter(file, 0, i+1, &time, &name);\n\t\t\tfprintf(stderr, \"\\tChapter #%d - %s - \\\"%s\\\"\\n\", i+1, format_duration(time, 1000, szDur), name);\n\t\t}\n\t}", "\tif (gf_isom_apple_get_tag(file, 0, &data, &data_len) == GF_OK) {\n\t\thas_itags = GF_TRUE;\n\t\tfprintf(stderr, \"\\niTunes Info:\\n\");", "\t\ti=0;\n\t\twhile (1) {\n\t\t\tu32 int_val2, flags, itype;\n\t\t\tGF_ISOiTunesTag tag;\n\t\t\tu64 int_val;\n\t\t\ts32 tag_idx;\n\t\t\tGF_Err e = gf_isom_apple_enum_tag(file, i, &tag, &data, &data_len, &int_val, &int_val2, &flags);\n\t\t\tif (e) break;\n\t\t\ti++;", "\t\t\ttag_idx = gf_itags_find_by_itag(tag);\n\t\t\tif (tag_idx<0) {\n\t\t\t\tfprintf(stderr, \"\\t%s: %s\\n\", gf_4cc_to_str(tag), data);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\t%s: \", gf_itags_get_name(tag_idx) );\n\t\t\titype = gf_itags_get_type(tag_idx);\n\t\t\tswitch (itype) {\n\t\t\tcase GF_ITAG_BOOL: fprintf(stderr, int_val ? \"yes\" : \"no\"); break;\n\t\t\tcase GF_ITAG_INT8:\n\t\t\tcase GF_ITAG_INT16:\n\t\t\tcase GF_ITAG_INT32:\n\t\t\tcase GF_ITAG_INT64:\n\t\t\t\tfprintf(stderr, LLU, int_val);\n\t\t\t\tbreak;\n\t\t\tcase GF_ITAG_FRAC6:\n\t\t\tcase GF_ITAG_FRAC8:\n\t\t\t\tfprintf(stderr, LLU\" / %u\", int_val, int_val2);\n\t\t\t\tbreak;\n\t\t\tcase GF_ITAG_FILE:\n\t\t\t\tif (flags==14) fprintf(stderr, \"PNG File\");\n\t\t\t\telse if (flags==13) fprintf(stderr, \"JPEG File\");\n\t\t\t\telse fprintf(stderr, \"unknown (flags %d)\", flags);\n\t\t\t\tbreak;\n\t\t\tcase GF_ITAG_ID3_GENRE:\n\t\t\t\tif (int_val) {\n\t\t\t\t\tfprintf(stderr, \"%s\", gf_id3_get_genre((u32) int_val) );\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t//fallthrough\n\t\t\tdefault:\n\t\t\t\tif (data)\n\t\t\t\t\tfprintf(stderr, \"%s\", data);\n\t\t\t\telse\n\t\t\t\t\tfprintf(stderr, data_len ? \"none\" : \"unknown\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t}\n\t}\n\ti=0;\n\twhile (1) {\n\t\tu32 type, version;\n\t\tchar *wmatag;\n\t\tGF_Err e = gf_isom_wma_enum_tag(file, i, &wmatag, &data, &data_len, &version, &type);\n\t\tif (e) break;\n\t\tif (!i) {\n\t\t\tfprintf(stderr, \"\\nWMA Info:\\n\");\n\t\t}\n\t\ti++;\n\t\tfprintf(stderr, \"\\t%s\", wmatag);\n\t\tif (version!=1)\n\t\t\tfprintf(stderr, \" (version %d)\", version);\n\t\tfprintf(stderr, \": \");", "\t\tif (type) {\n\t\t\tfprintf(stderr, \"unknown type %d\\n\", type);\n\t\t} else {\n\t\t\tu16 *src_str = (u16 *) data;\n\t\t\tu32 len = (u32) ( UTF8_MAX_BYTES_PER_CHAR * gf_utf8_wcslen(src_str) );\n\t\t\tchar *utf8str = (char *)gf_malloc(len + 1);\n\t\t\tu32 res_len = (u32) gf_utf8_wcstombs(utf8str, len, (const unsigned short **) &src_str);\n\t\t\tutf8str[res_len] = 0;\n\t\t\tfprintf(stderr, \"%s\\n\", utf8str);", "\t\t\tgf_free(utf8str);\n\t\t}\n\t}", "\n\tprint_udta(file, 0, has_itags);\n\tfprintf(stderr, \"\\n\");\n\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\tDumpTrackInfo(file, i+1, 0, GF_TRUE, dump_m4sys);\n\t}\n}", "#endif /*defined(GPAC_DISABLE_ISOM) || defined(GPAC_DISABLE_ISOM_WRITE)*/", "\n#ifndef GPAC_DISABLE_MPEG2TS", "\ntypedef struct\n{\n\t/* when writing to file */\n\tFILE *pes_out;\n\tchar dump[100];\n#if 0\n\tFILE *pes_out_nhml;\n\tchar nhml[100];\n\tFILE *pes_out_info;\n\tchar info[100];\n#endif\n\tBool is_info_dumped;", "\tu32 prog_number;\n\t/* For logging timing information (PCR, PTS/DTS) */\n\tFILE *timestamps_info_file;\n\tchar timestamps_info_name[100];", "\t/* when dumping TS information */\n\tu32 dump_pid;\n\tBool has_seen_pat;", "} GF_M2TS_Dump;", "", "static void on_m2ts_dump_event(GF_M2TS_Demuxer *ts, u32 evt_type, void *par)\n{\n\tu32 i, count;\n\tGF_M2TS_Program *prog;\n\tGF_M2TS_PES_PCK *pck;\n\tGF_M2TS_Dump *dumper = (GF_M2TS_Dump *)ts->user;", "\tswitch (evt_type) {\n\tcase GF_M2TS_EVT_PAT_FOUND:\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, 0);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_PAT_UPDATE:\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, 0);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_PAT_REPEAT:\n\t\t/* WARNING: We detect the pat on a repetition, probably to ensure that we also have seen all the PMT\n\t\t To be checked */\n\t\tdumper->has_seen_pat = 1;\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, 0);\n\t\t}\n//\t\tfprintf(stderr, \"Repeated PAT found - %d programs\\n\", gf_list_count(ts->programs) );\n\t\tbreak;\n\tcase GF_M2TS_EVT_CAT_FOUND:\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, 0);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_CAT_UPDATE:\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, 0);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_CAT_REPEAT:\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, 0);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_PMT_FOUND:\n\t\tprog = (GF_M2TS_Program*)par;\n\t\tif (gf_list_count(ts->programs)>1 && prog->number!=dumper->prog_number)\n\t\t\tbreak;", "\t\tcount = gf_list_count(prog->streams);", "\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"Program number %d found - %d streams:\\n\", prog->number, count));\n\t\tfor (i=0; i<count; i++) {\n\t\t\tGF_M2TS_ES *es = gf_list_get(prog->streams, i);\n\t\t\tif (es->pid == prog->pmt_pid) {\n\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"\\tPID %d: Program Map Table\\n\", es->pid));\n\t\t\t} else {\n\t\t\t\tGF_M2TS_PES *pes = (GF_M2TS_PES *)es;\n\t\t\t\tgf_m2ts_set_pes_framing(pes, dumper->pes_out ? GF_M2TS_PES_FRAMING_RAW : GF_M2TS_PES_FRAMING_DEFAULT);\n\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"\\tPID %d: %s \", pes->pid, gf_m2ts_get_stream_name(pes->stream_type) ));\n\t\t\t\tif (pes->mpeg4_es_id) GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\" - MPEG-4 ES ID %d\", pes->mpeg4_es_id));\n\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"\\n\"));\n\t\t\t}\n\t\t}\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, prog->pmt_pid);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_PMT_UPDATE:\n\t\tprog = (GF_M2TS_Program*)par;\n\t\tif (gf_list_count(ts->programs)>1 && prog->number!=dumper->prog_number)\n\t\t\tbreak;\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, prog->pmt_pid);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_PMT_REPEAT:\n\t\tprog = (GF_M2TS_Program*)par;\n\t\tif (gf_list_count(ts->programs)>1 && prog->number!=dumper->prog_number)\n\t\t\tbreak;\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, prog->pmt_pid);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_SDT_FOUND:\n#ifndef GPAC_DISABLE_LOG\n\t\tcount = gf_list_count(ts->SDTs) ;\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"Program Description found - %d desc:\\n\", count));\n\t\tfor (i=0; i<count; i++) {\n\t\t\tGF_M2TS_SDT *sdt = gf_list_get(ts->SDTs, i);\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"\\tServiceID %d - Provider %s - Name %s\\n\", sdt->service_id, sdt->provider, sdt->service));\n\t\t}\n#endif\n\t\tbreak;\n\tcase GF_M2TS_EVT_SDT_UPDATE:\n#ifndef GPAC_DISABLE_LOG\n\t\tcount = gf_list_count(ts->SDTs) ;\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"Program Description updated - %d desc\\n\", count));\n\t\tfor (i=0; i<count; i++) {\n\t\t\tGF_M2TS_SDT *sdt = gf_list_get(ts->SDTs, i);\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"\\tServiceID %d - Provider %s - Name %s\\n\", sdt->service_id, sdt->provider, sdt->service));\n\t\t}\n#endif\n\t\tbreak;\n\tcase GF_M2TS_EVT_SDT_REPEAT:\n\t\tbreak;\n\tcase GF_M2TS_EVT_PES_TIMING:\n\t\tpck = par;\n\t\tif (gf_list_count(ts->programs)>1 && pck->stream->program->number != dumper->prog_number)\n\t\t\tbreak;", "\t\tbreak;\n\tcase GF_M2TS_EVT_PES_PCK:\n\t\tpck = par;\n\t\tif (gf_list_count(ts->programs)>1 && pck->stream->program->number != dumper->prog_number)\n\t\t\tbreak;\n\t\tif (dumper->has_seen_pat) {", "\t\t\t/*We need the interpolated PCR for the pcrb, hence moved this calculus out, and saving the calculated value in index_info to put it in the pcrb*/\n\t\t\tGF_M2TS_PES *pes = pck->stream;\n\t\t\t/*FIXME : not used GF_M2TS_Program *prog = pes->program; */\n\t\t\t/* Interpolated PCR value for the TS packet containing the PES header start */\n\t\t\tu64 interpolated_pcr_value = 0;\n\t\t\tif (pes->last_pcr_value && pes->before_last_pcr_value_pck_number && pes->last_pcr_value > pes->before_last_pcr_value) {\n\t\t\t\tu32 delta_pcr_pck_num = pes->last_pcr_value_pck_number - pes->before_last_pcr_value_pck_number;\n\t\t\t\tu32 delta_pts_pcr_pck_num = pes->pes_start_packet_number - pes->last_pcr_value_pck_number;\n\t\t\t\tu64 delta_pcr_value = pes->last_pcr_value - pes->before_last_pcr_value;\n\t\t\t\tif ((pes->pes_start_packet_number > pes->last_pcr_value_pck_number)\n\t\t\t\t && (pes->last_pcr_value > pes->before_last_pcr_value)) {", "\t\t\t\t\tpes->last_pcr_value = pes->before_last_pcr_value;\n\t\t\t\t}\n\t\t\t\t/* we can compute the interpolated pcr value for the packet containing the PES header */\n\t\t\t\tinterpolated_pcr_value = pes->last_pcr_value + (u64)((delta_pcr_value*delta_pts_pcr_pck_num*1.0)/delta_pcr_pck_num);\n\t\t\t}", "\t\t\tif (dumper->timestamps_info_file) {\n\t\t\t\tDouble diff;\n\t\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\t\", pck->stream->pes_start_packet_number, pck->stream->pid);\n\t\t\t\tif (interpolated_pcr_value) fprintf(dumper->timestamps_info_file, \"%f\", interpolated_pcr_value/(300.0 * 90000));\n\t\t\t\tfprintf(dumper->timestamps_info_file, \"\\t\");\n\t\t\t\tif (pck->DTS) fprintf(dumper->timestamps_info_file, \"%f\", (pck->DTS / 90000.0));\n\t\t\t\tfprintf(dumper->timestamps_info_file, \"\\t%f\\t%d\\t%d\", pck->PTS / 90000.0, (pck->flags & GF_M2TS_PES_PCK_RAP) ? 1 : 0, (pck->flags & GF_M2TS_PES_PCK_DISCONTINUITY) ? 1 : 0);\n\t\t\t\tif (interpolated_pcr_value) {\n\t\t\t\t\tdiff = (pck->DTS ? pck->DTS : pck->PTS) / 90000.0;\n\t\t\t\t\tdiff -= pes->last_pcr_value / (300.0 * 90000);\n\t\t\t\t\tfprintf(dumper->timestamps_info_file, \"\\t%f\\n\", diff);\n\t\t\t\t\tif (diff<0) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_WARNING, (\"Warning: detected PTS/DTS value less than current PCR of %g sec\\n\", diff));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(dumper->timestamps_info_file, \"\\t\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\tif (dumper->has_seen_pat && dumper->pes_out && (dumper->dump_pid == pck->stream->pid)) {\n\t\t\tgf_fwrite(pck->data, pck->data_len, dumper->pes_out);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_PES_PCR:\n\t\tpck = par;\n\t\tif (gf_list_count(ts->programs)>1 && pck->stream->program->number != dumper->prog_number)\n\t\t\tbreak;\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\t%f\\t\\t\\t\\t%d\\n\", pck->stream->program->last_pcr_value_pck_number, pck->stream->pid, pck->PTS / (300*90000.0), (pck->flags & GF_M2TS_PES_PCK_DISCONTINUITY) ? 1 : 0);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_SL_PCK:\n#if 0\n\t{\n\t\tGF_M2TS_SL_PCK *sl_pck = par;\n\t\tif (dumper->pes_out && (dumper->dump_pid == sl_pck->stream->pid)) {\n\t\t\tGF_SLHeader header;\n\t\t\tu32 header_len;\n\t\t\tif (sl_pck->stream->mpeg4_es_id) {\n\t\t\t\tGF_ESD *esd = ((GF_M2TS_PES*)sl_pck->stream)->esd;\n\t\t\t\tif (!dumper->is_info_dumped) {\n\t\t\t\t\tif (esd->decoderConfig->decoderSpecificInfo) gf_fwrite(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, dumper->pes_out_info);\n\t\t\t\t\tdumper->is_info_dumped = 1;\n\t\t\t\t\tfprintf(dumper->pes_out_nhml, \"<NHNTStream version=\\\"1.0\\\" \");\n\t\t\t\t\tfprintf(dumper->pes_out_nhml, \"timeScale=\\\"%d\\\" \", esd->slConfig->timestampResolution);\n\t\t\t\t\tfprintf(dumper->pes_out_nhml, \"streamType=\\\"%d\\\" \", esd->decoderConfig->streamType);\n\t\t\t\t\tfprintf(dumper->pes_out_nhml, \"objectTypeIndication=\\\"%d\\\" \", esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tif (esd->decoderConfig->decoderSpecificInfo) fprintf(dumper->pes_out_nhml, \"specificInfoFile=\\\"%s\\\" \", dumper->info);\n\t\t\t\t\tfprintf(dumper->pes_out_nhml, \"baseMediaFile=\\\"%s\\\" \", dumper->dump);\n\t\t\t\t\tfprintf(dumper->pes_out_nhml, \"inRootOD=\\\"yes\\\">\\n\");\n\t\t\t\t}\n\t\t\t\tgf_sl_depacketize(esd->slConfig, &header, sl_pck->data, sl_pck->data_len, &header_len);\n\t\t\t\tgf_fwrite(sl_pck->data+header_len, sl_pck->data_len-header_len, dumper->pes_out);\n\t\t\t\tfprintf(dumper->pes_out_nhml, \"<NHNTSample DTS=\\\"\"LLD\"\\\" dataLength=\\\"%d\\\" isRAP=\\\"%s\\\"/>\\n\", header.decodingTimeStamp, sl_pck->data_len-header_len, (header.randomAccessPointFlag?\"yes\":\"no\"));\n\t\t\t}\n\t\t}\n\t}\n#endif\n\tbreak;\n\t}\n}", "void dump_mpeg2_ts(char *mpeg2ts_file, char *out_name, Bool prog_num)\n{\n\tu8 data[188];\n\tGF_M2TS_Dump dumper;", "\tu32 size;\n\tu64 fsize, fdone;\n\tGF_M2TS_Demuxer *ts;\n\tFILE *src;", "\tif (!prog_num && !out_name) {\n\t\tfprintf(stderr, \"No program number nor output filename specified. No timestamp file will be generated.\");\n\t}", "\tsrc = gf_fopen(mpeg2ts_file, \"rb\");\n\tif (!src) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Cannot open %s: no such file\\n\", mpeg2ts_file));\n\t\treturn;\n\t}\n\tts = gf_m2ts_demux_new();\n\tts->on_event = on_m2ts_dump_event;\n\tts->notify_pes_timing = 1;\n\tmemset(&dumper, 0, sizeof(GF_M2TS_Dump));\n\tts->user = &dumper;\n\tdumper.prog_number = prog_num;", "\t/*PES dumping*/\n\tif (out_name) {\n\t\tchar *pid = strrchr(out_name, '#');\n\t\tif (pid) {\n\t\t\tdumper.dump_pid = atoi(pid+1);\n\t\t\tpid[0] = 0;\n\t\t\tsprintf(dumper.dump, \"%s_%d.raw\", out_name, dumper.dump_pid);\n\t\t\tdumper.pes_out = gf_fopen(dumper.dump, \"wb\");\n#if 0\n\t\t\tsprintf(dumper.nhml, \"%s_%d.nhml\", pes_out_name, dumper.dump_pid);\n\t\t\tdumper.pes_out_nhml = gf_fopen(dumper.nhml, \"wt\");\n\t\t\tsprintf(dumper.info, \"%s_%d.info\", pes_out_name, dumper.dump_pid);\n\t\t\tdumper.pes_out_info = gf_fopen(dumper.info, \"wb\");\n#endif\n\t\t\tpid[0] = '#';\n\t\t}\n\t}", "\tgf_fseek(src, 0, SEEK_END);\n\tfsize = gf_ftell(src);\n\tgf_fseek(src, 0, SEEK_SET);", "\t/* first loop to process all packets between two PAT, and assume all signaling was found between these 2 PATs */\n\twhile (!feof(src)) {\n\t\tsize = (u32) gf_fread(data, 188, src);\n\t\tif (size<188) break;", "\t\tgf_m2ts_process_data(ts, data, size);\n\t\tif (dumper.has_seen_pat) break;\n\t}\n\tdumper.has_seen_pat = GF_TRUE;", "\tif (!prog_num) {\n\t\tGF_M2TS_Program *p = gf_list_get(ts->programs, 0);\n\t\tif (p) prog_num = p->number;\n\t\tfprintf(stderr, \"No program number specified, defaulting to first program\\n\");\n\t}", "\tif (!prog_num && !out_name) {\n\t\tfprintf(stderr, \"No program number nor output filename specified. No timestamp file will be generated\\n\");\n\t}", "\tif (prog_num) {\n\t\tsprintf(dumper.timestamps_info_name, \"%s_prog_%d_timestamps.txt\", mpeg2ts_file, prog_num/*, mpeg2ts_file*/);\n\t\tdumper.timestamps_info_file = gf_fopen(dumper.timestamps_info_name, \"wt\");\n\t\tif (!dumper.timestamps_info_file) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Cannot open file %s\\n\", dumper.timestamps_info_name));\n\t\t\treturn;\n\t\t}\n\t\tfprintf(dumper.timestamps_info_file, \"PCK#\\tPID\\tPCR\\tDTS\\tPTS\\tRAP\\tDiscontinuity\\tDTS-PCR Diff\\n\");\n\t}", "\tgf_m2ts_reset_parsers(ts);\n\tgf_fseek(src, 0, SEEK_SET);\n\tfdone = 0;", "\twhile (!feof(src)) {\n\t\tsize = (u32) gf_fread(data, 188, src);\n\t\tif (size<188) break;", "\t\tgf_m2ts_process_data(ts, data, size);", "\t\tfdone += size;\n\t\tgf_set_progress(\"MPEG-2 TS Parsing\", fdone, fsize);\n\t}", "\tgf_fclose(src);\n\tgf_m2ts_demux_del(ts);\n\tif (dumper.pes_out) gf_fclose(dumper.pes_out);\n#if 0\n\tif (dumper.pes_out_nhml) {\n\t\tif (dumper.is_info_dumped) fprintf(dumper.pes_out_nhml, \"</NHNTStream>\\n\");\n\t\tgf_fclose(dumper.pes_out_nhml);\n\t\tgf_fclose(dumper.pes_out_info);\n\t}\n#endif\n\tif (dumper.timestamps_info_file) gf_fclose(dumper.timestamps_info_file);\n}", "#endif /*GPAC_DISABLE_MPEG2TS*/", "\n#include <gpac/download.h>\n#include <gpac/mpd.h>", "void get_file_callback(void *usr_cbk, GF_NETIO_Parameter *parameter)\n{\n\tif (parameter->msg_type==GF_NETIO_DATA_EXCHANGE) {\n\t\tu64 tot_size, done, max;\n\t\tu32 bps;\n\t\tgf_dm_sess_get_stats(parameter->sess, NULL, NULL, &tot_size, &done, &bps, NULL);\n\t\tif (tot_size) {\n\t\t\tmax = done;\n\t\t\tmax *= 100;\n\t\t\tmax /= tot_size;\n\t\t\tfprintf(stderr, \"download %02d %% at %05d kpbs\\r\", (u32) max, bps*8/1000);\n\t\t}\n\t}\n}", "static GF_DownloadSession *get_file(const char *url, GF_DownloadManager *dm, GF_Err *e)\n{\n\tGF_DownloadSession *sess;\n\tsess = gf_dm_sess_new(dm, url, GF_NETIO_SESSION_NOT_THREADED, get_file_callback, NULL, e);\n\tif (!sess) return NULL;\n\t*e = gf_dm_sess_process(sess);\n\tif (*e) {\n\t\tgf_dm_sess_del(sess);\n\t\treturn NULL;\n\t}\n\treturn sess;\n}", "static void revert_cache_file(char *item_path)\n{\n\tchar szPATH[GF_MAX_PATH];\n\tconst char *url;\n\tGF_Config *cached;", "\tif (!strstr(item_path, \"gpac_cache_\")) {\n\t\tfprintf(stderr, \"%s is not a gpac cache file\\n\", item_path);\n\t\treturn;\n\t}\n\tif (!strncmp(item_path, \"./\", 2) || !strncmp(item_path, \".\\\\\", 2))\n\t\t\titem_path += 2;", " \tstrcpy(szPATH, item_path);\n\tstrcat(szPATH, \".txt\");", "\tcached = gf_cfg_new(NULL, szPATH);\n\turl = gf_cfg_get_key(cached, \"cache\", \"url\");\n\tif (url) url = strstr(url, \"://\");\n\tif (url) {\n\t\tu32 i, len, dir_len=0, k=0;\n\t\tchar *sep;\n\t\tchar *dst_name;\n\t\tsep = strstr(item_path, \"gpac_cache_\");\n\t\tif (sep) {\n\t\t\tsep[0] = 0;\n\t\t\tdir_len = (u32) strlen(item_path);\n\t\t\tsep[0] = 'g';\n\t\t}\n\t\turl+=3;\n\t\tlen = (u32) strlen(url);\n\t\tdst_name = gf_malloc(len+dir_len+1);\n\t\tmemset(dst_name, 0, len+dir_len+1);", "\t\tstrncpy(dst_name, item_path, dir_len);\n\t\tk=dir_len;\n\t\tfor (i=0; i<len; i++) {\n\t\t\tdst_name[k] = url[i];\n\t\t\tif (dst_name[k]==':') dst_name[k]='_';\n\t\t\telse if (dst_name[k]=='/') {\n\t\t\t\tif (!gf_dir_exists(dst_name))\n\t\t\t\t\tgf_mkdir(dst_name);\n\t\t\t}\n\t\t\tk++;\n\t\t}\n\t\tif (gf_file_exists(item_path)) {\n\t\t\tgf_file_move(item_path, dst_name);\n\t\t}", "\t\tgf_free(dst_name);\n\t} else {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to reverse %s cache file\\n\", item_path));\n\t}\n\tgf_cfg_del(cached);\n\tgf_file_delete(szPATH);\n}", "GF_Err rip_mpd(const char *mpd_src, const char *output_dir)\n{\n\tGF_DownloadSession *sess;\n\tu32 i, connect_time, reply_time, download_time, req_hdr_size, rsp_hdr_size;\n\tGF_Err e;\n\tGF_DOMParser *mpd_parser=NULL;\n\tGF_MPD *mpd=NULL;\n\tGF_MPD_Period *period;\n\tGF_MPD_AdaptationSet *as;\n\tGF_MPD_Representation *rep;\n\tchar szName[GF_MAX_PATH];\n\tGF_DownloadManager *dm;", "\tif (output_dir) {\n\t\tchar *sep;\n\t\tstrcpy(szName, output_dir);\n\t\tsep = gf_file_basename(szName);\n\t\tif (sep) sep[0] = 0;\n\t\tgf_opts_set_key(\"temp\", \"cache\", szName);\n\t} else {\n\t\tgf_opts_set_key(\"temp\", \"cache\", \".\");\n\t}\n\tgf_opts_set_key(\"temp\", \"clean-cache\", \"true\");\n\tdm = gf_dm_new(NULL);", "/*\n\tchar *name = strrchr(mpd_src, '/');\n\tif (!name) name = strrchr(mpd_src, '\\\\');\n\tif (!name) name = \"manifest.mpd\";\n\telse name ++;", "\tif (strchr(name, '?') || strchr(name, '&')) name = \"manifest.mpd\";\n*/", "\tfprintf(stderr, \"Downloading %s\\n\", mpd_src);\n\tsess = get_file(mpd_src, dm, &e);\n\tif (!sess) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"Error downloading MPD file %s: %s\\n\", mpd_src, gf_error_to_string(e) ));\n\t\tgoto err_exit;\n\t}\n\tstrcpy(szName, gf_dm_sess_get_cache_name(sess) );\n\tgf_dm_sess_get_header_sizes_and_times(sess, &req_hdr_size, &rsp_hdr_size, &connect_time, &reply_time, &download_time);\n\tgf_dm_sess_del(sess);", "\tif (e) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"Error fetching MPD file %s: %s\\n\", mpd_src, gf_error_to_string(e)));\n\t\tgoto err_exit;\n\t}\n\telse {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_APP, (\"Fetched file %s\\n\", mpd_src));\n\t}\n\tGF_LOG(GF_LOG_DEBUG, GF_LOG_APP, (\"GET Header size %d - Reply header size %d\\n\", req_hdr_size, rsp_hdr_size));\n\tGF_LOG(GF_LOG_DEBUG, GF_LOG_APP, (\"GET time: Connect Time %d - Reply Time %d - Download Time %d\\n\", connect_time, reply_time, download_time));", "\tmpd_parser = gf_xml_dom_new();\n\te = gf_xml_dom_parse(mpd_parser, szName, NULL, NULL);", "\tif (e != GF_OK) {\n\t\tgf_xml_dom_del(mpd_parser);\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"Error parsing MPD %s : %s\\n\", mpd_src, gf_error_to_string(e)));\n\t\treturn e;\n\t}\n\tmpd = gf_mpd_new();\n\te = gf_mpd_init_from_dom(gf_xml_dom_get_root(mpd_parser), mpd, mpd_src);\n\tgf_xml_dom_del(mpd_parser);\n\tmpd_parser=NULL;\n\tif (e) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"Error initializing MPD %s : %s\\n\", mpd_src, gf_error_to_string(e)));\n\t\tgoto err_exit;\n\t}\n\telse {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_APP, (\"MPD %s initialized: %s\\n\", szName, gf_error_to_string(e)));\n\t}", "\trevert_cache_file(szName);\n\tif (mpd->type==GF_MPD_TYPE_DYNAMIC) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"MPD rip is not supported on live sources\\n\"));\n\t\te = GF_NOT_SUPPORTED;\n\t\tgoto err_exit;\n\t}", "\ti=0;\n\twhile ((period = (GF_MPD_Period *) gf_list_enum(mpd->periods, &i))) {\n\t\tchar *initTemplate = NULL;\n\t\tBool segment_base = GF_FALSE;\n\t\tu32 j=0;", "\t\tif (period->segment_base) segment_base=GF_TRUE;", "\t\tif (period->segment_template && period->segment_template->initialization) {\n\t\t\tinitTemplate = period->segment_template->initialization;\n\t\t}", "\t\twhile ((as = gf_list_enum(period->adaptation_sets, &j))) {\n\t\t\tu32 k=0;\n\t\t\tif (!initTemplate && as->segment_template && as->segment_template->initialization) {\n\t\t\t\tinitTemplate = as->segment_template->initialization;\n\t\t\t}\n\t\t\tif (as->segment_base) segment_base=GF_TRUE;", "\t\t\twhile ((rep = gf_list_enum(as->representations, &k))) {\n\t\t\t\tu64 out_range_start, out_range_end, segment_duration;\n\t\t\t\tBool is_in_base_url;\n\t\t\t\tchar *seg_url;\n\t\t\t\tu32 seg_idx=0;\n\t\t\t\tif (rep->segment_template && rep->segment_template->initialization) {\n\t\t\t\t\tinitTemplate = rep->segment_template->initialization;\n\t\t\t\t} else if (k>1) {\n\t\t\t\t\tinitTemplate = NULL;\n\t\t\t\t}\n\t\t\t\tif (rep->segment_base) segment_base=GF_TRUE;", "\t\t\t\te = gf_mpd_resolve_url(mpd, rep, as, period, mpd_src, 0, GF_MPD_RESOLVE_URL_INIT, 0, 0, &seg_url, &out_range_start, &out_range_end, &segment_duration, &is_in_base_url, NULL, NULL, NULL);\n\t\t\t\tif (e) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"Error resolving init segment name : %s\\n\", gf_error_to_string(e)));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t//not a byte range, replace URL\n\t\t\t\tif (segment_base) {", "\t\t\t\t} else if (out_range_start || out_range_end || !seg_url) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"byte range rip not yet implemented\\n\"));\n\t\t\t\t\tif (seg_url) gf_free(seg_url);\n\t\t\t\t\te = GF_NOT_SUPPORTED;\n\t\t\t\t\tgoto err_exit;\n\t\t\t\t}", "\t\t\t\tfprintf(stderr, \"Downloading %s\\n\", seg_url);\n\t\t\t\tsess = get_file(seg_url, dm, &e);\n\t\t\t\tif (e) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"Error downloading init segment %s from MPD %s : %s\\n\", seg_url, mpd_src, gf_error_to_string(e)));\n\t\t\t\t\tgoto err_exit;\n\t\t\t\t}\n\t\t\t\trevert_cache_file((char *) gf_dm_sess_get_cache_name(sess) );\n\t\t\t\tgf_free(seg_url);\n\t\t\t\tgf_dm_sess_del(sess);", "\t\t\t\tif (segment_base) continue;", "\t\t\t\twhile (1) {\n\t\t\t\t\te = gf_mpd_resolve_url(mpd, rep, as, period, mpd_src, 0, GF_MPD_RESOLVE_URL_MEDIA, seg_idx, 0, &seg_url, &out_range_start, &out_range_end, &segment_duration, NULL, NULL, NULL, NULL);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tif (e<0) {\n\t\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"Error resolving segment name : %s\\n\", gf_error_to_string(e)));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}", "\t\t\t\t\tseg_idx++;", "\t\t\t\t\tif (out_range_start || out_range_end || !seg_url) {\n\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"byte range rip not yet implemented\\n\"));\n\t\t\t\t\t\tif (seg_url) gf_free(seg_url);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tfprintf(stderr, \"Downloading %s\\n\", seg_url);\n\t\t\t\t\tsess = get_file(seg_url, dm, &e);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tgf_free(seg_url);\n\t\t\t\t\t\tif (e != GF_URL_ERROR) {\n\t\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"Error downloading segment %s: %s\\n\", seg_url, gf_error_to_string(e)));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t//todo, properly detect end of dash representation\n\t\t\t\t\t\t\te = GF_OK;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\trevert_cache_file((char *) gf_dm_sess_get_cache_name(sess) );\n\t\t\t\t\tgf_free(seg_url);\n\t\t\t\t\tgf_dm_sess_del(sess);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "err_exit:\n\tif (mpd) gf_mpd_del(mpd);\n\tgf_dm_del(dm);\n\treturn e;\n}" ]
[ 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, 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, 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, 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, 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, 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, 1, 0, 0, 0, 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [2900], "buggy_code_start_loc": [2883], "filenames": ["applications/mp4box/filedump.c"], "fixing_code_end_loc": [2904], "fixing_code_start_loc": [2883], "message": "The DumpTrackInfo function in GPAC 1.0.1 allows attackers to cause a denial of service (NULL pointer dereference) via a crafted file in the MP4Box command.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gpac:gpac:1.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "82DD2D40-0A05-48FD-940D-32B4D8B51AB3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The DumpTrackInfo function in GPAC 1.0.1 allows attackers to cause a denial of service (NULL pointer dereference) via a crafted file in the MP4Box command."}, {"lang": "es", "value": "La funci\u00f3n DumpTrackInfo en GPAC versi\u00f3n 1.0.1, permite a atacantes causar una denegaci\u00f3n de servicio (desreferencia de puntero NULL) por medio de un archivo dise\u00f1ado en el comando MP4Box"}], "evaluatorComment": null, "id": "CVE-2021-32138", "lastModified": "2021-09-23T20:11:59.017", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-09-13T20:15:08.343", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gpac/gpac/commit/289ffce3e0d224d314f5f92a744d5fe35999f20b"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/gpac/gpac/issues/1767"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gpac/gpac/commit/289ffce3e0d224d314f5f92a744d5fe35999f20b"}, "type": "CWE-476"}
186
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n *\t\t\tGPAC - Multimedia Framework C SDK\n *\n *\t\t\tAuthors: Jean Le Feuvre\n *\t\t\tCopyright (c) Telecom ParisTech 2000-2021\n *\t\t\t\t\tAll rights reserved\n *\n * This file is part of GPAC / mp4box application\n *\n * GPAC is free software; you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2, or (at your option)\n * any later version.\n *\n * GPAC is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; see the file COPYING. If not, write to\n * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.\n *\n */", "#include \"mp4box.h\"", "#if defined(GPAC_DISABLE_ISOM) || defined(GPAC_DISABLE_ISOM_WRITE)", "#error \"Cannot compile MP4Box if GPAC is not built with ISO File Format support\"", "#else", "#ifndef GPAC_DISABLE_X3D\n#include <gpac/nodes_x3d.h>\n#endif\n#ifndef GPAC_DISABLE_BIFS\n#include <gpac/internal/bifs_dev.h>\n#endif\n#ifndef GPAC_DISABLE_VRML\n#include <gpac/nodes_mpeg4.h>\n#endif\n#include <gpac/constants.h>\n#include <gpac/avparse.h>\n#include <gpac/internal/media_dev.h>\n/*ISO 639 languages*/\n#include <gpac/iso639.h>\n#include <gpac/mpegts.h>", "#ifndef GPAC_DISABLE_SMGR\n#include <gpac/scene_manager.h>\n#endif\n#include <gpac/internal/media_dev.h>\n#include <gpac/media_tools.h>\n/*for built-in box printing*/\n#include <gpac/internal/isomedia_dev.h>", "extern u32 swf_flags;\nextern Float swf_flatten_angle;\nextern GF_FileType get_file_type_by_ext(char *inName);\nextern u32 fs_dump_flags;", "void scene_coding_log(void *cbk, GF_LOG_Level log_level, GF_LOG_Tool log_tool, const char *fmt, va_list vlist);", "\n#ifdef GPAC_DISABLE_LOG\nvoid mp4box_log(const char *fmt, ...)\n{\n\tva_list vl;\n\tva_start(vl, fmt);\n\tvfprintf(stderr, fmt, vlist);\n\tfflush(stderr);\n\tva_end(vl);\n}\n#endif", "\nu32 PrintLanguages(char *val, u32 opt)\n{\n\tu32 i=0, count = gf_lang_get_count();\n\tfprintf(stderr, \"Supported ISO 639 languages and codes:\\n\\n\");\n\tfor (i=0; i<count; i++) {\n\t\tif (gf_lang_get_2cc(i)) {\n\t\t\tfprintf(stderr, \"%s (%s - %s)\\n\", gf_lang_get_name(i), gf_lang_get_3cc(i), gf_lang_get_2cc(i));\n\t\t}\n\t}\n\treturn 1;\n}", "static const char *GetLanguage(char *lcode)\n{\n\ts32 idx = gf_lang_find(lcode);\n\tif (idx>=0) return gf_lang_get_name(idx);\n\treturn lcode;\n}", "GF_Err dump_isom_cover_art(GF_ISOFile *file, char *inName, Bool is_final_name)\n{\n\tconst u8 *tag;\n\tFILE *t;\n\tu32 tag_len;\n\tGF_Err e = gf_isom_apple_get_tag(file, GF_ISOM_ITUNE_COVER_ART, &tag, &tag_len);\n\tif (e!=GF_OK) {\n\t\tif (e==GF_URL_ERROR) {\n\t\t\tM4_LOG(GF_LOG_WARNING, (\"No cover art found\\n\"));\n\t\t\treturn GF_OK;\n\t\t}\n\t\treturn e;\n\t}", "\tif (inName) {\n\t\tchar szName[1024];\n\t\tif (is_final_name) {\n\t\t\tstrcpy(szName, inName);\n\t\t} else {\n\t\t\tsprintf(szName, \"%s.%s\", inName, (tag_len>>31) ? \"png\" : \"jpg\");\n\t\t}\n\t\tt = gf_fopen(szName, \"wb\");\n\t\tif (!t) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s for dumping\\n\", szName));\n\t\t\treturn GF_IO_ERR;\n\t\t}\n\t} else {\n\t\tt = stdout;\n\t}\n\tgf_fwrite(tag, tag_len & 0x7FFFFFFF, t);", "\tif (inName) gf_fclose(t);\n\treturn GF_OK;\n}", "#ifndef GPAC_DISABLE_SCENE_DUMP", "GF_Err dump_isom_scene(char *file, char *inName, Bool is_final_name, GF_SceneDumpFormat dump_mode, Bool do_log, Bool no_odf_conv)\n{\n\tGF_Err e;\n\tGF_SceneManager *ctx;\n\tGF_SceneGraph *sg;\n\tGF_SceneLoader load;\n\tGF_FileType ftype;\n\tgf_log_cbk prev_logs = NULL;\n\tFILE *logs = NULL;", "\tsg = gf_sg_new();\n\tctx = gf_sm_new(sg);\n\tmemset(&load, 0, sizeof(GF_SceneLoader));\n\tload.fileName = file;\n\tload.ctx = ctx;\n\tload.swf_import_flags = swf_flags;\n\tif (dump_mode == GF_SM_DUMP_SVG) {\n\t\tload.swf_import_flags |= GF_SM_SWF_USE_SVG;\n\t\tload.svgOutFile = inName;\n\t}\n\tload.swf_flatten_limit = swf_flatten_angle;", "\tftype = get_file_type_by_ext(file);\n\tif (ftype == GF_FILE_TYPE_ISO_MEDIA) {\n\t\tload.isom = gf_isom_open(file, GF_ISOM_OPEN_READ, NULL);\n\t\tif (!load.isom) {\n\t\t\te = gf_isom_last_error(NULL);\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Error opening file: %s\\n\", gf_error_to_string(e)));\n\t\t\tgf_sm_del(ctx);\n\t\t\tgf_sg_del(sg);\n\t\t\treturn e;\n\t\t}\n\t\tif (no_odf_conv)\n\t\t\tgf_isom_disable_odf_conversion(load.isom, GF_TRUE);", "\t} else if (ftype==GF_FILE_TYPE_LSR_SAF) {\n\t\tload.isom = gf_isom_open(\"saf_conv\", GF_ISOM_WRITE_EDIT, NULL);\n#ifndef GPAC_DISABLE_MEDIA_IMPORT\n\t\tif (load.isom) {\n\t\t\tGF_Fraction _frac = {0,0};\n\t\t\te = import_file(load.isom, file, 0, _frac, 0, NULL, NULL, 0);\n\t\t} else\n#else\n\t\tM4_LOG(GF_LOG_WARNING, (\"Warning: GPAC was compiled without Media Import support\\n\"));\n#endif\n\t\t\te = gf_isom_last_error(NULL);", "\t\tif (e) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Error importing file: %s\\n\", gf_error_to_string(e)));\n\t\t\tgf_sm_del(ctx);\n\t\t\tgf_sg_del(sg);\n\t\t\tif (load.isom) gf_isom_delete(load.isom);\n\t\t\treturn e;\n\t\t}\n\t}", "\tif (do_log) {\n\t\tchar szLog[GF_MAX_PATH];\n\t\tsprintf(szLog, \"%s_dec.logs\", inName);\n\t\tlogs = gf_fopen(szLog, \"wt\");", "\t\tgf_log_set_tool_level(GF_LOG_CODING, GF_LOG_DEBUG);\n\t\tprev_logs = gf_log_set_callback(logs, scene_coding_log);\n\t}\n\te = gf_sm_load_init(&load);\n\tif (!e) e = gf_sm_load_run(&load);\n\tgf_sm_load_done(&load);\n\tif (logs) {\n\t\tgf_log_set_tool_level(GF_LOG_CODING, GF_LOG_ERROR);\n\t\tgf_log_set_callback(NULL, prev_logs);\n\t\tgf_fclose(logs);\n\t}\n\tif (!e && dump_mode != GF_SM_DUMP_SVG) {\n\t\tu32 count = gf_list_count(ctx->streams);\n\t\tif (count)\n\t\t\tfprintf(stderr, \"Scene loaded - dumping %d systems streams\\n\", count);\n\t\telse\n\t\t\tfprintf(stderr, \"Scene loaded - dumping root scene\\n\");", "\t\te = gf_sm_dump(ctx, inName, is_final_name, dump_mode);\n\t}", "\tgf_sm_del(ctx);\n\tgf_sg_del(sg);\n\tif (e) M4_LOG(GF_LOG_ERROR, (\"Error loading scene: %s\\n\", gf_error_to_string(e)));\n\tif (load.isom) gf_isom_delete(load.isom);\n\treturn e;\n}\n#endif", "#ifndef GPAC_DISABLE_SCENE_STATS", "static void dump_stats(FILE *dump, const GF_SceneStatistics *stats)\n{\n\tu32 i;\n\ts32 created, count, draw_created, draw_count, deleted, draw_deleted;\n\tcreated = count = draw_created = draw_count = deleted = draw_deleted = 0;", "\tfprintf(dump, \"<NodeStatistics>\\n\");\n\tfprintf(dump, \"<General NumberOfNodeTypes=\\\"%d\\\"/>\\n\", gf_list_count(stats->node_stats));\n\tfor (i=0; i<gf_list_count(stats->node_stats); i++) {\n\t\tGF_NodeStats *ptr = gf_list_get(stats->node_stats, i);\n\t\tfprintf(dump, \"<NodeStat NodeName=\\\"%s\\\">\\n\", ptr->name);", "\t\tswitch (ptr->tag) {\n#ifndef GPAC_DISABLE_VRML\n\t\tcase TAG_MPEG4_Bitmap:\n\t\tcase TAG_MPEG4_Background2D:\n\t\tcase TAG_MPEG4_Background:\n\t\tcase TAG_MPEG4_Box:\n\t\tcase TAG_MPEG4_Circle:\n\t\tcase TAG_MPEG4_CompositeTexture2D:\n\t\tcase TAG_MPEG4_CompositeTexture3D:\n\t\tcase TAG_MPEG4_Cylinder:\n\t\tcase TAG_MPEG4_Cone:\n\t\tcase TAG_MPEG4_Curve2D:\n\t\tcase TAG_MPEG4_Extrusion:\n\t\tcase TAG_MPEG4_ElevationGrid:\n\t\tcase TAG_MPEG4_IndexedFaceSet2D:\n\t\tcase TAG_MPEG4_IndexedFaceSet:\n\t\tcase TAG_MPEG4_IndexedLineSet2D:\n\t\tcase TAG_MPEG4_IndexedLineSet:\n\t\tcase TAG_MPEG4_PointSet2D:\n\t\tcase TAG_MPEG4_PointSet:\n\t\tcase TAG_MPEG4_Rectangle:\n\t\tcase TAG_MPEG4_Sphere:\n\t\tcase TAG_MPEG4_Text:\n\t\tcase TAG_MPEG4_Ellipse:\n\t\tcase TAG_MPEG4_XCurve2D:\n\t\t\tdraw_count += ptr->nb_created + ptr->nb_used - ptr->nb_del;\n\t\t\tdraw_deleted += ptr->nb_del;\n\t\t\tdraw_created += ptr->nb_created;\n\t\t\tbreak;\n#endif /*GPAC_DISABLE_VRML*/\n\t\t}\n\t\tfprintf(dump, \"<Instanciation NbObjects=\\\"%d\\\" NbUse=\\\"%d\\\" NbDestroy=\\\"%d\\\"/>\\n\", ptr->nb_created, ptr->nb_used, ptr->nb_del);\n\t\tcount += ptr->nb_created + ptr->nb_used;\n\t\tdeleted += ptr->nb_del;\n\t\tcreated += ptr->nb_created;\n\t\tfprintf(dump, \"</NodeStat>\\n\");\n\t}\n\tif (i) {\n\t\tfprintf(dump, \"<CumulatedStat TotalNumberOfNodes=\\\"%d\\\" ReallyAllocatedNodes=\\\"%d\\\" DeletedNodes=\\\"%d\\\" NumberOfAttributes=\\\"%d\\\"/>\\n\", count, created, deleted, stats->nb_svg_attributes);\n\t\tfprintf(dump, \"<DrawableNodesCumulatedStat TotalNumberOfNodes=\\\"%d\\\" ReallyAllocatedNodes=\\\"%d\\\" DeletedNodes=\\\"%d\\\"/>\\n\", draw_count, draw_created, draw_deleted);\n\t}\n\tfprintf(dump, \"</NodeStatistics>\\n\");", "\tcreated = count = deleted = 0;\n\tif (gf_list_count(stats->proto_stats)) {\n\t\tfprintf(dump, \"<ProtoStatistics NumberOfProtoUsed=\\\"%d\\\">\\n\", gf_list_count(stats->proto_stats));\n\t\tfor (i=0; i<gf_list_count(stats->proto_stats); i++) {\n\t\t\tGF_NodeStats *ptr = gf_list_get(stats->proto_stats, i);\n\t\t\tfprintf(dump, \"<ProtoStat ProtoName=\\\"%s\\\">\\n\", ptr->name);\n\t\t\tfprintf(dump, \"<Instanciation NbObjects=\\\"%d\\\" NbUse=\\\"%d\\\" NbDestroy=\\\"%d\\\"/>\\n\", ptr->nb_created, ptr->nb_used, ptr->nb_del);\n\t\t\tcount += ptr->nb_created + ptr->nb_used;\n\t\t\tdeleted += ptr->nb_del;\n\t\t\tcreated += ptr->nb_created;\n\t\t\tfprintf(dump, \"</ProtoStat>\\n\");\n\t\t}\n\t\tif (i) fprintf(dump, \"<CumulatedStat TotalNumberOfProtos=\\\"%d\\\" ReallyAllocatedProtos=\\\"%d\\\" DeletedProtos=\\\"%d\\\"/>\\n\", count, created, deleted);\n\t\tfprintf(dump, \"</ProtoStatistics>\\n\");\n\t}\n\tfprintf(dump, \"<FixedValues min=\\\"%f\\\" max=\\\"%f\\\">\\n\", FIX2FLT( stats->min_fixed) , FIX2FLT( stats->max_fixed ));\n\tfprintf(dump, \"<Resolutions scaleIntegerPart=\\\"%d\\\" scaleFracPart=\\\"%d\\\" coordIntegerPart=\\\"%d\\\" coordFracPart=\\\"%d\\\"/>\\n\", stats->scale_int_res_2d, stats->scale_frac_res_2d, stats->int_res_2d, stats->frac_res_2d);\n\tfprintf(dump, \"</FixedValues>\\n\");\n\tfprintf(dump, \"<FieldStatistic FieldType=\\\"MFVec2f\\\">\\n\");\n\tfprintf(dump, \"<ParsingInfo NumParsed=\\\"%d\\\" NumRemoved=\\\"%d\\\"/>\\n\", stats->count_2d, stats->rem_2d);\n\tif (stats->count_2d) {\n\t\tfprintf(dump, \"<ExtendInfo MinVec2f=\\\"%f %f\\\" MaxVec2f=\\\"%f %f\\\"/>\\n\", FIX2FLT( stats->min_2d.x) , FIX2FLT( stats->min_2d.y ), FIX2FLT( stats->max_2d.x ), FIX2FLT( stats->max_2d.y ) );\n\t}\n\tfprintf(dump, \"</FieldStatistic>\\n\");", "\tfprintf(dump, \"<FieldStatistic FieldType=\\\"MFVec3f\\\">\\n\");\n\tfprintf(dump, \"<ParsingInfo NumParsed=\\\"%d\\\" NumRemoved=\\\"%d\\\"/>\", stats->count_3d, stats->rem_3d);\n\tif (stats->count_3d) {\n\t\tfprintf(dump, \"<ExtendInfo MinVec3f=\\\"%f %f %f\\\" MaxVec3f=\\\"%f %f %f\\\"/>\\n\", FIX2FLT( stats->min_3d.x ), FIX2FLT( stats->min_3d.y ), FIX2FLT( stats->min_3d.z ), FIX2FLT( stats->max_3d.x ), FIX2FLT( stats->max_3d.y ), FIX2FLT( stats->max_3d.z ) );\n\t}\n\tfprintf(dump, \"</FieldStatistic>\\n\");", "\tfprintf(dump, \"<FieldStatistic FieldType=\\\"MF/SFColor\\\">\\n\");\n\tfprintf(dump, \"<ParsingInfo NumParsed=\\\"%d\\\" NumRemoved=\\\"%d\\\"/>\", stats->count_color, stats->rem_color);\n\tfprintf(dump, \"</FieldStatistic>\\n\");", "\tfprintf(dump, \"<FieldStatistic FieldType=\\\"MF/SFFloat\\\">\\n\");\n\tfprintf(dump, \"<ParsingInfo NumParsed=\\\"%d\\\" NumRemoved=\\\"%d\\\"/>\", stats->count_float, stats->rem_float);\n\tfprintf(dump, \"</FieldStatistic>\\n\");", "\tfprintf(dump, \"<FieldStatistic FieldType=\\\"SFVec2f\\\">\\n\");\n\tfprintf(dump, \"<ParsingInfo NumParsed=\\\"%d\\\"/>\", stats->count_2f);\n\tfprintf(dump, \"</FieldStatistic>\\n\");\n\tfprintf(dump, \"<FieldStatistic FieldType=\\\"SFVec3f\\\">\\n\");\n\tfprintf(dump, \"<ParsingInfo NumParsed=\\\"%d\\\"/>\", stats->count_3f);\n\tfprintf(dump, \"</FieldStatistic>\\n\");\n}", "\nstatic void ReorderAU(GF_List *sample_list, GF_AUContext *au)\n{\n\tu32 i;\n\tfor (i=0; i<gf_list_count(sample_list); i++) {\n\t\tGF_AUContext *ptr = gf_list_get(sample_list, i);\n\t\tif (\n\t\t /*time ordered*/\n\t\t (ptr->timing_sec > au->timing_sec)\n\t\t /*set bifs first*/\n\t\t || ((ptr->timing_sec == au->timing_sec) && (ptr->owner->streamType < au->owner->streamType))\n\t\t) {\n\t\t\tgf_list_insert(sample_list, au, i);\n\t\t\treturn;\n\t\t}\n\t}\n\tgf_list_add(sample_list, au);\n}", "void dump_isom_scene_stats(char *file, char *inName, Bool is_final_name, u32 stat_level)\n{\n\tGF_Err e;\n\tFILE *dump;\n\tBool close;\n\tu32 i, j, count;\n\tchar szBuf[1024];\n\tGF_SceneManager *ctx;\n\tGF_SceneLoader load;\n\tGF_StatManager *sm;\n\tGF_List *sample_list;\n\tGF_SceneGraph *scene_graph;", "\tdump = NULL;\n\tsm = NULL;\n\tsample_list = NULL;", "\tclose = 0;", "\tscene_graph = gf_sg_new();\n\tctx = gf_sm_new(scene_graph);\n\tmemset(&load, 0, sizeof(GF_SceneLoader));\n\tload.fileName = file;\n\tload.ctx = ctx;", "\tif (get_file_type_by_ext(file) == 1) {\n\t\tload.isom = gf_isom_open(file, GF_ISOM_OPEN_READ, NULL);\n\t\tif (!load.isom) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Cannot open file: %s\\n\", gf_error_to_string(gf_isom_last_error(NULL))));\n\t\t\tgf_sm_del(ctx);\n\t\t\tgf_sg_del(scene_graph);\n\t\t\treturn;\n\t\t}\n\t}", "\te = gf_sm_load_init(&load);\n\tif (!e) e = gf_sm_load_run(&load);\n\tgf_sm_load_done(&load);\n\tif (e<0) goto exit;", "\tif (inName) {\n\t\tstrcpy(szBuf, inName);\n\t\tif (!is_final_name) strcat(szBuf, \"_stat.xml\");\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s for dumping\\n\", szBuf));\n\t\t\treturn;\n\t\t}\n\t\tclose = 1;\n\t} else {\n\t\tdump = stdout;\n\t\tclose = 0;\n\t}", "\tfprintf(stderr, \"Analysing Scene\\n\");", "\tfprintf(dump, \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\\n\");\n\tfprintf(dump, \"<!-- Scene Graph Statistics Generated by MP4Box - GPAC \");\n\tif (! gf_sys_is_test_mode())\n\t\tfprintf(dump, \"%s \", gf_gpac_version());\n\tfprintf(dump, \"-->\\n\");", "\tfprintf(dump, \"<SceneStatistics file=\\\"%s\\\" DumpType=\\\"%s\\\">\\n\", gf_file_basename(file), (stat_level==1) ? \"full scene\" : ((stat_level==2) ? \"AccessUnit based\" : \"SceneGraph after each AU\"));", "\tsm = gf_sm_stats_new();", "\t/*stat level 1: complete scene stat*/\n\tif (stat_level == 1) {\n\t\te = gf_sm_stats_for_scene(sm, ctx);\n\t\tif (!e) dump_stats(dump, gf_sm_stats_get(sm) );\n\t\tgoto exit;\n\t}\n\t/*re_order all BIFS-AUs*/\n\tsample_list = gf_list_new();\n\t/*configure all systems streams we're dumping*/\n\tfor (i=0; i<gf_list_count(ctx->streams); i++) {\n\t\tGF_StreamContext *sc = gf_list_get(ctx->streams, i);\n\t\tif (sc->streamType != GF_STREAM_SCENE) continue;\n\t\tfor (j=0; j<gf_list_count(sc->AUs); j++) {\n\t\t\tGF_AUContext *au = gf_list_get(sc->AUs, j);\n\t\t\tReorderAU(sample_list, au);\n\t\t}\n\t}", "\tcount = gf_list_count(sample_list);\n\tfor (i=0; i<count; i++) {\n\t\tGF_AUContext *au = gf_list_get(sample_list, i);", "\t\tfor (j=0; j<gf_list_count(au->commands); j++) {\n\t\t\tGF_Command *com = gf_list_get(au->commands, j);\n\t\t\t/*stat level 2 - get command stats*/\n\t\t\tif (stat_level==2) {\n\t\t\t\te = gf_sm_stats_for_command(sm, com);\n\t\t\t\tif (e) goto exit;\n\t\t\t}\n\t\t\t/*stat level 3 - apply command*/\n\t\t\tif (stat_level==3) gf_sg_command_apply(scene_graph, com, 0);\n\t\t}\n\t\t/*stat level 3: get graph stat*/\n\t\tif (stat_level==3) {\n\t\t\te = gf_sm_stats_for_graph(sm, scene_graph);\n\t\t\tif (e) goto exit;\n\t\t}\n\t\tif (stat_level==2) {\n\t\t\tfprintf(dump, \"<AUStatistics StreamID=\\\"%d\\\" AUTime=\\\"\"LLD\"\\\">\\n\", au->owner->ESID, au->timing);\n\t\t} else {\n\t\t\tfprintf(dump, \"<GraphStatistics StreamID=\\\"%d\\\" AUTime=\\\"\"LLD\"\\\">\\n\", au->owner->ESID, au->timing);\n\t\t}\n\t\t/*dump stats*/\n\t\tdump_stats(dump, gf_sm_stats_get(sm) );\n\t\t/*reset stats*/\n\t\tgf_sm_stats_reset(sm);\n\t\tif (stat_level==2) {\n\t\t\tfprintf(dump, \"</AUStatistics>\\n\");\n\t\t} else {\n\t\t\tfprintf(dump, \"</GraphStatistics>\\n\");\n\t\t}", "\t\tgf_set_progress(\"Analysing AU\", i+1, count);\n\t}", "\nexit:\n\tif (sample_list) gf_list_del(sample_list);\n\tif (sm) gf_sm_stats_del(sm);\n\tgf_sm_del(ctx);\n\tgf_sg_del(scene_graph);\n\tif (load.isom) gf_isom_delete(load.isom);\n\tif (e) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Stats error: %s\\n\", gf_error_to_string(e)));\n\t} else {\n\t\tfprintf(dump, \"</SceneStatistics>\\n\");\n\t}\n\tif (dump && close) gf_fclose(dump);\n\tfprintf(stderr, \"done\\n\");\n}\n#endif /*GPAC_DISABLE_SCENE_STATS*/", "", "#ifndef GPAC_DISABLE_VRML", "static void PrintFixed(Fixed val, Bool add_space)\n{\n\tif (add_space) fprintf(stderr, \" \");\n\tif (val==FIX_MIN) fprintf(stderr, \"-I\");\n\telse if (val==FIX_MAX) fprintf(stderr, \"+I\");\n\telse fprintf(stderr, \"%g\", FIX2FLT(val));\n}", "static void PrintNodeSFField(u32 type, void *far_ptr)\n{\n\tif (!far_ptr) return;\n\tswitch (type) {\n\tcase GF_SG_VRML_SFBOOL:\n\t\tfprintf(stderr, \"%s\", (*(SFBool *)far_ptr) ? \"TRUE\" : \"FALSE\");\n\t\tbreak;\n\tcase GF_SG_VRML_SFINT32:\n\t\tfprintf(stderr, \"%d\", (*(SFInt32 *)far_ptr));\n\t\tbreak;\n\tcase GF_SG_VRML_SFFLOAT:\n\t\tPrintFixed((*(SFFloat *)far_ptr), 0);\n\t\tbreak;\n\tcase GF_SG_VRML_SFTIME:\n\t\tfprintf(stderr, \"%g\", (*(SFTime *)far_ptr));\n\t\tbreak;\n\tcase GF_SG_VRML_SFVEC2F:\n\t\tPrintFixed(((SFVec2f *)far_ptr)->x, 0);\n\t\tPrintFixed(((SFVec2f *)far_ptr)->y, 1);\n\t\tbreak;\n\tcase GF_SG_VRML_SFVEC3F:\n\t\tPrintFixed(((SFVec3f *)far_ptr)->x, 0);\n\t\tPrintFixed(((SFVec3f *)far_ptr)->y, 1);\n\t\tPrintFixed(((SFVec3f *)far_ptr)->z, 1);\n\t\tbreak;\n\tcase GF_SG_VRML_SFROTATION:\n\t\tPrintFixed(((SFRotation *)far_ptr)->x, 0);\n\t\tPrintFixed(((SFRotation *)far_ptr)->y, 1);\n\t\tPrintFixed(((SFRotation *)far_ptr)->z, 1);\n\t\tPrintFixed(((SFRotation *)far_ptr)->q, 1);\n\t\tbreak;\n\tcase GF_SG_VRML_SFCOLOR:\n\t\tPrintFixed(((SFColor *)far_ptr)->red, 0);\n\t\tPrintFixed(((SFColor *)far_ptr)->green, 1);\n\t\tPrintFixed(((SFColor *)far_ptr)->blue, 1);\n\t\tbreak;\n\tcase GF_SG_VRML_SFSTRING:\n\t\tif (((SFString*)far_ptr)->buffer)\n\t\t\tfprintf(stderr, \"\\\"%s\\\"\", ((SFString*)far_ptr)->buffer);\n\t\telse\n\t\t\tfprintf(stderr, \"NULL\");\n\t\tbreak;\n\t}\n}\n#endif", "#ifndef GPAC_DISABLE_VRML\nstatic void do_print_node(GF_Node *node, GF_SceneGraph *sg, const char *name, u32 graph_type, Bool is_nodefield, Bool do_cov)\n{\n\tu32 nbF, i;\n\tGF_FieldInfo f;\n#ifndef GPAC_DISABLE_BIFS\n\tu8 qt, at;\n\tFixed bmin, bmax;\n\tu32 nbBits;\n#endif /*GPAC_DISABLE_BIFS*/", "\tnbF = gf_node_get_field_count(node);", "\tif (is_nodefield) {\n\t\tchar szField[1024];\n\t\tu32 tfirst, tlast;\n\t\tif (gf_node_get_field_by_name(node, szField, &f) != GF_OK) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Field %s is not a member of node %s\\n\", szField, name));\n\t\t\treturn;\n\t\t}\n\t\tfprintf(stderr, \"Allowed nodes in %s.%s:\\n\", name, szField);\n\t\tif (graph_type==1) {\n\t\t\ttfirst = GF_NODE_RANGE_FIRST_X3D;\n\t\t\ttlast = GF_NODE_RANGE_LAST_X3D;\n\t\t} else {\n\t\t\ttfirst = GF_NODE_RANGE_FIRST_MPEG4;\n\t\t\ttlast = GF_NODE_RANGE_LAST_MPEG4;\n\t\t}\n\t\tfor (i=tfirst; i<tlast; i++) {\n\t\t\tGF_Node *tmp = gf_node_new(sg, i);\n\t\t\tgf_node_register(tmp, NULL);\n\t\t\tif (gf_node_in_table_by_tag(i, f.NDTtype)) {\n\t\t\t\tconst char *nname = gf_node_get_class_name(tmp);\n\t\t\t\tif (nname && strcmp(nname, \"Unknown Node\")) {\n\t\t\t\t\tfprintf(stderr, \"\\t%s\\n\", nname);\n\t\t\t\t}\n\t\t\t}\n\t\t\tgf_node_unregister(tmp, NULL);\n\t\t}\n\t\treturn;\n\t}\n\tif (do_cov) {\n\t\tu32 ndt;\n\t\tif (graph_type==0) {\n\t\t\tu32 all;\n\t\t\tgf_node_mpeg4_type_by_class_name(name);\n\t\t\tgf_bifs_get_child_table(node);\n\t\t\tall = gf_node_get_num_fields_in_mode(node, GF_SG_FIELD_CODING_ALL);\n\t\t\tfor (i=0; i<all; i++) {\n\t\t\t\tu32 res;\n\t\t\t\tgf_sg_script_get_field_index(node, i, GF_SG_FIELD_CODING_ALL, &res);\n\t\t\t}", "\t\t\tgf_node_get_num_fields_in_mode(node, GF_SG_FIELD_CODING_DEF);\n\t\t\tgf_node_get_num_fields_in_mode(node, GF_SG_FIELD_CODING_IN);\n\t\t\tgf_node_get_num_fields_in_mode(node, GF_SG_FIELD_CODING_OUT);\n\t\t\tgf_node_get_num_fields_in_mode(node, GF_SG_FIELD_CODING_DYN);\n\t\t}\n\t\telse if (graph_type==1) gf_node_x3d_type_by_class_name(name);\n\t\tfor (ndt=NDT_SFWorldNode; ndt<NDT_LAST; ndt++) {\n\t\t\tgf_node_in_table_by_tag(gf_node_get_tag(node), ndt);\n\t\t}\n\t}\n\tfprintf(stderr, \"%s {\\n\", name);", "\tfor (i=0; i<nbF; i++) {\n\t\tgf_node_get_field(node, i, &f);\n\t\tif (graph_type==2) {\n\t\t\tfprintf(stderr, \"\\t%s=\\\"...\\\"\\n\", f.name);\n\t\t\tcontinue;\n\t\t}", "\t\tfprintf(stderr, \"\\t%s %s %s\", gf_sg_vrml_get_event_type_name(f.eventType, 0), gf_sg_vrml_get_field_type_name(f.fieldType), f.name);\n\t\tif (f.fieldType==GF_SG_VRML_SFNODE) fprintf(stderr, \" NULL\");\n\t\telse if (f.fieldType==GF_SG_VRML_MFNODE) fprintf(stderr, \" []\");\n\t\telse if (gf_sg_vrml_is_sf_field(f.fieldType)) {\n\t\t\tfprintf(stderr, \" \");\n\t\t\tPrintNodeSFField(f.fieldType, f.far_ptr);\n\t\t} else {\n\t\t\tvoid *ptr;\n\t\t\tu32 j, sftype;\n\t\t\tGenMFField *mffield = (GenMFField *) f.far_ptr;\n\t\t\tfprintf(stderr, \" [\");\n\t\t\tsftype = gf_sg_vrml_get_sf_type(f.fieldType);\n\t\t\tfor (j=0; j<mffield->count; j++) {\n\t\t\t\tif (j) fprintf(stderr, \" \");\n\t\t\t\tgf_sg_vrml_mf_get_item(f.far_ptr, f.fieldType, &ptr, j);\n\t\t\t\tPrintNodeSFField(sftype, ptr);\n\t\t\t}\n\t\t\tfprintf(stderr, \"]\");\n\t\t}\n#ifndef GPAC_DISABLE_BIFS\n\t\tif (gf_bifs_get_aq_info(node, i, &qt, &at, &bmin, &bmax, &nbBits)) {\n\t\t\tif (qt) {\n\t\t\t\tfprintf(stderr, \" #QP=%d\", qt);\n\t\t\t\tif (qt==13) fprintf(stderr, \" NbBits=%d\", nbBits);\n\t\t\t\tif (bmin && bmax) {\n\t\t\t\t\tfprintf(stderr, \" Bounds=[\");\n\t\t\t\t\tPrintFixed(bmin, 0);\n\t\t\t\t\tfprintf(stderr, \",\");\n\t\t\t\t\tPrintFixed(bmax, 0);\n\t\t\t\t\tfprintf(stderr, \"]\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n#endif /*GPAC_DISABLE_BIFS*/\n\t\tfprintf(stderr, \"\\n\");", "\t\tif (do_cov) {\n\t\t\tgf_node_get_field_by_name(node, (char *) f.name, &f);\n\t\t}\n\t}\n\tfprintf(stderr, \"}\\n\\n\");", "}\n#endif", "\nu32 PrintNode(const char *name, u32 graph_type)\n{\n#ifdef GPAC_DISABLE_VRML\n\tM4_LOG(GF_LOG_ERROR, (\"VRML/MPEG-4/X3D scene graph is disabled in this build of GPAC\\n\"));\n\treturn 2;\n#else\n\tconst char *std_name;\n\tGF_Node *node;\n\tGF_SceneGraph *sg;\n\tu32 tag;\n#ifndef GPAC_DISABLE_BIFS\n#endif /*GPAC_DISABLE_BIFS*/\n\tBool is_nodefield = 0;", "\tchar *sep = strchr(name, '.');\n\tif (sep) {\n\t\tsep[0] = 0;\n\t\tis_nodefield = 1;\n\t}", "\tif (graph_type==1) {\n#ifndef GPAC_DISABLE_X3D\n\t\ttag = gf_node_x3d_type_by_class_name(name);\n\t\tstd_name = \"X3D\";\n#else\n\t\tM4_LOG(GF_LOG_ERROR, (\"X3D node printing is not supported (X3D support disabled)\\n\"));\n\t\treturn 2;\n#endif\n\t} else {\n\t\ttag = gf_node_mpeg4_type_by_class_name(name);\n\t\tstd_name = \"MPEG4\";\n\t}\n\tif (!tag) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Unknown %s node %s\\n\", std_name, name));\n\t\treturn 2;\n\t}", "\tsg = gf_sg_new();\n\tnode = gf_node_new(sg, tag);\n\tgf_node_register(node, NULL);\n\tname = gf_node_get_class_name(node);\n\tif (!node) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Node %s not supported in current built\\n\", name));\n\t\treturn 2;\n\t}\n\tdo_print_node(node, sg, name, graph_type, is_nodefield, GF_FALSE);", "\tgf_node_unregister(node, NULL);\n\tgf_sg_del(sg);\n#endif /*GPAC_DISABLE_VRML*/\n\treturn 1;\n}", "u32 PrintBuiltInNodes(char *arg_val, u32 dump_type)\n{\n#if !defined(GPAC_DISABLE_VRML) && !defined(GPAC_DISABLE_X3D) && !defined(GPAC_DISABLE_SVG)\n\tGF_SceneGraph *sg;\n\tu32 i, nb_in, nb_not_in, start_tag, end_tag;\n\tu32 graph_type;\n\tBool dump_nodes = ((dump_type==1) || (dump_type==3)) ? 1 : 0;", "\tif (dump_type==4) graph_type = 2;\n\telse if ((dump_type==2) || (dump_type==3)) graph_type = 1;\n\telse graph_type = 0;", "\tif (graph_type==1) {\n#if !defined(GPAC_DISABLE_VRML) && !defined(GPAC_DISABLE_X3D)\n\t\tstart_tag = GF_NODE_RANGE_FIRST_X3D;\n\t\tend_tag = TAG_LastImplementedX3D;\n#else\n\t\tM4_LOG(GF_LOG_ERROR, (\"X3D scene graph disabled in this build of GPAC\\n\"));\n\t\treturn 2;\n#endif\n\t} else if (graph_type==2) {\n#ifdef GPAC_DISABLE_SVG\n\t\tM4_LOG(GF_LOG_ERROR, (\"SVG scene graph disabled in this build of GPAC\\n\"));\n\t\treturn 2;\n#else\n\t\tstart_tag = GF_NODE_RANGE_FIRST_SVG;\n\t\tend_tag = GF_NODE_RANGE_LAST_SVG;\n#endif\n\t} else {\n#ifdef GPAC_DISABLE_VRML\n\t\tM4_LOG(GF_LOG_ERROR, (\"VRML/MPEG-4 scene graph disabled in this build of GPAC\\n\"));\n\t\treturn 2;\n#else\n\t\tstart_tag = GF_NODE_RANGE_FIRST_MPEG4;\n\t\tend_tag = TAG_LastImplementedMPEG4;\n#endif\n\t}\n\tnb_in = nb_not_in = 0;\n\tsg = gf_sg_new();", "\tif (graph_type==1) {\n\t\tfprintf(stderr, \"Available X3D nodes in this build (dumping):\\n\");\n\t} else if (graph_type==2) {\n\t\tfprintf(stderr, \"Available SVG nodes in this build (dumping and LASeR coding):\\n\");\n\t} else {\n\t\tfprintf(stderr, \"Available MPEG-4 nodes in this build (encoding/decoding/dumping):\\n\");\n\t}\n\tfor (i=start_tag; i<end_tag; i++) {\n\t\tGF_Node *node = gf_node_new(sg, i);\n\t\tif (node) {\n\t\t\tgf_node_register(node, NULL);\n\t\t\tif (dump_nodes) {\n\t\t\t\tdo_print_node(node, sg, gf_node_get_class_name(node), graph_type, GF_FALSE, GF_TRUE);\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \" %s\\n\", gf_node_get_class_name(node));\n\t\t\t}\n\t\t\tgf_node_unregister(node, NULL);\n\t\t\tnb_in++;\n\t\t} else {\n\t\t\tif (graph_type==2)\n\t\t\t\tbreak;\n\t\t\tnb_not_in++;\n\t\t}\n\t}\n\tgf_sg_del(sg);\n\tif (graph_type==2) {\n\t\tfprintf(stderr, \"\\n%d nodes supported\\n\", nb_in);\n\t} else {\n\t\tfprintf(stderr, \"\\n%d nodes supported - %d nodes not supported\\n\", nb_in, nb_not_in);\n\t}\n\t//coverage\n\tif (dump_nodes) {\n\t\tfor (i=GF_SG_VRML_SFBOOL; i<GF_SG_VRML_SCRIPT_FUNCTION; i++) {\n\t\t\tvoid *fp = gf_sg_vrml_field_pointer_new(i);\n\t\t\tif (fp) {\n\t\t\t\tif (i==GF_SG_VRML_SFSCRIPT) gf_free(fp);\n\t\t\t\telse gf_sg_vrml_field_pointer_del(fp, i);\n\t\t\t}\n\t\t}", "\t}\n#else\n\tM4_LOG(GF_LOG_ERROR, (\"No scene graph enabled in this MP4Box build\\n\"));\n#endif\n\treturn 1;\n}", "\nu32 PrintBuiltInBoxes(char *argval, u32 do_cov)\n{\n\tu32 i, count=gf_isom_get_num_supported_boxes();\n\t\n\tfprintf(stdout, \"<Boxes>\\n\");\n\t//index 0 is our internal unknown box handler\n\tfor (i=1; i<count; i++) {\n\t\tgf_isom_dump_supported_box(i, stdout);\n if (do_cov) {\n\t\t\tu32 btype = gf_isom_get_supported_box_type(i);\n GF_Box *b=gf_isom_box_new(btype);\n if (b) {\n GF_Box *c=NULL;\n gf_isom_clone_box(b, &c);\n if (c) gf_isom_box_del(c);\n gf_isom_box_del(b);\n }\n }\n\t}\n\tfprintf(stdout, \"</Boxes>\\n\");\n\treturn 1;\n}", "#if !defined(GPAC_DISABLE_ISOM_HINTING) && !defined(GPAC_DISABLE_ISOM_DUMP)", "void dump_isom_rtp(GF_ISOFile *file, char *inName, Bool is_final_name)\n{\n\tu32 i, j, size;\n\tFILE *dump;\n\tconst char *sdp;", "\tif (inName) {\n\t\tchar szBuf[1024];\n\t\tstrcpy(szBuf, inName);\n\t\tif (!is_final_name) strcat(szBuf, \"_rtp.xml\");\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s\\n\", szBuf));\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t}", "\tfprintf(dump, \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\\n\");\n\tfprintf(dump, \"<!-- MP4Box RTP trace -->\\n\");\n\tfprintf(dump, \"<RTPFile>\\n\");", "\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\tif (gf_isom_get_media_type(file, i+1) != GF_ISOM_MEDIA_HINT) continue;", "\t\tfprintf(dump, \"<RTPHintTrack trackID=\\\"%d\\\">\\n\", gf_isom_get_track_id(file, i+1));\n\t\tgf_isom_sdp_track_get(file, i+1, &sdp, &size);\n\t\tfprintf(dump, \"<SDPInfo>%s</SDPInfo>\", sdp);", "#ifndef GPAC_DISABLE_ISOM_HINTING\n\t\tfor (j=0; j<gf_isom_get_sample_count(file, i+1); j++) {\n\t\t\tgf_isom_dump_hint_sample(file, i+1, j+1, dump);\n\t\t}\n#endif\n\t\tfprintf(dump, \"</RTPHintTrack>\\n\");\n\t}\n\tfprintf(dump, \"</RTPFile>\\n\");\n\tif (inName) gf_fclose(dump);\n}\n#endif", "\nvoid dump_isom_timestamps(GF_ISOFile *file, char *inName, Bool is_final_name, u32 dump_mode)\n{\n\tu32 i, j, k, count;\n\tBool has_ctts_error, is_fragmented=GF_FALSE;\n\tFILE *dump;\n\tBool skip_offset = ((dump_mode==2) || (dump_mode==4)) ? GF_TRUE : GF_FALSE;\n\tBool check_ts = ((dump_mode==3) || (dump_mode==4)) ? GF_TRUE : GF_FALSE;\n\tstruct _ts_info {\n\t\tu64 dts;\n\t\ts64 cts;\n\t};\n\tstruct _ts_info *timings = NULL;\n\tu32 nb_timings=0, nb_timings_alloc = 0;", "\n\tif (inName) {\n\t\tchar szBuf[1024];\n\t\tstrcpy(szBuf, inName);\n\t\tif (!is_final_name) strcat(szBuf, \"_ts.txt\");\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s\\n\", szBuf));\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t}\n\tif (gf_isom_is_fragmented(file))\n\t\tis_fragmented = GF_TRUE;", "\thas_ctts_error = GF_FALSE;\n\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\ts64 cts_dts_shift = gf_isom_get_cts_to_dts_shift(file, i+1);\n\t\tu32 has_cts_offset = gf_isom_has_time_offset(file, i+1);", "\t\tfprintf(dump, \"#dumping track ID %d timing:\\n\", gf_isom_get_track_id(file, i + 1));\n\t\tfprintf(dump, \"Num\\tDTS\\tCTS\\tSize\\tRAP%s\\tisLeading\\tDependsOn\\tDependedOn\\tRedundant\\tRAP-SampleGroup\\tRoll-SampleGroup\\tRoll-Distance\", skip_offset ? \"\" : \"\\tOffset\");\n\t\tif (is_fragmented) {\n\t\t\tfprintf(dump, \"\\tfrag_start\");\n\t\t}\n\t\tfprintf(dump, \"\\n\");", "\n\t\tcount = gf_isom_get_sample_count(file, i+1);\n\t\tif (has_cts_offset && check_ts) {\n\t\t\tif (nb_timings_alloc<count) {\n\t\t\t\tnb_timings_alloc = count;\n\t\t\t\ttimings = gf_realloc(timings, sizeof (struct _ts_info) * count);\n\t\t\t}\n\t\t\tnb_timings = 0;\n\t\t}", "\t\tfor (j=0; j<count; j++) {\n\t\t\ts64 cts;\n\t\t\tu64 dts, offset;\n\t\t\tu32 isLeading, dependsOn, dependedOn, redundant;\n\t\t\tBool is_rap;\n\t\t\tGF_ISOSampleRollType roll_type;\n\t\t\ts32 roll_distance;\n\t\t\tu32 index;\n\t\t\tGF_ISOSample *samp = gf_isom_get_sample_info(file, i+1, j+1, &index, &offset);\n\t\t\tif (!samp) {\n\t\t\t\tfprintf(dump, \" SAMPLE #%d IN TRACK #%d NOT THERE !!!\\n\", j+1, i+1);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tgf_isom_get_sample_flags(file, i+1, j+1, &isLeading, &dependsOn, &dependedOn, &redundant);\n\t\t\tgf_isom_get_sample_rap_roll_info(file, i+1, j+1, &is_rap, &roll_type, &roll_distance);\n\t\t\tdts = samp->DTS;\n\t\t\tcts = dts + (s32) samp->CTS_Offset;\n\t\t\tfprintf(dump, \"Sample %d\\tDTS \"LLU\"\\tCTS \"LLD\"\\t%d\\t%d\", j+1, dts, cts, samp->dataLength, samp->IsRAP);", "\t\t\tif (!skip_offset)\n\t\t\t\tfprintf(dump, \"\\t\"LLU, offset);", "\t\t\tfprintf(dump, \"\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\", isLeading, dependsOn, dependedOn, redundant, is_rap, roll_type, roll_distance);", "\t\t\tif (cts< (s64) dts) {\n\t\t\t\tif (has_cts_offset==2) {\n\t\t\t\t\tif (cts_dts_shift && (cts+cts_dts_shift < (s64) dts)) {\n\t\t\t\t\t\tfprintf(dump, \" #NEGATIVE CTS OFFSET!!!\");\n\t\t\t\t\t\thas_ctts_error = 1;\n\t\t\t\t\t} else if (!cts_dts_shift) {\n\t\t\t\t\t\tfprintf(dump, \" #possible negative CTS offset (no cslg in file)\");\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(dump, \" #NEGATIVE CTS OFFSET!!!\");\n\t\t\t\t\thas_ctts_error = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (has_cts_offset && check_ts) {\n\t\t\t\tfor (k=0; k<nb_timings; k++) {", "\t\t\t\t\tif (timings[k].dts==dts) {\n\t\t\t\t\t\tfprintf(dump, \" #SAME DTS USED!!!\");\n\t\t\t\t\t\thas_ctts_error = 1;\n\t\t\t\t\t}\n\t\t\t\t\tif (timings[k].cts==cts) {\n\t\t\t\t\t\tfprintf(dump, \" #SAME CTS USED!!! \");\n\t\t\t\t\t\thas_ctts_error = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ttimings[nb_timings].dts = dts;\n\t\t\t\ttimings[nb_timings].cts = cts;\n\t\t\t\tnb_timings++;\n\t\t\t}", "\t\t\tgf_isom_sample_del(&samp);", "\t\t\tif (is_fragmented) {\n\t\t\t\tfprintf(dump, \"\\t%d\", gf_isom_sample_is_fragment_start(file, i+1, j+1, NULL) );\n\t\t\t}\n\t\t\tfprintf(dump, \"\\n\");\n\t\t\tgf_set_progress(\"Dumping track timing\", j+1, count);\n\t\t}\n\t\tfprintf(dump, \"\\n\\n\");\n\t\tgf_set_progress(\"Dumping track timing\", count, count);\n\t}\n\tif (timings) gf_free(timings);", "\tif (inName) gf_fclose(dump);\n\tif (has_ctts_error) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"\\tFile has CTTS table errors\\n\"));\n\t}\n}", "", "static u32 read_nal_size_hdr(u8 *ptr, u32 nalh_size)\n{\n\tu32 nal_size=0;\n\tu32 v = nalh_size;\n\twhile (v) {\n\t\tnal_size |= (u8) *ptr;\n\t\tptr++;\n\t\tv-=1;\n\t\tif (v) nal_size <<= 8;\n\t}\n\treturn nal_size;\n}", "#ifndef GPAC_DISABLE_AV_PARSERS\nvoid gf_inspect_dump_nalu(FILE *dump, u8 *ptr, u32 ptr_size, Bool is_svc, HEVCState *hevc, AVCState *avc, VVCState *vvc, u32 nalh_size, Bool dump_crc, Bool is_encrypted);\n#endif", "\nstatic void dump_isom_nal_ex(GF_ISOFile *file, GF_ISOTrackID trackID, FILE *dump, u32 dump_flags)\n{\n\tu32 i, j, count, nb_descs, track, nalh_size, timescale, cur_extract_mode;\n\ts32 countRef;\n\tBool is_adobe_protected = GF_FALSE;\n\tBool is_cenc_protected = GF_FALSE;\n\tBool is_hevc = GF_FALSE;\n\tBool is_vvc = GF_FALSE;\n#ifndef GPAC_DISABLE_AV_PARSERS\n\tAVCState *avc_state = NULL;\n\tHEVCState *hevc_state = NULL;\n\tVVCState *vvc_state = NULL;\n#endif\n\tGF_AVCConfig *avccfg, *svccfg;\n\tGF_HEVCConfig *hevccfg, *lhvccfg;\n\tGF_VVCConfig *vvccfg;\n\tGF_NALUFFParam *slc;\n\tBool has_svcc = GF_FALSE;", "\ttrack = gf_isom_get_track_by_id(file, trackID);", "\tcount = gf_isom_get_sample_count(file, track);", "\ttimescale = gf_isom_get_media_timescale(file, track);", "\tcur_extract_mode = gf_isom_get_nalu_extract_mode(file, track);", "\tnb_descs = gf_isom_get_sample_description_count(file, track);\n\tif (!nb_descs) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Error: Track #%d has no sample description so is likely not NALU-based!\\n\", trackID));\n\t\treturn;\n\t}", "\tfprintf(dump, \"<NALUTrack trackID=\\\"%d\\\" SampleCount=\\\"%d\\\" TimeScale=\\\"%d\\\">\\n\", trackID, count, timescale);", "#ifndef GPAC_DISABLE_AV_PARSERS", "#define DUMP_ARRAY(arr, name, loc, _is_svc)\\\n\tif (arr) {\\\n\t\tfprintf(dump, \" <%sArray location=\\\"%s\\\">\\n\", name, loc);\\\n\t\tfor (i=0; i<gf_list_count(arr); i++) {\\\n\t\t\tslc = gf_list_get(arr, i);\\\n\t\t\tfprintf(dump, \" <NALU size=\\\"%d\\\" \", slc->size);\\\n\t\t\tgf_inspect_dump_nalu(dump, (u8 *) slc->data, slc->size, _is_svc, is_hevc ? hevc_state : NULL, avc_state, is_vvc ? vvc_state : NULL, nalh_size, (dump_flags&1) ? GF_TRUE : GF_FALSE, GF_FALSE);\\\n\t\t}\\\n\t\tfprintf(dump, \" </%sArray>\\n\", name);\\\n\t}\\", "#else", "#define DUMP_ARRAY(arr, name, loc, _is_svc)\\\n\tif (arr) {\\\n\t\tfprintf(dump, \" <%sArray location=\\\"%s\\\">\\n\", name, loc);\\\n\t\tfor (i=0; i<gf_list_count(arr); i++) {\\\n\t\t\tslc = gf_list_get(arr, i);\\\n\t\t\tfprintf(dump, \" <NALU size=\\\"%d\\\" \", slc->size);\\\n\t\t\tfprintf(dump, \"/>\\n\");\\\n\t\t}\\\n\t\tfprintf(dump, \" </%sArray>\\n\", name);\\\n\t}\\", "#endif", "\tnalh_size = 0;", "\tfor (j=0; j<nb_descs; j++) {\n\t\tGF_AVCConfig *mvccfg;\n\t\tBool is_svc;", "\t\tavccfg = gf_isom_avc_config_get(file, track, j+1);\n\t\tsvccfg = gf_isom_svc_config_get(file, track, j+1);\n\t\tmvccfg = gf_isom_mvc_config_get(file, track, j+1);\n\t\thevccfg = gf_isom_hevc_config_get(file, track, j+1);\n\t\tlhvccfg = gf_isom_lhvc_config_get(file, track, j+1);\n\t\tvvccfg = gf_isom_vvc_config_get(file, track, j+1);", "\t\tis_svc = (svccfg!=NULL) ? 1:0;", "\t\tif (hevccfg || lhvccfg) {\n\t\t\tis_hevc = 1;\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\tGF_SAFEALLOC(hevc_state, HEVCState)\n#endif\n\t\t} else if (vvccfg) {\n\t\t\tis_vvc = 1;\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\tGF_SAFEALLOC(vvc_state, VVCState)\n#endif\n\t\t} else if (avccfg || svccfg || mvccfg) {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\tGF_SAFEALLOC(avc_state, AVCState)\n#endif\n\t\t}", "\n\t\t//for tile tracks the hvcC is stored in the 'tbas' track\n\t\tif (!hevccfg && gf_isom_get_reference_count(file, track, GF_ISOM_REF_TBAS)) {\n\t\t\tu32 tk = 0;\n\t\t\tgf_isom_get_reference(file, track, GF_ISOM_REF_TBAS, 1, &tk);\n\t\t\thevccfg = gf_isom_hevc_config_get(file, tk, 1);\n\t\t}", "\t\tfprintf(dump, \" <NALUConfig>\\n\");", "\t\tif (!avccfg && !svccfg && !hevccfg && !lhvccfg && !vvccfg) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Error: Track #%d is not NALU or OBU based!\\n\", trackID));\n\t\t\treturn;\n\t\t}", "\t\tif (avccfg) {\n\t\t\tnalh_size = avccfg->nal_unit_size;", "\t\t\tDUMP_ARRAY(avccfg->sequenceParameterSets, \"AVCSPS\", \"avcC\", is_svc);\n\t\t\tDUMP_ARRAY(avccfg->pictureParameterSets, \"AVCPPS\", \"avcC\", is_svc)\n\t\t\tDUMP_ARRAY(avccfg->sequenceParameterSetExtensions, \"AVCSPSEx\", \"avcC\", is_svc)\n\t\t}\n\t\tif (is_svc) {\n\t\t\tif (!nalh_size) nalh_size = svccfg->nal_unit_size;\n\t\t\tDUMP_ARRAY(svccfg->sequenceParameterSets, \"SVCSPS\", \"svcC\", is_svc)\n\t\t\tDUMP_ARRAY(svccfg->pictureParameterSets, \"SVCPPS\", \"svcC\", is_svc)\n\t\t}\n\t\tif (mvccfg) {\n\t\t\tif (!nalh_size) nalh_size = mvccfg->nal_unit_size;\n\t\t\tDUMP_ARRAY(mvccfg->sequenceParameterSets, \"SVCSPS\", \"mvcC\", is_svc)\n\t\t\tDUMP_ARRAY(mvccfg->pictureParameterSets, \"SVCPPS\", \"mvcC\", is_svc)\n\t\t}\n\t\tif (hevccfg) {\n\t\t\tu32 idx;\n\t\t\tnalh_size = hevccfg->nal_unit_size;\n\t\t\tfor (idx=0; idx<gf_list_count(hevccfg->param_array); idx++) {\n\t\t\t\tGF_NALUFFParamArray *ar = gf_list_get(hevccfg->param_array, idx);\n\t\t\t\tif (ar->type==GF_HEVC_NALU_SEQ_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"HEVCSPS\", \"hvcC\", 0)\n\t\t\t\t} else if (ar->type==GF_HEVC_NALU_PIC_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"HEVCPPS\", \"hvcC\", 0)\n\t\t\t\t} else if (ar->type==GF_HEVC_NALU_VID_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"HEVCVPS\", \"hvcC\", 0)\n\t\t\t\t} else {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"HEVCUnknownPS\", \"hvcC\", 0)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (vvccfg) {\n\t\t\tu32 idx;\n\t\t\tnalh_size = vvccfg->nal_unit_size;\n\t\t\tfor (idx=0; idx<gf_list_count(vvccfg->param_array); idx++) {\n\t\t\t\tGF_NALUFFParamArray *ar = gf_list_get(vvccfg->param_array, idx);\n\t\t\t\tif (ar->type==GF_VVC_NALU_SEQ_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"VVCSPS\", \"vvcC\", 0)\n\t\t\t\t} else if (ar->type==GF_VVC_NALU_PIC_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"VVCPPS\", \"vvcC\", 0)\n\t\t\t\t} else if (ar->type==GF_VVC_NALU_VID_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"VVCVPS\", \"vvcC\", 0)\n\t\t\t\t} else {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"VVCUnknownPS\", \"vvcC\", 0)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (lhvccfg) {\n\t\t\tu32 idx;\n\t\t\tnalh_size = lhvccfg->nal_unit_size;\n\t\t\tfor (idx=0; idx<gf_list_count(lhvccfg->param_array); idx++) {\n\t\t\t\tGF_NALUFFParamArray *ar = gf_list_get(lhvccfg->param_array, idx);\n\t\t\t\tif (ar->type==GF_HEVC_NALU_SEQ_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"HEVCSPS\", \"lhcC\", 0)\n\t\t\t\t} else if (ar->type==GF_HEVC_NALU_PIC_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"HEVCPPS\", \"lhcC\", 0)\n\t\t\t\t} else if (ar->type==GF_HEVC_NALU_VID_PARAM) {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"HEVCVPS\", \"lhcC\", 0)\n\t\t\t\t} else {\n\t\t\t\t\tDUMP_ARRAY(ar->nalus, \"HEVCUnknownPS\", \"lhcC\", 0)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfprintf(dump, \" </NALUConfig>\\n\");", "\t\tif (avccfg) gf_odf_avc_cfg_del(avccfg);\n\t\tif (svccfg) {\n\t\t\tgf_odf_avc_cfg_del(svccfg);\n\t\t\thas_svcc = GF_TRUE;\n\t\t}\n\t\tif (hevccfg) gf_odf_hevc_cfg_del(hevccfg);\n\t\tif (vvccfg) gf_odf_vvc_cfg_del(vvccfg);\n\t\tif (lhvccfg) gf_odf_hevc_cfg_del(lhvccfg);\n\t}", "\t/*fixme: for dumping encrypted track: we don't have neither avccfg nor svccfg*/\n\tif (!nalh_size) nalh_size = 4;", "\t/*for testing dependency*/\n\tcountRef = gf_isom_get_reference_count(file, track, GF_ISOM_REF_SCAL);\n\tif (countRef > 0)\n\t{\n\t\tGF_ISOTrackID refTrackID;\n\t\tfprintf(dump, \" <SCALReferences>\\n\");\n\t\tfor (i = 1; i <= (u32) countRef; i++)\n\t\t{\n\t\t\tgf_isom_get_reference_ID(file, track, GF_ISOM_REF_SCAL, i, &refTrackID);\n\t\t\tfprintf(dump, \" <SCALReference number=\\\"%d\\\" refTrackID=\\\"%d\\\"/>\\n\", i, refTrackID);\n\t\t}", "\t\tfprintf(dump, \" </SCALReferences>\\n\");\n\t}", "\tfprintf(dump, \" <NALUSamples>\\n\");\n\tgf_isom_set_nalu_extract_mode(file, track, GF_ISOM_NALU_EXTRACT_INSPECT);\n\tis_adobe_protected = gf_isom_is_adobe_protection_media(file, track, 1);\n\tis_cenc_protected = gf_isom_is_cenc_media(file, track, 1);\n\tfor (i=0; i<count; i++) {\n\t\tu64 dts, cts;\n\t\tBool is_rap;\n\t\tu32 size, nal_size, idx, di;\n\t\tu8 *ptr;\n\t\tGF_ISOSample *samp = gf_isom_get_sample(file, track, i+1, &di);\n\t\tif (!samp) {\n\t\t\tfprintf(dump, \"<!-- Unable to fetch sample %d -->\\n\", i+1);\n\t\t\tcontinue;\n\t\t}\n\t\tdts = samp->DTS;\n\t\tcts = dts + (s32) samp->CTS_Offset;\n\t\tis_rap = samp->IsRAP;\n\t\tif (!is_rap) gf_isom_get_sample_rap_roll_info(file, track, i+1, &is_rap, NULL, NULL);", "\t\tif (dump_flags&2) {\n\t\t\tfprintf(dump, \" <Sample size=\\\"%d\\\" RAP=\\\"%d\\\"\", samp->dataLength, is_rap);\n\t\t} else {\n\t\t\tfprintf(dump, \" <Sample DTS=\\\"\"LLD\"\\\" CTS=\\\"\"LLD\"\\\" size=\\\"%d\\\" RAP=\\\"%d\\\"\", dts, cts, samp->dataLength, is_rap);\n\t\t}\n\t\tif (nb_descs>1)\n\t\t\tfprintf(dump, \" sample_description=\\\"%d\\\"\", di);\n\t\tfprintf(dump, \" >\\n\");", "\t\tif (cts<dts) fprintf(dump, \"<!-- NEGATIVE CTS OFFSET! -->\\n\");", "\t\tidx = 1;\n\t\tptr = samp->data;\n\t\tsize = samp->dataLength;\n\t\tif (is_adobe_protected) {\n\t\t\tu8 encrypted_au = ptr[0];\n\t\t\tif (encrypted_au) {\n\t\t\t\tfprintf(dump, \" <!-- Sample number %d is an Adobe's protected sample: can not be dumped -->\\n\", i+1);\n\t\t\t\tfprintf(dump, \" </Sample>\\n\\n\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tptr++;\n\t\t\t\tsize--;\n\t\t\t}\n\t\t}\n\t\twhile (size) {\n\t\t\tnal_size = read_nal_size_hdr(ptr, nalh_size);\n\t\t\tptr += nalh_size;", "\t\t\tif (nal_size >= UINT_MAX-nalh_size || nalh_size + nal_size > size) {\n\t\t\t\tfprintf(dump, \" <!-- NALU number %d is corrupted: size is %d but only %d remains -->\\n\", idx, nal_size, size);\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\tfprintf(dump, \" <NALU size=\\\"%d\\\" \", nal_size);\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\tBool is_encrypted = 0;\n\t\t\t\tif (is_cenc_protected) {\n\t\t\t\t\tGF_Err e = gf_isom_get_sample_cenc_info(file, track, i + 1, &is_encrypted, NULL, NULL, NULL, NULL);\n\t\t\t\t\tif (e != GF_OK) {\n\t\t\t\t\t\tfprintf(dump, \"dump_msg=\\\"Error %s while fetching encryption info for sample, assuming sample is encrypted\\\" \", gf_error_to_string(e) );\n\t\t\t\t\t\tis_encrypted = GF_TRUE;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgf_inspect_dump_nalu(dump, ptr, nal_size, has_svcc ? 1 : 0, hevc_state, avc_state, vvc_state, nalh_size, dump_flags, is_encrypted);\n#else\n\t\t\t\tfprintf(dump, \"/>\\n\");\n#endif\n\t\t\t}\n\t\t\tidx++;\n\t\t\tptr+=nal_size;\n\t\t\tsize -= nal_size + nalh_size;\n\t\t}\n\t\tfprintf(dump, \" </Sample>\\n\");\n\t\tgf_isom_sample_del(&samp);", "\t\tfprintf(dump, \"\\n\");\n\t\tgf_set_progress(\"Analysing Track NALUs\", i+1, count);\n\t}\n\tfprintf(dump, \" </NALUSamples>\\n\");\n\tfprintf(dump, \"</NALUTrack>\\n\");", "\tgf_isom_set_nalu_extract_mode(file, track, cur_extract_mode);", "#ifndef GPAC_DISABLE_AV_PARSERS\n\tif (hevc_state) gf_free(hevc_state);\n\tif (vvc_state) gf_free(vvc_state);\n\tif (avc_state) gf_free(avc_state);\n#endif\n}", "static void dump_isom_obu(GF_ISOFile *file, GF_ISOTrackID trackID, FILE *dump, Bool dump_crc);\nstatic void dump_qt_prores(GF_ISOFile *file, GF_ISOTrackID trackID, FILE *dump, Bool dump_crc);", "void dump_isom_nal(GF_ISOFile *file, GF_ISOTrackID trackID, char *inName, Bool is_final_name, u32 dump_flags)\n{\n\tBool is_av1 = GF_FALSE;\n\tBool is_prores = GF_FALSE;", "\tFILE *dump;\n\tif (inName) {\n\t\tGF_ESD* esd;\n\t\tchar szBuf[GF_MAX_PATH];", "\t\tstrcpy(szBuf, inName);", "\t\tu32 track = gf_isom_get_track_by_id(file, trackID);\n\t\tesd = gf_isom_get_esd(file, track, 1);", "\t\tif (!esd || !esd->decoderConfig) {\n\t\t\tswitch (gf_isom_get_media_subtype(file, track, 1)) {\n\t\t\tcase GF_ISOM_SUBTYPE_AV01:\n\t\t\t\tis_av1 = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tcase GF_QT_SUBTYPE_APCH:\n\t\t\tcase GF_QT_SUBTYPE_APCO:\n\t\t\tcase GF_QT_SUBTYPE_APCN:\n\t\t\tcase GF_QT_SUBTYPE_APCS:\n\t\t\tcase GF_QT_SUBTYPE_AP4X:\n\t\t\tcase GF_QT_SUBTYPE_AP4H:\n\t\t\t\tis_prores = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse if (esd->decoderConfig->objectTypeIndication == GF_CODECID_AV1) {\n\t\t\tis_av1 = GF_TRUE;\n\t\t}\n\t\tif (esd) gf_odf_desc_del((GF_Descriptor*)esd);", "\t\tif (!is_final_name) sprintf(szBuf, \"%s_%d_%s.xml\", inName, trackID, is_av1 ? \"obu\" : \"nalu\");\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s for dumping\\n\", szBuf));\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t}", "\tif (is_av1)\n\t\tdump_isom_obu(file, trackID, dump, dump_flags);\n\telse if (is_prores)\n\t\tdump_qt_prores(file, trackID, dump, dump_flags);\n\telse\n\t\tdump_isom_nal_ex(file, trackID, dump, dump_flags);", "\tif (inName) gf_fclose(dump);\n}", "#ifndef GPAC_DISABLE_AV_PARSERS\nvoid gf_inspect_dump_obu(FILE *dump, AV1State *av1, u8 *obu, u64 obu_length, ObuType obu_type, u64 obu_size, u32 hdr_size, Bool dump_crc);\n#endif", "static void dump_isom_obu(GF_ISOFile *file, GF_ISOTrackID trackID, FILE *dump, Bool dump_crc)\n{\n#ifndef GPAC_DISABLE_AV_PARSERS\n\tu32 i, count, track, timescale;\n\tAV1State av1;\n\tObuType obu_type;\n\tu64 obu_size;\n\tu32 hdr_size;\n\tGF_BitStream *bs;\n\tu32 idx;", "\ttrack = gf_isom_get_track_by_id(file, trackID);", "\tgf_av1_init_state(&av1);\n\tav1.config = gf_isom_av1_config_get(file, track, 1);\n\tif (!av1.config) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Error: Track #%d is not AV1!\\n\", trackID));\n\t\treturn;\n\t}", "\tcount = gf_isom_get_sample_count(file, track);\n\ttimescale = gf_isom_get_media_timescale(file, track);", "\tfprintf(dump, \"<OBUTrack trackID=\\\"%d\\\" SampleCount=\\\"%d\\\" TimeScale=\\\"%d\\\">\\n\", trackID, count, timescale);", "\tfprintf(dump, \" <OBUConfig>\\n\");", "\tfor (i=0; i<gf_list_count(av1.config->obu_array); i++) {\n\t\tGF_AV1_OBUArrayEntry *obu = gf_list_get(av1.config->obu_array, i);\n\t\tbs = gf_bs_new(obu->obu, (u32) obu->obu_length, GF_BITSTREAM_READ);\n\t\tgf_av1_parse_obu(bs, &obu_type, &obu_size, &hdr_size, &av1);\n\t\tgf_inspect_dump_obu(dump, &av1, obu->obu, obu->obu_length, obu_type, obu_size, hdr_size, dump_crc);\n\t\tgf_bs_del(bs);\n\t}\n\tfprintf(dump, \" </OBUConfig>\\n\");", "\tfprintf(dump, \" <OBUSamples>\\n\");", "\tfor (i=0; i<count; i++) {\n\t\tu64 dts, cts;\n\t\tu32 size;\n\t\tu8 *ptr;\n\t\tGF_ISOSample *samp = gf_isom_get_sample(file, track, i+1, NULL);\n\t\tif (!samp) {\n\t\t\tfprintf(dump, \"<!-- Unable to fetch sample %d -->\\n\", i+1);\n\t\t\tcontinue;\n\t\t}\n\t\tdts = samp->DTS;\n\t\tcts = dts + (s32) samp->CTS_Offset;", "\t\tfprintf(dump, \" <Sample number=\\\"%d\\\" DTS=\\\"\"LLD\"\\\" CTS=\\\"\"LLD\"\\\" size=\\\"%d\\\" RAP=\\\"%d\\\" >\\n\", i+1, dts, cts, samp->dataLength, samp->IsRAP);\n\t\tif (cts<dts) fprintf(dump, \"<!-- NEGATIVE CTS OFFSET! -->\\n\");", "\t\tidx = 1;\n\t\tptr = samp->data;\n\t\tsize = samp->dataLength;", "\t\tbs = gf_bs_new(ptr, size, GF_BITSTREAM_READ);\n\t\twhile (size) {\n\t\t\tgf_av1_parse_obu(bs, &obu_type, &obu_size, &hdr_size, &av1);\n\t\t\tif (obu_size > size) {\n\t\t\t\tfprintf(dump, \" <!-- OBU number %d is corrupted: size is %d but only %d remains -->\\n\", idx, (u32) obu_size, size);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tgf_inspect_dump_obu(dump, &av1, ptr, obu_size, obu_type, obu_size, hdr_size, dump_crc);\n\t\t\tptr += obu_size;\n\t\t\tsize -= (u32)obu_size;\n\t\t\tidx++;\n\t\t}\n\t\tgf_bs_del(bs);\n\t\tfprintf(dump, \" </Sample>\\n\");\n\t\tgf_isom_sample_del(&samp);", "\t\tfprintf(dump, \"\\n\");\n\t\tgf_set_progress(\"Analysing Track OBUs\", i+1, count);\n\t}\n\tfprintf(dump, \" </OBUSamples>\\n\");\n\tfprintf(dump, \"</OBUTrack>\\n\");", "\tif (av1.config) gf_odf_av1_cfg_del(av1.config);\n\tgf_av1_reset_state(&av1, GF_TRUE);\n#endif\n}", "static void dump_qt_prores(GF_ISOFile *file, u32 trackID, FILE *dump, Bool dump_crc)\n{\n#ifndef GPAC_DISABLE_AV_PARSERS\n\tu32 i, count, track, timescale;", "\ttrack = gf_isom_get_track_by_id(file, trackID);", "\tcount = gf_isom_get_sample_count(file, track);\n\ttimescale = gf_isom_get_media_timescale(file, track);", "\tfprintf(dump, \"<ProResTrack trackID=\\\"%d\\\" SampleCount=\\\"%d\\\" TimeScale=\\\"%d\\\">\\n\", trackID, count, timescale);", "\tfor (i=0; i<count; i++) {\n\t\tvoid gf_inspect_dump_prores(FILE *dump, u8 *ptr, u64 frame_size, Bool dump_crc);\n\t\tu64 dts, cts;\n\t\tGF_ISOSample *samp = gf_isom_get_sample(file, track, i+1, NULL);\n\t\tif (!samp) {\n\t\t\tfprintf(dump, \"<!-- Unable to fetch sample %d -->\\n\", i+1);\n\t\t\tcontinue;\n\t\t}\n\t\tdts = samp->DTS;\n\t\tcts = dts + (s32) samp->CTS_Offset;", "\t\tif (cts!=dts) fprintf(dump, \"<!-- Wrong timing info (CTS \"LLD\" vs DTS \"LLD\") ! -->\\n\", cts, dts);\n\t\tif (!samp->IsRAP) fprintf(dump, \"<!-- Wrong sync sample info, sample is not SAP1 ! -->\\n\");", "\t\tfprintf(dump, \" <Sample number=\\\"%d\\\" CTS=\\\"\"LLD\"\\\" size=\\\"%d\\\">\\n\", i+1, cts, samp->dataLength);", "\t\tgf_inspect_dump_prores(dump, samp->data, samp->dataLength, dump_crc);\n\t\tfprintf(dump, \" </Sample>\\n\");", "\t\tgf_isom_sample_del(&samp);", "\t\tfprintf(dump, \"\\n\");\n\t\tgf_set_progress(\"Analysing ProRes Track\", i+1, count);\n\t}\n\tfprintf(dump, \"</ProResTrack>\\n\");\n#endif\n}", "void dump_isom_saps(GF_ISOFile *file, GF_ISOTrackID trackID, u32 dump_saps_mode, char *inName, Bool is_final_name)\n{\n\tFILE *dump;\n\tu32 i, count;\n\ts64 media_offset=0;\n\tu32 track = gf_isom_get_track_by_id(file, trackID);\n\tif (inName) {\n\t\tchar szBuf[GF_MAX_PATH];\n\t\tstrcpy(szBuf, inName);", "\t\tif (!is_final_name) sprintf(szBuf, \"%s_%d_cues.xml\", inName, trackID);\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s for dumping\\n\", szBuf));\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t}", "\tfprintf(dump, \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n\tfprintf(dump, \"<DASHCues xmlns=\\\"urn:gpac:dash:schema:cues:2018\\\">\\n\");\n\tfprintf(dump, \"<Stream id=\\\"%d\\\" timescale=\\\"%d\\\"\", trackID, gf_isom_get_media_timescale(file, track) );\n\tif (dump_saps_mode==4) {\n\t\tfprintf(dump, \" mode=\\\"edit\\\"\");\n\t\tgf_isom_get_edit_list_type(file, track, &media_offset);\n\t}\n\tfprintf(dump, \">\\n\");", "\tcount = gf_isom_get_sample_count(file, track);\n\tfor (i=0; i<count; i++) {\n\t\ts64 cts, dts;\n\t\tu32 di;\n\t\tBool traf_start = 0;\n\t\tu32 sap_type = 0;\n\t\tu64 doffset;\n\t\t\n\t\tGF_ISOSample *samp = gf_isom_get_sample_info(file, track, i+1, &di, &doffset);", "\t\ttraf_start = gf_isom_sample_is_fragment_start(file, track, i+1, NULL);", "\t\tsap_type = samp->IsRAP;\n\t\tif (!sap_type) {\n\t\t\tBool is_rap;\n\t\t\tGF_ISOSampleRollType roll_type;\n\t\t\ts32 roll_dist;\n\t\t\tgf_isom_get_sample_rap_roll_info(file, track, i+1, &is_rap, &roll_type, &roll_dist);\n\t\t\tif (roll_type) sap_type = SAP_TYPE_4;\n\t\t\telse if (is_rap) sap_type = SAP_TYPE_3;\n\t\t}", "\t\tif (!sap_type) {\n\t\t\tgf_isom_sample_del(&samp);\n\t\t\tcontinue;\n\t\t}", "\t\tdts = cts = samp->DTS;\n\t\tcts += samp->CTS_Offset;\n\t\tfprintf(dump, \"<Cue sap=\\\"%d\\\"\", sap_type);\n\t\tif (dump_saps_mode==4) {\n\t\t\tcts += media_offset;\n\t\t\tfprintf(dump, \" cts=\\\"\"LLD\"\\\"\", cts);\n\t\t} else {\n\t\t\tif (!dump_saps_mode || (dump_saps_mode==1)) fprintf(dump, \" sample=\\\"%d\\\"\", i+1);\n\t\t\tif (!dump_saps_mode || (dump_saps_mode==2)) fprintf(dump, \" cts=\\\"\"LLD\"\\\"\", cts);\n\t\t\tif (!dump_saps_mode || (dump_saps_mode==3)) fprintf(dump, \" dts=\\\"\"LLD\"\\\"\", dts);\n\t\t}", "\t\tif (traf_start)\n\t\t\tfprintf(dump, \" wasFragStart=\\\"yes\\\"\");", "\t\tfprintf(dump, \"/>\\n\");", "\t\tgf_isom_sample_del(&samp);\n\t}\n\tfprintf(dump, \"</Stream>\\n\");\n\tfprintf(dump, \"</DASHCues>\\n\");\n\tif (inName) gf_fclose(dump);\n}", "#ifndef GPAC_DISABLE_ISOM_DUMP", "void dump_isom_ismacryp(GF_ISOFile *file, char *inName, Bool is_final_name)\n{\n\tu32 i, j;\n\tFILE *dump;", "\tif (inName) {\n\t\tchar szBuf[1024];\n\t\tstrcpy(szBuf, inName);\n\t\tif (!is_final_name) strcat(szBuf, \"_ismacryp.xml\");\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s for dumping\\n\", szBuf));\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t}", "\tfprintf(dump, \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\\n\");\n\tfprintf(dump, \"<!-- MP4Box ISMACryp trace -->\\n\");\n\tfprintf(dump, \"<ISMACrypFile>\\n\");", "\n\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\tif (gf_isom_get_media_subtype(file, i+1, 1) != GF_ISOM_SUBTYPE_MPEG4_CRYP) continue;", "\t\tgf_isom_dump_ismacryp_protection(file, i+1, dump);", "\t\tfprintf(dump, \"<ISMACrypTrack trackID=\\\"%d\\\">\\n\", gf_isom_get_track_id(file, i+1));\n\t\tfor (j=0; j<gf_isom_get_sample_count(file, i+1); j++) {\n\t\t\tgf_isom_dump_ismacryp_sample(file, i+1, j+1, dump);\n\t\t}\n\t\tfprintf(dump, \"</ISMACrypTrack >\\n\");\n\t}\n\tfprintf(dump, \"</ISMACrypFile>\\n\");\n\tif (inName) gf_fclose(dump);\n}", "\nvoid dump_isom_timed_text(GF_ISOFile *file, GF_ISOTrackID trackID, char *inName, Bool is_final_name, Bool is_convert, GF_TextDumpType dump_type)\n{\n\tFILE *dump;\n\tGF_Err e;\n\tu32 track;", "\ttrack = gf_isom_get_track_by_id(file, trackID);\n\tif (!track) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Cannot find track ID %d\\n\", trackID));\n\t\treturn;\n\t}", "\tswitch (gf_isom_get_media_type(file, track)) {\n\tcase GF_ISOM_MEDIA_TEXT:\n\tcase GF_ISOM_MEDIA_SUBT:\n\t\tbreak;\n\tdefault:\n\t\tM4_LOG(GF_LOG_ERROR, (\"Track ID %d is not a 3GPP text track\\n\", trackID));\n\t\treturn;\n\t}", "\tif (inName) {\n\t\tchar szBuf[1024];\n\t\tchar *ext;\n\t\text = ((dump_type==GF_TEXTDUMPTYPE_SVG) ? \"svg\" : ((dump_type==GF_TEXTDUMPTYPE_SRT) ? \"srt\" : \"ttxt\"));\n\t\tif (is_final_name) {\n\t\t\tstrcpy(szBuf, inName) ;\n\t\t} else if (is_convert)\n\t\t\tsprintf(szBuf, \"%s.%s\", inName, ext) ;\n\t\telse\n\t\t\tsprintf(szBuf, \"%s_%d_text.%s\", inName, trackID, ext);", "\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s for dumping\\n\", szBuf));\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t}\n\te = gf_isom_text_dump(file, track, dump, dump_type);\n\tif (inName) gf_fclose(dump);", "\tif (e) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Conversion failed (%s)\\n\", gf_error_to_string(e)));\n\t} else {\n\t\tfprintf(stderr, \"Conversion done\\n\");\n\t}\n}", "#endif /*GPAC_DISABLE_ISOM_DUMP*/", "#ifndef GPAC_DISABLE_ISOM_HINTING", "void dump_isom_sdp(GF_ISOFile *file, char *inName, Bool is_final_name)\n{\n\tconst char *sdp;\n\tu32 size, i;\n\tFILE *dump;", "\tif (inName) {\n\t\tchar szBuf[1024];\n\t\tstrcpy(szBuf, inName);\n\t\tif (!is_final_name) {\n\t\t\tchar *ext = strchr(szBuf, '.');\n\t\t\tif (ext) ext[0] = 0;\n\t\t\tstrcat(szBuf, \"_sdp.txt\");\n\t\t}\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s for dumping\\n\", szBuf));\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t\tfprintf(dump, \"# File SDP content \\n\\n\");\n\t}\n\t//get the movie SDP\n\tgf_isom_sdp_get(file, &sdp, &size);\n\tif (sdp && size)\n\t\tfprintf(dump, \"%s\", sdp);\n\tfprintf(dump, \"\\r\\n\");", "\t//then tracks\n\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\tif (gf_isom_get_media_type(file, i+1) != GF_ISOM_MEDIA_HINT) continue;\n\t\tgf_isom_sdp_track_get(file, i+1, &sdp, &size);\n\t\tfprintf(dump, \"%s\", sdp);\n\t}\n\tfprintf(dump, \"\\n\\n\");\n\tif (inName) gf_fclose(dump);\n}", "#endif", "\n#ifndef GPAC_DISABLE_ISOM_DUMP", "GF_Err dump_isom_xml(GF_ISOFile *file, char *inName, Bool is_final_name, Bool do_track_dump, Bool merge_vtt_cues, Bool skip_init, Bool skip_samples)\n{\n\tGF_Err e;\n\tFILE *dump = stdout;\n\tBool do_close=GF_FALSE;\n\tif (!file) return GF_ISOM_INVALID_FILE;", "\tif (inName) {\n\t\tchar szBuf[1024];\n\t\tstrcpy(szBuf, inName);\n\t\tif (!is_final_name) {\n\t\t\tstrcat(szBuf, do_track_dump ? \"_dump.xml\" : \"_info.xml\");\n\t\t}\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to open %s\\n\", szBuf));\n\t\t\treturn GF_IO_ERR;\n\t\t}\n\t\tdo_close=GF_TRUE;\n\t}", "\tfprintf(dump, \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n\tif (do_track_dump) {\n\t\tfprintf(dump, \"<ISOBaseMediaFileTrace>\\n\");\n\t}\n\te = gf_isom_dump(file, dump, skip_init, skip_samples);\n\tif (e) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Error dumping ISO structure\\n\"));\n\t}", "\tif (do_track_dump) {\n#ifndef GPAC_DISABLE_MEDIA_EXPORT\n\t\tu32 i;\n\t\t//because of dump mode we need to reopen in regular read mode to avoid mem leaks\n\t\tGF_ISOFile *the_file = gf_isom_open(gf_isom_get_filename(file), GF_ISOM_OPEN_READ, NULL);\n\t\tu32 tcount = gf_isom_get_track_count(the_file);\n\t\tfprintf(dump, \"<Tracks>\\n\");", "\t\tfor (i=0; i<tcount; i++) {\n\t\t\tGF_MediaExporter dumper;\n\t\t\tGF_ISOTrackID trackID = gf_isom_get_track_id(the_file, i+1);\n\t\t\tu32 mtype = gf_isom_get_media_type(the_file, i+1);\n\t\t\tu32 msubtype = gf_isom_get_media_subtype(the_file, i+1, 1);\n\t\t\tBool fmt_handled = GF_FALSE;\n\t\t\tmemset(&dumper, 0, sizeof(GF_MediaExporter));\n\t\t\tdumper.file = the_file;\n\t\t\tdumper.trackID = trackID;\n\t\t\tdumper.dump_file = dump;", "\t\t\tif (mtype == GF_ISOM_MEDIA_HINT) {\n#ifndef GPAC_DISABLE_ISOM_HINTING\n\t\t\t\tchar *name=NULL;\n\t\t\t\tif (msubtype==GF_ISOM_SUBTYPE_RTP) name = \"RTPHintTrack\";\n\t\t\t\telse if (msubtype==GF_ISOM_SUBTYPE_SRTP) name = \"SRTPHintTrack\";\n\t\t\t\telse if (msubtype==GF_ISOM_SUBTYPE_RRTP) name = \"RTPReceptionHintTrack\";\n\t\t\t\telse if (msubtype==GF_ISOM_SUBTYPE_RTCP) name = \"RTCPReceptionHintTrack\";\n\t\t\t\telse if (msubtype==GF_ISOM_SUBTYPE_FLUTE) name = \"FLUTEReceptionHintTrack\";\n\t\t\t\telse name = \"UnknownHintTrack\";", "\t\t\t\tfprintf(dump, \"<%s trackID=\\\"%d\\\">\\n\", name, trackID);", "#ifndef GPAC_DISABLE_ISOM_HINTING\n\t\t\t\tu32 j, scount=gf_isom_get_sample_count(the_file, i+1);\n\t\t\t\tfor (j=0; j<scount; j++) {\n\t\t\t\t\tgf_isom_dump_hint_sample(the_file, i+1, j+1, dump);\n\t\t\t\t}\n#endif\n\t\t\t\tfprintf(dump, \"</%s>\\n\", name);\n\t\t\t\tfmt_handled = GF_TRUE;\n#endif /*GPAC_DISABLE_ISOM_HINTING*/\n\t\t\t}\n\t\t\telse if (gf_isom_get_avc_svc_type(the_file, i+1, 1) || gf_isom_get_hevc_lhvc_type(the_file, i+1, 1)) {\n\t\t\t\tdump_isom_nal_ex(the_file, trackID, dump, GF_FALSE);\n\t\t\t\tfmt_handled = GF_TRUE;\n\t\t\t} else if ((mtype==GF_ISOM_MEDIA_TEXT) || (mtype==GF_ISOM_MEDIA_SUBT) ) {", "\t\t\t\tif (msubtype==GF_ISOM_SUBTYPE_WVTT) {\n\t\t\t\t\tgf_webvtt_dump_iso_track(&dumper, i+1, merge_vtt_cues, GF_TRUE);\n\t\t\t\t\tfmt_handled = GF_TRUE;\n\t\t\t\t} else if ((msubtype==GF_ISOM_SUBTYPE_TX3G) || (msubtype==GF_ISOM_SUBTYPE_TEXT)) {\n\t\t\t\t\tgf_isom_text_dump(the_file, i+1, dump, GF_TEXTDUMPTYPE_TTXT_BOXES);\n\t\t\t\t\tfmt_handled = GF_TRUE;\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (!fmt_handled) {\n\t\t\t\tdumper.flags = GF_EXPORT_NHML | GF_EXPORT_NHML_FULL;\n\t\t\t\tdumper.print_stats_graph = fs_dump_flags;\n\t\t\t\tgf_media_export(&dumper);\n\t\t\t}\n\t\t}\n#else\n\t\treturn GF_NOT_SUPPORTED;\n#endif /*GPAC_DISABLE_MEDIA_EXPORT*/\n\t\tgf_isom_delete(the_file);\n\t\tfprintf(dump, \"</Tracks>\\n\");\n\t\tfprintf(dump, \"</ISOBaseMediaFileTrace>\\n\");\n\t}\n\tif (do_close) gf_fclose(dump);\n\treturn e;\n}\n#endif", "\nstatic char *format_duration(u64 dur, u32 timescale, char *szDur)\n{\n\tu32 h, m, s, ms;\n\tif ((dur==(u64) -1) || (dur==(u32) -1)) {\n\t\tstrcpy(szDur, \"Unknown\");\n\t\treturn szDur;\n\t}\n\tdur = (u64) (( ((Double) (s64) dur)/timescale)*1000);\n\th = (u32) (dur / 3600000);\n\tm = (u32) (dur/ 60000) - h*60;\n\ts = (u32) (dur/1000) - h*3600 - m*60;\n\tms = (u32) (dur) - h*3600000 - m*60000 - s*1000;\n\tif (h<=24) {\n\t\tsprintf(szDur, \"%02d:%02d:%02d.%03d\", h, m, s, ms);\n\t} else {\n\t\tu32 d = (u32) (dur / 3600000 / 24);\n\t\th = (u32) (dur/3600000)-24*d;\n\t\tif (d<=365) {\n\t\t\tsprintf(szDur, \"%d Days, %02d:%02d:%02d.%03d\", d, h, m, s, ms);\n\t\t} else {\n\t\t\tu32 y=0;\n\t\t\twhile (d>365) {\n\t\t\t\ty++;\n\t\t\t\td-=365;\n\t\t\t\tif (y%4) d--;\n\t\t\t}\n\t\t\tsprintf(szDur, \"%d Years %d Days, %02d:%02d:%02d.%03d\", y, d, h, m, s, ms);\n\t\t}", "\t}\n\treturn szDur;\n}", "static char *format_date(u64 time, char *szTime)\n{\n\ttime_t now;\n\tif (!time) {\n\t\tstrcpy(szTime, \"UNKNOWN DATE\");\n\t} else {\n\t\ttime -= 2082844800;\n\t\tnow = (u32) time;\n\t\tsprintf(szTime, \"GMT %s\", asctime(gf_gmtime(&now)) );\n\t}\n\treturn szTime;\n}", "void print_udta(GF_ISOFile *file, u32 track_number, Bool has_itags)\n{\n\tu32 i, count;", "\tcount = gf_isom_get_udta_count(file, track_number);\n\tif (!count) return;", "\tif (has_itags) {\n\t\tfor (i=0; i<count; i++) {\n\t\t\tu32 type;\n\t\t\tbin128 uuid;\n\t\t\tgf_isom_get_udta_type(file, track_number, i+1, &type, &uuid);\n\t\t\tif (type == GF_ISOM_BOX_TYPE_META) {\n\t\t\t\tcount--;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!count) return;\n\t}", "\tfprintf(stderr, \"%d UDTA types: \", count);", "\tfor (i=0; i<count; i++) {\n\t\tu32 j, type, nb_items, first=GF_TRUE;\n\t\tbin128 uuid;\n\t\tgf_isom_get_udta_type(file, track_number, i+1, &type, &uuid);\n\t\tnb_items = gf_isom_get_user_data_count(file, track_number, type, uuid);\n\t\tfprintf(stderr, \"%s (%d) \", gf_4cc_to_str(type), nb_items);\n\t\tfor (j=0; j<nb_items; j++) {\n\t\t\tu8 *udta=NULL;\n\t\t\tu32 udta_size;\n\t\t\tgf_isom_get_user_data(file, track_number, type, uuid, j+1, &udta, &udta_size);\n\t\t\tif (!udta) continue;\n\t\t\tif (udta_size && gf_utf8_is_legal(udta, udta_size)) {\n\t\t\t\tu32 idx;\n\t\t\t\tif (first) {\n\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\tfirst = GF_FALSE;\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \"\\t\");\n\t\t\t\tfor (idx=0; idx<udta_size; idx++) {\n\t\t\t\t\tif (!udta[idx]) break;\n\t\t\t\t\tfprintf(stderr, \"%c\", udta[idx]);\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t}\n\t\t\tgf_free(udta);\n\t\t}\n\t}\n\tfprintf(stderr, \"\\n\");\n}", "GF_Err dump_isom_udta(GF_ISOFile *file, char *inName, Bool is_final_name, u32 dump_udta_type, u32 dump_udta_track)\n{\n\tu8 *data;\n\tFILE *t;\n\tbin128 uuid;\n\tu32 count, res;\n\tGF_Err e;", "\tmemset(uuid, 0, 16);\n\tcount = gf_isom_get_user_data_count(file, dump_udta_track, dump_udta_type, uuid);\n\tif (!count) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"No UDTA for type %s found\\n\", gf_4cc_to_str(dump_udta_type) ));\n\t\treturn GF_NOT_FOUND;\n\t}", "\tdata = NULL;\n\tcount = 0;\n\te = gf_isom_get_user_data(file, dump_udta_track, dump_udta_type, uuid, 0, &data, &count);\n\tif (e) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Error dumping UDTA %s: %s\\n\", gf_4cc_to_str(dump_udta_type), gf_error_to_string(e) ));\n\t\treturn e;\n\t}\n\tif (inName) {\n\t\tchar szName[1024];\n\t\tif (is_final_name)\n\t\t\tstrcpy(szName, inName);\n\t\telse\n\t\t\tsprintf(szName, \"%s_%s.udta\", inName, gf_4cc_to_str(dump_udta_type) );", "\t\tt = gf_fopen(szName, \"wb\");\n\t\tif (!t) {\n\t\t\tgf_free(data);\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Cannot open file %s\\n\", szName ));\n\t\t\treturn GF_IO_ERR;\n\t\t}\n\t} else {\n\t\tt = stdout;\n\t}\n\tres = (u32) gf_fwrite(data+8, count-8, t);\n\tif (inName) gf_fclose(t);\n\tgf_free(data);\n\tif (count-8 != res) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Error writing udta to file\\n\"));\n\t\treturn GF_IO_ERR;\n\t}\n\treturn GF_OK;\n}", "\nGF_Err dump_isom_chapters(GF_ISOFile *file, char *inName, Bool is_final_name, u32 dump_mode)\n{\n\tFILE *t;\n\tu32 i, count;\n\tu32 chap_tk = 0;\n\tcount = gf_isom_get_chapter_count(file, 0);", "\tif (dump_mode==2) dump_mode = GF_TEXTDUMPTYPE_OGG_CHAP;\n\telse if (dump_mode==3) dump_mode = GF_TEXTDUMPTYPE_ZOOM_CHAP;\n\telse dump_mode = GF_TEXTDUMPTYPE_TTXT_CHAP;", "\tif (!count) {\n\t\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\t\tif (gf_isom_get_reference_count(file, i+1, GF_ISOM_REF_CHAP)) {\n\t\t\t\tGF_Err e = gf_isom_get_reference(file, i+1, GF_ISOM_REF_CHAP, 1, &chap_tk);\n\t\t\t\tif (!e) break;\n\t\t\t}\n\t\t}\n\t\tif (!chap_tk) {\n\t\t\tM4_LOG(GF_LOG_WARNING, (\"No chapters or chapters track found in file\\n\"));\n\t\t\treturn GF_OK;\n\t\t}", "\t\tfprintf(stderr, \"Dumping chapter track %d\\n\", chap_tk);\n\t\tdump_isom_timed_text(file, gf_isom_get_track_id(file, chap_tk), inName, is_final_name, GF_FALSE, dump_mode);\n\t\treturn GF_OK;", "\t}\n\tif (inName) {\n\t\tchar szName[1024];\n\t\tstrcpy(szName, inName);\n\t\tif (!is_final_name) {\n\t\t\tif (dump_mode==GF_TEXTDUMPTYPE_OGG_CHAP) {\n\t\t\t\tstrcat(szName, \".txt\");\n\t\t\t} else if (dump_mode==GF_TEXTDUMPTYPE_ZOOM_CHAP) {\n\t\t\t\tstrcat(szName, \".txt\");\n\t\t\t} else {\n\t\t\t\tstrcat(szName, \".ttxt\");\n\t\t\t}\n\t\t}\n\t\tt = gf_fopen(szName, \"wt\");\n\t\tif (!t) return GF_IO_ERR;\n\t} else {\n\t\tt = stdout;\n\t}", "\tif (dump_mode==GF_TEXTDUMPTYPE_TTXT_CHAP) {\n\t\tfprintf(t, \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\\n\");\n\t\tfprintf(t, \"<TextStream version=\\\"1.1\\\">\\n\");\n\t\tfprintf(t, \"<TextStreamHeader width=\\\"0\\\" height=\\\"0\\\" layer=\\\"0\\\" translation_x=\\\"0\\\" translation_y=\\\"0\\\">\\n\");\n\t\tfprintf(t, \"<TextSampleDescription horizontalJustification=\\\"left\\\" backColor=\\\"0 0 0\\\" scroll=\\\"None\\\"/>\\n\");\n\t\tfprintf(t, \"</TextStreamHeader>\\n\");\n\t}", "\tfor (i=0; i<count; i++) {\n\t\tchar szDur[20];\n\t\tu64 chapter_time;\n\t\tconst char *name;\n\t\tgf_isom_get_chapter(file, 0, i+1, &chapter_time, &name);\n\t\tif (dump_mode==GF_TEXTDUMPTYPE_OGG_CHAP) {\n\t\t\tfprintf(t, \"CHAPTER%02d=%s\\n\", i+1, format_duration(chapter_time, 1000, szDur));\n\t\t\tfprintf(t, \"CHAPTER%02dNAME=%s\\n\", i+1, name);\n\t\t} else if (dump_mode==GF_TEXTDUMPTYPE_ZOOM_CHAP) {\n\t\t\tchapter_time /= 1000;\n\t\t\tfprintf(t, \"AddChapterBySecond(\"LLD\",%s)\\n\", chapter_time, name);\n\t\t} else {\n\t\t\tfprintf(t, \"<TextSample sampleTime=\\\"%s\\\" sampleDescriptionIndex=\\\"1\\\" xml:space=\\\"preserve\\\">%s</TextSample>\\n\"\n\t\t\t\t, format_duration(chapter_time, 1000, szDur), name);\n\t\t}\n\t}\n\tif (dump_mode==GF_TEXTDUMPTYPE_TTXT_CHAP) {\n\t\tfprintf(t, \"</TextStream>\\n\");\n\t}\n\tif (inName) gf_fclose(t);\n\treturn GF_OK;\n}", "\nstatic void dump_key_info(const u8 *key_info, u32 key_info_size, Bool is_protected)\n{\n\tif (!key_info) return;\n\tu32 j, k, kpos=3;\n\tu32 nb_keys = 1;\n\tif (key_info[0]) {\n\t\tnb_keys = key_info[1];\n\t\tnb_keys <<= 8;\n\t\tnb_keys |= key_info[2];\n\t}\n\tfor (k=0; k<nb_keys; k++) {\n\t\tu8 constant_iv_size=0;\n\t\tu8 iv_size=key_info[kpos+1];\n\t\tfprintf(stderr, \"\\t\\tKID\");\n\t\tif (nb_keys>1)\n\t\t\tfprintf(stderr, \"%d\", k+1);\n\t\tfprintf(stderr, \" \");\n\t\tfor (j=0; j<16; j++) fprintf(stderr, \"%02X\", key_info[kpos+1+j]);\n\t\tkpos+=17;\n\t\tif (!iv_size && is_protected) {\n\t\t\tconstant_iv_size = key_info[1];\n\t\t\tkpos += 1 + constant_iv_size;\n\t\t}\n\t\tfprintf(stderr, \" - %sIV size %d \\n\", constant_iv_size ? \"const \" : \"\", constant_iv_size ? constant_iv_size : iv_size);\n\t}\n}", "static void DumpMetaItem(GF_ISOFile *file, Bool root_meta, u32 tk_num, char *name)\n{\n\tchar szInd[2];\n\tu32 i, count, primary_id;\n\tu32 meta_type = gf_isom_get_meta_type(file, root_meta, tk_num);\n\tif (name[0]=='\\t') {\n\t\tszInd[0] = '\\t';\n\t\tszInd[1] = 0;\n\t} else {\n\t\tszInd[0] = 0;\n\t}", "\tcount = gf_isom_get_meta_item_count(file, root_meta, tk_num);\n\tprimary_id = gf_isom_get_meta_primary_item_id(file, root_meta, tk_num);\n\tfprintf(stderr, \"%s type: \\\"%s\\\" - %d resource item(s)\\n\", name, meta_type ? gf_4cc_to_str(meta_type) : \"undefined\", (count+(primary_id>0)));\n\tswitch (gf_isom_has_meta_xml(file, root_meta, tk_num)) {\n\tcase 1:\n\t\tfprintf(stderr, \"%sMeta has XML resource\\n\", szInd);\n\t\tbreak;\n\tcase 2:\n\t\tfprintf(stderr, \"%sMeta has BinaryXML resource\\n\", szInd);\n\t\tbreak;\n\t}\n\tif (primary_id) {\n\t\tfprintf(stderr, \"%sPrimary Item - ID %d\\n\", szInd, primary_id);\n\t}\n\tfor (i=0; i<count; i++) {\n\t\tconst char *it_name, *mime, *enc, *url, *urn;\n\t\tBool self_ref;\n\t\tu32 ID;\n\t\tu32 it_type, cenc_scheme, cenc_version;\n\t\tGF_Err e = gf_isom_get_meta_item_info(file, root_meta, tk_num, i+1, &ID, &it_type, &cenc_scheme, &cenc_version, &self_ref, &it_name, &mime, &enc, &url, &urn);\n\t\tif (e) {\n\t\t\tfprintf(stderr, \"%sItem #%d fetch info error: %s\\n\", szInd, i+1, gf_error_to_string(e) );\n\t\t\tcontinue;\n\t\t}\n\t\tfprintf(stderr, \"%sItem #%d: ID %d type %s\", szInd, i+1, ID, gf_4cc_to_str(it_type));\n\t\tif (self_ref) fprintf(stderr, \" Self-Reference\");\n\t\telse if (it_name && it_name[0]) fprintf(stderr, \" Name \\\"%s\\\"\", it_name);\n\t\tif (mime) fprintf(stderr, \" MIME: \\\"%s\\\"\", mime);\n\t\tif (enc) fprintf(stderr, \" ContentEncoding: \\\"%s\\\"\", enc);", "\t\tif (meta_type == GF_META_ITEM_TYPE_PICT) {\n\t\t\tGF_ImageItemProperties img_props;\n\t\t\te = gf_isom_get_meta_image_props(file, root_meta, tk_num, ID, &img_props);\n\t\t\tif (e) {\n\t\t\t\tfprintf(stderr, \" invalid image properties !\");\n\t\t\t} else {\n\t\t\t\tu32 j;\n\t\t\t\tBool chan_diff = 0;\n\t\t\t\tif (img_props.width && img_props.height) {\n\t\t\t\t\tfprintf(stderr, \" size %ux%u\", img_props.width, img_props.height);\n\t\t\t\t}\n\t\t\t\tif (img_props.hSpacing && img_props.vSpacing) {\n\t\t\t\t\tfprintf(stderr, \" SAR %u/%u\", img_props.hSpacing, img_props.vSpacing);\n\t\t\t\t}\n\t\t\t\tif (img_props.num_channels) {\n\t\t\t\t\tfprintf(stderr, \" %d channel%s (\", img_props.num_channels, (img_props.num_channels>1) ? \"s\" : \"\");\n\t\t\t\t\tfor (j=1; j<img_props.num_channels; j++) {\n\t\t\t\t\t\tif (img_props.bits_per_channel[0] != img_props.bits_per_channel[j])\n\t\t\t\t\t\t\tchan_diff = 1;\n\t\t\t\t\t}\n\t\t\t\t\tif (chan_diff) {\n\t\t\t\t\t\tfor (j=0; j<img_props.num_channels; j++) {\n\t\t\t\t\t\t\tif (j) fprintf(stderr, \",\");\n\t\t\t\t\t\t\tfprintf(stderr, \"%d\", img_props.bits_per_channel[j]);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfprintf(stderr, \"%d\", img_props.bits_per_channel[0]);\n\t\t\t\t\t}\n\t\t\t\t\tfprintf(stderr, \" bpc)\");\n\t\t\t\t}\n\t\t\t\tif (img_props.hOffset || img_props.vOffset)\n\t\t\t\t\tfprintf(stderr, \" Offset %ux%u\", img_props.hOffset, img_props.vOffset);\n\t\t\t\tif (img_props.alpha) fprintf(stderr, \" Alpha\");\n\t\t\t\tif (img_props.hidden) fprintf(stderr, \" Hidden\");\n\t\t\t\tif (img_props.angle) fprintf(stderr, \" Rotate %d\", img_props.angle);\n\t\t\t\tif (img_props.mirror) fprintf(stderr, \" Mirror %d\", img_props.mirror);\n\t\t\t\tif (img_props.clap_hden || img_props.clap_wden)\n\t\t\t\t\tfprintf(stderr, \" Clap %d/%d,%d/%d,%d/%d,%d/%d\", img_props.clap_wnum, img_props.clap_wden, img_props.clap_hnum, img_props.clap_hden, img_props.clap_honum, img_props.clap_hoden, img_props.clap_vonum, img_props.clap_voden);\n\t\t\t}\n\t\t}", "\t\tif (cenc_scheme) {\n\t\t\tBool is_protected;\n\t\t\tu8 skip_byte_block, crypt_byte_block;\n\t\t\tconst u8 *key_info;\n\t\t\tu32 key_info_size;\n\t\t\tfprintf(stderr, \" - Protection scheme: %s v0x%08X\", gf_4cc_to_str(cenc_scheme), cenc_version);", "\t\t\tgf_isom_extract_meta_item_get_cenc_info(file, root_meta, tk_num, ID, &is_protected, &skip_byte_block, &crypt_byte_block, &key_info, &key_info_size, NULL, NULL, NULL, NULL);\n\t\t\tif (skip_byte_block && crypt_byte_block)\n\t\t\t\tfprintf(stderr, \" - Pattern %d:%d\", skip_byte_block, crypt_byte_block);\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t\tdump_key_info(key_info, key_info_size, is_protected);\n\t\t}\n\t\tfprintf(stderr, \"\\n\");\n\t\tif (url) fprintf(stderr, \"%sURL: %s\\n\", szInd, url);\n\t\tif (urn) fprintf(stderr, \"%sURN: %s\\n\", szInd, urn);", "\t}\n}", "\nstatic void print_config_hash(GF_List *xps_array, char *szName)\n{\n\tu32 i, j;\n\tu8 hash[20];\n\tfor (i=0; i<gf_list_count(xps_array); i++) {\n\t\tGF_NALUFFParam *slc = gf_list_get(xps_array, i);\n\t\tgf_sha1_csum((u8 *) slc->data, slc->size, hash);\n\t\tfprintf(stderr, \"\\t%s#%d hash: \", szName, i+1);\n\t\tfor (j=0; j<20; j++) fprintf(stderr, \"%02X\", hash[j]);\n\t\tfprintf(stderr, \"\\n\");\n\t}\n}", "void dump_hevc_track_info(GF_ISOFile *file, u32 trackNum, GF_HEVCConfig *hevccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t, HEVCState *hevc_state\n#endif /*GPAC_DISABLE_AV_PARSERS && defined(GPAC_DISABLE_HEVC)*/\n\t)\n{\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\tu32 idx;\n#endif\n\tu32 k;\n\tBool non_hevc_base_layer=GF_FALSE;\n\tfprintf(stderr, \"\\t%s Info:\", hevccfg->is_lhvc ? \"LHVC\" : \"HEVC\");\n\tif (!hevccfg->is_lhvc)\n\t\tfprintf(stderr, \" Profile %s @ Level %g - Chroma Format %s\\n\", gf_hevc_get_profile_name(hevccfg->profile_idc), ((Double)hevccfg->level_idc) / 30.0, gf_avc_hevc_get_chroma_format_name(hevccfg->chromaFormat));\n\tfprintf(stderr, \"\\n\");\n\tfprintf(stderr, \"\\tNAL Unit length bits: %d\", 8*hevccfg->nal_unit_size);\n\tif (!hevccfg->is_lhvc)\n\t\tfprintf(stderr, \" - general profile compatibility 0x%08X\\n\", hevccfg->general_profile_compatibility_flags);\n\tfprintf(stderr, \"\\n\");\n\tfprintf(stderr, \"\\tParameter Sets: \");\n\tfor (k=0; k<gf_list_count(hevccfg->param_array); k++) {\n\t\tGF_NALUFFParamArray *ar=gf_list_get(hevccfg->param_array, k);\n\t\tif (ar->type==GF_HEVC_NALU_SEQ_PARAM) {\n\t\t\tfprintf(stderr, \"%d SPS \", gf_list_count(ar->nalus));\n\t\t}\n\t\tif (ar->type==GF_HEVC_NALU_PIC_PARAM) {\n\t\t\tfprintf(stderr, \"%d PPS \", gf_list_count(ar->nalus));\n\t\t}\n\t\tif (ar->type==GF_HEVC_NALU_VID_PARAM) {\n\t\t\tfprintf(stderr, \"%d VPS \", gf_list_count(ar->nalus));", "#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\tfor (idx=0; idx<gf_list_count(ar->nalus); idx++) {\n\t\t\t\tGF_NALUFFParam *vps = gf_list_get(ar->nalus, idx);\n\t\t\t\ts32 ps_idx=gf_hevc_read_vps(vps->data, vps->size, hevc_state);\n\t\t\t\tif (hevccfg->is_lhvc && (ps_idx>=0)) {\n\t\t\t\t\tnon_hevc_base_layer = ! hevc_state->vps[ps_idx].base_layer_internal_flag;\n\t\t\t\t}\n\t\t\t}\n#endif", "\t\t}\n\t}", "\tfprintf(stderr, \"\\n\");\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\tfor (k=0; k<gf_list_count(hevccfg->param_array); k++) {\n\t\tGF_NALUFFParamArray *ar=gf_list_get(hevccfg->param_array, k);\n\t\tu32 width, height;\n\t\ts32 par_n, par_d;", "\t\tif (ar->type !=GF_HEVC_NALU_SEQ_PARAM) continue;\n\t\tfor (idx=0; idx<gf_list_count(ar->nalus); idx++) {\n\t\t\tGF_Err e;\n\t\t\tGF_NALUFFParam *sps = gf_list_get(ar->nalus, idx);\n\t\t\tpar_n = par_d = -1;\n\t\t\te = gf_hevc_get_sps_info_with_state(hevc_state, sps->data, sps->size, NULL, &width, &height, &par_n, &par_d);\n\t\t\tif (e==GF_OK) {\n\t\t\t\tfprintf(stderr, \"\\tSPS resolution %dx%d\", width, height);\n\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\tu32 tw, th;\n\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\tfprintf(stderr, \" - Pixel Aspect Ratio %d:%d - Indicated track size %d x %d\", par_n, par_d, tw, th);\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t} else {\n\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to read SPS: %s\\n\\n\", gf_error_to_string(e) ));\n\t\t\t}\n\t\t}\n\t}\n#endif\n\tif (!hevccfg->is_lhvc)\n\t\tfprintf(stderr, \"\\tBit Depth luma %d - Chroma %d - %d temporal layers\\n\", hevccfg->luma_bit_depth, hevccfg->chroma_bit_depth, hevccfg->numTemporalLayers);\n\telse\n\t\tfprintf(stderr, \"\\t%d temporal layers\\n\", hevccfg->numTemporalLayers);\n\tif (hevccfg->is_lhvc) {\n\t\tfprintf(stderr, \"\\t%sHEVC base layer - Complete representation %d\\n\", non_hevc_base_layer ? \"Non-\" : \"\", hevccfg->complete_representation);\n\t}", "\tfor (k=0; k<gf_list_count(hevccfg->param_array); k++) {\n\t\tGF_NALUFFParamArray *ar=gf_list_get(hevccfg->param_array, k);\n\t\tif (ar->type==GF_HEVC_NALU_SEQ_PARAM) print_config_hash(ar->nalus, \"SPS\");\n\t\telse if (ar->type==GF_HEVC_NALU_PIC_PARAM) print_config_hash(ar->nalus, \"PPS\");\n\t\telse if (ar->type==GF_HEVC_NALU_VID_PARAM) print_config_hash(ar->nalus, \"VPS\");\n\t}\n}", "void dump_vvc_track_info(GF_ISOFile *file, u32 trackNum, GF_VVCConfig *vvccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t, VVCState *vvc_state\n#endif /*GPAC_DISABLE_AV_PARSERS && defined(GPAC_DISABLE_HEVC)*/\n\t)\n{\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\tu32 idx;\n#endif\n\tu32 k;\n\tfprintf(stderr, \"\\tVVC Info:\");", "\tfprintf(stderr, \" Profile %d @ Level %d - Chroma Format %s\\n\", vvccfg->general_profile_idc, vvccfg->general_level_idc, vvccfg->chromaformat_plus_one ? gf_avc_hevc_get_chroma_format_name(vvccfg->chromaformat_plus_one-1) : \"n/a\");\n\tfprintf(stderr, \"\\n\");\n\tfprintf(stderr, \"\\tNAL Unit length bits: %d\", 8*vvccfg->nal_unit_size);\n\tif (vvccfg->general_constraint_info && vvccfg->num_constraint_info && vvccfg->general_constraint_info[0]) {\n\t\tfprintf(stderr, \" - general constraint info 0x\");\n\t\tfor (idx=0; idx<vvccfg->num_constraint_info; idx++) {\n\t\t\tfprintf(stderr, \"%02X\", vvccfg->general_constraint_info[idx]);\n\t\t}\n\t}\n\tfprintf(stderr, \"\\n\");\n\tfprintf(stderr, \"\\tParameter Sets: \");\n\tfor (k=0; k<gf_list_count(vvccfg->param_array); k++) {\n\t\tGF_NALUFFParamArray *ar=gf_list_get(vvccfg->param_array, k);\n\t\tif (ar->type==GF_VVC_NALU_SEQ_PARAM) {\n\t\t\tfprintf(stderr, \"%d SPS \", gf_list_count(ar->nalus));\n\t\t}\n\t\tif (ar->type==GF_VVC_NALU_PIC_PARAM) {\n\t\t\tfprintf(stderr, \"%d PPS \", gf_list_count(ar->nalus));\n\t\t}\n\t\tif (ar->type==GF_VVC_NALU_VID_PARAM) {\n\t\t\tfprintf(stderr, \"%d VPS \", gf_list_count(ar->nalus));", "#if !defined(GPAC_DISABLE_AV_PARSERS) && 0 //TODO\n\t\t\tfor (idx=0; idx<gf_list_count(ar->nalus); idx++) {\n\t\t\t\tGF_NALUFFParam *vps = gf_list_get(ar->nalus, idx);\n\t\t\t\ts32 ps_idx=gf_hevc_read_vps(vps->data, vps->size, hevc_state);\n\t\t\t\tif (hevccfg->is_lhvc && (ps_idx>=0)) {\n\t\t\t\t\tnon_hevc_base_layer = ! hevc_state->vps[ps_idx].base_layer_internal_flag;\n\t\t\t\t}\n\t\t\t}\n#endif", "\t\t}\n\t}", "\tfprintf(stderr, \"\\n\");\n#if !defined(GPAC_DISABLE_AV_PARSERS) && 0 //TODO\n\tfor (k=0; k<gf_list_count(vvccfg->param_array); k++) {\n\t\tGF_NALUFFParamArray *ar=gf_list_get(vvccfg->param_array, k);\n\t\tu32 width, height;\n\t\ts32 par_n, par_d;", "\t\tif (ar->type !=GF_VVC_NALU_SEQ_PARAM) continue;\n\t\tfor (idx=0; idx<gf_list_count(ar->nalus); idx++) {\n\t\t\tGF_Err e;\n\t\t\tGF_NALUFFParam *sps = gf_list_get(ar->nalus, idx);\n\t\t\tpar_n = par_d = -1;\n\t\t\te = gf_vvc_get_sps_info_with_state(vvc_state, sps->data, sps->size, NULL, &width, &height, &par_n, &par_d);\n\t\t\tif (e==GF_OK) {\n\t\t\t\tfprintf(stderr, \"\\tSPS resolution %dx%d\", width, height);\n\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\tu32 tw, th;\n\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\tfprintf(stderr, \" - Pixel Aspect Ratio %d:%d - Indicated track size %d x %d\", par_n, par_d, tw, th);\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t} else {\n\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"\\nFailed to read SPS: %s\\n\\n\", gf_error_to_string(e) ));\n\t\t\t}\n\t\t}\n\t}\n#endif\n\tfprintf(stderr, \"\\tBit Depth %d - %d temporal layers\\n\", vvccfg->bit_depth_plus_one-1, vvccfg->numTemporalLayers);", "\tfor (k=0; k<gf_list_count(vvccfg->param_array); k++) {\n\t\tGF_NALUFFParamArray *ar=gf_list_get(vvccfg->param_array, k);\n\t\tif (ar->type==GF_VVC_NALU_SEQ_PARAM) print_config_hash(ar->nalus, \"SPS\");\n\t\telse if (ar->type==GF_VVC_NALU_PIC_PARAM) print_config_hash(ar->nalus, \"PPS\");\n\t\telse if (ar->type==GF_VVC_NALU_VID_PARAM) print_config_hash(ar->nalus, \"VPS\");\n\t}\n}", "void gf_inspect_format_timecode(const u8 *data, u32 size, u32 tmcd_flags, u32 tc_num, u32 tc_den, u32 tmcd_fpt, char szFmt[100]);", "void DumpTrackInfo(GF_ISOFile *file, GF_ISOTrackID trackID, Bool full_dump, Bool is_track_num, Bool dump_m4sys)\n{\n\tchar szCodec[RFC6381_CODEC_NAME_SIZE_MAX];\n\tDouble scale, max_rate, rate;\n\tBool is_od_track = 0;\n\tu32 trackNum, i, j, ts, mtype, msub_type, timescale, sr, nb_ch, count, alt_group, nb_groups, nb_edits, cdur, csize, bps, pfmt, codecid;\n\tu64 time_slice, dur, size;\n\ts32 cts_shift;\n\tGF_ESD *esd;\n\tchar szDur[50];\n\tchar *lang;", "\tif (!is_track_num) {\n\t\ttrackNum = gf_isom_get_track_by_id(file, trackID);\n\t} else {\n\t\ttrackNum = trackID;\n\t\ttrackID = gf_isom_get_track_id(file, trackNum);\n\t}\n\tif (!trackNum) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"No track with ID %d found\\n\", trackID));\n\t\treturn;\n\t}", "\ttimescale = gf_isom_get_media_timescale(file, trackNum);\n\tfprintf(stderr, \"# Track %d Info - ID %d - TimeScale %d\\n\", trackNum, trackID, timescale);", "\tdur = gf_isom_get_media_original_duration(file, trackNum);\n\tsize = gf_isom_get_media_duration(file, trackNum);\n\tfprintf(stderr, \"Media Duration %s \", format_duration(dur, timescale, szDur));\n\tif (dur != size)\n\t\tfprintf(stderr, \" (recomputed %s)\", format_duration(size, timescale, szDur));\n\tfprintf(stderr, \"\\n\");", "\tif (gf_isom_check_data_reference(file, trackNum, 1) != GF_OK) {\n\t\tM4_LOG(GF_LOG_WARNING, (\"Track uses external data reference not supported by GPAC!\\n\"));\n\t}", "\tnb_edits = gf_isom_get_edits_count(file, trackNum);\n\tif (nb_edits)\n\t\tfprintf(stderr, \"Track has %d edits: track duration is %s\\n\", nb_edits, format_duration(gf_isom_get_track_duration(file, trackNum), gf_isom_get_timescale(file), szDur));", "\tcts_shift = gf_isom_get_composition_offset_shift(file, trackNum);\n\tif (cts_shift)\n\t\tfprintf(stderr, \"Track composition offset shift (negative CTS offset): %d\\n\", cts_shift);", "\tif (gf_isom_is_track_in_root_od(file, trackNum) ) fprintf(stderr, \"Track is present in Root OD\\n\");\n\tif (!gf_isom_is_track_enabled(file, trackNum)) fprintf(stderr, \"Track is disabled\\n\");\n\tgf_isom_get_media_language(file, trackNum, &lang);\n\tfprintf(stderr, \"Media Info: Language \\\"%s (%s)\\\" - \", GetLanguage(lang), lang );\n\tgf_free(lang);\n\tmtype = gf_isom_get_media_type(file, trackNum);\n\tfprintf(stderr, \"Type \\\"%s:\", gf_4cc_to_str(mtype));\n\tmsub_type = gf_isom_get_mpeg4_subtype(file, trackNum, 1);\n\tif (!msub_type) msub_type = gf_isom_get_media_subtype(file, trackNum, 1);\n\tfprintf(stderr, \"%s\\\" - %d samples\\n\", gf_4cc_to_str(msub_type), gf_isom_get_sample_count(file, trackNum));", "\tpfmt = gf_pixel_fmt_from_qt_type(msub_type);\n\tcodecid = gf_codec_id_from_isobmf(msub_type);", "\tcount = gf_isom_get_track_kind_count(file, trackNum);\n\tfor (i = 0; i < count; i++) {\n\t\tchar *kind_scheme, *kind_value;\n\t\tgf_isom_get_track_kind(file, trackNum, i, &kind_scheme, &kind_value);\n\t\tfprintf(stderr, \"Kind: %s - %s\\n\", kind_scheme ? kind_scheme : \"null\", kind_value ? kind_value : \"null\");\n\t\tif (kind_scheme) gf_free(kind_scheme);\n\t\tif (kind_value) gf_free(kind_value);\n\t}", "\tif (gf_isom_is_track_fragmented(file, trackID) ) {\n\t\tu32 defaultDuration, defaultSize, defaultDescriptionIndex, defaultRandomAccess;\n\t\tu8 defaultPadding;\n\t\tu16 defaultDegradationPriority;\n\t\tu32 frag_samples;\n\t\tu64 frag_duration;\n\t\tgf_isom_get_fragmented_samples_info(file, trackID, &frag_samples, &frag_duration);\n\t\tfprintf(stderr, \"Fragmented track: %d samples - Media Duration %s\\n\", frag_samples, format_duration(frag_duration, timescale, szDur));", "\t\tgf_isom_get_fragment_defaults(file, trackNum, &defaultDuration, &defaultSize, &defaultDescriptionIndex, &defaultRandomAccess, &defaultPadding, &defaultDegradationPriority);", "\t\tfprintf(stderr, \"Fragment sample defaults: duration %d size %d stsd %d sync %d padding %d degradation_priority %d\\n\",\n\t\t\t\tdefaultDuration, defaultSize, defaultDescriptionIndex, defaultRandomAccess,\n\t\t\t\t(u32) defaultPadding, (u32) defaultDegradationPriority\n\t\t);\n\t}", "\tif (!gf_isom_is_self_contained(file, trackNum, 1)) {\n\t\tconst char *url, *urn;\n\t\tgf_isom_get_data_reference(file, trackNum, 1, &url, &urn);\n\t\tfprintf(stderr, \"Media Data Location: %s\\n\", url ? url : urn);\n\t}", "\tif (full_dump) {\n\t\tconst char *handler_name;\n\t\tgf_isom_get_handler_name(file, trackNum, &handler_name);\n\t\tfprintf(stderr, \"Handler name: %s\\n\", handler_name);\n\t}", "\tprint_udta(file, trackNum, GF_FALSE);", "\tif (gf_isom_is_video_handler_type(mtype) ) {\n\t\ts32 tx, ty;\n\t\tu32 w, h;\n\t\tu16 bit_depth;", "\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tgf_isom_get_visual_bit_depth(file, trackNum, 1, &bit_depth);\n\t\tfprintf(stderr, \"Visual Sample Entry Info: width=%d height=%d (depth=%d bits)\\n\", w, h, (int)bit_depth);", "\t\tgf_isom_get_track_layout_info(file, trackNum, &w, &h, &tx, &ty, NULL);\n\t\tfprintf(stderr, \"Visual Track layout: x=%d y=%d width=%d height=%d\\n\", tx, ty, w, h);\n\t}", "\tgf_isom_get_audio_info(file, trackNum, 1, &sr, &nb_ch, &bps);\n\tgf_isom_set_nalu_extract_mode(file, trackNum, GF_ISOM_NALU_EXTRACT_INSPECT);", "\tmsub_type = gf_isom_get_media_subtype(file, trackNum, 1);\n\tif (msub_type==GF_ISOM_SUBTYPE_MPEG4_CRYP)\n\t\tgf_isom_get_original_format_type(file, trackNum, 1, &msub_type);", "\tif ((msub_type==GF_ISOM_SUBTYPE_MPEG4)\n\t || (msub_type==GF_ISOM_SUBTYPE_AVC_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_AVC2_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_AVC3_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_AVC4_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_SVC_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_MVC_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_LSR1)\n\t || (msub_type==GF_ISOM_SUBTYPE_HVC1)\n\t || (msub_type==GF_ISOM_SUBTYPE_HEV1)\n\t || (msub_type==GF_ISOM_SUBTYPE_HVC2)\n\t || (msub_type==GF_ISOM_SUBTYPE_HEV2)\n\t || (msub_type==GF_ISOM_SUBTYPE_LHV1)\n\t || (msub_type==GF_ISOM_SUBTYPE_LHE1)\n\t || (msub_type==GF_ISOM_SUBTYPE_HVT1)\n\t ) {\n\t\tesd = gf_isom_get_esd(file, trackNum, 1);\n\t\tif (!esd || !esd->decoderConfig) {\n\t\t\tM4_LOG(GF_LOG_WARNING, (\"WARNING: Broken MPEG-4 Track\\n\"));\n\t\t\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);\n\t\t} else {\n\t\t\tconst char *st = gf_stream_type_name(esd->decoderConfig->streamType);\n\t\t\tif (dump_m4sys) {\n\t\t\t\tif (st) {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Config%s%s Stream - ObjectTypeIndication 0x%02x\\n\",\n\t\t\t\t\t\t\tfull_dump ? \"\\n\\t\" : \": \", st, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Config%sStream Type 0x%02x - ObjectTypeIndication 0x%02x\\n\",\n\t\t\t\t\t\t\tfull_dump ? \"\\n\\t\" : \": \", esd->decoderConfig->streamType, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (esd->decoderConfig->streamType==GF_STREAM_OD)\n\t\t\t\tis_od_track=1;", "\t\t\tif (esd->decoderConfig->streamType==GF_STREAM_VISUAL) {\n\t\t\t\tu32 w, h;\n\t\t\t\tu16 rvc_predef;\n\t\t\t\tw = h = 0;\n\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\tif (!esd->decoderConfig->decoderSpecificInfo) {\n#else\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Visual Size %d x %d\\n\", w, h);\n#endif\n\t\t\t\t\t\tM4_LOG(GF_LOG_WARNING, (\"Non-compliant MPEG-4 Visual track: video_object_layer infos not found in sample description\\n\"));\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t} else {\n\t\t\t\t\t\tGF_M4VDecSpecInfo dsi;\n\t\t\t\t\t\tgf_m4v_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &dsi);\n\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\tw = dsi.width;\n\t\t\t\t\t\th = dsi.height;\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-4 Visual Size %d x %d - %s\\n\", w, h, gf_m4v_get_profile_name(dsi.VideoPL));\n\t\t\t\t\t\tif (dsi.par_den && dsi.par_num) {\n\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\tfprintf(stderr, \"Pixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", dsi.par_num, dsi.par_den, tw, th);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#endif\n\t\t\t\t} else if (gf_isom_get_avc_svc_type(file, trackNum, 1) != GF_ISOM_AVCTYPE_NONE) {\n\t\t\t\t\tGF_AVCConfig *avccfg, *svccfg, *mvccfg;", "\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"AVC/H264 Video - Visual Size %d x %d\\n\", w, h);", "\t\t\t\t\tavccfg = gf_isom_avc_config_get(file, trackNum, 1);\n\t\t\t\t\tsvccfg = gf_isom_svc_config_get(file, trackNum, 1);\n\t\t\t\t\tmvccfg = gf_isom_mvc_config_get(file, trackNum, 1);\n\t\t\t\t\tif (!avccfg && !svccfg && !mvccfg) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"\\tNon-compliant AVC track: SPS/PPS not found in sample description\\n\"));\n\t\t\t\t\t} else if (avccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tAVC Info: %d SPS - %d PPS\", gf_list_count(avccfg->sequenceParameterSets) , gf_list_count(avccfg->pictureParameterSets) );\n\t\t\t\t\t\tfprintf(stderr, \" - Profile %s @ Level %g\\n\", gf_avc_get_profile_name(avccfg->AVCProfileIndication), ((Double)avccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tNAL Unit length bits: %d\\n\", 8*avccfg->nal_unit_size);", "#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; i<gf_list_count(avccfg->sequenceParameterSets); i++) {\n\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(avccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, NULL, NULL, NULL, &par_n, &par_d);\n\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!full_dump) break;\n\t\t\t\t\t\t}\n#endif", "\t\t\t\t\t\tif (avccfg->chroma_bit_depth) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tChroma format %s - Luma bit depth %d - chroma bit depth %d\\n\", gf_avc_hevc_get_chroma_format_name(avccfg->chroma_format), avccfg->luma_bit_depth, avccfg->chroma_bit_depth);\n\t\t\t\t\t\t}", "\t\t\t\t\t\tprint_config_hash(avccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(avccfg->pictureParameterSets, \"PPS\");", "\t\t\t\t\t\tgf_odf_avc_cfg_del(avccfg);\n\t\t\t\t\t}\n\t\t\t\t\tif (svccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tSVC Info: %d SPS - %d PPS - Profile %s @ Level %g\\n\", gf_list_count(svccfg->sequenceParameterSets) , gf_list_count(svccfg->pictureParameterSets), gf_avc_get_profile_name(svccfg->AVCProfileIndication), ((Double)svccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tSVC NAL Unit length bits: %d\\n\", 8*svccfg->nal_unit_size);\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; i<gf_list_count(svccfg->sequenceParameterSets); i++) {\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(svccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tif (slc) {\n\t\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\t\tu32 s_w, s_h, sps_id;\n\t\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, &sps_id, &s_w, &s_h, &par_n, &par_d);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\t\\tSPS ID %d - Visual Size %d x %d\\n\", sps_id, s_w, s_h);\n\t\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\tprint_config_hash(svccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(svccfg->pictureParameterSets, \"PPS\");\n\t\t\t\t\t\tprint_config_hash(svccfg->sequenceParameterSetExtensions, \"SPSEx\");", "\t\t\t\t\t\tgf_odf_avc_cfg_del(svccfg);\n\t\t\t\t\t}", "\t\t\t\t\tif (mvccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tMVC Info: %d SPS - %d PPS - Profile %s @ Level %g\\n\", gf_list_count(mvccfg->sequenceParameterSets) , gf_list_count(mvccfg->pictureParameterSets), gf_avc_get_profile_name(mvccfg->AVCProfileIndication), ((Double)mvccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tMVC NAL Unit length bits: %d\\n\", 8*mvccfg->nal_unit_size);\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; i<gf_list_count(mvccfg->sequenceParameterSets); i++) {\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(mvccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tif (slc) {\n\t\t\t\t\t\t\t\tu32 s_w, s_h, sps_id;\n\t\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, &sps_id, &s_w, &s_h, &par_n, &par_d);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\t\\tSPS ID %d - Visual Size %d x %d\\n\", sps_id, s_w, s_h);\n\t\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\tprint_config_hash(mvccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(mvccfg->pictureParameterSets, \"PPS\");\n\t\t\t\t\t\tgf_odf_avc_cfg_del(mvccfg);\n\t\t\t\t\t}", "\t\t\t\t} else if ((esd->decoderConfig->objectTypeIndication==GF_CODECID_HEVC)\n\t\t\t\t || (esd->decoderConfig->objectTypeIndication==GF_CODECID_LHVC)\n\t\t\t\t ) {\n\t\t\t\t\tGF_HEVCConfig *hevccfg, *lhvccfg;\n\t\t\t\t\tGF_OperatingPointsInformation *oinf;\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\tHEVCState hevc_state;\n\t\t\t\t\tmemset(&hevc_state, 0, sizeof(HEVCState));\n\t\t\t\t\thevc_state.sps_active_idx = -1;\n#endif", "\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"HEVC Video - Visual Size %d x %d\\n\", w, h);\n\t\t\t\t\thevccfg = gf_isom_hevc_config_get(file, trackNum, 1);\n\t\t\t\t\tlhvccfg = gf_isom_lhvc_config_get(file, trackNum, 1);", "\t\t\t\t\tif (msub_type==GF_ISOM_SUBTYPE_HVT1) {\n\t\t\t\t\t\tconst u8 *data;\n\t\t\t\t\t\tu32 tsize;\n\t\t\t\t\t\tu32 is_default, tx,ty,tw,th, id, independent;\n\t\t\t\t\t\tBool full_frame;\n\t\t\t\t\t\tif (gf_isom_get_tile_info(file, trackNum, 1, &is_default, &id, &independent, &full_frame, &tx, &ty, &tw, &th)) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile - ID %d independent %d (x,y,w,h)=%d,%d,%d,%d \\n\", id, independent, tx, ty, tw, th);\n\t\t\t\t\t\t} else if (gf_isom_get_sample_group_info(file, trackNum, 1, GF_ISOM_SAMPLE_GROUP_TRIF, &is_default, &data, &tsize)) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile track containing a tile set\\n\");\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile track without tiling info\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (!hevccfg && !lhvccfg) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"\\tNon-compliant HEVC track: No hvcC or shcC found in sample description\\n\"));\n\t\t\t\t\t}", "\t\t\t\t\tif (gf_isom_get_reference_count(file, trackNum, GF_ISOM_REF_SABT)) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile base track\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif (hevccfg) {\n\t\t\t\t\t\tdump_hevc_track_info(file, trackNum, hevccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\t\t\t, &hevc_state\n#endif\n\t\t\t\t\t\t);\n\t\t\t\t\t\tgf_odf_hevc_cfg_del(hevccfg);\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif (lhvccfg) {\n\t\t\t\t\t\tdump_hevc_track_info(file, trackNum, lhvccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\t\t\t, &hevc_state\n#endif\n\t\t\t\t\t\t);\n\t\t\t\t\t\tgf_odf_hevc_cfg_del(lhvccfg);\n\t\t\t\t\t}", "\t\t\t\t\tif (gf_isom_get_oinf_info(file, trackNum, &oinf)) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tOperating Points Information -\");\n\t\t\t\t\t\tfprintf(stderr, \" scalability_mask %d (\", oinf->scalability_mask);\n\t\t\t\t\t\tswitch (oinf->scalability_mask) {\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\tfprintf(stderr, \"Multiview\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 4:\n\t\t\t\t\t\t\tfprintf(stderr, \"Spatial scalability\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 8:\n\t\t\t\t\t\t\tfprintf(stderr, \"Auxilary\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tfprintf(stderr, \"unknown\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//TODO: need to dump more info ?\n\t\t\t\t\t\tfprintf(stderr, \") num_profile_tier_level %d \", gf_list_count(oinf->profile_tier_levels) );\n\t\t\t\t\t\tfprintf(stderr, \" num_operating_points %d dependency layers %d \\n\", gf_list_count(oinf->operating_points), gf_list_count(oinf->dependency_layers) );\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\t/*OGG media*/\n\t\t\t\telse if (esd->decoderConfig->objectTypeIndication==GF_CODECID_THEORA) {\n\t\t\t\t\tchar *szName;\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tif (!strnicmp((char *) &esd->decoderConfig->decoderSpecificInfo->data[3], \"theora\", 6)) szName = \"Theora\";\n\t\t\t\t\telse szName = \"Unknown\";\n\t\t\t\t\tfprintf(stderr, \"Ogg/%s video / GPAC Mux - Visual Size %d x %d\\n\", szName, w, h);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t//check if we know this codec from its OTI\n\t\t\t\t\tu32 codec_id = gf_codecid_from_oti(GF_STREAM_VISUAL, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tif (codec_id) {\n\t\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\t\tfprintf(stderr, \"%s - Visual Size %d x %d\\n\", gf_codecid_name(codec_id), w, h);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!w || !h) {\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"Visual Size %d x %d\\n\", w, h);\n\t\t\t\t}\n\t\t\t\tif (gf_isom_get_rvc_config(file, trackNum, 1, &rvc_predef, NULL, NULL, NULL)==GF_OK) {\n\t\t\t\t\tfprintf(stderr, \"Has RVC signaled - Predefined configuration %d\\n\", rvc_predef);\n\t\t\t\t}", "\t\t\t} else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\tGF_M4ADecSpecInfo a_cfg;\n\t\t\t\tGF_Err e;\n\t\t\t\tu32 oti;\n#endif\n\t\t\t\tu32 codec_id;\n\t\t\t\tBool is_mp2 = GF_FALSE;\n\t\t\t\tswitch (esd->decoderConfig->objectTypeIndication) {\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_MP:\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_LCP:\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_SSRP:\n\t\t\t\t\tis_mp2 = GF_TRUE;\n\t\t\t\tcase GF_CODECID_AAC_MPEG4:\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\tif (!esd->decoderConfig->decoderSpecificInfo)\n\t\t\t\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t\t\telse\n\t\t\t\t\t\te = gf_m4a_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &a_cfg);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Corrupted AAC Config\\n\"));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchar *signaling = \"implicit\";\n\t\t\t\t\t\tchar *heaac = \"\";\n\t\t\t\t\t\tif (!is_mp2 && a_cfg.has_sbr) {\n\t\t\t\t\t\t\tif (a_cfg.has_ps) heaac = \"(HE-AAC v2) \";\n\t\t\t\t\t\t\telse heaac = \"(HE-AAC v1) \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (a_cfg.base_object_type==2) {\n\t\t\t\t\t\t\tif (a_cfg.has_ps || a_cfg.has_sbr)\n\t\t\t\t\t\t\t\tsignaling = \"backward compatible\";\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsignaling = \"hierarchical\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfprintf(stderr, \"%s (AOT=%d %s) %s- %d Channel(s) - SampleRate %d\", gf_m4a_object_type_name(a_cfg.base_object_type), a_cfg.base_object_type, signaling, heaac, a_cfg.nb_chan, a_cfg.base_sr);\n\t\t\t\t\t\tif (is_mp2) fprintf(stderr, \" (MPEG-2 Signaling)\");\n\t\t\t\t\t\tif (a_cfg.has_sbr) fprintf(stderr, \" - SBR: SampleRate %d Type %s\", a_cfg.sbr_sr, gf_m4a_object_type_name(a_cfg.sbr_object_type));\n\t\t\t\t\t\tif (a_cfg.has_ps) fprintf(stderr, \" - PS\");\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n#else\n\t\t\t\t\tfprintf(stderr, \"MPEG-2/4 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n#endif\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_MPEG2_PART3:\n\t\t\t\tcase GF_CODECID_MPEG_AUDIO:\n\t\t\t\t\tif (msub_type == GF_ISOM_SUBTYPE_MPEG4_CRYP) {\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-1/2 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n\t\t\t\t\t} else {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tGF_ISOSample *samp = gf_isom_get_sample(file, trackNum, 1, &oti);\n\t\t\t\t\t\tif (samp) {\n\t\t\t\t\t\t\tu32 mhdr = GF_4CC((u8)samp->data[0], (u8)samp->data[1], (u8)samp->data[2], (u8)samp->data[3]);\n\t\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\t\tfprintf(stderr, \"%s Audio - %d Channel(s) - SampleRate %d - Layer %d\\n\",\n\t\t\t\t\t\t\t gf_mp3_version_name(mhdr),\n\t\t\t\t\t\t\t gf_mp3_num_channels(mhdr),\n\t\t\t\t\t\t\t gf_mp3_sampling_rate(mhdr),\n\t\t\t\t\t\t\t gf_mp3_layer(mhdr)\n\t\t\t\t\t\t\t );\n\t\t\t\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Error fetching sample: %s\\n\", gf_error_to_string(gf_isom_last_error(file)) ));\n\t\t\t\t\t\t}\n#else\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-1/2 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n#endif\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_EVRC:\n\t\t\t\t\tfprintf(stderr, \"EVRC Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_SMV:\n\t\t\t\t\tfprintf(stderr, \"SMV Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_QCELP:\n\t\t\t\t\tfprintf(stderr, \"QCELP Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\t/*packetVideo hack for EVRC...*/\n\t\t\t\tcase GF_CODECID_EVRC_PV:\n\t\t\t\t\tif (esd->decoderConfig->decoderSpecificInfo && (esd->decoderConfig->decoderSpecificInfo->dataLength==8)\n\t\t\t\t\t && !strnicmp((char *)esd->decoderConfig->decoderSpecificInfo->data, \"pvmm\", 4)) {\n\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\tfprintf(stderr, \"EVRC Audio (PacketVideo Mux) - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tcodec_id = gf_codecid_from_oti(GF_STREAM_AUDIO, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tif (codec_id) {\n\t\t\t\t\t\tfprintf(stderr, \"%s - Sample Rate %d - %d channel(s)\\n\", gf_codecid_name(codec_id), sr, nb_ch);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (esd->decoderConfig->streamType==GF_STREAM_SCENE) {\n\t\t\t\tif (esd->decoderConfig->objectTypeIndication<=4) {\n\t\t\t\t\tGF_BIFSConfig *b_cfg = gf_odf_get_bifs_config(esd->decoderConfig->decoderSpecificInfo, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tfprintf(stderr, \"BIFS Scene description - %s stream\\n\", b_cfg->elementaryMasks ? \"Animation\" : \"Command\");\n\t\t\t\t\tif (full_dump && !b_cfg->elementaryMasks) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tWidth %d Height %d Pixel Metrics %s\\n\", b_cfg->pixelWidth, b_cfg->pixelHeight, b_cfg->pixelMetrics ? \"yes\" : \"no\");\n\t\t\t\t\t}\n\t\t\t\t\tgf_odf_desc_del((GF_Descriptor *)b_cfg);\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_AFX) {\n\t\t\t\t\tu8 tag = esd->decoderConfig->decoderSpecificInfo ? esd->decoderConfig->decoderSpecificInfo->data[0] : 0xFF;\n\t\t\t\t\tconst char *afxtype = gf_stream_type_afx_name(tag);\n\t\t\t\t\tfprintf(stderr, \"AFX Stream - type %s (%d)\\n\", afxtype, tag);\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_FONT) {\n\t\t\t\t\tfprintf(stderr, \"Font Data stream\\n\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_LASER) {\n\t\t\t\t\tGF_LASERConfig l_cfg;\n\t\t\t\t\tgf_odf_get_laser_config(esd->decoderConfig->decoderSpecificInfo, &l_cfg);\n\t\t\t\t\tfprintf(stderr, \"LASER Stream - %s\\n\", l_cfg.newSceneIndicator ? \"Full Scene\" : \"Scene Segment\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_TEXT_MPEG4) {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Streaming Text stream\\n\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_SYNTHESIZED_TEXTURE) {\n\t\t\t\t\tfprintf(stderr, \"Synthetized Texture stream stream\\n\");\n\t\t\t\t} else {\n\t\t\t\t\tM4_LOG(GF_LOG_WARNING, (\"Unknown Systems stream OTI %d\\n\", esd->decoderConfig->objectTypeIndication));\n\t\t\t\t}\n\t\t\t}", "\t\t\t/*sync is only valid if we open all tracks to take care of default MP4 sync..*/\n\t\t\tif (!full_dump) {\n\t\t\t\tif (dump_m4sys) {\n\t\t\t\t\tif (!esd->OCRESID || (esd->OCRESID == esd->ESID))\n\t\t\t\t\t\tfprintf(stderr, \"Self-synchronized\\n\");\n\t\t\t\t\telse\n\t\t\t\t\t\tfprintf(stderr, \"Synchronized on stream %d\\n\", esd->OCRESID);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"\\tDecoding Buffer size %d - Bitrate: avg %d - max %d kbps\\n\", esd->decoderConfig->bufferSizeDB, esd->decoderConfig->avgBitrate/1000, esd->decoderConfig->maxBitrate/1000);\n\t\t\t\tif (esd->dependsOnESID)\n\t\t\t\t\tfprintf(stderr, \"\\tDepends on stream %d for decoding\\n\", esd->dependsOnESID);\n\t\t\t\telse\n\t\t\t\t\tfprintf(stderr, \"\\tNo stream dependencies for decoding\\n\");", "\t\t\t\tfprintf(stderr, \"\\tStreamPriority %d\\n\", esd->streamPriority);\n\t\t\t\tif (esd->URLString) fprintf(stderr, \"\\tRemote Data Source %s\\n\", esd->URLString);\n\t\t\t}\n\t\t\tgf_odf_desc_del((GF_Descriptor *) esd);\n\t\t}\n\t} else if (msub_type == GF_ISOM_SUBTYPE_AV01) {\n\t\tGF_AV1Config *av1c;\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\tAOM AV1 stream - Resolution %d x %d\\n\", w, h);", "\t\tav1c = gf_isom_av1_config_get(file, trackNum, 1);", "\t\tif (!av1c) {\n\t\t\tfprintf(stderr, \"\\tCorrupted av1 config\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"\\tversion=%u, profile=%u, level_idx0=%u, tier=%u\\n\", (u32)av1c->version, (u32)av1c->seq_profile, (u32)av1c->seq_level_idx_0, (u32)av1c->seq_tier_0);\n\t\t\tfprintf(stderr, \"\\thigh_bitdepth=%u, twelve_bit=%u, monochrome=%u\\n\", (u32)av1c->high_bitdepth, (u32)av1c->twelve_bit, (u32)av1c->monochrome);\n\t\t\tfprintf(stderr, \"\\tchroma: subsampling_x=%u, subsampling_y=%u, sample_position=%u\\n\", (u32)av1c->chroma_subsampling_x, (u32)av1c->chroma_subsampling_y, (u32)av1c->chroma_sample_position);", "\t\t\tif (av1c->initial_presentation_delay_present)\n\t\t\t\tfprintf(stderr, \"\\tInitial presentation delay %u\\n\", (u32) av1c->initial_presentation_delay_minus_one+1);", "\t\t\tcount = gf_list_count(av1c->obu_array);\n\t\t\tfor (i=0; i<count; i++) {\n\t\t\t\tu8 hash[20];\n\t\t\t\tGF_AV1_OBUArrayEntry *obu = gf_list_get(av1c->obu_array, i);\n\t\t\t\tgf_sha1_csum((u8*)obu->obu, (u32)obu->obu_length, hash);\n\t\t\t\tfprintf(stderr, \"\\tOBU#%d %s hash: \", i+1, gf_av1_get_obu_name(obu->obu_type) );\n\t\t\t\tfor (j=0; j<20; j++) fprintf(stderr, \"%02X\", hash[j]);\n\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t}\n\t\t\tgf_odf_av1_cfg_del(av1c);\n\t\t}", "\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_H263) {\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\t3GPP H263 stream - Resolution %d x %d\\n\", w, h);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_MJP2) {\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\tMotionJPEG2000 stream - Resolution %d x %d\\n\", w, h);\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_3GP_AMR) || (msub_type == GF_ISOM_SUBTYPE_3GP_AMR_WB)) {\n\t\tfprintf(stderr, \"\\t3GPP AMR%s stream - Sample Rate %d - %d channel(s) %d bps\\n\", (msub_type == GF_ISOM_SUBTYPE_3GP_AMR_WB) ? \" Wide Band\" : \"\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_EVRC) {\n\t\tfprintf(stderr, \"\\t3GPP EVRC stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_QCELP) {\n\t\tfprintf(stderr, \"\\t3GPP QCELP stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_MP3) {\n\t\tfprintf(stderr, \"\\tMPEG 1/2 Audio stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_AC3) || (msub_type == GF_ISOM_SUBTYPE_EC3)) {\n\t\tu32 br = 0;\n\t\tconst char *lfe = \"\";\n\t\tBool is_ec3 = (msub_type == GF_ISOM_SUBTYPE_EC3) ? GF_TRUE : GF_FALSE;\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\tGF_AC3Config *ac3 = gf_isom_ac3_config_get(file, trackNum, 1);\n\t\tif (ac3) {\n\t\t\tnb_ch = gf_ac3_get_channels(ac3->streams[0].acmod);\n\t\t\tfor (i=0; i<ac3->streams[0].nb_dep_sub; ++i) {\n\t\t\t\tassert(ac3->streams[0].nb_dep_sub == 1);\n\t\t\t\tnb_ch += gf_ac3_get_channels(ac3->streams[0].chan_loc);\n\t\t\t}\n\t\t\tif (ac3->streams[0].lfon) lfe = \".1\";\n\t\t\tbr = ac3->is_ec3 ? ac3->brcode : gf_ac3_get_bitrate(ac3->brcode);\n\t\t\tis_ec3 = ac3->is_ec3;\n\t\t\tgf_free(ac3);\n\t\t}\n#endif\n\t\tfprintf(stderr, \"\\t%s stream - Sample Rate %d - %d%s channel(s) - bitrate %d\\n\", is_ec3 ? \"EC-3\" : \"AC-3\", sr, nb_ch, lfe, br);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_SMV) {\n\t\tfprintf(stderr, \"\\t3GPP SMV stream - Sample Rate %d - %d channel(s) %d bits per samples\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_DIMS) {\n\t\tu32 w, h;\n\t\tGF_DIMSDescription dims;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);", "\t\tgf_isom_get_dims_description(file, trackNum, 1, &dims);\n\t\tfprintf(stderr, \"\\t3GPP DIMS stream - size %d x %d - Profile %d - Level %d\\n\", w, h, dims.profile, dims.level);\n\t\tfprintf(stderr, \"\\tpathComponents: %d - useFullRequestHost: %s\\n\", dims.pathComponents, dims.fullRequestHost ? \"yes\" : \"no\");\n\t\tfprintf(stderr, \"\\tstream type: %s - redundant: %s\\n\", dims.streamType ? \"primary\" : \"secondary\", (dims.containsRedundant==1) ? \"main\" : ((dims.containsRedundant==2) ? \"redundant\" : \"main+redundant\") );\n\t\tif (dims.textEncoding[0]) fprintf(stderr, \"\\ttext encoding %s\\n\", dims.textEncoding);\n\t\tif (dims.contentEncoding[0]) fprintf(stderr, \"\\tcontent encoding %s\\n\", dims.contentEncoding);\n\t\tif (dims.content_script_types) fprintf(stderr, \"\\tscript languages %s\\n\", dims.content_script_types);\n\t} else if (mtype==GF_ISOM_MEDIA_HINT) {\n\t\tu32 refTrack;\n\t\ts32 refCount = gf_isom_get_reference_count(file, trackNum, GF_ISOM_REF_HINT);\n\t\tif (refCount>0) {\n\t\t\tfprintf(stderr, \"Streaming Hint Track for track%s \", (refCount>1) ? \"s\" :\"\");\n\t\t\tfor (i=0; i<(u32) refCount; i++) {\n\t\t\t\tgf_isom_get_reference(file, trackNum, GF_ISOM_REF_HINT, i+1, &refTrack);\n\t\t\t\tif (i) fprintf(stderr, \" - \");\n\t\t\t\tfprintf(stderr, \"ID %d\", gf_isom_get_track_id(file, refTrack));\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"Streaming Hint Track (no refs)\\n\");\n\t\t}\n#ifndef GPAC_DISABLE_ISOM_HINTING\n\t\trefCount = gf_isom_get_payt_count(file, trackNum);\n\t\tif (refCount>0) {\n\t\t\tfor (i=0; i<(u32) refCount; i++) {\n\t\t\t\tconst char *name = gf_isom_get_payt_info(file, trackNum, i+1, &refTrack);\n\t\t\t\tfprintf(stderr, \"\\tPayload ID %d: type %s\\n\", refTrack, name);\n\t\t\t}\n\t\t}\n#endif\n\t} else if (mtype==GF_ISOM_MEDIA_FLASH) {\n\t\tfprintf(stderr, \"Macromedia Flash Movie\\n\");\n\t} else if ((mtype==GF_ISOM_MEDIA_TEXT) || (mtype==GF_ISOM_MEDIA_SUBT) || (mtype==GF_ISOM_MEDIA_MPEG_SUBT)) {\n\t\tu32 w, h;\n\t\ts16 l;\n\t\ts32 tx, ty;\n\t\tconst char *content_encoding = NULL;\n\t\tconst char *mime = NULL;\n\t\tconst char *config = NULL;\n\t\tconst char *_namespace = NULL;\n\t\tconst char *schema_loc = NULL;\n\t\tconst char *auxiliary_mimes = NULL;\n\t\tgf_isom_get_track_layout_info(file, trackNum, &w, &h, &tx, &ty, &l);\n\t\tif (msub_type == GF_ISOM_SUBTYPE_SBTT) {\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Textual Subtitle Stream \");\n\t\t\tfprintf(stderr, \"- mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_STXT) {\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Simple Timed Text Stream \");\n\t\t\tfprintf(stderr, \"- mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_STPP) {\n\t\t\tgf_isom_xml_subtitle_get_description(file, trackNum, 1, &_namespace, &schema_loc, &auxiliary_mimes);\n\t\t\tfprintf(stderr, \"XML Subtitle Stream \");\n\t\t\tfprintf(stderr, \"- namespace %s\", _namespace);\n\t\t\tif (schema_loc != NULL) {\n\t\t\t\tfprintf(stderr, \" - schema-location %s\", schema_loc);\n\t\t\t}\n\t\t\tif (auxiliary_mimes != NULL) {\n\t\t\t\tfprintf(stderr, \" - auxiliary-mime-types %s\", auxiliary_mimes);\n\t\t\t}\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown Text Stream\");\n\t\t}\n\t\tfprintf(stderr, \"\\n Size %d x %d - Translation X=%d Y=%d - Layer %d\\n\", w, h, tx, ty, l);\n\t} else if (mtype == GF_ISOM_MEDIA_META) {\n\t\tconst char *content_encoding = NULL;\n\t\tif (msub_type == GF_ISOM_SUBTYPE_METT) {\n\t\t\tconst char *mime = NULL;\n\t\t\tconst char *config = NULL;\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Textual Metadata Stream - mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_METX) {\n\t\t\tconst char *_namespace = NULL;\n\t\t\tconst char *schema_loc = NULL;\n\t\t\tgf_isom_get_xml_metadata_description(file, trackNum, 1, &_namespace, &schema_loc, &content_encoding);\n\t\t\tfprintf(stderr, \"XML Metadata Stream - namespace %s\", _namespace);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (schema_loc != NULL) {\n\t\t\t\tfprintf(stderr, \" - schema-location %s\", schema_loc);\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown Metadata Stream\\n\");\n\t\t}\n\t} else if ((msub_type==GF_ISOM_SUBTYPE_VVC1) || (msub_type==GF_ISOM_SUBTYPE_VVI1)) {\n\t\tGF_VVCConfig *vvccfg;\n\t\tu32 w, h;\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\tVVCState *vvc_state;\n\t\tGF_SAFEALLOC(vvc_state, VVCState);\n\t\tif (vvc_state) vvc_state->sps_active_idx = -1;\n#endif", "\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\tfprintf(stderr, \"VVC Video - Visual Size %d x %d\\n\", w, h);\n\t\tvvccfg = gf_isom_vvc_config_get(file, trackNum, 1);", "\t\tif (!vvccfg) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Non-compliant VVC track: No vvcC found in sample description\\n\"));\n\t\t} else {\n\t\t\tdump_vvc_track_info(file, trackNum, vvccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\t\t\t, vvc_state\n#endif\n\t\t\t);\n\t\t\tgf_odf_vvc_cfg_del(vvccfg);\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t}\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\tif (vvc_state) gf_free(vvc_state);\n#endif\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_MH3D_MHA1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHA2)\n\t\t\t|| (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM2)\n\t) {\n\t\tconst u8 *compat_profiles;\n\t\tu32 nb_compat_profiles;\n\t\tBool valid = GF_FALSE;\n\t\tBool allow_inband = GF_FALSE;\n\t\tif ( (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM2))\n\t\t\tallow_inband = GF_TRUE;", "\t\tfprintf(stderr, \"\\tMPEG-H Audio stream - Sample Rate %d\\n\", sr);", "\t\tesd = gf_media_map_esd(file, trackNum, 1);\n\t\tif (!esd || !esd->decoderConfig || !esd->decoderConfig->decoderSpecificInfo\n\t\t\t|| !esd->decoderConfig->decoderSpecificInfo->data\n\t\t) {\n\t\t\tif (allow_inband) {\n\t\t\t\tGF_ISOSample *samp = gf_isom_get_sample(file, trackNum, 1, NULL);\n\t\t\t\tif (samp) {\n\t\t\t\t\tu64 ch_layout=0;\n\t\t\t\t\ts32 PL = gf_mpegh_get_mhas_pl(samp->data, samp->dataLength, &ch_layout);\n\t\t\t\t\tif (PL>=0) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tProfileLevelIndication: 0x%02X\", PL);\n\t\t\t\t\t\tif (ch_layout)\n\t\t\t\t\t\t\tfprintf(stderr, \" - Reference Channel Layout %s\", gf_audio_fmt_get_layout_name(ch_layout) );\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t\t}\n\t\t\t\tvalid = GF_TRUE;\n\t\t\t}\n\t\t} else if (esd->decoderConfig->decoderSpecificInfo->dataLength>=5) {\n\t\t\tfprintf(stderr, \"\\tProfileLevelIndication: 0x%02X - Reference Channel Layout %s\\n\", esd->decoderConfig->decoderSpecificInfo->data[1]\n\t\t\t\t, gf_audio_fmt_get_layout_name_from_cicp(esd->decoderConfig->decoderSpecificInfo->data[2])\n\t\t\t);\n\t\t\tvalid = GF_TRUE;\n\t\t}\n\t\tif (!valid) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Invalid MPEG-H audio config\\n\"));\n\t\t}\n\t\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);\n\t\tcompat_profiles = gf_isom_get_mpegh_compatible_profiles(file, trackNum, 1, &nb_compat_profiles);\n\t\tfor (i=0; i<nb_compat_profiles; i++) {\n\t\t\tif (!i)\n\t\t\t\tfprintf(stderr, \"\\tCompatible profiles:\");\n\t\t\tfprintf(stderr, \" 0x%02X\", compat_profiles[i]);\n\t\t}\n\t\tif (i) fprintf(stderr, \"\\n\");\n\t} else if (msub_type==GF_ISOM_SUBTYPE_MLPA) {\n\t\tu32 fmt, prate;\n\t\tif (gf_isom_truehd_config_get(file, trackNum, 1, &fmt, &prate) != GF_OK) {\n\t\t\tfprintf(stderr, \"\\tInvalid TrueHD audio config\\n\");\n\t\t}\n\t\tfprintf(stderr, \"TrueHD Audio stream - Sample Rate %u - channels %u - format %u peak rate %u\\n\", sr, nb_ch, fmt, prate);\n\t} else if (codecid) {\n\t\tif (gf_isom_is_video_handler_type(mtype) ) {\n\t\t\tu32 w, h;\n\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\tfprintf(stderr, \"%s - Resolution %d x %d\\n\", gf_codecid_name(codecid), w, h);\n\t\t} else if (mtype==GF_ISOM_MEDIA_AUDIO) {\n\t\t\tgf_isom_get_audio_info(file, trackNum, 1, &sr, &nb_ch, NULL);\n\t\t\tfprintf(stderr, \"%s - Sample Rate %d - %d channel(s)\\n\", gf_codecid_name(codecid), sr, nb_ch);\n\t\t} else {\n\t\t\tfprintf(stderr, \"%s\\n\", gf_codecid_name(codecid) );\n\t\t}\n\t} else if (pfmt) {\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"Raw video %s - Resolution %d x %d\\n\", gf_pixel_fmt_name(pfmt), w, h);\n\t} else if (msub_type==GF_QT_SUBTYPE_TMCD) {\n\t\tu32 stsd_idx;\n\t\tGF_ISOSample *sample = gf_isom_get_sample(file, trackNum, 1, &stsd_idx);\n\t\tfprintf(stderr, \"Time Code stream\\n\");\n\t\tif (sample) {\n\t\t\tchar szTimecode[100];\n\t\t\tu32 tmcd_flags, tmcd_num, tmcd_den, tmcd_fpt;", "\t\t\tgf_isom_get_tmcd_config(file, trackNum, stsd_idx, &tmcd_flags, &tmcd_num, &tmcd_den, &tmcd_fpt);", "\t\t\tgf_inspect_format_timecode(sample->data, sample->dataLength, tmcd_flags, tmcd_num, tmcd_den, tmcd_fpt, szTimecode);", "\t\t\tgf_isom_sample_del(&sample);\n\t\t\tfprintf(stderr, \"\\tFirst timecode: %s\\n\", szTimecode);\n\t\t}\n\t} else {\n\t\tGF_GenericSampleDescription *udesc;", "\t\tudesc = gf_isom_get_generic_sample_description(file, trackNum, 1);\n\t\tif (udesc) {\n\t\t\tif (gf_isom_is_video_handler_type(mtype) ) {\n fprintf(stderr, \"%s - Compressor \\\"%s\\\" - Resolution %d x %d\\n\",\n\t\t\t\t\t\t( (mtype == GF_ISOM_MEDIA_VISUAL ? \"Visual\" : \"Auxiliary Video\") ),\n udesc->compressor_name, udesc->width, udesc->height);\n\t\t\t} else if (mtype==GF_ISOM_MEDIA_AUDIO) {\n\t\t\t\tfprintf(stderr, \"Audio - Sample Rate %d - %d channel(s)\\n\", udesc->samplerate, udesc->nb_channels);\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"Unknown media type\\n\");\n\t\t\t}\n\t\t\tif (udesc->vendor_code)\n\t\t\t\tfprintf(stderr, \"\\tVendor code \\\"%s\\\" - Version %d - revision %d\\n\", gf_4cc_to_str(udesc->vendor_code), udesc->version, udesc->revision);", "\t\t\tif (udesc->extension_buf) {\n\t\t\t\tfprintf(stderr, \"\\tCodec configuration data size: %d bytes\\n\", udesc->extension_buf_size);\n\t\t\t\tgf_free(udesc->extension_buf);\n\t\t\t}\n\t\t\tgf_free(udesc);\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown track type\\n\");\n\t\t}\n\t}", "\n\t/*Crypto info*/\n\tif (gf_isom_is_track_encrypted(file, trackNum)) {\n\t\tconst char *scheme_URI, *KMS_URI;\n\t\tu32 scheme_type, version;\n\t\tu32 IV_size;\n\t\tBool use_sel_enc;", "\t\tif (gf_isom_is_ismacryp_media(file, trackNum, 1)) {\n\t\t\tgf_isom_get_ismacryp_info(file, trackNum, 1, NULL, &scheme_type, &version, &scheme_URI, &KMS_URI, &use_sel_enc, &IV_size, NULL);\n\t\t\tfprintf(stderr, \"\\n\\tProtected by ISMA E&A scheme %s (version %d)\\n\", gf_4cc_to_str(scheme_type), version);\n\t\t\tif (scheme_URI) fprintf(stderr, \"scheme location: %s\\n\", scheme_URI);\n\t\t\tif (KMS_URI) {\n\t\t\t\tif (!strnicmp(KMS_URI, \"(key)\", 5)) fprintf(stderr, \"\\tKMS location: key in file\\n\");\n\t\t\t\telse fprintf(stderr, \"\\tKMS location: %s\\n\", KMS_URI);\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\tSelective Encryption: %s\\n\", use_sel_enc ? \"Yes\" : \"No\");\n\t\t\tif (IV_size) fprintf(stderr, \"\\tInitialization Vector size: %d bits\\n\", IV_size*8);\n\t\t} else if (gf_isom_is_omadrm_media(file, trackNum, 1)) {\n\t\t\tconst char *textHdrs;\n\t\t\tu32 enc_type, hdr_len;\n\t\t\tu64 orig_len;\n\t\t\tgf_isom_get_omadrm_info(file, trackNum, 1, NULL, &scheme_type, &version, &scheme_URI, &KMS_URI, &textHdrs, &hdr_len, &orig_len, &enc_type, &use_sel_enc, &IV_size, NULL);\n\t\t\tfprintf(stderr, \"\\n\\tProtected by OMA DRM scheme %s (version %d)\\n\", gf_4cc_to_str(scheme_type), version);\n\t\t\tfprintf(stderr, \"\\tRights Issuer: %s\\n\", KMS_URI);\n\t\t\tfprintf(stderr, \"\\tContent ID: %s\\n\", scheme_URI);\n\t\t\tif (textHdrs) {\n\t\t\t\tu32 offset;\n\t\t\t\tconst char *start = textHdrs;\n\t\t\t\tfprintf(stderr, \"\\tOMA Textual Headers:\\n\");\n\t\t\t\ti=0;\n\t\t\t\toffset=0;\n\t\t\t\twhile (i<hdr_len) {\n\t\t\t\t\tif (start[i]==0) {\n\t\t\t\t\t\tfprintf(stderr, \"\\t\\t%s\\n\", start+offset);\n\t\t\t\t\t\toffset=i+1;\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \"\\\\tt%s\\n\", start+offset);\n\t\t\t}\n\t\t\tif (orig_len) fprintf(stderr, \"\\tOriginal media size \"LLD\"\\n\", orig_len);\n\t\t\tfprintf(stderr, \"\\tEncryption algorithm %s\\n\", (enc_type==1) ? \"AEA 128 CBC\" : (enc_type ? \"AEA 128 CTR\" : \"None\"));\n\t\t\tfprintf(stderr, \"\\tSelective Encryption: %s\\n\", use_sel_enc ? \"Yes\" : \"No\");\n\t\t\tif (IV_size) fprintf(stderr, \"\\tInitialization Vector size: %d bits\\n\", IV_size*8);\n\t\t} else if(gf_isom_is_cenc_media(file, trackNum, 1)) {\n\t\t\tconst u8 *def_key;\n\t\t\tu32 def_key_size;\n\t\t\tBool IsEncrypted;\n\t\t\tu8 crypt_byte_block, skip_byte_block;\n\t\t\tIV_size = 0;\n\t\t\tgf_isom_get_cenc_info(file, trackNum, 1, NULL, &scheme_type, &version);", "\t\t\tgf_isom_cenc_get_default_info(file, trackNum, 1, NULL, &IsEncrypted, &crypt_byte_block, &skip_byte_block, &def_key, &def_key_size);", "\t\t\tfprintf(stderr, \"\\n\\tProtected by CENC scheme %s version 0x%08X\", gf_4cc_to_str(scheme_type), version);", "\t\t\tif (crypt_byte_block && skip_byte_block)\n\t\t\t\tfprintf(stderr, \" - Pattern %d:%d\", (u32) skip_byte_block, (u32) crypt_byte_block);\n\t\t\tif (def_key && def_key[0])\n\t\t\t\tfprintf(stderr, \" - MultiKey\");", "\t\t\tfprintf(stderr, \"\\n\");\n\t\t\tdump_key_info(def_key, def_key_size, IsEncrypted);", "\t\t} else if(gf_isom_is_adobe_protection_media(file, trackNum, 1)) {\n\t\t\tgf_isom_get_adobe_protection_info(file, trackNum, 1, NULL, &scheme_type, &version, NULL);\n\t\t\tfprintf(stderr, \"\\nProtected by Adobe scheme %s (version %d)\\n\", gf_4cc_to_str(scheme_type), version);\n\t\t} else {\n\t\t\tfprintf(stderr, \"\\nProtected by unknown scheme %s\\n\", gf_4cc_to_str(gf_isom_is_media_encrypted(file, trackNum, 0) ));\n\t\t}\n\t\tfprintf(stderr, \"\\n\");\n\t}", "\tif ( gf_media_get_rfc_6381_codec_name(file, trackNum, szCodec, GF_FALSE, GF_FALSE) == GF_OK) {\n\t\tfprintf(stderr, \"\\tRFC6381 Codec Parameters: %s\\n\", szCodec);\n\t}", "\n\tDumpMetaItem(file, 0, trackNum, \"\\tTrack Meta\");", "\tgf_isom_get_track_switch_group_count(file, trackNum, &alt_group, &nb_groups);\n\tif (alt_group) {\n\t\tfprintf(stderr, \"Alternate Group ID %d\\n\", alt_group);\n\t\tfor (i=0; i<nb_groups; i++) {\n\t\t\tu32 nb_crit, switchGroupID;\n\t\t\tconst u32 *criterias = gf_isom_get_track_switch_parameter(file, trackNum, i+1, &switchGroupID, &nb_crit);\n\t\t\tif (!nb_crit) {\n\t\t\t\tfprintf(stderr, \"\\tNo criteria in %s group\\n\", switchGroupID ? \"switch\" : \"alternate\");\n\t\t\t} else {\n\t\t\t\tif (switchGroupID) {\n\t\t\t\t\tfprintf(stderr, \"\\tSwitchGroup ID %d criterias: \", switchGroupID);\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(stderr, \"\\tAlternate Group criterias: \");\n\t\t\t\t}\n\t\t\t\tfor (j=0; j<nb_crit; j++) {\n\t\t\t\t\tif (j) fprintf(stderr, \" \");\n\t\t\t\t\tfprintf(stderr, \"%s\", gf_4cc_to_str(criterias[j]) );\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t}\n\t\t}\n\t}", "\tswitch (gf_isom_has_sync_points(file, trackNum)) {\n\tcase 0:\n\t\tfprintf(stderr, \"\\tAll samples are sync\\n\");\n\t\tbreak;\n\tcase 1:\n\t{\n\t\tu32 nb_sync = gf_isom_get_sync_point_count(file, trackNum) - 1;\n\t\tif (! nb_sync) {\n\t\t\tfprintf(stderr, \"\\tOnly one sync sample\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"\\tAverage GOP length: %d samples\\n\", gf_isom_get_sample_count(file, trackNum) / nb_sync);\n\t\t}\n\t}\n\tbreak;\n\tcase 2:\n\t\tfprintf(stderr, \"\\tNo sync sample found\\n\");\n\t\tbreak;\n\t}\n\tfprintf(stderr, \"\\tMax sample duration: %d / %d\\n\", gf_isom_get_max_sample_delta(file, trackNum), timescale);", "\tif (!full_dump) {\n\t\tfprintf(stderr, \"\\n\");\n\t\treturn;\n\t}", "\tdur = size = 0;\n\tmax_rate = rate = 0;\n\ttime_slice = 0;\n\tts = gf_isom_get_media_timescale(file, trackNum);\n\tcsize = gf_isom_get_constant_sample_size(file, trackNum);\n\tcdur = gf_isom_get_constant_sample_duration(file, trackNum);\n\tcount = gf_isom_get_sample_count(file, trackNum);\n\tif (csize && cdur) {\n\t\tsize = count * csize;\n\t\tdur = cdur * count;\n\t} else {", "\t\tfor (j=0; j<count; j++) {\n\t\t\tGF_ISOSample *samp;\n\t\t\tif (is_od_track) {\n\t\t\t\tsamp = gf_isom_get_sample(file, trackNum, j+1, NULL);\n\t\t\t} else {\n\t\t\t\tsamp = gf_isom_get_sample_info(file, trackNum, j+1, NULL, NULL);\n\t\t\t}\n\t\t\tif (!samp) {\n\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to fetch sample %d\\n\", j+1));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdur = samp->DTS+samp->CTS_Offset;\n\t\t\tsize += samp->dataLength;\n\t\t\trate += samp->dataLength;\n\t\t\tif (samp->DTS - time_slice > ts) {\n\t\t\t\tDouble max_tmp = rate * ts / (samp->DTS - time_slice);\n\t\t\t\tif (max_rate < max_tmp )\n\t\t\t\t\tmax_rate = max_tmp;", "\t\t\t\trate = 0;\n\t\t\t\ttime_slice = samp->DTS;\n\t\t\t}\n\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t}\n\tfprintf(stderr, \"\\nComputed info from media:\\n\");\n\tif (csize && cdur) {\n\t\tfprintf(stderr, \"\\tConstant sample size %d bytes and dur %d / %d\\n\", csize, cdur, ts);\n\t}\n\tscale = 1000.0 / ts;\n\tdur = (u64) (scale * dur);\n\tfprintf(stderr, \"\\tTotal size \"LLU\" bytes - Total samples duration \"LLU\" ms\\n\", size, dur);\n\tif (!dur) {\n\t\tfprintf(stderr, \"\\n\");\n\t\treturn;\n\t}\n\t/*rate in byte, dur is in ms*/\n\trate = 8000.0 * size / dur;", "\tif (!max_rate)\n\t\tmax_rate = rate;\n\telse\n\t\tmax_rate *= 8.0;", "\tif (rate >= 1500) {\n\t\tfprintf(stderr, \"\\tAverage rate %.2f kbps - Max Rate %.2f kbps\\n\", rate/1000, max_rate/1000);\n\t} else {\n\t\tfprintf(stderr, \"\\tAverage rate %.2f bps - Max Rate %.2f bps\\n\", rate, max_rate);\n\t}", "\t{\n\t\tu32 dmin, dmax, davg, smin, smax, savg;\n\t\tgf_isom_get_chunks_infos(file, trackNum, &dmin, &davg, &dmax, &smin, &savg, &smax);\n\t\tfprintf(stderr, \"\\tChunk durations: min %d ms - max %d ms - average %d ms\\n\", (1000*dmin)/ts, (1000*dmax)/ts, (1000*davg)/ts);\n\t\tfprintf(stderr, \"\\tChunk sizes (bytes): min %d - max %d - average %d\\n\", smin, smax, savg);\n\t}\n\tfprintf(stderr, \"\\n\");", "\tcount = gf_isom_get_chapter_count(file, trackNum);\n\tif (count) {\n\t\tconst char *name;\n\t\tu64 time;\n\t\tfprintf(stderr, \"\\nChapters:\\n\");\n\t\tfor (j=0; j<count; j++) {\n\t\t\tgf_isom_get_chapter(file, trackNum, j+1, &time, &name);\n\t\t\tfprintf(stderr, \"\\tChapter #%d - %s - \\\"%s\\\"\\n\", j+1, format_duration(time, 1000, szDur), name);\n\t\t}\n\t}\n}", "void DumpMovieInfo(GF_ISOFile *file)\n{\n\tGF_InitialObjectDescriptor *iod;\n\tBool dump_m4sys = GF_FALSE;\n\tu32 i, brand, min, timescale, count, data_len;\n\tconst u8 *data;\n\tu64 create, modif;\n\tBool has_itags = GF_FALSE;\n\tchar szDur[50];", "\tDumpMetaItem(file, 1, 0, \"# File Meta\");\n\tif (!gf_isom_has_movie(file)) {\n\t\tif (gf_isom_has_segment(file, &brand, &min)) {\n\t\t\tcount = gf_isom_segment_get_fragment_count(file);\n\t\t\tfprintf(stderr, \"File is a segment - %d movie fragments - Brand %s (version %d):\\n\", count, gf_4cc_to_str(brand), min);\n\t\t\tfor (i=0; i<count; i++) {\n\t\t\t\tu32 j, traf_count = gf_isom_segment_get_track_fragment_count(file, i+1);\n\t\t\t\tfor (j=0; j<traf_count; j++) {\n\t\t\t\t\tu32 ID;\n\t\t\t\t\tu64 tfdt;\n\t\t\t\t\tID = gf_isom_segment_get_track_fragment_decode_time(file, i+1, j+1, &tfdt);\n\t\t\t\t\tfprintf(stderr, \"\\tFragment #%d Track ID %d - TFDT \"LLU\"\\n\", i+1, ID, tfdt);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfprintf(stderr, \"File has no movie (moov) - static data container\\n\");\n\t\t}\n\t\treturn;\n\t}", "\ttimescale = gf_isom_get_timescale(file);\n\ti=gf_isom_get_track_count(file);\n\tfprintf(stderr, \"# Movie Info - %d track%s - TimeScale %d\\n\", i, i>1 ? \"s\" : \"\", timescale);", "\tmodif = gf_isom_get_duration(file);\n\tcreate = gf_isom_get_original_duration(file);\n\tfprintf(stderr, \"Duration %s\", format_duration(create, timescale, szDur));\n\tif (create!=modif) {\n\t\tfprintf(stderr, \" (recomputed %s)\", format_duration(modif, timescale, szDur));\n\t}\n\tfprintf(stderr, \"\\n\");", "#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\tif (gf_isom_is_fragmented(file)) {\n\t\tfprintf(stderr, \"Fragmented: yes - duration %s\\n%d fragments - %d SegmentIndexes\\n\", format_duration(gf_isom_get_fragmented_duration(file), timescale, szDur), gf_isom_get_fragments_count(file, 0) , gf_isom_get_fragments_count(file, 1) );\n\t} else {\n\t\tfprintf(stderr, \"Fragmented: no\\n\");\n\t}\n#endif", "\tif (gf_isom_moov_first(file))\n\t\tfprintf(stderr, \"Progressive (moov before mdat)\\n\");", "\tif (gf_isom_get_brand_info(file, &brand, &min, &count) == GF_OK) {\n\t\tfprintf(stderr, \"Major Brand %s - version %d - compatible brands:\", gf_4cc_to_str(brand), min);\n\t\tfor (i=0; i<count;i++) {\n\t\t\tif (gf_isom_get_alternate_brand(file, i+1, &brand)==GF_OK)\n\t\t\t\tfprintf(stderr, \" %s\", gf_4cc_to_str(brand) );\n\t\t}\n\t\tfprintf(stderr, \"\\n\");\n\t}\n\tgf_isom_get_creation_time(file, &create, &modif);\n\tfprintf(stderr, \"Created: %s\", format_date(create, szDur));\n\tif (create != modif)\n\t\tfprintf(stderr, \"Modified: %s\", format_date(modif, szDur));\n\tfprintf(stderr, \"\\n\");", "\tDumpMetaItem(file, 0, 0, \"# Movie Meta\");", "\tiod = (GF_InitialObjectDescriptor *) gf_isom_get_root_od(file);\n\tif (iod) {\n\t\tu32 desc_size = gf_odf_desc_size((GF_Descriptor *)iod);\n\t\tif (iod->tag == GF_ODF_IOD_TAG) {\n\t\t\tfprintf(stderr, \"File has root IOD (%d bytes)\\n\", desc_size);\n\t\t\tfprintf(stderr, \"Scene PL 0x%02x - Graphics PL 0x%02x - OD PL 0x%02x\\n\", iod->scene_profileAndLevel, iod->graphics_profileAndLevel, iod->OD_profileAndLevel);\n\t\t\tfprintf(stderr, \"Visual PL: %s (0x%02x)\\n\", gf_m4v_get_profile_name(iod->visual_profileAndLevel), iod->visual_profileAndLevel);\n\t\t\tfprintf(stderr, \"Audio PL: %s (0x%02x)\\n\", gf_m4a_get_profile_name(iod->audio_profileAndLevel), iod->audio_profileAndLevel);\n\t\t\t//fprintf(stderr, \"inline profiles included %s\\n\", iod->inlineProfileFlag ? \"yes\" : \"no\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"File has root OD (%d bytes)\\n\", desc_size);\n\t\t}\n\t\tif (!gf_list_count(iod->ESDescriptors))\n\t\t\tfprintf(stderr, \"No streams included in root OD\\n\");\n\t\telse\n\t\t\tdump_m4sys = GF_TRUE;", "\t\tgf_odf_desc_del((GF_Descriptor *) iod);\n\t}\n\tif (gf_isom_is_JPEG2000(file)) fprintf(stderr, \"File is JPEG 2000\\n\");", "\tcount = gf_isom_get_copyright_count(file);\n\tif (count) {\n\t\tconst char *lang, *note;\n\t\tfprintf(stderr, \"\\nCopyrights:\\n\");\n\t\tfor (i=0; i<count; i++) {\n\t\t\tgf_isom_get_copyright(file, i+1, &lang, &note);\n\t\t\tfprintf(stderr, \"\\t(%s) %s\\n\", lang, note);\n\t\t}\n\t}", "\tcount = gf_isom_get_chapter_count(file, 0);\n\tif (count) {\n\t\tconst char *name;\n\t\tu64 time;\n\t\tfprintf(stderr, \"\\nChapters:\\n\");\n\t\tfor (i=0; i<count; i++) {\n\t\t\tgf_isom_get_chapter(file, 0, i+1, &time, &name);\n\t\t\tfprintf(stderr, \"\\tChapter #%d - %s - \\\"%s\\\"\\n\", i+1, format_duration(time, 1000, szDur), name);\n\t\t}\n\t}", "\tif (gf_isom_apple_get_tag(file, 0, &data, &data_len) == GF_OK) {\n\t\thas_itags = GF_TRUE;\n\t\tfprintf(stderr, \"\\niTunes Info:\\n\");", "\t\ti=0;\n\t\twhile (1) {\n\t\t\tu32 int_val2, flags, itype;\n\t\t\tGF_ISOiTunesTag tag;\n\t\t\tu64 int_val;\n\t\t\ts32 tag_idx;\n\t\t\tGF_Err e = gf_isom_apple_enum_tag(file, i, &tag, &data, &data_len, &int_val, &int_val2, &flags);\n\t\t\tif (e) break;\n\t\t\ti++;", "\t\t\ttag_idx = gf_itags_find_by_itag(tag);\n\t\t\tif (tag_idx<0) {\n\t\t\t\tfprintf(stderr, \"\\t%s: %s\\n\", gf_4cc_to_str(tag), data);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\t%s: \", gf_itags_get_name(tag_idx) );\n\t\t\titype = gf_itags_get_type(tag_idx);\n\t\t\tswitch (itype) {\n\t\t\tcase GF_ITAG_BOOL: fprintf(stderr, int_val ? \"yes\" : \"no\"); break;\n\t\t\tcase GF_ITAG_INT8:\n\t\t\tcase GF_ITAG_INT16:\n\t\t\tcase GF_ITAG_INT32:\n\t\t\tcase GF_ITAG_INT64:\n\t\t\t\tfprintf(stderr, LLU, int_val);\n\t\t\t\tbreak;\n\t\t\tcase GF_ITAG_FRAC6:\n\t\t\tcase GF_ITAG_FRAC8:\n\t\t\t\tfprintf(stderr, LLU\" / %u\", int_val, int_val2);\n\t\t\t\tbreak;\n\t\t\tcase GF_ITAG_FILE:\n\t\t\t\tif (flags==14) fprintf(stderr, \"PNG File\");\n\t\t\t\telse if (flags==13) fprintf(stderr, \"JPEG File\");\n\t\t\t\telse fprintf(stderr, \"unknown (flags %d)\", flags);\n\t\t\t\tbreak;\n\t\t\tcase GF_ITAG_ID3_GENRE:\n\t\t\t\tif (int_val) {\n\t\t\t\t\tfprintf(stderr, \"%s\", gf_id3_get_genre((u32) int_val) );\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t//fallthrough\n\t\t\tdefault:\n\t\t\t\tif (data)\n\t\t\t\t\tfprintf(stderr, \"%s\", data);\n\t\t\t\telse\n\t\t\t\t\tfprintf(stderr, data_len ? \"none\" : \"unknown\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t}\n\t}\n\ti=0;\n\twhile (1) {\n\t\tu32 type, version;\n\t\tchar *wmatag;\n\t\tGF_Err e = gf_isom_wma_enum_tag(file, i, &wmatag, &data, &data_len, &version, &type);\n\t\tif (e) break;\n\t\tif (!i) {\n\t\t\tfprintf(stderr, \"\\nWMA Info:\\n\");\n\t\t}\n\t\ti++;\n\t\tfprintf(stderr, \"\\t%s\", wmatag);\n\t\tif (version!=1)\n\t\t\tfprintf(stderr, \" (version %d)\", version);\n\t\tfprintf(stderr, \": \");", "\t\tif (type) {\n\t\t\tfprintf(stderr, \"unknown type %d\\n\", type);\n\t\t} else {\n\t\t\tu16 *src_str = (u16 *) data;\n\t\t\tu32 len = (u32) ( UTF8_MAX_BYTES_PER_CHAR * gf_utf8_wcslen(src_str) );\n\t\t\tchar *utf8str = (char *)gf_malloc(len + 1);\n\t\t\tu32 res_len = (u32) gf_utf8_wcstombs(utf8str, len, (const unsigned short **) &src_str);\n\t\t\tutf8str[res_len] = 0;\n\t\t\tfprintf(stderr, \"%s\\n\", utf8str);", "\t\t\tgf_free(utf8str);\n\t\t}\n\t}", "\n\tprint_udta(file, 0, has_itags);\n\tfprintf(stderr, \"\\n\");\n\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\tDumpTrackInfo(file, i+1, 0, GF_TRUE, dump_m4sys);\n\t}\n}", "#endif /*defined(GPAC_DISABLE_ISOM) || defined(GPAC_DISABLE_ISOM_WRITE)*/", "\n#ifndef GPAC_DISABLE_MPEG2TS", "\ntypedef struct\n{\n\t/* when writing to file */\n\tFILE *pes_out;\n\tchar dump[100];\n#if 0\n\tFILE *pes_out_nhml;\n\tchar nhml[100];\n\tFILE *pes_out_info;\n\tchar info[100];\n#endif\n\tBool is_info_dumped;", "\tu32 prog_number;\n\t/* For logging timing information (PCR, PTS/DTS) */\n\tFILE *timestamps_info_file;\n\tchar timestamps_info_name[100];", "\t/* when dumping TS information */\n\tu32 dump_pid;\n\tBool has_seen_pat;", "} GF_M2TS_Dump;", "", "static void on_m2ts_dump_event(GF_M2TS_Demuxer *ts, u32 evt_type, void *par)\n{\n\tu32 i, count;\n\tGF_M2TS_Program *prog;\n\tGF_M2TS_PES_PCK *pck;\n\tGF_M2TS_Dump *dumper = (GF_M2TS_Dump *)ts->user;", "\tswitch (evt_type) {\n\tcase GF_M2TS_EVT_PAT_FOUND:\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, 0);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_PAT_UPDATE:\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, 0);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_PAT_REPEAT:\n\t\t/* WARNING: We detect the pat on a repetition, probably to ensure that we also have seen all the PMT\n\t\t To be checked */\n\t\tdumper->has_seen_pat = 1;\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, 0);\n\t\t}\n//\t\tfprintf(stderr, \"Repeated PAT found - %d programs\\n\", gf_list_count(ts->programs) );\n\t\tbreak;\n\tcase GF_M2TS_EVT_CAT_FOUND:\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, 0);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_CAT_UPDATE:\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, 0);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_CAT_REPEAT:\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, 0);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_PMT_FOUND:\n\t\tprog = (GF_M2TS_Program*)par;\n\t\tif (gf_list_count(ts->programs)>1 && prog->number!=dumper->prog_number)\n\t\t\tbreak;", "\t\tcount = gf_list_count(prog->streams);", "\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"Program number %d found - %d streams:\\n\", prog->number, count));\n\t\tfor (i=0; i<count; i++) {\n\t\t\tGF_M2TS_ES *es = gf_list_get(prog->streams, i);\n\t\t\tif (es->pid == prog->pmt_pid) {\n\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"\\tPID %d: Program Map Table\\n\", es->pid));\n\t\t\t} else {\n\t\t\t\tGF_M2TS_PES *pes = (GF_M2TS_PES *)es;\n\t\t\t\tgf_m2ts_set_pes_framing(pes, dumper->pes_out ? GF_M2TS_PES_FRAMING_RAW : GF_M2TS_PES_FRAMING_DEFAULT);\n\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"\\tPID %d: %s \", pes->pid, gf_m2ts_get_stream_name(pes->stream_type) ));\n\t\t\t\tif (pes->mpeg4_es_id) GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\" - MPEG-4 ES ID %d\", pes->mpeg4_es_id));\n\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"\\n\"));\n\t\t\t}\n\t\t}\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, prog->pmt_pid);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_PMT_UPDATE:\n\t\tprog = (GF_M2TS_Program*)par;\n\t\tif (gf_list_count(ts->programs)>1 && prog->number!=dumper->prog_number)\n\t\t\tbreak;\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, prog->pmt_pid);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_PMT_REPEAT:\n\t\tprog = (GF_M2TS_Program*)par;\n\t\tif (gf_list_count(ts->programs)>1 && prog->number!=dumper->prog_number)\n\t\t\tbreak;\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\n\", ts->pck_number, prog->pmt_pid);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_SDT_FOUND:\n#ifndef GPAC_DISABLE_LOG\n\t\tcount = gf_list_count(ts->SDTs) ;\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"Program Description found - %d desc:\\n\", count));\n\t\tfor (i=0; i<count; i++) {\n\t\t\tGF_M2TS_SDT *sdt = gf_list_get(ts->SDTs, i);\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"\\tServiceID %d - Provider %s - Name %s\\n\", sdt->service_id, sdt->provider, sdt->service));\n\t\t}\n#endif\n\t\tbreak;\n\tcase GF_M2TS_EVT_SDT_UPDATE:\n#ifndef GPAC_DISABLE_LOG\n\t\tcount = gf_list_count(ts->SDTs) ;\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"Program Description updated - %d desc\\n\", count));\n\t\tfor (i=0; i<count; i++) {\n\t\t\tGF_M2TS_SDT *sdt = gf_list_get(ts->SDTs, i);\n\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"\\tServiceID %d - Provider %s - Name %s\\n\", sdt->service_id, sdt->provider, sdt->service));\n\t\t}\n#endif\n\t\tbreak;\n\tcase GF_M2TS_EVT_SDT_REPEAT:\n\t\tbreak;\n\tcase GF_M2TS_EVT_PES_TIMING:\n\t\tpck = par;\n\t\tif (gf_list_count(ts->programs)>1 && pck->stream->program->number != dumper->prog_number)\n\t\t\tbreak;", "\t\tbreak;\n\tcase GF_M2TS_EVT_PES_PCK:\n\t\tpck = par;\n\t\tif (gf_list_count(ts->programs)>1 && pck->stream->program->number != dumper->prog_number)\n\t\t\tbreak;\n\t\tif (dumper->has_seen_pat) {", "\t\t\t/*We need the interpolated PCR for the pcrb, hence moved this calculus out, and saving the calculated value in index_info to put it in the pcrb*/\n\t\t\tGF_M2TS_PES *pes = pck->stream;\n\t\t\t/*FIXME : not used GF_M2TS_Program *prog = pes->program; */\n\t\t\t/* Interpolated PCR value for the TS packet containing the PES header start */\n\t\t\tu64 interpolated_pcr_value = 0;\n\t\t\tif (pes->last_pcr_value && pes->before_last_pcr_value_pck_number && pes->last_pcr_value > pes->before_last_pcr_value) {\n\t\t\t\tu32 delta_pcr_pck_num = pes->last_pcr_value_pck_number - pes->before_last_pcr_value_pck_number;\n\t\t\t\tu32 delta_pts_pcr_pck_num = pes->pes_start_packet_number - pes->last_pcr_value_pck_number;\n\t\t\t\tu64 delta_pcr_value = pes->last_pcr_value - pes->before_last_pcr_value;\n\t\t\t\tif ((pes->pes_start_packet_number > pes->last_pcr_value_pck_number)\n\t\t\t\t && (pes->last_pcr_value > pes->before_last_pcr_value)) {", "\t\t\t\t\tpes->last_pcr_value = pes->before_last_pcr_value;\n\t\t\t\t}\n\t\t\t\t/* we can compute the interpolated pcr value for the packet containing the PES header */\n\t\t\t\tinterpolated_pcr_value = pes->last_pcr_value + (u64)((delta_pcr_value*delta_pts_pcr_pck_num*1.0)/delta_pcr_pck_num);\n\t\t\t}", "\t\t\tif (dumper->timestamps_info_file) {\n\t\t\t\tDouble diff;\n\t\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\t\", pck->stream->pes_start_packet_number, pck->stream->pid);\n\t\t\t\tif (interpolated_pcr_value) fprintf(dumper->timestamps_info_file, \"%f\", interpolated_pcr_value/(300.0 * 90000));\n\t\t\t\tfprintf(dumper->timestamps_info_file, \"\\t\");\n\t\t\t\tif (pck->DTS) fprintf(dumper->timestamps_info_file, \"%f\", (pck->DTS / 90000.0));\n\t\t\t\tfprintf(dumper->timestamps_info_file, \"\\t%f\\t%d\\t%d\", pck->PTS / 90000.0, (pck->flags & GF_M2TS_PES_PCK_RAP) ? 1 : 0, (pck->flags & GF_M2TS_PES_PCK_DISCONTINUITY) ? 1 : 0);\n\t\t\t\tif (interpolated_pcr_value) {\n\t\t\t\t\tdiff = (pck->DTS ? pck->DTS : pck->PTS) / 90000.0;\n\t\t\t\t\tdiff -= pes->last_pcr_value / (300.0 * 90000);\n\t\t\t\t\tfprintf(dumper->timestamps_info_file, \"\\t%f\\n\", diff);\n\t\t\t\t\tif (diff<0) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_WARNING, (\"Warning: detected PTS/DTS value less than current PCR of %g sec\\n\", diff));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(dumper->timestamps_info_file, \"\\t\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\tif (dumper->has_seen_pat && dumper->pes_out && (dumper->dump_pid == pck->stream->pid)) {\n\t\t\tgf_fwrite(pck->data, pck->data_len, dumper->pes_out);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_PES_PCR:\n\t\tpck = par;\n\t\tif (gf_list_count(ts->programs)>1 && pck->stream->program->number != dumper->prog_number)\n\t\t\tbreak;\n\t\tif (dumper->timestamps_info_file) {\n\t\t\tfprintf(dumper->timestamps_info_file, \"%u\\t%d\\t%f\\t\\t\\t\\t%d\\n\", pck->stream->program->last_pcr_value_pck_number, pck->stream->pid, pck->PTS / (300*90000.0), (pck->flags & GF_M2TS_PES_PCK_DISCONTINUITY) ? 1 : 0);\n\t\t}\n\t\tbreak;\n\tcase GF_M2TS_EVT_SL_PCK:\n#if 0\n\t{\n\t\tGF_M2TS_SL_PCK *sl_pck = par;\n\t\tif (dumper->pes_out && (dumper->dump_pid == sl_pck->stream->pid)) {\n\t\t\tGF_SLHeader header;\n\t\t\tu32 header_len;\n\t\t\tif (sl_pck->stream->mpeg4_es_id) {\n\t\t\t\tGF_ESD *esd = ((GF_M2TS_PES*)sl_pck->stream)->esd;\n\t\t\t\tif (!dumper->is_info_dumped) {\n\t\t\t\t\tif (esd->decoderConfig->decoderSpecificInfo) gf_fwrite(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, dumper->pes_out_info);\n\t\t\t\t\tdumper->is_info_dumped = 1;\n\t\t\t\t\tfprintf(dumper->pes_out_nhml, \"<NHNTStream version=\\\"1.0\\\" \");\n\t\t\t\t\tfprintf(dumper->pes_out_nhml, \"timeScale=\\\"%d\\\" \", esd->slConfig->timestampResolution);\n\t\t\t\t\tfprintf(dumper->pes_out_nhml, \"streamType=\\\"%d\\\" \", esd->decoderConfig->streamType);\n\t\t\t\t\tfprintf(dumper->pes_out_nhml, \"objectTypeIndication=\\\"%d\\\" \", esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tif (esd->decoderConfig->decoderSpecificInfo) fprintf(dumper->pes_out_nhml, \"specificInfoFile=\\\"%s\\\" \", dumper->info);\n\t\t\t\t\tfprintf(dumper->pes_out_nhml, \"baseMediaFile=\\\"%s\\\" \", dumper->dump);\n\t\t\t\t\tfprintf(dumper->pes_out_nhml, \"inRootOD=\\\"yes\\\">\\n\");\n\t\t\t\t}\n\t\t\t\tgf_sl_depacketize(esd->slConfig, &header, sl_pck->data, sl_pck->data_len, &header_len);\n\t\t\t\tgf_fwrite(sl_pck->data+header_len, sl_pck->data_len-header_len, dumper->pes_out);\n\t\t\t\tfprintf(dumper->pes_out_nhml, \"<NHNTSample DTS=\\\"\"LLD\"\\\" dataLength=\\\"%d\\\" isRAP=\\\"%s\\\"/>\\n\", header.decodingTimeStamp, sl_pck->data_len-header_len, (header.randomAccessPointFlag?\"yes\":\"no\"));\n\t\t\t}\n\t\t}\n\t}\n#endif\n\tbreak;\n\t}\n}", "void dump_mpeg2_ts(char *mpeg2ts_file, char *out_name, Bool prog_num)\n{\n\tu8 data[188];\n\tGF_M2TS_Dump dumper;", "\tu32 size;\n\tu64 fsize, fdone;\n\tGF_M2TS_Demuxer *ts;\n\tFILE *src;", "\tif (!prog_num && !out_name) {\n\t\tfprintf(stderr, \"No program number nor output filename specified. No timestamp file will be generated.\");\n\t}", "\tsrc = gf_fopen(mpeg2ts_file, \"rb\");\n\tif (!src) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Cannot open %s: no such file\\n\", mpeg2ts_file));\n\t\treturn;\n\t}\n\tts = gf_m2ts_demux_new();\n\tts->on_event = on_m2ts_dump_event;\n\tts->notify_pes_timing = 1;\n\tmemset(&dumper, 0, sizeof(GF_M2TS_Dump));\n\tts->user = &dumper;\n\tdumper.prog_number = prog_num;", "\t/*PES dumping*/\n\tif (out_name) {\n\t\tchar *pid = strrchr(out_name, '#');\n\t\tif (pid) {\n\t\t\tdumper.dump_pid = atoi(pid+1);\n\t\t\tpid[0] = 0;\n\t\t\tsprintf(dumper.dump, \"%s_%d.raw\", out_name, dumper.dump_pid);\n\t\t\tdumper.pes_out = gf_fopen(dumper.dump, \"wb\");\n#if 0\n\t\t\tsprintf(dumper.nhml, \"%s_%d.nhml\", pes_out_name, dumper.dump_pid);\n\t\t\tdumper.pes_out_nhml = gf_fopen(dumper.nhml, \"wt\");\n\t\t\tsprintf(dumper.info, \"%s_%d.info\", pes_out_name, dumper.dump_pid);\n\t\t\tdumper.pes_out_info = gf_fopen(dumper.info, \"wb\");\n#endif\n\t\t\tpid[0] = '#';\n\t\t}\n\t}", "\tgf_fseek(src, 0, SEEK_END);\n\tfsize = gf_ftell(src);\n\tgf_fseek(src, 0, SEEK_SET);", "\t/* first loop to process all packets between two PAT, and assume all signaling was found between these 2 PATs */\n\twhile (!feof(src)) {\n\t\tsize = (u32) gf_fread(data, 188, src);\n\t\tif (size<188) break;", "\t\tgf_m2ts_process_data(ts, data, size);\n\t\tif (dumper.has_seen_pat) break;\n\t}\n\tdumper.has_seen_pat = GF_TRUE;", "\tif (!prog_num) {\n\t\tGF_M2TS_Program *p = gf_list_get(ts->programs, 0);\n\t\tif (p) prog_num = p->number;\n\t\tfprintf(stderr, \"No program number specified, defaulting to first program\\n\");\n\t}", "\tif (!prog_num && !out_name) {\n\t\tfprintf(stderr, \"No program number nor output filename specified. No timestamp file will be generated\\n\");\n\t}", "\tif (prog_num) {\n\t\tsprintf(dumper.timestamps_info_name, \"%s_prog_%d_timestamps.txt\", mpeg2ts_file, prog_num/*, mpeg2ts_file*/);\n\t\tdumper.timestamps_info_file = gf_fopen(dumper.timestamps_info_name, \"wt\");\n\t\tif (!dumper.timestamps_info_file) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Cannot open file %s\\n\", dumper.timestamps_info_name));\n\t\t\treturn;\n\t\t}\n\t\tfprintf(dumper.timestamps_info_file, \"PCK#\\tPID\\tPCR\\tDTS\\tPTS\\tRAP\\tDiscontinuity\\tDTS-PCR Diff\\n\");\n\t}", "\tgf_m2ts_reset_parsers(ts);\n\tgf_fseek(src, 0, SEEK_SET);\n\tfdone = 0;", "\twhile (!feof(src)) {\n\t\tsize = (u32) gf_fread(data, 188, src);\n\t\tif (size<188) break;", "\t\tgf_m2ts_process_data(ts, data, size);", "\t\tfdone += size;\n\t\tgf_set_progress(\"MPEG-2 TS Parsing\", fdone, fsize);\n\t}", "\tgf_fclose(src);\n\tgf_m2ts_demux_del(ts);\n\tif (dumper.pes_out) gf_fclose(dumper.pes_out);\n#if 0\n\tif (dumper.pes_out_nhml) {\n\t\tif (dumper.is_info_dumped) fprintf(dumper.pes_out_nhml, \"</NHNTStream>\\n\");\n\t\tgf_fclose(dumper.pes_out_nhml);\n\t\tgf_fclose(dumper.pes_out_info);\n\t}\n#endif\n\tif (dumper.timestamps_info_file) gf_fclose(dumper.timestamps_info_file);\n}", "#endif /*GPAC_DISABLE_MPEG2TS*/", "\n#include <gpac/download.h>\n#include <gpac/mpd.h>", "void get_file_callback(void *usr_cbk, GF_NETIO_Parameter *parameter)\n{\n\tif (parameter->msg_type==GF_NETIO_DATA_EXCHANGE) {\n\t\tu64 tot_size, done, max;\n\t\tu32 bps;\n\t\tgf_dm_sess_get_stats(parameter->sess, NULL, NULL, &tot_size, &done, &bps, NULL);\n\t\tif (tot_size) {\n\t\t\tmax = done;\n\t\t\tmax *= 100;\n\t\t\tmax /= tot_size;\n\t\t\tfprintf(stderr, \"download %02d %% at %05d kpbs\\r\", (u32) max, bps*8/1000);\n\t\t}\n\t}\n}", "static GF_DownloadSession *get_file(const char *url, GF_DownloadManager *dm, GF_Err *e)\n{\n\tGF_DownloadSession *sess;\n\tsess = gf_dm_sess_new(dm, url, GF_NETIO_SESSION_NOT_THREADED, get_file_callback, NULL, e);\n\tif (!sess) return NULL;\n\t*e = gf_dm_sess_process(sess);\n\tif (*e) {\n\t\tgf_dm_sess_del(sess);\n\t\treturn NULL;\n\t}\n\treturn sess;\n}", "static void revert_cache_file(char *item_path)\n{\n\tchar szPATH[GF_MAX_PATH];\n\tconst char *url;\n\tGF_Config *cached;", "\tif (!strstr(item_path, \"gpac_cache_\")) {\n\t\tfprintf(stderr, \"%s is not a gpac cache file\\n\", item_path);\n\t\treturn;\n\t}\n\tif (!strncmp(item_path, \"./\", 2) || !strncmp(item_path, \".\\\\\", 2))\n\t\t\titem_path += 2;", " \tstrcpy(szPATH, item_path);\n\tstrcat(szPATH, \".txt\");", "\tcached = gf_cfg_new(NULL, szPATH);\n\turl = gf_cfg_get_key(cached, \"cache\", \"url\");\n\tif (url) url = strstr(url, \"://\");\n\tif (url) {\n\t\tu32 i, len, dir_len=0, k=0;\n\t\tchar *sep;\n\t\tchar *dst_name;\n\t\tsep = strstr(item_path, \"gpac_cache_\");\n\t\tif (sep) {\n\t\t\tsep[0] = 0;\n\t\t\tdir_len = (u32) strlen(item_path);\n\t\t\tsep[0] = 'g';\n\t\t}\n\t\turl+=3;\n\t\tlen = (u32) strlen(url);\n\t\tdst_name = gf_malloc(len+dir_len+1);\n\t\tmemset(dst_name, 0, len+dir_len+1);", "\t\tstrncpy(dst_name, item_path, dir_len);\n\t\tk=dir_len;\n\t\tfor (i=0; i<len; i++) {\n\t\t\tdst_name[k] = url[i];\n\t\t\tif (dst_name[k]==':') dst_name[k]='_';\n\t\t\telse if (dst_name[k]=='/') {\n\t\t\t\tif (!gf_dir_exists(dst_name))\n\t\t\t\t\tgf_mkdir(dst_name);\n\t\t\t}\n\t\t\tk++;\n\t\t}\n\t\tif (gf_file_exists(item_path)) {\n\t\t\tgf_file_move(item_path, dst_name);\n\t\t}", "\t\tgf_free(dst_name);\n\t} else {\n\t\tM4_LOG(GF_LOG_ERROR, (\"Failed to reverse %s cache file\\n\", item_path));\n\t}\n\tgf_cfg_del(cached);\n\tgf_file_delete(szPATH);\n}", "GF_Err rip_mpd(const char *mpd_src, const char *output_dir)\n{\n\tGF_DownloadSession *sess;\n\tu32 i, connect_time, reply_time, download_time, req_hdr_size, rsp_hdr_size;\n\tGF_Err e;\n\tGF_DOMParser *mpd_parser=NULL;\n\tGF_MPD *mpd=NULL;\n\tGF_MPD_Period *period;\n\tGF_MPD_AdaptationSet *as;\n\tGF_MPD_Representation *rep;\n\tchar szName[GF_MAX_PATH];\n\tGF_DownloadManager *dm;", "\tif (output_dir) {\n\t\tchar *sep;\n\t\tstrcpy(szName, output_dir);\n\t\tsep = gf_file_basename(szName);\n\t\tif (sep) sep[0] = 0;\n\t\tgf_opts_set_key(\"temp\", \"cache\", szName);\n\t} else {\n\t\tgf_opts_set_key(\"temp\", \"cache\", \".\");\n\t}\n\tgf_opts_set_key(\"temp\", \"clean-cache\", \"true\");\n\tdm = gf_dm_new(NULL);", "/*\n\tchar *name = strrchr(mpd_src, '/');\n\tif (!name) name = strrchr(mpd_src, '\\\\');\n\tif (!name) name = \"manifest.mpd\";\n\telse name ++;", "\tif (strchr(name, '?') || strchr(name, '&')) name = \"manifest.mpd\";\n*/", "\tfprintf(stderr, \"Downloading %s\\n\", mpd_src);\n\tsess = get_file(mpd_src, dm, &e);\n\tif (!sess) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"Error downloading MPD file %s: %s\\n\", mpd_src, gf_error_to_string(e) ));\n\t\tgoto err_exit;\n\t}\n\tstrcpy(szName, gf_dm_sess_get_cache_name(sess) );\n\tgf_dm_sess_get_header_sizes_and_times(sess, &req_hdr_size, &rsp_hdr_size, &connect_time, &reply_time, &download_time);\n\tgf_dm_sess_del(sess);", "\tif (e) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"Error fetching MPD file %s: %s\\n\", mpd_src, gf_error_to_string(e)));\n\t\tgoto err_exit;\n\t}\n\telse {\n\t\tGF_LOG(GF_LOG_INFO, GF_LOG_APP, (\"Fetched file %s\\n\", mpd_src));\n\t}\n\tGF_LOG(GF_LOG_DEBUG, GF_LOG_APP, (\"GET Header size %d - Reply header size %d\\n\", req_hdr_size, rsp_hdr_size));\n\tGF_LOG(GF_LOG_DEBUG, GF_LOG_APP, (\"GET time: Connect Time %d - Reply Time %d - Download Time %d\\n\", connect_time, reply_time, download_time));", "\tmpd_parser = gf_xml_dom_new();\n\te = gf_xml_dom_parse(mpd_parser, szName, NULL, NULL);", "\tif (e != GF_OK) {\n\t\tgf_xml_dom_del(mpd_parser);\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"Error parsing MPD %s : %s\\n\", mpd_src, gf_error_to_string(e)));\n\t\treturn e;\n\t}\n\tmpd = gf_mpd_new();\n\te = gf_mpd_init_from_dom(gf_xml_dom_get_root(mpd_parser), mpd, mpd_src);\n\tgf_xml_dom_del(mpd_parser);\n\tmpd_parser=NULL;\n\tif (e) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"Error initializing MPD %s : %s\\n\", mpd_src, gf_error_to_string(e)));\n\t\tgoto err_exit;\n\t}\n\telse {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_APP, (\"MPD %s initialized: %s\\n\", szName, gf_error_to_string(e)));\n\t}", "\trevert_cache_file(szName);\n\tif (mpd->type==GF_MPD_TYPE_DYNAMIC) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"MPD rip is not supported on live sources\\n\"));\n\t\te = GF_NOT_SUPPORTED;\n\t\tgoto err_exit;\n\t}", "\ti=0;\n\twhile ((period = (GF_MPD_Period *) gf_list_enum(mpd->periods, &i))) {\n\t\tchar *initTemplate = NULL;\n\t\tBool segment_base = GF_FALSE;\n\t\tu32 j=0;", "\t\tif (period->segment_base) segment_base=GF_TRUE;", "\t\tif (period->segment_template && period->segment_template->initialization) {\n\t\t\tinitTemplate = period->segment_template->initialization;\n\t\t}", "\t\twhile ((as = gf_list_enum(period->adaptation_sets, &j))) {\n\t\t\tu32 k=0;\n\t\t\tif (!initTemplate && as->segment_template && as->segment_template->initialization) {\n\t\t\t\tinitTemplate = as->segment_template->initialization;\n\t\t\t}\n\t\t\tif (as->segment_base) segment_base=GF_TRUE;", "\t\t\twhile ((rep = gf_list_enum(as->representations, &k))) {\n\t\t\t\tu64 out_range_start, out_range_end, segment_duration;\n\t\t\t\tBool is_in_base_url;\n\t\t\t\tchar *seg_url;\n\t\t\t\tu32 seg_idx=0;\n\t\t\t\tif (rep->segment_template && rep->segment_template->initialization) {\n\t\t\t\t\tinitTemplate = rep->segment_template->initialization;\n\t\t\t\t} else if (k>1) {\n\t\t\t\t\tinitTemplate = NULL;\n\t\t\t\t}\n\t\t\t\tif (rep->segment_base) segment_base=GF_TRUE;", "\t\t\t\te = gf_mpd_resolve_url(mpd, rep, as, period, mpd_src, 0, GF_MPD_RESOLVE_URL_INIT, 0, 0, &seg_url, &out_range_start, &out_range_end, &segment_duration, &is_in_base_url, NULL, NULL, NULL);\n\t\t\t\tif (e) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"Error resolving init segment name : %s\\n\", gf_error_to_string(e)));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t//not a byte range, replace URL\n\t\t\t\tif (segment_base) {", "\t\t\t\t} else if (out_range_start || out_range_end || !seg_url) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"byte range rip not yet implemented\\n\"));\n\t\t\t\t\tif (seg_url) gf_free(seg_url);\n\t\t\t\t\te = GF_NOT_SUPPORTED;\n\t\t\t\t\tgoto err_exit;\n\t\t\t\t}", "\t\t\t\tfprintf(stderr, \"Downloading %s\\n\", seg_url);\n\t\t\t\tsess = get_file(seg_url, dm, &e);\n\t\t\t\tif (e) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"Error downloading init segment %s from MPD %s : %s\\n\", seg_url, mpd_src, gf_error_to_string(e)));\n\t\t\t\t\tgoto err_exit;\n\t\t\t\t}\n\t\t\t\trevert_cache_file((char *) gf_dm_sess_get_cache_name(sess) );\n\t\t\t\tgf_free(seg_url);\n\t\t\t\tgf_dm_sess_del(sess);", "\t\t\t\tif (segment_base) continue;", "\t\t\t\twhile (1) {\n\t\t\t\t\te = gf_mpd_resolve_url(mpd, rep, as, period, mpd_src, 0, GF_MPD_RESOLVE_URL_MEDIA, seg_idx, 0, &seg_url, &out_range_start, &out_range_end, &segment_duration, NULL, NULL, NULL, NULL);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tif (e<0) {\n\t\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"Error resolving segment name : %s\\n\", gf_error_to_string(e)));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}", "\t\t\t\t\tseg_idx++;", "\t\t\t\t\tif (out_range_start || out_range_end || !seg_url) {\n\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"byte range rip not yet implemented\\n\"));\n\t\t\t\t\t\tif (seg_url) gf_free(seg_url);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tfprintf(stderr, \"Downloading %s\\n\", seg_url);\n\t\t\t\t\tsess = get_file(seg_url, dm, &e);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tgf_free(seg_url);\n\t\t\t\t\t\tif (e != GF_URL_ERROR) {\n\t\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_APP, (\"Error downloading segment %s: %s\\n\", seg_url, gf_error_to_string(e)));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t//todo, properly detect end of dash representation\n\t\t\t\t\t\t\te = GF_OK;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\trevert_cache_file((char *) gf_dm_sess_get_cache_name(sess) );\n\t\t\t\t\tgf_free(seg_url);\n\t\t\t\t\tgf_dm_sess_del(sess);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "err_exit:\n\tif (mpd) gf_mpd_del(mpd);\n\tgf_dm_del(dm);\n\treturn e;\n}" ]
[ 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, 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, 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, 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, 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, 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, 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [2900], "buggy_code_start_loc": [2883], "filenames": ["applications/mp4box/filedump.c"], "fixing_code_end_loc": [2904], "fixing_code_start_loc": [2883], "message": "The DumpTrackInfo function in GPAC 1.0.1 allows attackers to cause a denial of service (NULL pointer dereference) via a crafted file in the MP4Box command.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gpac:gpac:1.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "82DD2D40-0A05-48FD-940D-32B4D8B51AB3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The DumpTrackInfo function in GPAC 1.0.1 allows attackers to cause a denial of service (NULL pointer dereference) via a crafted file in the MP4Box command."}, {"lang": "es", "value": "La funci\u00f3n DumpTrackInfo en GPAC versi\u00f3n 1.0.1, permite a atacantes causar una denegaci\u00f3n de servicio (desreferencia de puntero NULL) por medio de un archivo dise\u00f1ado en el comando MP4Box"}], "evaluatorComment": null, "id": "CVE-2021-32138", "lastModified": "2021-09-23T20:11:59.017", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-09-13T20:15:08.343", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gpac/gpac/commit/289ffce3e0d224d314f5f92a744d5fe35999f20b"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/gpac/gpac/issues/1767"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gpac/gpac/commit/289ffce3e0d224d314f5f92a744d5fe35999f20b"}, "type": "CWE-476"}
186
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * This Source Code Form is subject to the terms of the Mozilla Public License,\n * v. 2.0. If a copy of the MPL was not distributed with this file, You can\n * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under\n * the terms of the Healthcare Disclaimer located at http://openmrs.org/license.\n *\n * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS\n * graphic logo is a trademark of OpenMRS Inc.\n */\npackage org.openmrs.web.filter;", "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.nio.charset.StandardCharsets;", "", "import java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Properties;", "import javax.servlet.Filter;\nimport javax.servlet.FilterChain;\nimport javax.servlet.FilterConfig;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRequest;\nimport javax.servlet.ServletResponse;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;", "import org.apache.commons.lang3.ArrayUtils;\nimport org.apache.velocity.VelocityContext;\nimport org.apache.velocity.app.VelocityEngine;\nimport org.apache.velocity.runtime.RuntimeConstants;\nimport org.apache.velocity.runtime.log.CommonsLogLogChute;\nimport org.apache.velocity.tools.Scope;\nimport org.apache.velocity.tools.ToolContext;\nimport org.apache.velocity.tools.ToolManager;\nimport org.apache.velocity.tools.config.DefaultKey;\nimport org.apache.velocity.tools.config.FactoryConfiguration;\nimport org.apache.velocity.tools.config.ToolConfiguration;\nimport org.apache.velocity.tools.config.ToolboxConfiguration;\nimport org.codehaus.jackson.map.ObjectMapper;\nimport org.openmrs.OpenmrsCharacterEscapes;\nimport org.openmrs.api.APIException;\nimport org.openmrs.api.context.Context;\nimport org.openmrs.util.*;\nimport org.openmrs.web.WebConstants;\nimport org.openmrs.web.filter.initialization.InitializationFilter;\nimport org.openmrs.web.filter.update.UpdateFilter;\nimport org.openmrs.web.filter.util.FilterUtil;\nimport org.openmrs.web.filter.util.LocalizationTool;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;", "/**\n * Abstract class used when a small wizard is needed before Spring, jsp, etc has been started up.\n *\n * @see UpdateFilter\n * @see InitializationFilter\n */\npublic abstract class StartupFilter implements Filter {\n\t\n\tprivate static final Logger log = LoggerFactory.getLogger(StartupFilter.class);\n\t\n\tprotected static VelocityEngine velocityEngine = null;\n\t\n\tpublic static final String AUTO_RUN_OPENMRS = \"auto_run_openmrs\";\n\t\n\t/**\n\t * Set by the {@link #init(FilterConfig)} method so that we have access to the current\n\t * {@link ServletContext}\n\t */\n\tprotected FilterConfig filterConfig = null;\n\t\n\t/**\n\t * Records errors that will be displayed to the user\n\t */\n\tprotected Map<String, Object[]> errors = new HashMap<>();\n\t\n\t/**\n\t * Messages that will be displayed to the user\n\t */\n\tprotected Map<String, Object[]> msgs = new HashMap<>();\n\t\n\t/**\n\t * Used for configuring tools within velocity toolbox\n\t */\n\tprivate ToolContext toolContext = null;\n\t\n\t/**\n\t * The web.xml file sets this {@link StartupFilter} to be the first filter for all requests.\n\t *\n\t * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,\n\t * javax.servlet.FilterChain)\n\t */\n\t@Override\n\tpublic final void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)\n\t throws IOException, ServletException {\n\t\tif (skipFilter((HttpServletRequest) request)) {\n\t\t\tchain.doFilter(request, response);\n\t\t} else {\n\t\t\t\n\t\t\tHttpServletRequest httpRequest = (HttpServletRequest) request;\n\t\t\tHttpServletResponse httpResponse = (HttpServletResponse) response;\n\t\t\t\n\t\t\tString servletPath = httpRequest.getServletPath();\n\t\t\t// for all /images and /initfilter/scripts files, write the path\n\t\t\t// (the \"/initfilter\" part is needed so that the openmrs_static_context-servlet.xml file doesn't\n\t\t\t// get instantiated early, before the locale messages are all set up)\n\t\t\tif (servletPath.startsWith(\"/images\") || servletPath.startsWith(\"/initfilter/scripts\")) {", "\t\t\t\tservletPath = servletPath.replaceFirst(\"/initfilter\", \"/WEB-INF/view\"); // strip out the /initfilter part", "\t\t\t\t// writes the actual image file path to the response", "\t\t\t\tFile file = new File(filterConfig.getServletContext().getRealPath(servletPath));", "\t\t\t\tif (httpRequest.getPathInfo() != null) {", "\t\t\t\t\tfile = new File(file, httpRequest.getPathInfo());", "\t\t\t\t}\n\t\t\t\t", "\t\t\t\tInputStream imageFileInputStream = null;\n\t\t\t\ttry {\n\t\t\t\t\timageFileInputStream = new FileInputStream(file);", "\t\t\t\t\tOpenmrsUtil.copyFile(imageFileInputStream, httpResponse.getOutputStream());\n\t\t\t\t}\n\t\t\t\tcatch (FileNotFoundException e) {", "\t\t\t\t\tlog.error(\"Unable to find file: \" + file.getAbsolutePath());", "\t\t\t\t}", "\t\t\t\tfinally {\n\t\t\t\t\tif (imageFileInputStream != null) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\timageFileInputStream.close();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (IOException io) {\n\t\t\t\t\t\t\tlog.warn(\"Couldn't close imageFileInputStream: \" + io);\n\t\t\t\t\t\t}\n\t\t\t\t\t}", "\t\t\t\t}\n\t\t\t} else if (servletPath.startsWith(\"/scripts\")) {\n\t\t\t\tlog.error(\n\t\t\t\t \"Calling /scripts during the initializationfilter pages will cause the openmrs_static_context-servlet.xml to initialize too early and cause errors after startup. Use '/initfilter\"\n\t\t\t\t + servletPath + \"' instead.\");\n\t\t\t}\n\t\t\t// for anything but /initialsetup\n\t\t\telse if (!httpRequest.getServletPath().equals(\"/\" + WebConstants.SETUP_PAGE_URL)\n\t\t\t && !httpRequest.getServletPath().equals(\"/\" + AUTO_RUN_OPENMRS)) {\n\t\t\t\t// send the user to the setup page\n\t\t\t\thttpResponse.sendRedirect(\"/\" + WebConstants.WEBAPP_NAME + \"/\" + WebConstants.SETUP_PAGE_URL);\n\t\t\t} else {\n\t\t\t\t\n\t\t\t\tif (\"GET\".equals(httpRequest.getMethod())) {\n\t\t\t\t\tdoGet(httpRequest, httpResponse);\n\t\t\t\t} else if (\"POST\".equals(httpRequest.getMethod())) {\n\t\t\t\t\t// only clear errors before POSTS so that redirects can show errors too.\n\t\t\t\t\terrors.clear();\n\t\t\t\t\tmsgs.clear();\n\t\t\t\t\tdoPost(httpRequest, httpResponse);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Don't continue down the filter chain otherwise Spring complains\n\t\t\t// that it hasn't been set up yet.\n\t\t\t// The jsp and servlet filter are also on this chain, so writing to\n\t\t\t// the response directly here is the only option\n\t\t}\n\t}\n\t\n\t/**\n\t * Convenience method to set up the velocity context properly\n\t */\n\tprivate void initializeVelocity() {\n\t\tif (velocityEngine == null) {\n\t\t\tvelocityEngine = new VelocityEngine();\n\t\t\t\n\t\t\tProperties props = new Properties();\n\t\t\tprops.setProperty(RuntimeConstants.RUNTIME_LOG, \"startup_wizard_vel.log\");\n\t\t\t// Linux requires setting logging properties to initialize Velocity Context.\n\t\t\tprops.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,\n\t\t\t \"org.apache.velocity.runtime.log.CommonsLogLogChute\");\n\t\t\tprops.setProperty(CommonsLogLogChute.LOGCHUTE_COMMONS_LOG_NAME, \"initial_wizard_velocity\");\n\t\t\t\n\t\t\t// so the vm pages can import the header/footer\n\t\t\tprops.setProperty(RuntimeConstants.RESOURCE_LOADER, \"class\");\n\t\t\tprops.setProperty(\"class.resource.loader.description\", \"Velocity Classpath Resource Loader\");\n\t\t\tprops.setProperty(\"class.resource.loader.class\",\n\t\t\t \"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader\");\n\t\t\t\n\t\t\ttry {\n\t\t\t\tvelocityEngine.init(props);\n\t\t\t}\n\t\t\tcatch (Exception e) {", "\t\t\t\tlog.error(\"velocity init failed, because: \" + e);", "\t\t\t}\n\t\t}\n\t}\n\t\n\t/**\n\t * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on GET requests\n\t *\n\t * @param httpRequest\n\t * @param httpResponse\n\t */\n\tprotected abstract void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse)\n\t throws IOException, ServletException;\n\t\n\t/**\n\t * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on POST requests\n\t *\n\t * @param httpRequest\n\t * @param httpResponse\n\t */\n\tprotected abstract void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse)\n\t throws IOException, ServletException;\n\t\n\t/**\n\t * All private attributes on this class are returned to the template via the velocity context and\n\t * reflection\n\t *\n\t * @param templateName the name of the velocity file to render. This name is prepended with\n\t * {@link #getTemplatePrefix()}\n\t * @param referenceMap\n\t * @param httpResponse\n\t */\n\tprotected void renderTemplate(String templateName, Map<String, Object> referenceMap, HttpServletResponse httpResponse)\n\t throws IOException {\n\t\t// first we should get velocity tools context for current client request (within\n\t\t// his http session) and merge that tools context with basic velocity context\n\t\tif (referenceMap == null) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tObject locale = referenceMap.get(FilterUtil.LOCALE_ATTRIBUTE);\n\t\tToolContext velocityToolContext = getToolContext(\n\t\t locale != null ? locale.toString() : Context.getLocale().toString());\n\t\tVelocityContext velocityContext = new VelocityContext(velocityToolContext);\n\t\t\n\t\tfor (Map.Entry<String, Object> entry : referenceMap.entrySet()) {\n\t\t\tvelocityContext.put(entry.getKey(), entry.getValue());\n\t\t}\n\t\t\n\t\tObject model = getUpdateFilterModel();\n\t\t\n\t\t// put each of the private varibles into the template for convenience\n\t\tfor (Field field : model.getClass().getDeclaredFields()) {\n\t\t\ttry {\n\t\t\t\tfield.setAccessible(true);\n\t\t\t\tvelocityContext.put(field.getName(), field.get(model));\n\t\t\t}\n\t\t\tcatch (IllegalArgumentException | IllegalAccessException e) {\n\t\t\t\tlog.error(\"Error generated while getting field value: \" + field.getName(), e);\n\t\t\t}\n\t\t}\n\t\t\n\t\tString fullTemplatePath = getTemplatePrefix() + templateName;\n\t\tInputStream templateInputStream = getClass().getClassLoader().getResourceAsStream(fullTemplatePath);\n\t\tif (templateInputStream == null) {\n\t\t\tthrow new IOException(\"Unable to find \" + fullTemplatePath);\n\t\t}\n\t\t\n\t\tvelocityContext.put(\"errors\", errors);\n\t\tvelocityContext.put(\"msgs\", msgs);\n\t\t\n\t\t// explicitly set the content type for the response because some servlet containers are assuming text/plain\n\t\thttpResponse.setContentType(\"text/html\");\n\t\t\n\t\ttry {\n\t\t\tvelocityEngine.evaluate(velocityContext, httpResponse.getWriter(), this.getClass().getName(),\n\t\t\t new InputStreamReader(templateInputStream, StandardCharsets.UTF_8));\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tthrow new APIException(\"Unable to process template: \" + fullTemplatePath, e);\n\t\t}\n\t}\n\t\n\t/**\n\t * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)\n\t */\n\t@Override\n\tpublic void init(FilterConfig filterConfig) throws ServletException {\n\t\tthis.filterConfig = filterConfig;\n\t\tinitializeVelocity();\n\t}\n\t\n\t/**\n\t * @see javax.servlet.Filter#destroy()\n\t */\n\t@Override\n\tpublic void destroy() {\n\t}\n\t\n\t/**\n\t * This string is prepended to all templateNames passed to\n\t * {@link #renderTemplate(String, Map, HttpServletResponse)}\n\t *\n\t * @return string to prepend as the path for the templates\n\t */\n\tprotected String getTemplatePrefix() {\n\t\treturn \"org/openmrs/web/filter/\";\n\t}\n\t\n\t/**\n\t * The model that is used as the backer for all pages in this startup wizard. Should never return\n\t * null.\n\t *\n\t * @return the stored formbacking/model object\n\t */\n\tprotected abstract Object getUpdateFilterModel();\n\t\n\t/**\n\t * If this returns true, this filter fails early and quickly. All logic is skipped and startup and\n\t * usage continue normally.\n\t *\n\t * @return true if this filter can be skipped\n\t */\n\tpublic abstract boolean skipFilter(HttpServletRequest request);", "\t/**\n\t * Convenience method to read the last 5 log lines from the MemoryAppender\n\t * \n\t * The log lines will be added to the \"logLines\" key\n\t * \n\t * @param result A map to be returned as a JSON document\n\t */\n\tprotected void addLogLinesToResponse(Map<String, Object> result) {\n\t\tMemoryAppender appender = OpenmrsUtil.getMemoryAppender();\n\t\tif (appender != null) {\n\t\t\tList<String> logLines = appender.getLogLines();\n\t\t\t\n\t\t\t// truncate the list to the last five so we don't overwhelm jquery\n\t\t\tif (logLines.size() > 5) {\n\t\t\t\tlogLines = logLines.subList(logLines.size() - 5, logLines.size());\n\t\t\t}\n\t\t\t\n\t\t\tresult.put(\"logLines\", logLines);\n\t\t} else {\n\t\t\tresult.put(\"logLines\", Collections.emptyList());\n\t\t}\n\t}\n\t\n\t/**\n\t * Convenience method to convert the given object to a JSON string. Supports Maps, Lists, Strings,\n\t * Boolean, Double\n\t *\n\t * @param object object to convert to json\n\t * @return JSON string to be eval'd in javascript\n\t */\n\tprotected String toJSONString(Object object) {\n\t\tObjectMapper mapper = new ObjectMapper();\n\t\tmapper.getJsonFactory().setCharacterEscapes(new OpenmrsCharacterEscapes());\n\t\ttry {\n\t\t\treturn mapper.writeValueAsString(object);\n\t\t}\n\t\tcatch (IOException e) {\n\t\t\tlog.error(\"Failed to convert object to JSON\");\n\t\t\tthrow new APIException(e);\n\t\t}\n\t}\n\t\n\t/**\n\t * Gets tool context for specified locale parameter. If context does not exists, it creates new\n\t * context, configured for that locale. Otherwise, it changes locale property of\n\t * {@link LocalizationTool} object, that is being contained in tools context\n\t *\n\t * @param locale the string with locale parameter for configuring tools context\n\t * @return the tool context object\n\t */\n\tpublic ToolContext getToolContext(String locale) {\n\t\tLocale systemLocale = LocaleUtility.fromSpecification(locale);\n\t\t//Defaults to en if systemLocale is null or invalid e.g en_GBs\n\t\tif (systemLocale == null || !ArrayUtils.contains(Locale.getAvailableLocales(), systemLocale)) {\n\t\t\tsystemLocale = Locale.ENGLISH;\n\t\t}\n\t\t// If tool context has not been configured yet\n\t\tif (toolContext == null) {\n\t\t\t// first we are creating manager for tools, factory for configuring tools \n\t\t\t// and empty configuration object for velocity tool box\n\t\t\tToolManager velocityToolManager = new ToolManager();\n\t\t\tFactoryConfiguration factoryConfig = new FactoryConfiguration();\n\t\t\t// since we are using one tool box for all request within wizard\n\t\t\t// we should propagate toolbox's scope on all application \n\t\t\tToolboxConfiguration toolbox = new ToolboxConfiguration();\n\t\t\ttoolbox.setScope(Scope.APPLICATION);\n\t\t\t// next we are directly configuring custom localization tool by\n\t\t\t// setting its class name, locale property etc.\n\t\t\tToolConfiguration localizationTool = new ToolConfiguration();\n\t\t\tlocalizationTool.setClassname(LocalizationTool.class.getName());\n\t\t\tlocalizationTool.setProperty(ToolContext.LOCALE_KEY, systemLocale);\n\t\t\tlocalizationTool.setProperty(LocalizationTool.BUNDLES_KEY, \"messages\");\n\t\t\t// and finally we are adding just configured tool into toolbox\n\t\t\t// and creating tool context for this toolbox\n\t\t\ttoolbox.addTool(localizationTool);\n\t\t\tfactoryConfig.addToolbox(toolbox);\n\t\t\tvelocityToolManager.configure(factoryConfig);\n\t\t\ttoolContext = velocityToolManager.createContext();\n\t\t\ttoolContext.setUserCanOverwriteTools(true);\n\t\t} else {\n\t\t\t// if it already has been configured, we just pull out our custom localization tool \n\t\t\t// from tool context, then changing its locale property and putting this tool back to the context\n\t\t\t// First, we need to obtain the value of default key annotation of our localization tool\n\t\t\t// class using reflection\n\t\t\tAnnotation annotation = LocalizationTool.class.getAnnotation(DefaultKey.class);\n\t\t\tDefaultKey defaultKeyAnnotation = (DefaultKey) annotation;\n\t\t\tString key = defaultKeyAnnotation.value();\n\t\t\t//\n\t\t\tLocalizationTool localizationTool = (LocalizationTool) toolContext.get(key);\n\t\t\tlocalizationTool.setLocale(systemLocale);\n\t\t\ttoolContext.put(key, localizationTool);\n\t\t}\n\t\treturn toolContext;\n\t}\n}" ]
[ 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [197], "buggy_code_start_loc": [20], "filenames": ["web/src/main/java/org/openmrs/web/filter/StartupFilter.java"], "fixing_code_end_loc": [196], "fixing_code_start_loc": [21], "message": "OpenMRS is a patient-based medical record system focusing on giving providers a free customizable electronic medical record system. Affected versions are subject to arbitrary file exfiltration due to failure to sanitize request when satisfying GET requests for `/images` & `/initfilter/scripts`. This can allow an attacker to access any file on a system running OpenMRS that is accessible to the user id OpenMRS is running under. Affected implementations should update to the latest patch version of OpenMRS Core for the minor version they use. These are: 2.1.5, 2.2.1, 2.3.5, 2.4.5 and 2.5.3. As a general rule, this vulnerability is already mitigated by Tomcat's URL normalization in Tomcat 7.0.28+. Users on older versions of Tomcat should consider upgrading their Tomcat instance as well as their OpenMRS instance.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:openmrs:openmrs:*:*:*:*:*:*:*:*", "matchCriteriaId": "CC9D911E-1D03-4348-A3E8-42EF336C3CB1", "versionEndExcluding": "2.1.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.6", "vulnerable": true}, {"criteria": "cpe:2.3:a:openmrs:openmrs:*:*:*:*:*:*:*:*", "matchCriteriaId": "AB9FD95F-109C-46B6-9997-1467E85C2EA9", "versionEndExcluding": "2.2.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.2.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:openmrs:openmrs:*:*:*:*:*:*:*:*", "matchCriteriaId": "3CDFE507-8377-4B9E-A91E-4EAEB3893CAD", "versionEndExcluding": "2.3.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.3.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:openmrs:openmrs:*:*:*:*:*:*:*:*", "matchCriteriaId": "DE611740-A309-4E76-BFE2-A18978D9C50A", "versionEndExcluding": "2.4.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:openmrs:openmrs:*:*:*:*:*:*:*:*", "matchCriteriaId": "E69117E5-4694-44D3-8DC4-AE189857C002", "versionEndExcluding": "2.5.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.5.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "OpenMRS is a patient-based medical record system focusing on giving providers a free customizable electronic medical record system. Affected versions are subject to arbitrary file exfiltration due to failure to sanitize request when satisfying GET requests for `/images` & `/initfilter/scripts`. This can allow an attacker to access any file on a system running OpenMRS that is accessible to the user id OpenMRS is running under. Affected implementations should update to the latest patch version of OpenMRS Core for the minor version they use. These are: 2.1.5, 2.2.1, 2.3.5, 2.4.5 and 2.5.3. As a general rule, this vulnerability is already mitigated by Tomcat's URL normalization in Tomcat 7.0.28+. Users on older versions of Tomcat should consider upgrading their Tomcat instance as well as their OpenMRS instance."}, {"lang": "es", "value": "OpenMRS es un sistema de registro m\u00e9dico basado en el paciente que se centra en ofrecer a los proveedores un sistema de registro m\u00e9dico electr\u00f3nico gratuito y personalizable. Las versiones afectadas est\u00e1n sujetas a la exfiltraci\u00f3n arbitraria de archivos debido a un fallo en el saneo de la petici\u00f3n cuando son satisfechas peticiones GET para \"/images\" &amp; \"/initfilter/scripts\". Esto puede permitir a un atacante acceder a cualquier archivo en un sistema que ejecute OpenMRS que sea accesible para el ID de usuario con el que es ejecutado OpenMRS. Las implementaciones afectadas deben actualizar a la \u00faltima versi\u00f3n del parche de OpenMRS Core para la versi\u00f3n menor que usan. Estas son: 2.1.5, 2.2.1, 2.3.5, 2.4.5 y 2.5.3. Como regla general, esta vulnerabilidad ya est\u00e1 mitigada por la normalizaci\u00f3n de URL de Tomcat en Tomcat versi\u00f3n 7.0.28+. Los usuarios de versiones anteriores de Tomcat deber\u00edan considerar la posibilidad de actualizar su instancia de Tomcat, as\u00ed como su instancia de OpenMRS"}], "evaluatorComment": null, "id": "CVE-2022-23612", "lastModified": "2022-03-02T14:17:24.563", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-02-22T23:15:11.400", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openmrs/openmrs-core/blob/ee3373a7a775bfdfa263e2e912c72e64342fb4f0/web/src/main/java/org/openmrs/web/filter/StartupFilter.java#L123"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openmrs/openmrs-core/commit/db8454bf19a092a78d53ee4dba2af628b730a6e7#diff-7c64d9f61d4d4e2ddba92920d7cf63ec96091b308d43904956b3846bc0c26d80R128"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/openmrs/openmrs-core/security/advisories/GHSA-8rgr-ww69-jv65"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://lgtm.com/projects/g/openmrs/openmrs-core/snapshot/fb1335c925ca4c94be5a546707b90d2c1efa4dcc/files/web/src/main/java/org/openmrs/web/filter/StartupFilter.java#L123"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/openmrs/openmrs-core/commit/db8454bf19a092a78d53ee4dba2af628b730a6e7#diff-7c64d9f61d4d4e2ddba92920d7cf63ec96091b308d43904956b3846bc0c26d80R128"}, "type": "CWE-22"}
187
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * This Source Code Form is subject to the terms of the Mozilla Public License,\n * v. 2.0. If a copy of the MPL was not distributed with this file, You can\n * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under\n * the terms of the Healthcare Disclaimer located at http://openmrs.org/license.\n *\n * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS\n * graphic logo is a trademark of OpenMRS Inc.\n */\npackage org.openmrs.web.filter;", "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.nio.charset.StandardCharsets;", "import java.nio.file.Path;\nimport java.nio.file.Paths;", "import java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Properties;", "import javax.servlet.Filter;\nimport javax.servlet.FilterChain;\nimport javax.servlet.FilterConfig;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRequest;\nimport javax.servlet.ServletResponse;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;", "import org.apache.commons.lang3.ArrayUtils;\nimport org.apache.velocity.VelocityContext;\nimport org.apache.velocity.app.VelocityEngine;\nimport org.apache.velocity.runtime.RuntimeConstants;\nimport org.apache.velocity.runtime.log.CommonsLogLogChute;\nimport org.apache.velocity.tools.Scope;\nimport org.apache.velocity.tools.ToolContext;\nimport org.apache.velocity.tools.ToolManager;\nimport org.apache.velocity.tools.config.DefaultKey;\nimport org.apache.velocity.tools.config.FactoryConfiguration;\nimport org.apache.velocity.tools.config.ToolConfiguration;\nimport org.apache.velocity.tools.config.ToolboxConfiguration;\nimport org.codehaus.jackson.map.ObjectMapper;\nimport org.openmrs.OpenmrsCharacterEscapes;\nimport org.openmrs.api.APIException;\nimport org.openmrs.api.context.Context;\nimport org.openmrs.util.*;\nimport org.openmrs.web.WebConstants;\nimport org.openmrs.web.filter.initialization.InitializationFilter;\nimport org.openmrs.web.filter.update.UpdateFilter;\nimport org.openmrs.web.filter.util.FilterUtil;\nimport org.openmrs.web.filter.util.LocalizationTool;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;", "/**\n * Abstract class used when a small wizard is needed before Spring, jsp, etc has been started up.\n *\n * @see UpdateFilter\n * @see InitializationFilter\n */\npublic abstract class StartupFilter implements Filter {\n\t\n\tprivate static final Logger log = LoggerFactory.getLogger(StartupFilter.class);\n\t\n\tprotected static VelocityEngine velocityEngine = null;\n\t\n\tpublic static final String AUTO_RUN_OPENMRS = \"auto_run_openmrs\";\n\t\n\t/**\n\t * Set by the {@link #init(FilterConfig)} method so that we have access to the current\n\t * {@link ServletContext}\n\t */\n\tprotected FilterConfig filterConfig = null;\n\t\n\t/**\n\t * Records errors that will be displayed to the user\n\t */\n\tprotected Map<String, Object[]> errors = new HashMap<>();\n\t\n\t/**\n\t * Messages that will be displayed to the user\n\t */\n\tprotected Map<String, Object[]> msgs = new HashMap<>();\n\t\n\t/**\n\t * Used for configuring tools within velocity toolbox\n\t */\n\tprivate ToolContext toolContext = null;\n\t\n\t/**\n\t * The web.xml file sets this {@link StartupFilter} to be the first filter for all requests.\n\t *\n\t * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,\n\t * javax.servlet.FilterChain)\n\t */\n\t@Override\n\tpublic final void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)\n\t throws IOException, ServletException {\n\t\tif (skipFilter((HttpServletRequest) request)) {\n\t\t\tchain.doFilter(request, response);\n\t\t} else {\n\t\t\t\n\t\t\tHttpServletRequest httpRequest = (HttpServletRequest) request;\n\t\t\tHttpServletResponse httpResponse = (HttpServletResponse) response;\n\t\t\t\n\t\t\tString servletPath = httpRequest.getServletPath();\n\t\t\t// for all /images and /initfilter/scripts files, write the path\n\t\t\t// (the \"/initfilter\" part is needed so that the openmrs_static_context-servlet.xml file doesn't\n\t\t\t// get instantiated early, before the locale messages are all set up)\n\t\t\tif (servletPath.startsWith(\"/images\") || servletPath.startsWith(\"/initfilter/scripts\")) {", "\t\t\t\t// strip out the /initfilter part\n\t\t\t\tservletPath = servletPath.replaceFirst(\"/initfilter\", \"/WEB-INF/view\");", "\t\t\t\t// writes the actual image file path to the response", "\t\t\t\tPath filePath = Paths.get(filterConfig.getServletContext().getRealPath(servletPath)).normalize();\n\t\t\t\tPath fullFilePath = filePath;", "\t\t\t\tif (httpRequest.getPathInfo() != null) {", "\t\t\t\t\tfullFilePath = fullFilePath.resolve(httpRequest.getPathInfo());\n\t\t\t\t\tif (!(fullFilePath.normalize().startsWith(filePath))) {\n\t\t\t\t\t\tlog.warn(\"Detected attempted directory traversal in request for {}\", httpRequest.getPathInfo());\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}", "\t\t\t\t}\n\t\t\t\t", "\t\t\t\ttry (InputStream imageFileInputStream = new FileInputStream(fullFilePath.normalize().toFile())) {", "\t\t\t\t\tOpenmrsUtil.copyFile(imageFileInputStream, httpResponse.getOutputStream());\n\t\t\t\t}\n\t\t\t\tcatch (FileNotFoundException e) {", "\t\t\t\t\tlog.error(\"Unable to find file: {}\", filePath, e);", "\t\t\t\t}", "\t\t\t\tcatch (IOException e) {\n\t\t\t\t\tlog.warn(\"An error occurred while handling file {}\", filePath, e);", "\t\t\t\t}\n\t\t\t} else if (servletPath.startsWith(\"/scripts\")) {\n\t\t\t\tlog.error(\n\t\t\t\t \"Calling /scripts during the initializationfilter pages will cause the openmrs_static_context-servlet.xml to initialize too early and cause errors after startup. Use '/initfilter\"\n\t\t\t\t + servletPath + \"' instead.\");\n\t\t\t}\n\t\t\t// for anything but /initialsetup\n\t\t\telse if (!httpRequest.getServletPath().equals(\"/\" + WebConstants.SETUP_PAGE_URL)\n\t\t\t && !httpRequest.getServletPath().equals(\"/\" + AUTO_RUN_OPENMRS)) {\n\t\t\t\t// send the user to the setup page\n\t\t\t\thttpResponse.sendRedirect(\"/\" + WebConstants.WEBAPP_NAME + \"/\" + WebConstants.SETUP_PAGE_URL);\n\t\t\t} else {\n\t\t\t\t\n\t\t\t\tif (\"GET\".equals(httpRequest.getMethod())) {\n\t\t\t\t\tdoGet(httpRequest, httpResponse);\n\t\t\t\t} else if (\"POST\".equals(httpRequest.getMethod())) {\n\t\t\t\t\t// only clear errors before POSTS so that redirects can show errors too.\n\t\t\t\t\terrors.clear();\n\t\t\t\t\tmsgs.clear();\n\t\t\t\t\tdoPost(httpRequest, httpResponse);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Don't continue down the filter chain otherwise Spring complains\n\t\t\t// that it hasn't been set up yet.\n\t\t\t// The jsp and servlet filter are also on this chain, so writing to\n\t\t\t// the response directly here is the only option\n\t\t}\n\t}\n\t\n\t/**\n\t * Convenience method to set up the velocity context properly\n\t */\n\tprivate void initializeVelocity() {\n\t\tif (velocityEngine == null) {\n\t\t\tvelocityEngine = new VelocityEngine();\n\t\t\t\n\t\t\tProperties props = new Properties();\n\t\t\tprops.setProperty(RuntimeConstants.RUNTIME_LOG, \"startup_wizard_vel.log\");\n\t\t\t// Linux requires setting logging properties to initialize Velocity Context.\n\t\t\tprops.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,\n\t\t\t \"org.apache.velocity.runtime.log.CommonsLogLogChute\");\n\t\t\tprops.setProperty(CommonsLogLogChute.LOGCHUTE_COMMONS_LOG_NAME, \"initial_wizard_velocity\");\n\t\t\t\n\t\t\t// so the vm pages can import the header/footer\n\t\t\tprops.setProperty(RuntimeConstants.RESOURCE_LOADER, \"class\");\n\t\t\tprops.setProperty(\"class.resource.loader.description\", \"Velocity Classpath Resource Loader\");\n\t\t\tprops.setProperty(\"class.resource.loader.class\",\n\t\t\t \"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader\");\n\t\t\t\n\t\t\ttry {\n\t\t\t\tvelocityEngine.init(props);\n\t\t\t}\n\t\t\tcatch (Exception e) {", "\t\t\t\tlog.error(\"velocity init failed, because: {}\", e, e);", "\t\t\t}\n\t\t}\n\t}\n\t\n\t/**\n\t * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on GET requests\n\t *\n\t * @param httpRequest\n\t * @param httpResponse\n\t */\n\tprotected abstract void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse)\n\t throws IOException, ServletException;\n\t\n\t/**\n\t * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on POST requests\n\t *\n\t * @param httpRequest\n\t * @param httpResponse\n\t */\n\tprotected abstract void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse)\n\t throws IOException, ServletException;\n\t\n\t/**\n\t * All private attributes on this class are returned to the template via the velocity context and\n\t * reflection\n\t *\n\t * @param templateName the name of the velocity file to render. This name is prepended with\n\t * {@link #getTemplatePrefix()}\n\t * @param referenceMap\n\t * @param httpResponse\n\t */\n\tprotected void renderTemplate(String templateName, Map<String, Object> referenceMap, HttpServletResponse httpResponse)\n\t throws IOException {\n\t\t// first we should get velocity tools context for current client request (within\n\t\t// his http session) and merge that tools context with basic velocity context\n\t\tif (referenceMap == null) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tObject locale = referenceMap.get(FilterUtil.LOCALE_ATTRIBUTE);\n\t\tToolContext velocityToolContext = getToolContext(\n\t\t locale != null ? locale.toString() : Context.getLocale().toString());\n\t\tVelocityContext velocityContext = new VelocityContext(velocityToolContext);\n\t\t\n\t\tfor (Map.Entry<String, Object> entry : referenceMap.entrySet()) {\n\t\t\tvelocityContext.put(entry.getKey(), entry.getValue());\n\t\t}\n\t\t\n\t\tObject model = getUpdateFilterModel();\n\t\t\n\t\t// put each of the private varibles into the template for convenience\n\t\tfor (Field field : model.getClass().getDeclaredFields()) {\n\t\t\ttry {\n\t\t\t\tfield.setAccessible(true);\n\t\t\t\tvelocityContext.put(field.getName(), field.get(model));\n\t\t\t}\n\t\t\tcatch (IllegalArgumentException | IllegalAccessException e) {\n\t\t\t\tlog.error(\"Error generated while getting field value: \" + field.getName(), e);\n\t\t\t}\n\t\t}\n\t\t\n\t\tString fullTemplatePath = getTemplatePrefix() + templateName;\n\t\tInputStream templateInputStream = getClass().getClassLoader().getResourceAsStream(fullTemplatePath);\n\t\tif (templateInputStream == null) {\n\t\t\tthrow new IOException(\"Unable to find \" + fullTemplatePath);\n\t\t}\n\t\t\n\t\tvelocityContext.put(\"errors\", errors);\n\t\tvelocityContext.put(\"msgs\", msgs);\n\t\t\n\t\t// explicitly set the content type for the response because some servlet containers are assuming text/plain\n\t\thttpResponse.setContentType(\"text/html\");\n\t\t\n\t\ttry {\n\t\t\tvelocityEngine.evaluate(velocityContext, httpResponse.getWriter(), this.getClass().getName(),\n\t\t\t new InputStreamReader(templateInputStream, StandardCharsets.UTF_8));\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tthrow new APIException(\"Unable to process template: \" + fullTemplatePath, e);\n\t\t}\n\t}\n\t\n\t/**\n\t * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)\n\t */\n\t@Override\n\tpublic void init(FilterConfig filterConfig) throws ServletException {\n\t\tthis.filterConfig = filterConfig;\n\t\tinitializeVelocity();\n\t}\n\t\n\t/**\n\t * @see javax.servlet.Filter#destroy()\n\t */\n\t@Override\n\tpublic void destroy() {\n\t}\n\t\n\t/**\n\t * This string is prepended to all templateNames passed to\n\t * {@link #renderTemplate(String, Map, HttpServletResponse)}\n\t *\n\t * @return string to prepend as the path for the templates\n\t */\n\tprotected String getTemplatePrefix() {\n\t\treturn \"org/openmrs/web/filter/\";\n\t}\n\t\n\t/**\n\t * The model that is used as the backer for all pages in this startup wizard. Should never return\n\t * null.\n\t *\n\t * @return the stored formbacking/model object\n\t */\n\tprotected abstract Object getUpdateFilterModel();\n\t\n\t/**\n\t * If this returns true, this filter fails early and quickly. All logic is skipped and startup and\n\t * usage continue normally.\n\t *\n\t * @return true if this filter can be skipped\n\t */\n\tpublic abstract boolean skipFilter(HttpServletRequest request);", "\t/**\n\t * Convenience method to read the last 5 log lines from the MemoryAppender\n\t * \n\t * The log lines will be added to the \"logLines\" key\n\t * \n\t * @param result A map to be returned as a JSON document\n\t */\n\tprotected void addLogLinesToResponse(Map<String, Object> result) {\n\t\tMemoryAppender appender = OpenmrsUtil.getMemoryAppender();\n\t\tif (appender != null) {\n\t\t\tList<String> logLines = appender.getLogLines();\n\t\t\t\n\t\t\t// truncate the list to the last five so we don't overwhelm jquery\n\t\t\tif (logLines.size() > 5) {\n\t\t\t\tlogLines = logLines.subList(logLines.size() - 5, logLines.size());\n\t\t\t}\n\t\t\t\n\t\t\tresult.put(\"logLines\", logLines);\n\t\t} else {\n\t\t\tresult.put(\"logLines\", Collections.emptyList());\n\t\t}\n\t}\n\t\n\t/**\n\t * Convenience method to convert the given object to a JSON string. Supports Maps, Lists, Strings,\n\t * Boolean, Double\n\t *\n\t * @param object object to convert to json\n\t * @return JSON string to be eval'd in javascript\n\t */\n\tprotected String toJSONString(Object object) {\n\t\tObjectMapper mapper = new ObjectMapper();\n\t\tmapper.getJsonFactory().setCharacterEscapes(new OpenmrsCharacterEscapes());\n\t\ttry {\n\t\t\treturn mapper.writeValueAsString(object);\n\t\t}\n\t\tcatch (IOException e) {\n\t\t\tlog.error(\"Failed to convert object to JSON\");\n\t\t\tthrow new APIException(e);\n\t\t}\n\t}\n\t\n\t/**\n\t * Gets tool context for specified locale parameter. If context does not exists, it creates new\n\t * context, configured for that locale. Otherwise, it changes locale property of\n\t * {@link LocalizationTool} object, that is being contained in tools context\n\t *\n\t * @param locale the string with locale parameter for configuring tools context\n\t * @return the tool context object\n\t */\n\tpublic ToolContext getToolContext(String locale) {\n\t\tLocale systemLocale = LocaleUtility.fromSpecification(locale);\n\t\t//Defaults to en if systemLocale is null or invalid e.g en_GBs\n\t\tif (systemLocale == null || !ArrayUtils.contains(Locale.getAvailableLocales(), systemLocale)) {\n\t\t\tsystemLocale = Locale.ENGLISH;\n\t\t}\n\t\t// If tool context has not been configured yet\n\t\tif (toolContext == null) {\n\t\t\t// first we are creating manager for tools, factory for configuring tools \n\t\t\t// and empty configuration object for velocity tool box\n\t\t\tToolManager velocityToolManager = new ToolManager();\n\t\t\tFactoryConfiguration factoryConfig = new FactoryConfiguration();\n\t\t\t// since we are using one tool box for all request within wizard\n\t\t\t// we should propagate toolbox's scope on all application \n\t\t\tToolboxConfiguration toolbox = new ToolboxConfiguration();\n\t\t\ttoolbox.setScope(Scope.APPLICATION);\n\t\t\t// next we are directly configuring custom localization tool by\n\t\t\t// setting its class name, locale property etc.\n\t\t\tToolConfiguration localizationTool = new ToolConfiguration();\n\t\t\tlocalizationTool.setClassname(LocalizationTool.class.getName());\n\t\t\tlocalizationTool.setProperty(ToolContext.LOCALE_KEY, systemLocale);\n\t\t\tlocalizationTool.setProperty(LocalizationTool.BUNDLES_KEY, \"messages\");\n\t\t\t// and finally we are adding just configured tool into toolbox\n\t\t\t// and creating tool context for this toolbox\n\t\t\ttoolbox.addTool(localizationTool);\n\t\t\tfactoryConfig.addToolbox(toolbox);\n\t\t\tvelocityToolManager.configure(factoryConfig);\n\t\t\ttoolContext = velocityToolManager.createContext();\n\t\t\ttoolContext.setUserCanOverwriteTools(true);\n\t\t} else {\n\t\t\t// if it already has been configured, we just pull out our custom localization tool \n\t\t\t// from tool context, then changing its locale property and putting this tool back to the context\n\t\t\t// First, we need to obtain the value of default key annotation of our localization tool\n\t\t\t// class using reflection\n\t\t\tAnnotation annotation = LocalizationTool.class.getAnnotation(DefaultKey.class);\n\t\t\tDefaultKey defaultKeyAnnotation = (DefaultKey) annotation;\n\t\t\tString key = defaultKeyAnnotation.value();\n\t\t\t//\n\t\t\tLocalizationTool localizationTool = (LocalizationTool) toolContext.get(key);\n\t\t\tlocalizationTool.setLocale(systemLocale);\n\t\t\ttoolContext.put(key, localizationTool);\n\t\t}\n\t\treturn toolContext;\n\t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [197], "buggy_code_start_loc": [20], "filenames": ["web/src/main/java/org/openmrs/web/filter/StartupFilter.java"], "fixing_code_end_loc": [196], "fixing_code_start_loc": [21], "message": "OpenMRS is a patient-based medical record system focusing on giving providers a free customizable electronic medical record system. Affected versions are subject to arbitrary file exfiltration due to failure to sanitize request when satisfying GET requests for `/images` & `/initfilter/scripts`. This can allow an attacker to access any file on a system running OpenMRS that is accessible to the user id OpenMRS is running under. Affected implementations should update to the latest patch version of OpenMRS Core for the minor version they use. These are: 2.1.5, 2.2.1, 2.3.5, 2.4.5 and 2.5.3. As a general rule, this vulnerability is already mitigated by Tomcat's URL normalization in Tomcat 7.0.28+. Users on older versions of Tomcat should consider upgrading their Tomcat instance as well as their OpenMRS instance.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:openmrs:openmrs:*:*:*:*:*:*:*:*", "matchCriteriaId": "CC9D911E-1D03-4348-A3E8-42EF336C3CB1", "versionEndExcluding": "2.1.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.6", "vulnerable": true}, {"criteria": "cpe:2.3:a:openmrs:openmrs:*:*:*:*:*:*:*:*", "matchCriteriaId": "AB9FD95F-109C-46B6-9997-1467E85C2EA9", "versionEndExcluding": "2.2.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.2.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:openmrs:openmrs:*:*:*:*:*:*:*:*", "matchCriteriaId": "3CDFE507-8377-4B9E-A91E-4EAEB3893CAD", "versionEndExcluding": "2.3.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.3.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:openmrs:openmrs:*:*:*:*:*:*:*:*", "matchCriteriaId": "DE611740-A309-4E76-BFE2-A18978D9C50A", "versionEndExcluding": "2.4.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:openmrs:openmrs:*:*:*:*:*:*:*:*", "matchCriteriaId": "E69117E5-4694-44D3-8DC4-AE189857C002", "versionEndExcluding": "2.5.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.5.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "OpenMRS is a patient-based medical record system focusing on giving providers a free customizable electronic medical record system. Affected versions are subject to arbitrary file exfiltration due to failure to sanitize request when satisfying GET requests for `/images` & `/initfilter/scripts`. This can allow an attacker to access any file on a system running OpenMRS that is accessible to the user id OpenMRS is running under. Affected implementations should update to the latest patch version of OpenMRS Core for the minor version they use. These are: 2.1.5, 2.2.1, 2.3.5, 2.4.5 and 2.5.3. As a general rule, this vulnerability is already mitigated by Tomcat's URL normalization in Tomcat 7.0.28+. Users on older versions of Tomcat should consider upgrading their Tomcat instance as well as their OpenMRS instance."}, {"lang": "es", "value": "OpenMRS es un sistema de registro m\u00e9dico basado en el paciente que se centra en ofrecer a los proveedores un sistema de registro m\u00e9dico electr\u00f3nico gratuito y personalizable. Las versiones afectadas est\u00e1n sujetas a la exfiltraci\u00f3n arbitraria de archivos debido a un fallo en el saneo de la petici\u00f3n cuando son satisfechas peticiones GET para \"/images\" &amp; \"/initfilter/scripts\". Esto puede permitir a un atacante acceder a cualquier archivo en un sistema que ejecute OpenMRS que sea accesible para el ID de usuario con el que es ejecutado OpenMRS. Las implementaciones afectadas deben actualizar a la \u00faltima versi\u00f3n del parche de OpenMRS Core para la versi\u00f3n menor que usan. Estas son: 2.1.5, 2.2.1, 2.3.5, 2.4.5 y 2.5.3. Como regla general, esta vulnerabilidad ya est\u00e1 mitigada por la normalizaci\u00f3n de URL de Tomcat en Tomcat versi\u00f3n 7.0.28+. Los usuarios de versiones anteriores de Tomcat deber\u00edan considerar la posibilidad de actualizar su instancia de Tomcat, as\u00ed como su instancia de OpenMRS"}], "evaluatorComment": null, "id": "CVE-2022-23612", "lastModified": "2022-03-02T14:17:24.563", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-02-22T23:15:11.400", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openmrs/openmrs-core/blob/ee3373a7a775bfdfa263e2e912c72e64342fb4f0/web/src/main/java/org/openmrs/web/filter/StartupFilter.java#L123"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openmrs/openmrs-core/commit/db8454bf19a092a78d53ee4dba2af628b730a6e7#diff-7c64d9f61d4d4e2ddba92920d7cf63ec96091b308d43904956b3846bc0c26d80R128"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/openmrs/openmrs-core/security/advisories/GHSA-8rgr-ww69-jv65"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://lgtm.com/projects/g/openmrs/openmrs-core/snapshot/fb1335c925ca4c94be5a546707b90d2c1efa4dcc/files/web/src/main/java/org/openmrs/web/filter/StartupFilter.java#L123"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/openmrs/openmrs-core/commit/db8454bf19a092a78d53ee4dba2af628b730a6e7#diff-7c64d9f61d4d4e2ddba92920d7cf63ec96091b308d43904956b3846bc0c26d80R128"}, "type": "CWE-22"}
187
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n//\n// ZoneMinder web zone view file, $Date$, $Revision$\n// Copyright (C) 2001-2008 Philip Coombes\n//\n// This program is free software; you can redistribute it and/or\n// modify it under the terms of the GNU General Public License\n// as published by the Free Software Foundation; either version 2\n// of the License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with this program; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n//", "\nif ( !canView( 'Monitors' ) )\n{\n $view = \"error\";\n return;\n}", "$mid = validInt($_REQUEST['mid']);\n$zid = !empty($_REQUEST['zid'])?validInt($_REQUEST['zid']):0;", "\nif ( $zid > 0 ) {\n $newZone = dbFetchOne( 'SELECT * FROM Zones WHERE MonitorId = ? AND Id = ?', NULL, array( $mid, $zid) );\n} else {\n $view = \"error\";\n return;\n}\n$monitor = dbFetchMonitor ( $mid );", "$plugin = $_REQUEST['pl'];", "\n$plugin_path = dirname(ZM_PLUGINS_CONFIG_PATH).\"/\".$plugin;", "$focusWindow = true;", "xhtmlHeaders(__FILE__, translate('Plugin') );", "\n$pluginOptions=array(\n 'Enabled'=>array(\n 'Type'=>'select',\n 'Name'=>'Enabled',\n 'Choices'=>'yes,no',\n 'Value'=>'no'\n )\n );", "$optionNames=array();\nif(file_exists($plugin_path.\"/config.php\"))\n{\n include_once($plugin_path.\"/config.php\");\n} ", "$sql='SELECT * FROM PluginsConfig WHERE MonitorId=? AND ZoneId=? AND pluginName=?';\nforeach( dbFetchAll( $sql, NULL, array( $mid, $zid, $plugin ) ) as $popt )\n{\n if(array_key_exists($popt['Name'], $pluginOptions) \n && $popt['Type']==$pluginOptions[$popt['Name']]['Type']\n && $popt['Choices']==$pluginOptions[$popt['Name']]['Choices']\n )\n {\n $pluginOptions[$popt['Name']]=$popt;\n array_push($optionNames, $popt['Name']);\n } else {\n dbQuery('DELETE FROM PluginsConfig WHERE Id=?', array( $popt['Id'] ) );\n }\n}\nforeach($pluginOptions as $name => $values)\n{\n if(!in_array($name, $optionNames))\n {\n $popt=$pluginOptions[$name];\n $sql=\"INSERT INTO PluginsConfig VALUES ('',?,?,?,?,?,?,?)\";\n dbQuery($sql, array( $popt['Name'], $popt['Value'], $popt['Type'], $popt['Choices'], $mid, $zid, $plugin ) );\n }\n}", "$PLANG=array();\nif(file_exists($plugin_path.\"/lang/\".$user['Language'].\".php\")) {\n include_once($plugin_path.\"/lang/\".$user['Language'].\".php\");\n}", "function pLang($name)\n{\n global $PLANG;\n if(array_key_exists($name, $PLANG))\n return $PLANG[$name];\n else\n return $name;\n}", "\n?>\n<body>\n <div id=\"page\">\n <div id=\"header\">", " <h2><?php echo translate('Monitor') ?> <?php echo $monitor['Name'] ?> - <?php echo translate('Zone') ?> <?php echo $newZone['Name'] ?> - <?php echo translate('Plugin') ?> <?php echo $plugin ?></h2>", " </div>\n <div id=\"content\">\n <form name=\"pluginForm\" id=\"pluginForm\" method=\"post\" action=\"<?php echo $_SERVER['PHP_SELF'] ?>\">\n <input type=\"hidden\" name=\"view\" value=\"<?php echo $view ?>\"/>\n <input type=\"hidden\" name=\"action\" value=\"plugin\"/>\n <input type=\"hidden\" name=\"mid\" value=\"<?php echo $mid ?>\"/>\n <input type=\"hidden\" name=\"zid\" value=\"<?php echo $zid ?>\"/>", " <input type=\"hidden\" name=\"pl\" value=\"<?php echo $plugin ?>\"/>", "\n <div id=\"settingsPanel\">\n <table id=\"pluginSettings\" cellspacing=\"0\">\n <tbody>\n<?php\nforeach($pluginOptions as $name => $popt)\n{\n ?>\n <tr><th scope=\"row\"><?php echo pLang($name) ?></th> \n <?php\n switch($popt['Type'])\n {\n case \"checkbox\":\n echo \"CHECKBOX\";\n break;\n case \"select\":\n $pchoices=explode(',',$popt['Choices']);\n ?>\n <td colspan=\"2\">\n <select name=\"pluginOpt[<?php echo $popt['Name'] ?>]\" id=\"pluginOpt[<?php echo $popt['Name'] ?>]\">\n <?php\n foreach($pchoices as $pchoice)\n {\n $psel=\"\";\n if($popt['Value']==$pchoice)\n $psel=\"selected\";\n ?>\n <option value=\"<?php echo $pchoice ?>\" <?php echo $psel ?>><?php echo pLang($pchoice) ?></option>\n <?php\n }\n ?>\n </td>\n </select>\n <?php\n break;\n case \"text\":\n default:\n echo \"DEFAULT\";\n }\n ?>\n </tr>\n <?php\n}\n?>\n </tbody>\n </table>\n <input type=\"submit\" id=\"submitBtn\" name=\"submitBtn\" value=\"<?php echo translate('Save') ?>\" onclick=\"return saveChanges( this )\"<?php if (!canEdit( 'Monitors' ) || (false && $selfIntersecting)) { ?> disabled=\"disabled\"<?php } ?>/>\n <input type=\"button\" value=\"<?php echo translate('Cancel') ?>\" data-on-click=\"closeWindow\"/>\n </div>\n </form>\n </div>\n </div>\n</body>\n</html>" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [115], "buggy_code_start_loc": [39], "filenames": ["web/skins/classic/views/plugin.php"], "fixing_code_end_loc": [116], "fixing_code_start_loc": [39], "message": "An issue was discovered in ZoneMinder v1.32.3. Reflected XSS exists in web/skins/classic/views/plugin.php via the zm/index.php?view=plugin pl parameter.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:zoneminder:zoneminder:1.32.3:*:*:*:*:*:*:*", "matchCriteriaId": "E5A2481D-4A45-48A2-B7DE-86C7D161F6EA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "An issue was discovered in ZoneMinder v1.32.3. Reflected XSS exists in web/skins/classic/views/plugin.php via the zm/index.php?view=plugin pl parameter."}, {"lang": "es", "value": "Se ha descubierto un problema en ZoneMinder v1.32.3. Existe Cross-Site Scripting (XSS) reflejado en web/skins/classic/views/plugin.php mediante el par\u00e1metro \"pl\" en zm/index.php?view=plugin."}], "evaluatorComment": null, "id": "CVE-2019-6777", "lastModified": "2019-01-24T20:14:50.837", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-01-24T15:29:01.017", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Third Party Advisory"], "url": "https://github.com/ZoneMinder/zoneminder/issues/2436"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mnoorenberghe/ZoneMinder/commit/59cc65411f02c7e39a270fda3ecb4966d7b48d41"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/mnoorenberghe/ZoneMinder/commit/59cc65411f02c7e39a270fda3ecb4966d7b48d41"}, "type": "CWE-79"}
188
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n//\n// ZoneMinder web zone view file, $Date$, $Revision$\n// Copyright (C) 2001-2008 Philip Coombes\n//\n// This program is free software; you can redistribute it and/or\n// modify it under the terms of the GNU General Public License\n// as published by the Free Software Foundation; either version 2\n// of the License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with this program; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n//", "\nif ( !canView( 'Monitors' ) )\n{\n $view = \"error\";\n return;\n}", "$mid = validInt($_REQUEST['mid']);\n$zid = !empty($_REQUEST['zid'])?validInt($_REQUEST['zid']):0;", "\nif ( $zid > 0 ) {\n $newZone = dbFetchOne( 'SELECT * FROM Zones WHERE MonitorId = ? AND Id = ?', NULL, array( $mid, $zid) );\n} else {\n $view = \"error\";\n return;\n}\n$monitor = dbFetchMonitor ( $mid );", "// Only allow certain filename characters (not including a period) to prevent directory traversal.\n$plugin = preg_replace('/[^-a-zA-Z0-9]/', '', $_REQUEST['pl']);", "\n$plugin_path = dirname(ZM_PLUGINS_CONFIG_PATH).\"/\".$plugin;", "$focusWindow = true;", "xhtmlHeaders(__FILE__, translate('Plugin') );", "\n$pluginOptions=array(\n 'Enabled'=>array(\n 'Type'=>'select',\n 'Name'=>'Enabled',\n 'Choices'=>'yes,no',\n 'Value'=>'no'\n )\n );", "$optionNames=array();\nif(file_exists($plugin_path.\"/config.php\"))\n{\n include_once($plugin_path.\"/config.php\");\n} ", "$sql='SELECT * FROM PluginsConfig WHERE MonitorId=? AND ZoneId=? AND pluginName=?';\nforeach( dbFetchAll( $sql, NULL, array( $mid, $zid, $plugin ) ) as $popt )\n{\n if(array_key_exists($popt['Name'], $pluginOptions) \n && $popt['Type']==$pluginOptions[$popt['Name']]['Type']\n && $popt['Choices']==$pluginOptions[$popt['Name']]['Choices']\n )\n {\n $pluginOptions[$popt['Name']]=$popt;\n array_push($optionNames, $popt['Name']);\n } else {\n dbQuery('DELETE FROM PluginsConfig WHERE Id=?', array( $popt['Id'] ) );\n }\n}\nforeach($pluginOptions as $name => $values)\n{\n if(!in_array($name, $optionNames))\n {\n $popt=$pluginOptions[$name];\n $sql=\"INSERT INTO PluginsConfig VALUES ('',?,?,?,?,?,?,?)\";\n dbQuery($sql, array( $popt['Name'], $popt['Value'], $popt['Type'], $popt['Choices'], $mid, $zid, $plugin ) );\n }\n}", "$PLANG=array();\nif(file_exists($plugin_path.\"/lang/\".$user['Language'].\".php\")) {\n include_once($plugin_path.\"/lang/\".$user['Language'].\".php\");\n}", "function pLang($name)\n{\n global $PLANG;\n if(array_key_exists($name, $PLANG))\n return $PLANG[$name];\n else\n return $name;\n}", "\n?>\n<body>\n <div id=\"page\">\n <div id=\"header\">", " <h2><?php echo translate('Monitor') ?> <?php echo $monitor['Name'] ?> - <?php echo translate('Zone') ?> <?php echo $newZone['Name'] ?> - <?php echo translate('Plugin') ?> <?php echo validHtmlStr($plugin) ?></h2>", " </div>\n <div id=\"content\">\n <form name=\"pluginForm\" id=\"pluginForm\" method=\"post\" action=\"<?php echo $_SERVER['PHP_SELF'] ?>\">\n <input type=\"hidden\" name=\"view\" value=\"<?php echo $view ?>\"/>\n <input type=\"hidden\" name=\"action\" value=\"plugin\"/>\n <input type=\"hidden\" name=\"mid\" value=\"<?php echo $mid ?>\"/>\n <input type=\"hidden\" name=\"zid\" value=\"<?php echo $zid ?>\"/>", " <input type=\"hidden\" name=\"pl\" value=\"<?php echo validHtmlStr($plugin) ?>\"/>", "\n <div id=\"settingsPanel\">\n <table id=\"pluginSettings\" cellspacing=\"0\">\n <tbody>\n<?php\nforeach($pluginOptions as $name => $popt)\n{\n ?>\n <tr><th scope=\"row\"><?php echo pLang($name) ?></th> \n <?php\n switch($popt['Type'])\n {\n case \"checkbox\":\n echo \"CHECKBOX\";\n break;\n case \"select\":\n $pchoices=explode(',',$popt['Choices']);\n ?>\n <td colspan=\"2\">\n <select name=\"pluginOpt[<?php echo $popt['Name'] ?>]\" id=\"pluginOpt[<?php echo $popt['Name'] ?>]\">\n <?php\n foreach($pchoices as $pchoice)\n {\n $psel=\"\";\n if($popt['Value']==$pchoice)\n $psel=\"selected\";\n ?>\n <option value=\"<?php echo $pchoice ?>\" <?php echo $psel ?>><?php echo pLang($pchoice) ?></option>\n <?php\n }\n ?>\n </td>\n </select>\n <?php\n break;\n case \"text\":\n default:\n echo \"DEFAULT\";\n }\n ?>\n </tr>\n <?php\n}\n?>\n </tbody>\n </table>\n <input type=\"submit\" id=\"submitBtn\" name=\"submitBtn\" value=\"<?php echo translate('Save') ?>\" onclick=\"return saveChanges( this )\"<?php if (!canEdit( 'Monitors' ) || (false && $selfIntersecting)) { ?> disabled=\"disabled\"<?php } ?>/>\n <input type=\"button\" value=\"<?php echo translate('Cancel') ?>\" data-on-click=\"closeWindow\"/>\n </div>\n </form>\n </div>\n </div>\n</body>\n</html>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [115], "buggy_code_start_loc": [39], "filenames": ["web/skins/classic/views/plugin.php"], "fixing_code_end_loc": [116], "fixing_code_start_loc": [39], "message": "An issue was discovered in ZoneMinder v1.32.3. Reflected XSS exists in web/skins/classic/views/plugin.php via the zm/index.php?view=plugin pl parameter.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:zoneminder:zoneminder:1.32.3:*:*:*:*:*:*:*", "matchCriteriaId": "E5A2481D-4A45-48A2-B7DE-86C7D161F6EA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "An issue was discovered in ZoneMinder v1.32.3. Reflected XSS exists in web/skins/classic/views/plugin.php via the zm/index.php?view=plugin pl parameter."}, {"lang": "es", "value": "Se ha descubierto un problema en ZoneMinder v1.32.3. Existe Cross-Site Scripting (XSS) reflejado en web/skins/classic/views/plugin.php mediante el par\u00e1metro \"pl\" en zm/index.php?view=plugin."}], "evaluatorComment": null, "id": "CVE-2019-6777", "lastModified": "2019-01-24T20:14:50.837", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-01-24T15:29:01.017", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Third Party Advisory"], "url": "https://github.com/ZoneMinder/zoneminder/issues/2436"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mnoorenberghe/ZoneMinder/commit/59cc65411f02c7e39a270fda3ecb4966d7b48d41"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/mnoorenberghe/ZoneMinder/commit/59cc65411f02c7e39a270fda3ecb4966d7b48d41"}, "type": "CWE-79"}
188
Determine whether the {function_name} code is vulnerable or not.
[ "/*\nCopyright (c) 2007-2013. The YARA Authors. All Rights Reserved.", "Redistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:", "1. Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.", "2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation and/or\nother materials provided with the distribution.", "3. Neither the name of the copyright holder nor the names of its contributors\nmay be used to endorse or promote products derived from this software without\nspecific prior written permission.", "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/", "%{", "\n#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n#include <limits.h>\n#include <stddef.h>", "\n#include <yara/integers.h>\n#include <yara/utils.h>\n#include <yara/strutils.h>\n#include <yara/compiler.h>\n#include <yara/object.h>\n#include <yara/sizedstr.h>\n#include <yara/exec.h>\n#include <yara/error.h>\n#include <yara/mem.h>\n#include <yara/lexer.h>\n#include <yara/parser.h>", "\n#define YYERROR_VERBOSE", "#define YYMALLOC yr_malloc\n#define YYFREE yr_free", "#define INTEGER_SET_ENUMERATION 1\n#define INTEGER_SET_RANGE 2", "#define ERROR_IF(x) \\\n if (x) \\\n { \\\n yyerror(yyscanner, compiler, NULL); \\\n YYERROR; \\\n } \\", "\n#define CHECK_TYPE(expression, expected_type, op) \\\n if (((expression.type) & (expected_type)) == 0) \\\n { \\\n switch(expression.type) \\\n { \\\n case EXPRESSION_TYPE_INTEGER: \\\n yr_compiler_set_error_extra_info( \\\n compiler, \"wrong type \\\"integer\\\" for \" op \" operator\"); \\\n break; \\\n case EXPRESSION_TYPE_FLOAT: \\\n yr_compiler_set_error_extra_info( \\\n compiler, \"wrong type \\\"float\\\" for \" op \" operator\"); \\\n break; \\\n case EXPRESSION_TYPE_STRING: \\\n yr_compiler_set_error_extra_info( \\\n compiler, \"wrong type \\\"string\\\" for \" op \" operator\"); \\\n break; \\\n case EXPRESSION_TYPE_BOOLEAN: \\\n yr_compiler_set_error_extra_info( \\\n compiler, \"wrong type \\\"boolean\\\" for \" op \" operator\"); \\\n break; \\\n } \\\n compiler->last_result = ERROR_WRONG_TYPE; \\\n yyerror(yyscanner, compiler, NULL); \\\n YYERROR; \\\n }\n%}", "\n%expect 1 // expect 1 shift/reduce conflicts", "// Uncomment this line to print parsing information that can be useful to\n// debug YARA's grammar.", "// %debug", "%name-prefix=\"yara_yy\"\n%pure-parser\n%parse-param {void *yyscanner}\n%parse-param {YR_COMPILER* compiler}\n%lex-param {yyscan_t yyscanner}\n%lex-param {YR_COMPILER* compiler}", "%token _DOT_DOT_\n%token _RULE_\n%token _PRIVATE_\n%token _GLOBAL_\n%token _META_\n%token <string> _STRINGS_\n%token _CONDITION_\n%token <c_string> _IDENTIFIER_\n%token <c_string> _STRING_IDENTIFIER_\n%token <c_string> _STRING_COUNT_\n%token <c_string> _STRING_OFFSET_\n%token <c_string> _STRING_LENGTH_\n%token <c_string> _STRING_IDENTIFIER_WITH_WILDCARD_\n%token <integer> _NUMBER_\n%token <double_> _DOUBLE_\n%token <integer> _INTEGER_FUNCTION_\n%token <sized_string> _TEXT_STRING_\n%token <sized_string> _HEX_STRING_\n%token <sized_string> _REGEXP_\n%token _ASCII_\n%token _WIDE_\n%token _NOCASE_\n%token _FULLWORD_\n%token _AT_\n%token _FILESIZE_\n%token _ENTRYPOINT_\n%token _ALL_\n%token _ANY_\n%token _IN_\n%token _OF_\n%token _FOR_\n%token _THEM_\n%token _MATCHES_\n%token _CONTAINS_\n%token _IMPORT_", "%token _TRUE_\n%token _FALSE_", "%left _OR_\n%left _AND_\n%left '|'\n%left '^'\n%left '&'\n%left _EQ_ _NEQ_\n%left _LT_ _LE_ _GT_ _GE_\n%left _SHIFT_LEFT_ _SHIFT_RIGHT_\n%left '+' '-'\n%left '*' '\\\\' '%'\n%right _NOT_ '~' UNARY_MINUS", "%type <rule> rule", "%type <string> strings\n%type <string> string_declaration\n%type <string> string_declarations", "%type <meta> meta\n%type <meta> meta_declaration\n%type <meta> meta_declarations", "%type <c_string> tags\n%type <c_string> tag_list", "%type <integer> string_modifier\n%type <integer> string_modifiers", "%type <integer> integer_set", "%type <integer> rule_modifier\n%type <integer> rule_modifiers", "\n%type <expression> primary_expression\n%type <expression> boolean_expression\n%type <expression> expression\n%type <expression> identifier\n%type <expression> regexp", "%type <c_string> arguments\n%type <c_string> arguments_list", "%destructor { yr_free($$); } _IDENTIFIER_\n%destructor { yr_free($$); } _STRING_COUNT_\n%destructor { yr_free($$); } _STRING_OFFSET_\n%destructor { yr_free($$); } _STRING_LENGTH_\n%destructor { yr_free($$); } _STRING_IDENTIFIER_\n%destructor { yr_free($$); } _STRING_IDENTIFIER_WITH_WILDCARD_\n%destructor { yr_free($$); } _TEXT_STRING_\n%destructor { yr_free($$); } _HEX_STRING_\n%destructor { yr_free($$); } _REGEXP_", "%union {\n EXPRESSION expression;\n SIZED_STRING* sized_string;\n char* c_string;\n int64_t integer;\n double double_;\n YR_STRING* string;\n YR_META* meta;\n YR_RULE* rule;\n}", "\n%%", "rules\n : /* empty */\n | rules rule\n | rules import\n | rules error rule /* on error skip until next rule..*/\n | rules error import /* .. or import statement */\n | rules error \"include\" /* .. or include statement */\n ;", "\nimport\n : _IMPORT_ _TEXT_STRING_\n {\n int result = yr_parser_reduce_import(yyscanner, $2);", " yr_free($2);", " ERROR_IF(result != ERROR_SUCCESS);\n }\n ;", "\nrule\n : rule_modifiers _RULE_ _IDENTIFIER_\n {\n YR_RULE* rule = yr_parser_reduce_rule_declaration_phase_1(\n yyscanner, (int32_t) $1, $3);", " ERROR_IF(rule == NULL);", " $<rule>$ = rule;\n }\n tags '{' meta strings\n {\n YR_RULE* rule = $<rule>4; // rule created in phase 1", " rule->tags = $5;\n rule->metas = $7;\n rule->strings = $8;\n }\n condition '}'\n {\n YR_RULE* rule = $<rule>4; // rule created in phase 1", " compiler->last_result = yr_parser_reduce_rule_declaration_phase_2(\n yyscanner, rule);", " yr_free($3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n ;", "\nmeta\n : /* empty */\n {\n $$ = NULL;\n }\n | _META_ ':' meta_declarations\n {\n // Each rule have a list of meta-data info, consisting in a\n // sequence of YR_META structures. The last YR_META structure does\n // not represent a real meta-data, it's just a end-of-list marker\n // identified by a specific type (META_TYPE_NULL). Here we\n // write the end-of-list marker.", " YR_META null_meta;", " memset(&null_meta, 0xFF, sizeof(YR_META));\n null_meta.type = META_TYPE_NULL;", " compiler->last_result = yr_arena_write_data(\n compiler->metas_arena,\n &null_meta,\n sizeof(YR_META),\n NULL);", " $$ = $3;", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n ;", "\nstrings\n : /* empty */\n {\n $$ = NULL;\n }\n | _STRINGS_ ':' string_declarations\n {\n // Each rule have a list of strings, consisting in a sequence\n // of YR_STRING structures. The last YR_STRING structure does not\n // represent a real string, it's just a end-of-list marker\n // identified by a specific flag (STRING_FLAGS_NULL). Here we\n // write the end-of-list marker.", " YR_STRING null_string;", " memset(&null_string, 0xFF, sizeof(YR_STRING));\n null_string.g_flags = STRING_GFLAGS_NULL;", " compiler->last_result = yr_arena_write_data(\n compiler->strings_arena,\n &null_string,\n sizeof(YR_STRING),\n NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$ = $3;\n }\n ;", "\ncondition\n : _CONDITION_ ':' boolean_expression\n ;", "\nrule_modifiers\n : /* empty */ { $$ = 0; }\n | rule_modifiers rule_modifier { $$ = $1 | $2; }\n ;", "\nrule_modifier\n : _PRIVATE_ { $$ = RULE_GFLAGS_PRIVATE; }\n | _GLOBAL_ { $$ = RULE_GFLAGS_GLOBAL; }\n ;", "\ntags\n : /* empty */\n {\n $$ = NULL;\n }\n | ':' tag_list\n {\n // Tags list is represented in the arena as a sequence\n // of null-terminated strings, the sequence ends with an\n // additional null character. Here we write the ending null\n //character. Example: tag1\\0tag2\\0tag3\\0\\0", " compiler->last_result = yr_arena_write_string(\n yyget_extra(yyscanner)->sz_arena, \"\", NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$ = $2;\n }\n ;", "\ntag_list\n : _IDENTIFIER_\n {\n char* identifier;", " compiler->last_result = yr_arena_write_string(\n yyget_extra(yyscanner)->sz_arena, $1, &identifier);", " yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$ = identifier;\n }\n | tag_list _IDENTIFIER_\n {\n char* tag_name = $1;\n size_t tag_length = tag_name != NULL ? strlen(tag_name) : 0;", " while (tag_length > 0)\n {\n if (strcmp(tag_name, $2) == 0)\n {\n yr_compiler_set_error_extra_info(compiler, tag_name);\n compiler->last_result = ERROR_DUPLICATED_TAG_IDENTIFIER;\n break;\n }", " tag_name = (char*) yr_arena_next_address(\n yyget_extra(yyscanner)->sz_arena,\n tag_name,\n tag_length + 1);", " tag_length = tag_name != NULL ? strlen(tag_name) : 0;\n }", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_arena_write_string(\n yyget_extra(yyscanner)->sz_arena, $2, NULL);", " yr_free($2);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$ = $1;\n }\n ;", "", "meta_declarations\n : meta_declaration { $$ = $1; }\n | meta_declarations meta_declaration { $$ = $1; }\n ;", "\nmeta_declaration\n : _IDENTIFIER_ '=' _TEXT_STRING_\n {\n SIZED_STRING* sized_string = $3;", " $$ = yr_parser_reduce_meta_declaration(\n yyscanner,\n META_TYPE_STRING,\n $1,\n sized_string->c_string,\n 0);", " yr_free($1);\n yr_free($3);", " ERROR_IF($$ == NULL);\n }\n | _IDENTIFIER_ '=' _NUMBER_\n {\n $$ = yr_parser_reduce_meta_declaration(\n yyscanner,\n META_TYPE_INTEGER,\n $1,\n NULL,\n $3);", " yr_free($1);", " ERROR_IF($$ == NULL);\n }\n | _IDENTIFIER_ '=' '-' _NUMBER_\n {\n $$ = yr_parser_reduce_meta_declaration(\n yyscanner,\n META_TYPE_INTEGER,\n $1,\n NULL,\n -$4);", " yr_free($1);", " ERROR_IF($$ == NULL);\n }\n | _IDENTIFIER_ '=' _TRUE_\n {\n $$ = yr_parser_reduce_meta_declaration(\n yyscanner,\n META_TYPE_BOOLEAN,\n $1,\n NULL,\n TRUE);", " yr_free($1);", " ERROR_IF($$ == NULL);\n }\n | _IDENTIFIER_ '=' _FALSE_\n {\n $$ = yr_parser_reduce_meta_declaration(\n yyscanner,\n META_TYPE_BOOLEAN,\n $1,\n NULL,\n FALSE);", " yr_free($1);", " ERROR_IF($$ == NULL);\n }\n ;", "\nstring_declarations\n : string_declaration { $$ = $1; }\n | string_declarations string_declaration { $$ = $1; }\n ;", "\nstring_declaration\n : _STRING_IDENTIFIER_ '='\n {\n compiler->error_line = yyget_lineno(yyscanner);\n }\n _TEXT_STRING_ string_modifiers\n {\n $$ = yr_parser_reduce_string_declaration(\n yyscanner, (int32_t) $5, $1, $4);", " yr_free($1);\n yr_free($4);", " ERROR_IF($$ == NULL);\n compiler->error_line = 0;\n }\n | _STRING_IDENTIFIER_ '='\n {\n compiler->error_line = yyget_lineno(yyscanner);\n }\n _REGEXP_ string_modifiers\n {\n $$ = yr_parser_reduce_string_declaration(\n yyscanner, (int32_t) $5 | STRING_GFLAGS_REGEXP, $1, $4);", " yr_free($1);\n yr_free($4);", " ERROR_IF($$ == NULL);", " compiler->error_line = 0;\n }\n | _STRING_IDENTIFIER_ '=' _HEX_STRING_\n {\n $$ = yr_parser_reduce_string_declaration(\n yyscanner, STRING_GFLAGS_HEXADECIMAL, $1, $3);", " yr_free($1);\n yr_free($3);", " ERROR_IF($$ == NULL);\n }\n ;", "\nstring_modifiers\n : /* empty */ { $$ = 0; }\n | string_modifiers string_modifier { $$ = $1 | $2; }\n ;", "\nstring_modifier\n : _WIDE_ { $$ = STRING_GFLAGS_WIDE; }\n | _ASCII_ { $$ = STRING_GFLAGS_ASCII; }\n | _NOCASE_ { $$ = STRING_GFLAGS_NO_CASE; }\n | _FULLWORD_ { $$ = STRING_GFLAGS_FULL_WORD; }\n ;", "\nidentifier\n : _IDENTIFIER_\n {\n int var_index = yr_parser_lookup_loop_variable(yyscanner, $1);", " if (var_index >= 0)\n {\n compiler->last_result = yr_parser_emit_with_arg(\n yyscanner,\n OP_PUSH_M,\n LOOP_LOCAL_VARS * var_index,\n NULL,\n NULL);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n $$.identifier = compiler->loop_identifier[var_index];\n }\n else\n {\n // Search for identifier within the global namespace, where the\n // externals variables reside.", " YR_OBJECT* object = (YR_OBJECT*) yr_hash_table_lookup(\n compiler->objects_table, $1, NULL);", " if (object == NULL)\n {\n // If not found, search within the current namespace.\n char* ns = compiler->current_namespace->name;", " object = (YR_OBJECT*) yr_hash_table_lookup(\n compiler->objects_table, $1, ns);\n }", " if (object != NULL)\n {\n char* id;", " compiler->last_result = yr_arena_write_string(\n compiler->sz_arena, $1, &id);", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_OBJ_LOAD,\n id,\n NULL,\n NULL);", " $$.type = EXPRESSION_TYPE_OBJECT;\n $$.value.object = object;\n $$.identifier = object->identifier;\n }\n else\n {\n YR_RULE* rule = (YR_RULE*) yr_hash_table_lookup(\n compiler->rules_table,\n $1,\n compiler->current_namespace->name);", " if (rule != NULL)\n {\n compiler->last_result = yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_PUSH_RULE,\n rule,\n NULL,\n NULL);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n $$.value.integer = UNDEFINED;\n $$.identifier = rule->identifier;\n }\n else\n {\n yr_compiler_set_error_extra_info(compiler, $1);\n compiler->last_result = ERROR_UNDEFINED_IDENTIFIER;\n }\n }\n }", " yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n | identifier '.' _IDENTIFIER_\n {\n YR_OBJECT* field = NULL;", " if ($1.type == EXPRESSION_TYPE_OBJECT &&\n $1.value.object->type == OBJECT_TYPE_STRUCTURE)\n {\n field = yr_object_lookup_field($1.value.object, $3);", " if (field != NULL)\n {\n char* ident;", " compiler->last_result = yr_arena_write_string(\n compiler->sz_arena, $3, &ident);", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_OBJ_FIELD,\n ident,\n NULL,\n NULL);", " $$.type = EXPRESSION_TYPE_OBJECT;\n $$.value.object = field;\n $$.identifier = field->identifier;\n }\n else\n {\n yr_compiler_set_error_extra_info(compiler, $3);\n compiler->last_result = ERROR_INVALID_FIELD_NAME;\n }\n }\n else\n {\n yr_compiler_set_error_extra_info(\n compiler, $1.identifier);", " compiler->last_result = ERROR_NOT_A_STRUCTURE;\n }", " yr_free($3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n | identifier '[' primary_expression ']'\n {\n YR_OBJECT_ARRAY* array;\n YR_OBJECT_DICTIONARY* dict;", " if ($1.type == EXPRESSION_TYPE_OBJECT &&\n $1.value.object->type == OBJECT_TYPE_ARRAY)\n {\n if ($3.type != EXPRESSION_TYPE_INTEGER)\n {\n yr_compiler_set_error_extra_info(\n compiler, \"array indexes must be of integer type\");\n compiler->last_result = ERROR_WRONG_TYPE;\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " compiler->last_result = yr_parser_emit(\n yyscanner, OP_INDEX_ARRAY, NULL);", " array = (YR_OBJECT_ARRAY*) $1.value.object;", " $$.type = EXPRESSION_TYPE_OBJECT;\n $$.value.object = array->prototype_item;\n $$.identifier = array->identifier;\n }\n else if ($1.type == EXPRESSION_TYPE_OBJECT &&\n $1.value.object->type == OBJECT_TYPE_DICTIONARY)\n {\n if ($3.type != EXPRESSION_TYPE_STRING)\n {\n yr_compiler_set_error_extra_info(\n compiler, \"dictionary keys must be of string type\");\n compiler->last_result = ERROR_WRONG_TYPE;\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " compiler->last_result = yr_parser_emit(\n yyscanner, OP_LOOKUP_DICT, NULL);", " dict = (YR_OBJECT_DICTIONARY*) $1.value.object;", " $$.type = EXPRESSION_TYPE_OBJECT;\n $$.value.object = dict->prototype_item;\n $$.identifier = dict->identifier;\n }\n else\n {\n yr_compiler_set_error_extra_info(\n compiler, $1.identifier);", " compiler->last_result = ERROR_NOT_INDEXABLE;\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }", " | identifier '(' arguments ')'\n {\n YR_OBJECT_FUNCTION* function;\n char* args_fmt;", " if ($1.type == EXPRESSION_TYPE_OBJECT &&\n $1.value.object->type == OBJECT_TYPE_FUNCTION)\n {\n compiler->last_result = yr_parser_check_types(\n compiler, (YR_OBJECT_FUNCTION*) $1.value.object, $3);", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_arena_write_string(\n compiler->sz_arena, $3, &args_fmt);", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_CALL,\n args_fmt,\n NULL,\n NULL);", " function = (YR_OBJECT_FUNCTION*) $1.value.object;", " $$.type = EXPRESSION_TYPE_OBJECT;\n $$.value.object = function->return_obj;\n $$.identifier = function->identifier;\n }\n else\n {\n yr_compiler_set_error_extra_info(\n compiler, $1.identifier);", " compiler->last_result = ERROR_NOT_A_FUNCTION;\n }", " yr_free($3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n ;", "\narguments\n : /* empty */ { $$ = yr_strdup(\"\"); }\n | arguments_list { $$ = $1; }", "\narguments_list\n : expression\n {\n $$ = (char*) yr_malloc(MAX_FUNCTION_ARGS + 1);", " switch($1.type)\n {\n case EXPRESSION_TYPE_INTEGER:\n strlcpy($$, \"i\", MAX_FUNCTION_ARGS);\n break;\n case EXPRESSION_TYPE_FLOAT:\n strlcpy($$, \"f\", MAX_FUNCTION_ARGS);\n break;\n case EXPRESSION_TYPE_BOOLEAN:\n strlcpy($$, \"b\", MAX_FUNCTION_ARGS);\n break;\n case EXPRESSION_TYPE_STRING:\n strlcpy($$, \"s\", MAX_FUNCTION_ARGS);\n break;\n case EXPRESSION_TYPE_REGEXP:\n strlcpy($$, \"r\", MAX_FUNCTION_ARGS);\n break;\n }", " ERROR_IF($$ == NULL);\n }\n | arguments_list ',' expression\n {\n if (strlen($1) == MAX_FUNCTION_ARGS)\n {\n compiler->last_result = ERROR_TOO_MANY_ARGUMENTS;\n }\n else\n {\n switch($3.type)\n {\n case EXPRESSION_TYPE_INTEGER:\n strlcat($1, \"i\", MAX_FUNCTION_ARGS);\n break;\n case EXPRESSION_TYPE_FLOAT:\n strlcat($1, \"f\", MAX_FUNCTION_ARGS);\n break;\n case EXPRESSION_TYPE_BOOLEAN:\n strlcat($1, \"b\", MAX_FUNCTION_ARGS);\n break;\n case EXPRESSION_TYPE_STRING:\n strlcat($1, \"s\", MAX_FUNCTION_ARGS);\n break;\n case EXPRESSION_TYPE_REGEXP:\n strlcat($1, \"r\", MAX_FUNCTION_ARGS);\n break;\n }\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$ = $1;\n }\n ;", "\nregexp\n : _REGEXP_\n {\n SIZED_STRING* sized_string = $1;\n RE* re;\n RE_ERROR error;", " int re_flags = 0;", " if (sized_string->flags & SIZED_STRING_FLAGS_NO_CASE)\n re_flags |= RE_FLAGS_NO_CASE;", " if (sized_string->flags & SIZED_STRING_FLAGS_DOT_ALL)\n re_flags |= RE_FLAGS_DOT_ALL;", " compiler->last_result = yr_re_compile(\n sized_string->c_string,\n re_flags,\n compiler->re_code_arena,\n &re,\n &error);", " yr_free($1);", " if (compiler->last_result == ERROR_INVALID_REGULAR_EXPRESSION)\n yr_compiler_set_error_extra_info(compiler, error.message);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_PUSH,\n re->root_node->forward_code,\n NULL,\n NULL);", " yr_re_destroy(re);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_REGEXP;\n }\n ;", "\nboolean_expression\n : expression\n {\n if ($1.type == EXPRESSION_TYPE_STRING)\n {\n if ($1.value.sized_string != NULL)\n {\n yywarning(yyscanner,\n \"Using literal string \\\"%s\\\" in a boolean operation.\",\n $1.value.sized_string->c_string);\n }", " compiler->last_result = yr_parser_emit(\n yyscanner, OP_STR_TO_BOOL, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n ;", "expression\n : _TRUE_\n {\n compiler->last_result = yr_parser_emit_with_arg(\n yyscanner, OP_PUSH, 1, NULL, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | _FALSE_\n {\n compiler->last_result = yr_parser_emit_with_arg(\n yyscanner, OP_PUSH, 0, NULL, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression _MATCHES_ regexp\n {\n CHECK_TYPE($1, EXPRESSION_TYPE_STRING, \"matches\");\n CHECK_TYPE($3, EXPRESSION_TYPE_REGEXP, \"matches\");", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_parser_emit(\n yyscanner,\n OP_MATCHES,\n NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression _CONTAINS_ primary_expression\n {\n CHECK_TYPE($1, EXPRESSION_TYPE_STRING, \"contains\");\n CHECK_TYPE($3, EXPRESSION_TYPE_STRING, \"contains\");", " compiler->last_result = yr_parser_emit(\n yyscanner, OP_CONTAINS, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | _STRING_IDENTIFIER_\n {\n int result = yr_parser_reduce_string_identifier(\n yyscanner,\n $1,\n OP_FOUND,\n UNDEFINED);", " yr_free($1);", " ERROR_IF(result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | _STRING_IDENTIFIER_ _AT_ primary_expression\n {\n CHECK_TYPE($3, EXPRESSION_TYPE_INTEGER, \"at\");", " compiler->last_result = yr_parser_reduce_string_identifier(\n yyscanner, $1, OP_FOUND_AT, $3.value.integer);", " yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | _STRING_IDENTIFIER_ _IN_ range\n {\n compiler->last_result = yr_parser_reduce_string_identifier(\n yyscanner, $1, OP_FOUND_IN, UNDEFINED);", " yr_free($1);", " ERROR_IF(compiler->last_result!= ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | _FOR_ for_expression error\n {", " compiler->loop_depth--;\n compiler->loop_identifier[compiler->loop_depth] = NULL;", " }\n | _FOR_ for_expression _IDENTIFIER_ _IN_\n {\n int var_index;", " if (compiler->loop_depth == MAX_LOOP_NESTING)\n compiler->last_result = \\\n ERROR_LOOP_NESTING_LIMIT_EXCEEDED;", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " var_index = yr_parser_lookup_loop_variable(\n yyscanner, $3);", " if (var_index >= 0)\n {\n yr_compiler_set_error_extra_info(\n compiler, $3);", " compiler->last_result = \\\n ERROR_DUPLICATED_LOOP_IDENTIFIER;\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " // Push end-of-list marker\n compiler->last_result = yr_parser_emit_with_arg(\n yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n integer_set ':'\n {\n int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth;\n uint8_t* addr;", " // Clear counter for number of expressions evaluating\n // to TRUE.\n yr_parser_emit_with_arg(\n yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL);", " // Clear iterations counter\n yr_parser_emit_with_arg(\n yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL);", " if ($6 == INTEGER_SET_ENUMERATION)\n {\n // Pop the first integer\n yr_parser_emit_with_arg(\n yyscanner, OP_POP_M, mem_offset, &addr, NULL);\n }\n else // INTEGER_SET_RANGE\n {\n // Pop higher bound of set range\n yr_parser_emit_with_arg(\n yyscanner, OP_POP_M, mem_offset + 3, &addr, NULL);", " // Pop lower bound of set range\n yr_parser_emit_with_arg(\n yyscanner, OP_POP_M, mem_offset, NULL, NULL);\n }", " compiler->loop_address[compiler->loop_depth] = addr;\n compiler->loop_identifier[compiler->loop_depth] = $3;\n compiler->loop_depth++;\n }\n '(' boolean_expression ')'\n {\n int mem_offset;", " compiler->loop_depth--;\n mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth;", " // The value at the top of the stack is the result of\n // evaluating the boolean expression, so it could be\n // 0, 1 or UNDEFINED. Add this value to a counter\n // keeping the number of expressions evaluating to true.\n // If the value is UNDEFINED instruction OP_ADD_M\n // does nothing.", " yr_parser_emit_with_arg(\n yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL);", " // Increment iterations counter\n yr_parser_emit_with_arg(\n yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL);", " if ($6 == INTEGER_SET_ENUMERATION)\n {\n yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_JNUNDEF,\n compiler->loop_address[compiler->loop_depth],\n NULL,\n NULL);\n }\n else // INTEGER_SET_RANGE\n {\n // Increment lower bound of integer set\n yr_parser_emit_with_arg(\n yyscanner, OP_INCR_M, mem_offset, NULL, NULL);", " // Push lower bound of integer set\n yr_parser_emit_with_arg(\n yyscanner, OP_PUSH_M, mem_offset, NULL, NULL);", " // Push higher bound of integer set\n yr_parser_emit_with_arg(\n yyscanner, OP_PUSH_M, mem_offset + 3, NULL, NULL);", " // Compare higher bound with lower bound, do loop again\n // if lower bound is still lower or equal than higher bound\n yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_JLE,\n compiler->loop_address[compiler->loop_depth],\n NULL,\n NULL);", " yr_parser_emit(yyscanner, OP_POP, NULL);\n yr_parser_emit(yyscanner, OP_POP, NULL);\n }", " // Pop end-of-list marker.\n yr_parser_emit(yyscanner, OP_POP, NULL);", " // At this point the loop quantifier (any, all, 1, 2,..)\n // is at the top of the stack. Check if the quantifier\n // is undefined (meaning \"all\") and replace it with the\n // iterations counter in that case.\n yr_parser_emit_with_arg(\n yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL);", " // Compare the loop quantifier with the number of\n // expressions evaluating to TRUE.\n yr_parser_emit_with_arg(\n yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL);", " yr_parser_emit(yyscanner, OP_INT_LE, NULL);", " compiler->loop_identifier[compiler->loop_depth] = NULL;\n yr_free($3);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | _FOR_ for_expression _OF_ string_set ':'\n {\n int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth;\n uint8_t* addr;", " if (compiler->loop_depth == MAX_LOOP_NESTING)\n compiler->last_result = \\\n ERROR_LOOP_NESTING_LIMIT_EXCEEDED;", " if (compiler->loop_for_of_mem_offset != -1)\n compiler->last_result = \\\n ERROR_NESTED_FOR_OF_LOOP;", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " yr_parser_emit_with_arg(\n yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL);", " yr_parser_emit_with_arg(\n yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL);", " // Pop the first string.\n yr_parser_emit_with_arg(\n yyscanner, OP_POP_M, mem_offset, &addr, NULL);", " compiler->loop_for_of_mem_offset = mem_offset;\n compiler->loop_address[compiler->loop_depth] = addr;\n compiler->loop_identifier[compiler->loop_depth] = NULL;\n compiler->loop_depth++;\n }\n '(' boolean_expression ')'\n {\n int mem_offset;", " compiler->loop_depth--;\n compiler->loop_for_of_mem_offset = -1;", " mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth;", " // Increment counter by the value returned by the\n // boolean expression (0 or 1). If the boolean expression\n // returned UNDEFINED the OP_ADD_M won't do anything.", " yr_parser_emit_with_arg(\n yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL);", " // Increment iterations counter.\n yr_parser_emit_with_arg(\n yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL);", " // If next string is not undefined, go back to the\n // beginning of the loop.\n yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_JNUNDEF,\n compiler->loop_address[compiler->loop_depth],\n NULL,\n NULL);", " // Pop end-of-list marker.\n yr_parser_emit(yyscanner, OP_POP, NULL);", " // At this point the loop quantifier (any, all, 1, 2,..)\n // is at top of the stack. Check if the quantifier is\n // undefined (meaning \"all\") and replace it with the\n // iterations counter in that case.\n yr_parser_emit_with_arg(\n yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL);", " // Compare the loop quantifier with the number of\n // expressions evaluating to TRUE.\n yr_parser_emit_with_arg(\n yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL);", " yr_parser_emit(yyscanner, OP_INT_LE, NULL);", " $$.type = EXPRESSION_TYPE_BOOLEAN;", " }\n | for_expression _OF_ string_set\n {\n yr_parser_emit(yyscanner, OP_OF, NULL);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | _NOT_ boolean_expression\n {\n yr_parser_emit(yyscanner, OP_NOT, NULL);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | boolean_expression _AND_\n {\n YR_FIXUP* fixup;\n void* jmp_destination_addr;", " compiler->last_result = yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_JFALSE,\n 0, // still don't know the jump destination\n NULL,\n &jmp_destination_addr);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " // create a fixup entry for the jump and push it in the stack\n fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP));", " if (fixup == NULL)\n compiler->last_error = ERROR_INSUFFICIENT_MEMORY;", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " fixup->address = jmp_destination_addr;\n fixup->next = compiler->fixup_stack_head;\n compiler->fixup_stack_head = fixup;\n }\n boolean_expression\n {\n YR_FIXUP* fixup;\n uint8_t* and_addr;", " // Ensure that we have at least two consecutive bytes in the arena's\n // current page, one for the AND opcode and one for opcode following the\n // AND. This is necessary because we need to compute the address for the\n // opcode following the AND, and we don't want the AND in one page and\n // the following opcode in another page.", " compiler->last_result = yr_arena_reserve_memory(\n compiler->code_arena, 2);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " compiler->last_result = yr_parser_emit(yyscanner, OP_AND, &and_addr);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " // Now we know the jump destination, which is the address of the\n // instruction following the AND. Let's fixup the jump address.", " fixup = compiler->fixup_stack_head;", " // We know that the AND opcode and the following one are within the same\n // page, so we can compute the address for the opcode following the AND\n // by simply adding one to its address.", " *(void**)(fixup->address) = (void*)(and_addr + 1);", " compiler->fixup_stack_head = fixup->next;\n yr_free(fixup);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | boolean_expression _OR_\n {\n YR_FIXUP* fixup;\n void* jmp_destination_addr;", " compiler->last_result = yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_JTRUE,\n 0, // still don't know the jump destination\n NULL,\n &jmp_destination_addr);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP));", " if (fixup == NULL)\n compiler->last_error = ERROR_INSUFFICIENT_MEMORY;", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " fixup->address = jmp_destination_addr;\n fixup->next = compiler->fixup_stack_head;\n compiler->fixup_stack_head = fixup;\n }\n boolean_expression\n {\n YR_FIXUP* fixup;\n uint8_t* or_addr;", " // Ensure that we have at least two consecutive bytes in the arena's\n // current page, one for the OR opcode and one for opcode following the\n // OR. This is necessary because we need to compute the address for the\n // opcode following the OR, and we don't want the OR in one page and\n // the following opcode in another page.", " compiler->last_result = yr_arena_reserve_memory(\n compiler->code_arena, 2);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " compiler->last_result = yr_parser_emit(yyscanner, OP_OR, &or_addr);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " // Now we know the jump destination, which is the address of the\n // instruction following the OP_OR. Let's fixup the jump address.", " fixup = compiler->fixup_stack_head;", " // We know that the OR opcode and the following one are within the same\n // page, so we can compute the address for the opcode following the OR\n // by simply adding one to its address.", " *(void**)(fixup->address) = (void*)(or_addr + 1);", " compiler->fixup_stack_head = fixup->next;\n yr_free(fixup);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression _LT_ primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \"<\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression _GT_ primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \">\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression _LE_ primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \"<=\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression _GE_ primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \">=\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression _EQ_ primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \"==\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression _NEQ_ primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \"!=\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression\n {\n $$ = $1;\n }\n |'(' expression ')'\n {\n $$ = $2;\n }\n ;", "\ninteger_set\n : '(' integer_enumeration ')' { $$ = INTEGER_SET_ENUMERATION; }\n | range { $$ = INTEGER_SET_RANGE; }\n ;", "\nrange\n : '(' primary_expression _DOT_DOT_ primary_expression ')'\n {\n if ($2.type != EXPRESSION_TYPE_INTEGER)\n {\n yr_compiler_set_error_extra_info(\n compiler, \"wrong type for range's lower bound\");\n compiler->last_result = ERROR_WRONG_TYPE;\n }", " if ($4.type != EXPRESSION_TYPE_INTEGER)\n {\n yr_compiler_set_error_extra_info(\n compiler, \"wrong type for range's upper bound\");\n compiler->last_result = ERROR_WRONG_TYPE;\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n ;", "\ninteger_enumeration\n : primary_expression\n {\n if ($1.type != EXPRESSION_TYPE_INTEGER)\n {\n yr_compiler_set_error_extra_info(\n compiler, \"wrong type for enumeration item\");\n compiler->last_result = ERROR_WRONG_TYPE;", " }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n | integer_enumeration ',' primary_expression\n {\n if ($3.type != EXPRESSION_TYPE_INTEGER)\n {\n yr_compiler_set_error_extra_info(\n compiler, \"wrong type for enumeration item\");\n compiler->last_result = ERROR_WRONG_TYPE;\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n ;", "\nstring_set\n : '('\n {\n // Push end-of-list marker\n yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);\n }\n string_enumeration ')'\n | _THEM_\n {\n yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);\n yr_parser_emit_pushes_for_strings(yyscanner, \"$*\");", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n ;", "\nstring_enumeration\n : string_enumeration_item\n | string_enumeration ',' string_enumeration_item\n ;", "\nstring_enumeration_item\n : _STRING_IDENTIFIER_\n {\n yr_parser_emit_pushes_for_strings(yyscanner, $1);\n yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n | _STRING_IDENTIFIER_WITH_WILDCARD_\n {\n yr_parser_emit_pushes_for_strings(yyscanner, $1);\n yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n ;", "\nfor_expression\n : primary_expression\n | _ALL_\n {\n yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);\n }\n | _ANY_\n {\n yr_parser_emit_with_arg(yyscanner, OP_PUSH, 1, NULL, NULL);\n }\n ;", "\nprimary_expression\n : '(' primary_expression ')'\n {\n $$ = $2;\n }\n | _FILESIZE_\n {\n compiler->last_result = yr_parser_emit(\n yyscanner, OP_FILESIZE, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n | _ENTRYPOINT_\n {\n yywarning(yyscanner,\n \"Using deprecated \\\"entrypoint\\\" keyword. Use the \\\"entry_point\\\" \"\n \"function from PE module instead.\");", " compiler->last_result = yr_parser_emit(\n yyscanner, OP_ENTRYPOINT, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n | _INTEGER_FUNCTION_ '(' primary_expression ')'\n {\n CHECK_TYPE($3, EXPRESSION_TYPE_INTEGER, \"intXXXX or uintXXXX\");", " // _INTEGER_FUNCTION_ could be any of int8, int16, int32, uint8,\n // uint32, etc. $1 contains an index that added to OP_READ_INT results\n // in the proper OP_INTXX opcode.", " compiler->last_result = yr_parser_emit(\n yyscanner, (uint8_t) (OP_READ_INT + $1), NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n | _NUMBER_\n {\n compiler->last_result = yr_parser_emit_with_arg(\n yyscanner, OP_PUSH, $1, NULL, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = $1;\n }\n | _DOUBLE_\n {\n compiler->last_result = yr_parser_emit_with_arg_double(\n yyscanner, OP_PUSH, $1, NULL, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_FLOAT;\n }\n | _TEXT_STRING_\n {\n SIZED_STRING* sized_string;", " compiler->last_result = yr_arena_write_data(\n compiler->sz_arena,\n $1,\n $1->length + sizeof(SIZED_STRING),\n (void**) &sized_string);", " yr_free($1);", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_PUSH,\n sized_string,\n NULL,\n NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_STRING;\n $$.value.sized_string = sized_string;\n }\n | _STRING_COUNT_\n {\n compiler->last_result = yr_parser_reduce_string_identifier(\n yyscanner, $1, OP_COUNT, UNDEFINED);", " yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n | _STRING_OFFSET_ '[' primary_expression ']'\n {\n compiler->last_result = yr_parser_reduce_string_identifier(\n yyscanner, $1, OP_OFFSET, UNDEFINED);", " yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n | _STRING_OFFSET_\n {\n compiler->last_result = yr_parser_emit_with_arg(\n yyscanner, OP_PUSH, 1, NULL, NULL);", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_parser_reduce_string_identifier(\n yyscanner, $1, OP_OFFSET, UNDEFINED);", " yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n | _STRING_LENGTH_ '[' primary_expression ']'\n {\n compiler->last_result = yr_parser_reduce_string_identifier(\n yyscanner, $1, OP_LENGTH, UNDEFINED);", " yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n | _STRING_LENGTH_\n {\n compiler->last_result = yr_parser_emit_with_arg(\n yyscanner, OP_PUSH, 1, NULL, NULL);", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_parser_reduce_string_identifier(\n yyscanner, $1, OP_LENGTH, UNDEFINED);", " yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n | identifier\n {\n if ($1.type == EXPRESSION_TYPE_INTEGER) // loop identifier\n {\n $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n else if ($1.type == EXPRESSION_TYPE_BOOLEAN) // rule identifier\n {\n $$.type = EXPRESSION_TYPE_BOOLEAN;\n $$.value.integer = UNDEFINED;\n }\n else if ($1.type == EXPRESSION_TYPE_OBJECT)\n {\n compiler->last_result = yr_parser_emit(\n yyscanner, OP_OBJ_VALUE, NULL);", " switch($1.value.object->type)\n {\n case OBJECT_TYPE_INTEGER:\n $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n break;\n case OBJECT_TYPE_FLOAT:\n $$.type = EXPRESSION_TYPE_FLOAT;\n break;\n case OBJECT_TYPE_STRING:\n $$.type = EXPRESSION_TYPE_STRING;\n $$.value.sized_string = NULL;\n break;\n default:\n yr_compiler_set_error_extra_info_fmt(\n compiler,\n \"wrong usage of identifier \\\"%s\\\"\",\n $1.identifier);\n compiler->last_result = ERROR_WRONG_TYPE;\n }\n }\n else\n {\n assert(FALSE);\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n | '-' primary_expression %prec UNARY_MINUS\n {\n CHECK_TYPE($2, EXPRESSION_TYPE_INTEGER | EXPRESSION_TYPE_FLOAT, \"-\");", " if ($2.type == EXPRESSION_TYPE_INTEGER)\n {\n $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = ($2.value.integer == UNDEFINED) ?\n UNDEFINED : -($2.value.integer);\n compiler->last_result = yr_parser_emit(yyscanner, OP_INT_MINUS, NULL);\n }\n else if ($2.type == EXPRESSION_TYPE_FLOAT)\n {\n $$.type = EXPRESSION_TYPE_FLOAT;\n compiler->last_result = yr_parser_emit(yyscanner, OP_DBL_MINUS, NULL);\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n | primary_expression '+' primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \"+\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " if ($1.type == EXPRESSION_TYPE_INTEGER &&\n $3.type == EXPRESSION_TYPE_INTEGER)\n {\n $$.value.integer = OPERATION(+, $1.value.integer, $3.value.integer);\n $$.type = EXPRESSION_TYPE_INTEGER;\n }\n else\n {\n $$.type = EXPRESSION_TYPE_FLOAT;\n }\n }\n | primary_expression '-' primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \"-\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " if ($1.type == EXPRESSION_TYPE_INTEGER &&\n $3.type == EXPRESSION_TYPE_INTEGER)\n {\n $$.value.integer = OPERATION(-, $1.value.integer, $3.value.integer);\n $$.type = EXPRESSION_TYPE_INTEGER;\n }\n else\n {\n $$.type = EXPRESSION_TYPE_FLOAT;\n }\n }\n | primary_expression '*' primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \"*\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " if ($1.type == EXPRESSION_TYPE_INTEGER &&\n $3.type == EXPRESSION_TYPE_INTEGER)\n {\n $$.value.integer = OPERATION(*, $1.value.integer, $3.value.integer);\n $$.type = EXPRESSION_TYPE_INTEGER;\n }\n else\n {\n $$.type = EXPRESSION_TYPE_FLOAT;\n }\n }\n | primary_expression '\\\\' primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \"\\\\\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " if ($1.type == EXPRESSION_TYPE_INTEGER &&\n $3.type == EXPRESSION_TYPE_INTEGER)\n {\n if ($3.value.integer != 0)\n {\n $$.value.integer = OPERATION(/, $1.value.integer, $3.value.integer);\n $$.type = EXPRESSION_TYPE_INTEGER;\n }\n else\n {\n compiler->last_result = ERROR_DIVISION_BY_ZERO;\n ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n }\n else\n {\n $$.type = EXPRESSION_TYPE_FLOAT;\n }\n }\n | primary_expression '%' primary_expression\n {\n CHECK_TYPE($1, EXPRESSION_TYPE_INTEGER, \"%\");\n CHECK_TYPE($3, EXPRESSION_TYPE_INTEGER, \"%\");", " yr_parser_emit(yyscanner, OP_MOD, NULL);", " if ($3.value.integer != 0)\n {\n $$.value.integer = OPERATION(%, $1.value.integer, $3.value.integer);\n $$.type = EXPRESSION_TYPE_INTEGER;\n }\n else\n {\n compiler->last_result = ERROR_DIVISION_BY_ZERO;\n ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n }\n | primary_expression '^' primary_expression\n {\n CHECK_TYPE($1, EXPRESSION_TYPE_INTEGER, \"^\");\n CHECK_TYPE($3, EXPRESSION_TYPE_INTEGER, \"^\");", " yr_parser_emit(yyscanner, OP_BITWISE_XOR, NULL);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = OPERATION(^, $1.value.integer, $3.value.integer);\n }\n | primary_expression '&' primary_expression\n {\n CHECK_TYPE($1, EXPRESSION_TYPE_INTEGER, \"^\");\n CHECK_TYPE($3, EXPRESSION_TYPE_INTEGER, \"^\");", " yr_parser_emit(yyscanner, OP_BITWISE_AND, NULL);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = OPERATION(&, $1.value.integer, $3.value.integer);\n }\n | primary_expression '|' primary_expression\n {\n CHECK_TYPE($1, EXPRESSION_TYPE_INTEGER, \"|\");\n CHECK_TYPE($3, EXPRESSION_TYPE_INTEGER, \"|\");", " yr_parser_emit(yyscanner, OP_BITWISE_OR, NULL);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = OPERATION(|, $1.value.integer, $3.value.integer);\n }\n | '~' primary_expression\n {\n CHECK_TYPE($2, EXPRESSION_TYPE_INTEGER, \"~\");", " yr_parser_emit(yyscanner, OP_BITWISE_NOT, NULL);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = ($2.value.integer == UNDEFINED) ?\n UNDEFINED : ~($2.value.integer);\n }\n | primary_expression _SHIFT_LEFT_ primary_expression\n {\n CHECK_TYPE($1, EXPRESSION_TYPE_INTEGER, \"<<\");\n CHECK_TYPE($3, EXPRESSION_TYPE_INTEGER, \"<<\");", " yr_parser_emit(yyscanner, OP_SHL, NULL);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = OPERATION(<<, $1.value.integer, $3.value.integer);\n }\n | primary_expression _SHIFT_RIGHT_ primary_expression\n {\n CHECK_TYPE($1, EXPRESSION_TYPE_INTEGER, \">>\");\n CHECK_TYPE($3, EXPRESSION_TYPE_INTEGER, \">>\");", " yr_parser_emit(yyscanner, OP_SHR, NULL);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = OPERATION(>>, $1.value.integer, $3.value.integer);\n }\n | regexp\n {\n $$ = $1;\n }\n ;", "%%" ]
[ 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, 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, 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, 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, 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, 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, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [1022], "buggy_code_start_loc": [1020], "filenames": ["libyara/grammar.y"], "fixing_code_end_loc": [1025], "fixing_code_start_loc": [1020], "message": "libyara/grammar.y in YARA 3.5.0 allows remote attackers to cause a denial of service (use-after-free and application crash) via a crafted rule that is mishandled in the yr_compiler_destroy function.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:virustotal:yara:3.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "0254F781-4B89-4557-8F17-1F228A3A8216", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "libyara/grammar.y in YARA 3.5.0 allows remote attackers to cause a denial of service (use-after-free and application crash) via a crafted rule that is mishandled in the yr_compiler_destroy function."}, {"lang": "es", "value": "libyara/grammar.y en YARA 3.5.0 permite a atacantes remotos provocar una denegaci\u00f3n de servicio (uso despu\u00e9s de liberaci\u00f3n de memoria y ca\u00edda de la aplicaci\u00f3n) a trav\u00e9s de una regla manipulada que no se maneja correctamente en la funci\u00f3n yr_compiler_destroy."}], "evaluatorComment": null, "id": "CVE-2017-5924", "lastModified": "2017-05-02T01:59:02.937", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-04-03T05:59:00.737", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/98075"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/VirusTotal/yara/commit/7f02eca670f29c00a1d2c305e96febae6ce5d37b"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Patch"], "url": "https://github.com/VirusTotal/yara/issues/593"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-416"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/VirusTotal/yara/commit/7f02eca670f29c00a1d2c305e96febae6ce5d37b"}, "type": "CWE-416"}
189
Determine whether the {function_name} code is vulnerable or not.
[ "/*\nCopyright (c) 2007-2013. The YARA Authors. All Rights Reserved.", "Redistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:", "1. Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.", "2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation and/or\nother materials provided with the distribution.", "3. Neither the name of the copyright holder nor the names of its contributors\nmay be used to endorse or promote products derived from this software without\nspecific prior written permission.", "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/", "%{", "\n#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n#include <limits.h>\n#include <stddef.h>", "\n#include <yara/integers.h>\n#include <yara/utils.h>\n#include <yara/strutils.h>\n#include <yara/compiler.h>\n#include <yara/object.h>\n#include <yara/sizedstr.h>\n#include <yara/exec.h>\n#include <yara/error.h>\n#include <yara/mem.h>\n#include <yara/lexer.h>\n#include <yara/parser.h>", "\n#define YYERROR_VERBOSE", "#define YYMALLOC yr_malloc\n#define YYFREE yr_free", "#define INTEGER_SET_ENUMERATION 1\n#define INTEGER_SET_RANGE 2", "#define ERROR_IF(x) \\\n if (x) \\\n { \\\n yyerror(yyscanner, compiler, NULL); \\\n YYERROR; \\\n } \\", "\n#define CHECK_TYPE(expression, expected_type, op) \\\n if (((expression.type) & (expected_type)) == 0) \\\n { \\\n switch(expression.type) \\\n { \\\n case EXPRESSION_TYPE_INTEGER: \\\n yr_compiler_set_error_extra_info( \\\n compiler, \"wrong type \\\"integer\\\" for \" op \" operator\"); \\\n break; \\\n case EXPRESSION_TYPE_FLOAT: \\\n yr_compiler_set_error_extra_info( \\\n compiler, \"wrong type \\\"float\\\" for \" op \" operator\"); \\\n break; \\\n case EXPRESSION_TYPE_STRING: \\\n yr_compiler_set_error_extra_info( \\\n compiler, \"wrong type \\\"string\\\" for \" op \" operator\"); \\\n break; \\\n case EXPRESSION_TYPE_BOOLEAN: \\\n yr_compiler_set_error_extra_info( \\\n compiler, \"wrong type \\\"boolean\\\" for \" op \" operator\"); \\\n break; \\\n } \\\n compiler->last_result = ERROR_WRONG_TYPE; \\\n yyerror(yyscanner, compiler, NULL); \\\n YYERROR; \\\n }\n%}", "\n%expect 1 // expect 1 shift/reduce conflicts", "// Uncomment this line to print parsing information that can be useful to\n// debug YARA's grammar.", "// %debug", "%name-prefix=\"yara_yy\"\n%pure-parser\n%parse-param {void *yyscanner}\n%parse-param {YR_COMPILER* compiler}\n%lex-param {yyscan_t yyscanner}\n%lex-param {YR_COMPILER* compiler}", "%token _DOT_DOT_\n%token _RULE_\n%token _PRIVATE_\n%token _GLOBAL_\n%token _META_\n%token <string> _STRINGS_\n%token _CONDITION_\n%token <c_string> _IDENTIFIER_\n%token <c_string> _STRING_IDENTIFIER_\n%token <c_string> _STRING_COUNT_\n%token <c_string> _STRING_OFFSET_\n%token <c_string> _STRING_LENGTH_\n%token <c_string> _STRING_IDENTIFIER_WITH_WILDCARD_\n%token <integer> _NUMBER_\n%token <double_> _DOUBLE_\n%token <integer> _INTEGER_FUNCTION_\n%token <sized_string> _TEXT_STRING_\n%token <sized_string> _HEX_STRING_\n%token <sized_string> _REGEXP_\n%token _ASCII_\n%token _WIDE_\n%token _NOCASE_\n%token _FULLWORD_\n%token _AT_\n%token _FILESIZE_\n%token _ENTRYPOINT_\n%token _ALL_\n%token _ANY_\n%token _IN_\n%token _OF_\n%token _FOR_\n%token _THEM_\n%token _MATCHES_\n%token _CONTAINS_\n%token _IMPORT_", "%token _TRUE_\n%token _FALSE_", "%left _OR_\n%left _AND_\n%left '|'\n%left '^'\n%left '&'\n%left _EQ_ _NEQ_\n%left _LT_ _LE_ _GT_ _GE_\n%left _SHIFT_LEFT_ _SHIFT_RIGHT_\n%left '+' '-'\n%left '*' '\\\\' '%'\n%right _NOT_ '~' UNARY_MINUS", "%type <rule> rule", "%type <string> strings\n%type <string> string_declaration\n%type <string> string_declarations", "%type <meta> meta\n%type <meta> meta_declaration\n%type <meta> meta_declarations", "%type <c_string> tags\n%type <c_string> tag_list", "%type <integer> string_modifier\n%type <integer> string_modifiers", "%type <integer> integer_set", "%type <integer> rule_modifier\n%type <integer> rule_modifiers", "\n%type <expression> primary_expression\n%type <expression> boolean_expression\n%type <expression> expression\n%type <expression> identifier\n%type <expression> regexp", "%type <c_string> arguments\n%type <c_string> arguments_list", "%destructor { yr_free($$); } _IDENTIFIER_\n%destructor { yr_free($$); } _STRING_COUNT_\n%destructor { yr_free($$); } _STRING_OFFSET_\n%destructor { yr_free($$); } _STRING_LENGTH_\n%destructor { yr_free($$); } _STRING_IDENTIFIER_\n%destructor { yr_free($$); } _STRING_IDENTIFIER_WITH_WILDCARD_\n%destructor { yr_free($$); } _TEXT_STRING_\n%destructor { yr_free($$); } _HEX_STRING_\n%destructor { yr_free($$); } _REGEXP_", "%union {\n EXPRESSION expression;\n SIZED_STRING* sized_string;\n char* c_string;\n int64_t integer;\n double double_;\n YR_STRING* string;\n YR_META* meta;\n YR_RULE* rule;\n}", "\n%%", "rules\n : /* empty */\n | rules rule\n | rules import\n | rules error rule /* on error skip until next rule..*/\n | rules error import /* .. or import statement */\n | rules error \"include\" /* .. or include statement */\n ;", "\nimport\n : _IMPORT_ _TEXT_STRING_\n {\n int result = yr_parser_reduce_import(yyscanner, $2);", " yr_free($2);", " ERROR_IF(result != ERROR_SUCCESS);\n }\n ;", "\nrule\n : rule_modifiers _RULE_ _IDENTIFIER_\n {\n YR_RULE* rule = yr_parser_reduce_rule_declaration_phase_1(\n yyscanner, (int32_t) $1, $3);", " ERROR_IF(rule == NULL);", " $<rule>$ = rule;\n }\n tags '{' meta strings\n {\n YR_RULE* rule = $<rule>4; // rule created in phase 1", " rule->tags = $5;\n rule->metas = $7;\n rule->strings = $8;\n }\n condition '}'\n {\n YR_RULE* rule = $<rule>4; // rule created in phase 1", " compiler->last_result = yr_parser_reduce_rule_declaration_phase_2(\n yyscanner, rule);", " yr_free($3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n ;", "\nmeta\n : /* empty */\n {\n $$ = NULL;\n }\n | _META_ ':' meta_declarations\n {\n // Each rule have a list of meta-data info, consisting in a\n // sequence of YR_META structures. The last YR_META structure does\n // not represent a real meta-data, it's just a end-of-list marker\n // identified by a specific type (META_TYPE_NULL). Here we\n // write the end-of-list marker.", " YR_META null_meta;", " memset(&null_meta, 0xFF, sizeof(YR_META));\n null_meta.type = META_TYPE_NULL;", " compiler->last_result = yr_arena_write_data(\n compiler->metas_arena,\n &null_meta,\n sizeof(YR_META),\n NULL);", " $$ = $3;", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n ;", "\nstrings\n : /* empty */\n {\n $$ = NULL;\n }\n | _STRINGS_ ':' string_declarations\n {\n // Each rule have a list of strings, consisting in a sequence\n // of YR_STRING structures. The last YR_STRING structure does not\n // represent a real string, it's just a end-of-list marker\n // identified by a specific flag (STRING_FLAGS_NULL). Here we\n // write the end-of-list marker.", " YR_STRING null_string;", " memset(&null_string, 0xFF, sizeof(YR_STRING));\n null_string.g_flags = STRING_GFLAGS_NULL;", " compiler->last_result = yr_arena_write_data(\n compiler->strings_arena,\n &null_string,\n sizeof(YR_STRING),\n NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$ = $3;\n }\n ;", "\ncondition\n : _CONDITION_ ':' boolean_expression\n ;", "\nrule_modifiers\n : /* empty */ { $$ = 0; }\n | rule_modifiers rule_modifier { $$ = $1 | $2; }\n ;", "\nrule_modifier\n : _PRIVATE_ { $$ = RULE_GFLAGS_PRIVATE; }\n | _GLOBAL_ { $$ = RULE_GFLAGS_GLOBAL; }\n ;", "\ntags\n : /* empty */\n {\n $$ = NULL;\n }\n | ':' tag_list\n {\n // Tags list is represented in the arena as a sequence\n // of null-terminated strings, the sequence ends with an\n // additional null character. Here we write the ending null\n //character. Example: tag1\\0tag2\\0tag3\\0\\0", " compiler->last_result = yr_arena_write_string(\n yyget_extra(yyscanner)->sz_arena, \"\", NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$ = $2;\n }\n ;", "\ntag_list\n : _IDENTIFIER_\n {\n char* identifier;", " compiler->last_result = yr_arena_write_string(\n yyget_extra(yyscanner)->sz_arena, $1, &identifier);", " yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$ = identifier;\n }\n | tag_list _IDENTIFIER_\n {\n char* tag_name = $1;\n size_t tag_length = tag_name != NULL ? strlen(tag_name) : 0;", " while (tag_length > 0)\n {\n if (strcmp(tag_name, $2) == 0)\n {\n yr_compiler_set_error_extra_info(compiler, tag_name);\n compiler->last_result = ERROR_DUPLICATED_TAG_IDENTIFIER;\n break;\n }", " tag_name = (char*) yr_arena_next_address(\n yyget_extra(yyscanner)->sz_arena,\n tag_name,\n tag_length + 1);", " tag_length = tag_name != NULL ? strlen(tag_name) : 0;\n }", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_arena_write_string(\n yyget_extra(yyscanner)->sz_arena, $2, NULL);", " yr_free($2);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$ = $1;\n }\n ;", "", "meta_declarations\n : meta_declaration { $$ = $1; }\n | meta_declarations meta_declaration { $$ = $1; }\n ;", "\nmeta_declaration\n : _IDENTIFIER_ '=' _TEXT_STRING_\n {\n SIZED_STRING* sized_string = $3;", " $$ = yr_parser_reduce_meta_declaration(\n yyscanner,\n META_TYPE_STRING,\n $1,\n sized_string->c_string,\n 0);", " yr_free($1);\n yr_free($3);", " ERROR_IF($$ == NULL);\n }\n | _IDENTIFIER_ '=' _NUMBER_\n {\n $$ = yr_parser_reduce_meta_declaration(\n yyscanner,\n META_TYPE_INTEGER,\n $1,\n NULL,\n $3);", " yr_free($1);", " ERROR_IF($$ == NULL);\n }\n | _IDENTIFIER_ '=' '-' _NUMBER_\n {\n $$ = yr_parser_reduce_meta_declaration(\n yyscanner,\n META_TYPE_INTEGER,\n $1,\n NULL,\n -$4);", " yr_free($1);", " ERROR_IF($$ == NULL);\n }\n | _IDENTIFIER_ '=' _TRUE_\n {\n $$ = yr_parser_reduce_meta_declaration(\n yyscanner,\n META_TYPE_BOOLEAN,\n $1,\n NULL,\n TRUE);", " yr_free($1);", " ERROR_IF($$ == NULL);\n }\n | _IDENTIFIER_ '=' _FALSE_\n {\n $$ = yr_parser_reduce_meta_declaration(\n yyscanner,\n META_TYPE_BOOLEAN,\n $1,\n NULL,\n FALSE);", " yr_free($1);", " ERROR_IF($$ == NULL);\n }\n ;", "\nstring_declarations\n : string_declaration { $$ = $1; }\n | string_declarations string_declaration { $$ = $1; }\n ;", "\nstring_declaration\n : _STRING_IDENTIFIER_ '='\n {\n compiler->error_line = yyget_lineno(yyscanner);\n }\n _TEXT_STRING_ string_modifiers\n {\n $$ = yr_parser_reduce_string_declaration(\n yyscanner, (int32_t) $5, $1, $4);", " yr_free($1);\n yr_free($4);", " ERROR_IF($$ == NULL);\n compiler->error_line = 0;\n }\n | _STRING_IDENTIFIER_ '='\n {\n compiler->error_line = yyget_lineno(yyscanner);\n }\n _REGEXP_ string_modifiers\n {\n $$ = yr_parser_reduce_string_declaration(\n yyscanner, (int32_t) $5 | STRING_GFLAGS_REGEXP, $1, $4);", " yr_free($1);\n yr_free($4);", " ERROR_IF($$ == NULL);", " compiler->error_line = 0;\n }\n | _STRING_IDENTIFIER_ '=' _HEX_STRING_\n {\n $$ = yr_parser_reduce_string_declaration(\n yyscanner, STRING_GFLAGS_HEXADECIMAL, $1, $3);", " yr_free($1);\n yr_free($3);", " ERROR_IF($$ == NULL);\n }\n ;", "\nstring_modifiers\n : /* empty */ { $$ = 0; }\n | string_modifiers string_modifier { $$ = $1 | $2; }\n ;", "\nstring_modifier\n : _WIDE_ { $$ = STRING_GFLAGS_WIDE; }\n | _ASCII_ { $$ = STRING_GFLAGS_ASCII; }\n | _NOCASE_ { $$ = STRING_GFLAGS_NO_CASE; }\n | _FULLWORD_ { $$ = STRING_GFLAGS_FULL_WORD; }\n ;", "\nidentifier\n : _IDENTIFIER_\n {\n int var_index = yr_parser_lookup_loop_variable(yyscanner, $1);", " if (var_index >= 0)\n {\n compiler->last_result = yr_parser_emit_with_arg(\n yyscanner,\n OP_PUSH_M,\n LOOP_LOCAL_VARS * var_index,\n NULL,\n NULL);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n $$.identifier = compiler->loop_identifier[var_index];\n }\n else\n {\n // Search for identifier within the global namespace, where the\n // externals variables reside.", " YR_OBJECT* object = (YR_OBJECT*) yr_hash_table_lookup(\n compiler->objects_table, $1, NULL);", " if (object == NULL)\n {\n // If not found, search within the current namespace.\n char* ns = compiler->current_namespace->name;", " object = (YR_OBJECT*) yr_hash_table_lookup(\n compiler->objects_table, $1, ns);\n }", " if (object != NULL)\n {\n char* id;", " compiler->last_result = yr_arena_write_string(\n compiler->sz_arena, $1, &id);", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_OBJ_LOAD,\n id,\n NULL,\n NULL);", " $$.type = EXPRESSION_TYPE_OBJECT;\n $$.value.object = object;\n $$.identifier = object->identifier;\n }\n else\n {\n YR_RULE* rule = (YR_RULE*) yr_hash_table_lookup(\n compiler->rules_table,\n $1,\n compiler->current_namespace->name);", " if (rule != NULL)\n {\n compiler->last_result = yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_PUSH_RULE,\n rule,\n NULL,\n NULL);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n $$.value.integer = UNDEFINED;\n $$.identifier = rule->identifier;\n }\n else\n {\n yr_compiler_set_error_extra_info(compiler, $1);\n compiler->last_result = ERROR_UNDEFINED_IDENTIFIER;\n }\n }\n }", " yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n | identifier '.' _IDENTIFIER_\n {\n YR_OBJECT* field = NULL;", " if ($1.type == EXPRESSION_TYPE_OBJECT &&\n $1.value.object->type == OBJECT_TYPE_STRUCTURE)\n {\n field = yr_object_lookup_field($1.value.object, $3);", " if (field != NULL)\n {\n char* ident;", " compiler->last_result = yr_arena_write_string(\n compiler->sz_arena, $3, &ident);", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_OBJ_FIELD,\n ident,\n NULL,\n NULL);", " $$.type = EXPRESSION_TYPE_OBJECT;\n $$.value.object = field;\n $$.identifier = field->identifier;\n }\n else\n {\n yr_compiler_set_error_extra_info(compiler, $3);\n compiler->last_result = ERROR_INVALID_FIELD_NAME;\n }\n }\n else\n {\n yr_compiler_set_error_extra_info(\n compiler, $1.identifier);", " compiler->last_result = ERROR_NOT_A_STRUCTURE;\n }", " yr_free($3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n | identifier '[' primary_expression ']'\n {\n YR_OBJECT_ARRAY* array;\n YR_OBJECT_DICTIONARY* dict;", " if ($1.type == EXPRESSION_TYPE_OBJECT &&\n $1.value.object->type == OBJECT_TYPE_ARRAY)\n {\n if ($3.type != EXPRESSION_TYPE_INTEGER)\n {\n yr_compiler_set_error_extra_info(\n compiler, \"array indexes must be of integer type\");\n compiler->last_result = ERROR_WRONG_TYPE;\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " compiler->last_result = yr_parser_emit(\n yyscanner, OP_INDEX_ARRAY, NULL);", " array = (YR_OBJECT_ARRAY*) $1.value.object;", " $$.type = EXPRESSION_TYPE_OBJECT;\n $$.value.object = array->prototype_item;\n $$.identifier = array->identifier;\n }\n else if ($1.type == EXPRESSION_TYPE_OBJECT &&\n $1.value.object->type == OBJECT_TYPE_DICTIONARY)\n {\n if ($3.type != EXPRESSION_TYPE_STRING)\n {\n yr_compiler_set_error_extra_info(\n compiler, \"dictionary keys must be of string type\");\n compiler->last_result = ERROR_WRONG_TYPE;\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " compiler->last_result = yr_parser_emit(\n yyscanner, OP_LOOKUP_DICT, NULL);", " dict = (YR_OBJECT_DICTIONARY*) $1.value.object;", " $$.type = EXPRESSION_TYPE_OBJECT;\n $$.value.object = dict->prototype_item;\n $$.identifier = dict->identifier;\n }\n else\n {\n yr_compiler_set_error_extra_info(\n compiler, $1.identifier);", " compiler->last_result = ERROR_NOT_INDEXABLE;\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }", " | identifier '(' arguments ')'\n {\n YR_OBJECT_FUNCTION* function;\n char* args_fmt;", " if ($1.type == EXPRESSION_TYPE_OBJECT &&\n $1.value.object->type == OBJECT_TYPE_FUNCTION)\n {\n compiler->last_result = yr_parser_check_types(\n compiler, (YR_OBJECT_FUNCTION*) $1.value.object, $3);", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_arena_write_string(\n compiler->sz_arena, $3, &args_fmt);", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_CALL,\n args_fmt,\n NULL,\n NULL);", " function = (YR_OBJECT_FUNCTION*) $1.value.object;", " $$.type = EXPRESSION_TYPE_OBJECT;\n $$.value.object = function->return_obj;\n $$.identifier = function->identifier;\n }\n else\n {\n yr_compiler_set_error_extra_info(\n compiler, $1.identifier);", " compiler->last_result = ERROR_NOT_A_FUNCTION;\n }", " yr_free($3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n ;", "\narguments\n : /* empty */ { $$ = yr_strdup(\"\"); }\n | arguments_list { $$ = $1; }", "\narguments_list\n : expression\n {\n $$ = (char*) yr_malloc(MAX_FUNCTION_ARGS + 1);", " switch($1.type)\n {\n case EXPRESSION_TYPE_INTEGER:\n strlcpy($$, \"i\", MAX_FUNCTION_ARGS);\n break;\n case EXPRESSION_TYPE_FLOAT:\n strlcpy($$, \"f\", MAX_FUNCTION_ARGS);\n break;\n case EXPRESSION_TYPE_BOOLEAN:\n strlcpy($$, \"b\", MAX_FUNCTION_ARGS);\n break;\n case EXPRESSION_TYPE_STRING:\n strlcpy($$, \"s\", MAX_FUNCTION_ARGS);\n break;\n case EXPRESSION_TYPE_REGEXP:\n strlcpy($$, \"r\", MAX_FUNCTION_ARGS);\n break;\n }", " ERROR_IF($$ == NULL);\n }\n | arguments_list ',' expression\n {\n if (strlen($1) == MAX_FUNCTION_ARGS)\n {\n compiler->last_result = ERROR_TOO_MANY_ARGUMENTS;\n }\n else\n {\n switch($3.type)\n {\n case EXPRESSION_TYPE_INTEGER:\n strlcat($1, \"i\", MAX_FUNCTION_ARGS);\n break;\n case EXPRESSION_TYPE_FLOAT:\n strlcat($1, \"f\", MAX_FUNCTION_ARGS);\n break;\n case EXPRESSION_TYPE_BOOLEAN:\n strlcat($1, \"b\", MAX_FUNCTION_ARGS);\n break;\n case EXPRESSION_TYPE_STRING:\n strlcat($1, \"s\", MAX_FUNCTION_ARGS);\n break;\n case EXPRESSION_TYPE_REGEXP:\n strlcat($1, \"r\", MAX_FUNCTION_ARGS);\n break;\n }\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$ = $1;\n }\n ;", "\nregexp\n : _REGEXP_\n {\n SIZED_STRING* sized_string = $1;\n RE* re;\n RE_ERROR error;", " int re_flags = 0;", " if (sized_string->flags & SIZED_STRING_FLAGS_NO_CASE)\n re_flags |= RE_FLAGS_NO_CASE;", " if (sized_string->flags & SIZED_STRING_FLAGS_DOT_ALL)\n re_flags |= RE_FLAGS_DOT_ALL;", " compiler->last_result = yr_re_compile(\n sized_string->c_string,\n re_flags,\n compiler->re_code_arena,\n &re,\n &error);", " yr_free($1);", " if (compiler->last_result == ERROR_INVALID_REGULAR_EXPRESSION)\n yr_compiler_set_error_extra_info(compiler, error.message);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_PUSH,\n re->root_node->forward_code,\n NULL,\n NULL);", " yr_re_destroy(re);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_REGEXP;\n }\n ;", "\nboolean_expression\n : expression\n {\n if ($1.type == EXPRESSION_TYPE_STRING)\n {\n if ($1.value.sized_string != NULL)\n {\n yywarning(yyscanner,\n \"Using literal string \\\"%s\\\" in a boolean operation.\",\n $1.value.sized_string->c_string);\n }", " compiler->last_result = yr_parser_emit(\n yyscanner, OP_STR_TO_BOOL, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n ;", "expression\n : _TRUE_\n {\n compiler->last_result = yr_parser_emit_with_arg(\n yyscanner, OP_PUSH, 1, NULL, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | _FALSE_\n {\n compiler->last_result = yr_parser_emit_with_arg(\n yyscanner, OP_PUSH, 0, NULL, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression _MATCHES_ regexp\n {\n CHECK_TYPE($1, EXPRESSION_TYPE_STRING, \"matches\");\n CHECK_TYPE($3, EXPRESSION_TYPE_REGEXP, \"matches\");", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_parser_emit(\n yyscanner,\n OP_MATCHES,\n NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression _CONTAINS_ primary_expression\n {\n CHECK_TYPE($1, EXPRESSION_TYPE_STRING, \"contains\");\n CHECK_TYPE($3, EXPRESSION_TYPE_STRING, \"contains\");", " compiler->last_result = yr_parser_emit(\n yyscanner, OP_CONTAINS, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | _STRING_IDENTIFIER_\n {\n int result = yr_parser_reduce_string_identifier(\n yyscanner,\n $1,\n OP_FOUND,\n UNDEFINED);", " yr_free($1);", " ERROR_IF(result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | _STRING_IDENTIFIER_ _AT_ primary_expression\n {\n CHECK_TYPE($3, EXPRESSION_TYPE_INTEGER, \"at\");", " compiler->last_result = yr_parser_reduce_string_identifier(\n yyscanner, $1, OP_FOUND_AT, $3.value.integer);", " yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | _STRING_IDENTIFIER_ _IN_ range\n {\n compiler->last_result = yr_parser_reduce_string_identifier(\n yyscanner, $1, OP_FOUND_IN, UNDEFINED);", " yr_free($1);", " ERROR_IF(compiler->last_result!= ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | _FOR_ for_expression error\n {", " if (compiler->loop_depth > 0)\n {\n compiler->loop_depth--;\n compiler->loop_identifier[compiler->loop_depth] = NULL;\n }", " }\n | _FOR_ for_expression _IDENTIFIER_ _IN_\n {\n int var_index;", " if (compiler->loop_depth == MAX_LOOP_NESTING)\n compiler->last_result = \\\n ERROR_LOOP_NESTING_LIMIT_EXCEEDED;", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " var_index = yr_parser_lookup_loop_variable(\n yyscanner, $3);", " if (var_index >= 0)\n {\n yr_compiler_set_error_extra_info(\n compiler, $3);", " compiler->last_result = \\\n ERROR_DUPLICATED_LOOP_IDENTIFIER;\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " // Push end-of-list marker\n compiler->last_result = yr_parser_emit_with_arg(\n yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n integer_set ':'\n {\n int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth;\n uint8_t* addr;", " // Clear counter for number of expressions evaluating\n // to TRUE.\n yr_parser_emit_with_arg(\n yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL);", " // Clear iterations counter\n yr_parser_emit_with_arg(\n yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL);", " if ($6 == INTEGER_SET_ENUMERATION)\n {\n // Pop the first integer\n yr_parser_emit_with_arg(\n yyscanner, OP_POP_M, mem_offset, &addr, NULL);\n }\n else // INTEGER_SET_RANGE\n {\n // Pop higher bound of set range\n yr_parser_emit_with_arg(\n yyscanner, OP_POP_M, mem_offset + 3, &addr, NULL);", " // Pop lower bound of set range\n yr_parser_emit_with_arg(\n yyscanner, OP_POP_M, mem_offset, NULL, NULL);\n }", " compiler->loop_address[compiler->loop_depth] = addr;\n compiler->loop_identifier[compiler->loop_depth] = $3;\n compiler->loop_depth++;\n }\n '(' boolean_expression ')'\n {\n int mem_offset;", " compiler->loop_depth--;\n mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth;", " // The value at the top of the stack is the result of\n // evaluating the boolean expression, so it could be\n // 0, 1 or UNDEFINED. Add this value to a counter\n // keeping the number of expressions evaluating to true.\n // If the value is UNDEFINED instruction OP_ADD_M\n // does nothing.", " yr_parser_emit_with_arg(\n yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL);", " // Increment iterations counter\n yr_parser_emit_with_arg(\n yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL);", " if ($6 == INTEGER_SET_ENUMERATION)\n {\n yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_JNUNDEF,\n compiler->loop_address[compiler->loop_depth],\n NULL,\n NULL);\n }\n else // INTEGER_SET_RANGE\n {\n // Increment lower bound of integer set\n yr_parser_emit_with_arg(\n yyscanner, OP_INCR_M, mem_offset, NULL, NULL);", " // Push lower bound of integer set\n yr_parser_emit_with_arg(\n yyscanner, OP_PUSH_M, mem_offset, NULL, NULL);", " // Push higher bound of integer set\n yr_parser_emit_with_arg(\n yyscanner, OP_PUSH_M, mem_offset + 3, NULL, NULL);", " // Compare higher bound with lower bound, do loop again\n // if lower bound is still lower or equal than higher bound\n yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_JLE,\n compiler->loop_address[compiler->loop_depth],\n NULL,\n NULL);", " yr_parser_emit(yyscanner, OP_POP, NULL);\n yr_parser_emit(yyscanner, OP_POP, NULL);\n }", " // Pop end-of-list marker.\n yr_parser_emit(yyscanner, OP_POP, NULL);", " // At this point the loop quantifier (any, all, 1, 2,..)\n // is at the top of the stack. Check if the quantifier\n // is undefined (meaning \"all\") and replace it with the\n // iterations counter in that case.\n yr_parser_emit_with_arg(\n yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL);", " // Compare the loop quantifier with the number of\n // expressions evaluating to TRUE.\n yr_parser_emit_with_arg(\n yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL);", " yr_parser_emit(yyscanner, OP_INT_LE, NULL);", " compiler->loop_identifier[compiler->loop_depth] = NULL;\n yr_free($3);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | _FOR_ for_expression _OF_ string_set ':'\n {\n int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth;\n uint8_t* addr;", " if (compiler->loop_depth == MAX_LOOP_NESTING)\n compiler->last_result = \\\n ERROR_LOOP_NESTING_LIMIT_EXCEEDED;", " if (compiler->loop_for_of_mem_offset != -1)\n compiler->last_result = \\\n ERROR_NESTED_FOR_OF_LOOP;", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " yr_parser_emit_with_arg(\n yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL);", " yr_parser_emit_with_arg(\n yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL);", " // Pop the first string.\n yr_parser_emit_with_arg(\n yyscanner, OP_POP_M, mem_offset, &addr, NULL);", " compiler->loop_for_of_mem_offset = mem_offset;\n compiler->loop_address[compiler->loop_depth] = addr;\n compiler->loop_identifier[compiler->loop_depth] = NULL;\n compiler->loop_depth++;\n }\n '(' boolean_expression ')'\n {\n int mem_offset;", " compiler->loop_depth--;\n compiler->loop_for_of_mem_offset = -1;", " mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth;", " // Increment counter by the value returned by the\n // boolean expression (0 or 1). If the boolean expression\n // returned UNDEFINED the OP_ADD_M won't do anything.", " yr_parser_emit_with_arg(\n yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL);", " // Increment iterations counter.\n yr_parser_emit_with_arg(\n yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL);", " // If next string is not undefined, go back to the\n // beginning of the loop.\n yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_JNUNDEF,\n compiler->loop_address[compiler->loop_depth],\n NULL,\n NULL);", " // Pop end-of-list marker.\n yr_parser_emit(yyscanner, OP_POP, NULL);", " // At this point the loop quantifier (any, all, 1, 2,..)\n // is at top of the stack. Check if the quantifier is\n // undefined (meaning \"all\") and replace it with the\n // iterations counter in that case.\n yr_parser_emit_with_arg(\n yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL);", " // Compare the loop quantifier with the number of\n // expressions evaluating to TRUE.\n yr_parser_emit_with_arg(\n yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL);", " yr_parser_emit(yyscanner, OP_INT_LE, NULL);", " $$.type = EXPRESSION_TYPE_BOOLEAN;", " }\n | for_expression _OF_ string_set\n {\n yr_parser_emit(yyscanner, OP_OF, NULL);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | _NOT_ boolean_expression\n {\n yr_parser_emit(yyscanner, OP_NOT, NULL);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | boolean_expression _AND_\n {\n YR_FIXUP* fixup;\n void* jmp_destination_addr;", " compiler->last_result = yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_JFALSE,\n 0, // still don't know the jump destination\n NULL,\n &jmp_destination_addr);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " // create a fixup entry for the jump and push it in the stack\n fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP));", " if (fixup == NULL)\n compiler->last_error = ERROR_INSUFFICIENT_MEMORY;", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " fixup->address = jmp_destination_addr;\n fixup->next = compiler->fixup_stack_head;\n compiler->fixup_stack_head = fixup;\n }\n boolean_expression\n {\n YR_FIXUP* fixup;\n uint8_t* and_addr;", " // Ensure that we have at least two consecutive bytes in the arena's\n // current page, one for the AND opcode and one for opcode following the\n // AND. This is necessary because we need to compute the address for the\n // opcode following the AND, and we don't want the AND in one page and\n // the following opcode in another page.", " compiler->last_result = yr_arena_reserve_memory(\n compiler->code_arena, 2);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " compiler->last_result = yr_parser_emit(yyscanner, OP_AND, &and_addr);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " // Now we know the jump destination, which is the address of the\n // instruction following the AND. Let's fixup the jump address.", " fixup = compiler->fixup_stack_head;", " // We know that the AND opcode and the following one are within the same\n // page, so we can compute the address for the opcode following the AND\n // by simply adding one to its address.", " *(void**)(fixup->address) = (void*)(and_addr + 1);", " compiler->fixup_stack_head = fixup->next;\n yr_free(fixup);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | boolean_expression _OR_\n {\n YR_FIXUP* fixup;\n void* jmp_destination_addr;", " compiler->last_result = yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_JTRUE,\n 0, // still don't know the jump destination\n NULL,\n &jmp_destination_addr);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP));", " if (fixup == NULL)\n compiler->last_error = ERROR_INSUFFICIENT_MEMORY;", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " fixup->address = jmp_destination_addr;\n fixup->next = compiler->fixup_stack_head;\n compiler->fixup_stack_head = fixup;\n }\n boolean_expression\n {\n YR_FIXUP* fixup;\n uint8_t* or_addr;", " // Ensure that we have at least two consecutive bytes in the arena's\n // current page, one for the OR opcode and one for opcode following the\n // OR. This is necessary because we need to compute the address for the\n // opcode following the OR, and we don't want the OR in one page and\n // the following opcode in another page.", " compiler->last_result = yr_arena_reserve_memory(\n compiler->code_arena, 2);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " compiler->last_result = yr_parser_emit(yyscanner, OP_OR, &or_addr);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " // Now we know the jump destination, which is the address of the\n // instruction following the OP_OR. Let's fixup the jump address.", " fixup = compiler->fixup_stack_head;", " // We know that the OR opcode and the following one are within the same\n // page, so we can compute the address for the opcode following the OR\n // by simply adding one to its address.", " *(void**)(fixup->address) = (void*)(or_addr + 1);", " compiler->fixup_stack_head = fixup->next;\n yr_free(fixup);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression _LT_ primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \"<\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression _GT_ primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \">\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression _LE_ primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \"<=\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression _GE_ primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \">=\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression _EQ_ primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \"==\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression _NEQ_ primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \"!=\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_BOOLEAN;\n }\n | primary_expression\n {\n $$ = $1;\n }\n |'(' expression ')'\n {\n $$ = $2;\n }\n ;", "\ninteger_set\n : '(' integer_enumeration ')' { $$ = INTEGER_SET_ENUMERATION; }\n | range { $$ = INTEGER_SET_RANGE; }\n ;", "\nrange\n : '(' primary_expression _DOT_DOT_ primary_expression ')'\n {\n if ($2.type != EXPRESSION_TYPE_INTEGER)\n {\n yr_compiler_set_error_extra_info(\n compiler, \"wrong type for range's lower bound\");\n compiler->last_result = ERROR_WRONG_TYPE;\n }", " if ($4.type != EXPRESSION_TYPE_INTEGER)\n {\n yr_compiler_set_error_extra_info(\n compiler, \"wrong type for range's upper bound\");\n compiler->last_result = ERROR_WRONG_TYPE;\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n ;", "\ninteger_enumeration\n : primary_expression\n {\n if ($1.type != EXPRESSION_TYPE_INTEGER)\n {\n yr_compiler_set_error_extra_info(\n compiler, \"wrong type for enumeration item\");\n compiler->last_result = ERROR_WRONG_TYPE;", " }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n | integer_enumeration ',' primary_expression\n {\n if ($3.type != EXPRESSION_TYPE_INTEGER)\n {\n yr_compiler_set_error_extra_info(\n compiler, \"wrong type for enumeration item\");\n compiler->last_result = ERROR_WRONG_TYPE;\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n ;", "\nstring_set\n : '('\n {\n // Push end-of-list marker\n yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);\n }\n string_enumeration ')'\n | _THEM_\n {\n yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);\n yr_parser_emit_pushes_for_strings(yyscanner, \"$*\");", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n ;", "\nstring_enumeration\n : string_enumeration_item\n | string_enumeration ',' string_enumeration_item\n ;", "\nstring_enumeration_item\n : _STRING_IDENTIFIER_\n {\n yr_parser_emit_pushes_for_strings(yyscanner, $1);\n yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n | _STRING_IDENTIFIER_WITH_WILDCARD_\n {\n yr_parser_emit_pushes_for_strings(yyscanner, $1);\n yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n ;", "\nfor_expression\n : primary_expression\n | _ALL_\n {\n yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL);\n }\n | _ANY_\n {\n yr_parser_emit_with_arg(yyscanner, OP_PUSH, 1, NULL, NULL);\n }\n ;", "\nprimary_expression\n : '(' primary_expression ')'\n {\n $$ = $2;\n }\n | _FILESIZE_\n {\n compiler->last_result = yr_parser_emit(\n yyscanner, OP_FILESIZE, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n | _ENTRYPOINT_\n {\n yywarning(yyscanner,\n \"Using deprecated \\\"entrypoint\\\" keyword. Use the \\\"entry_point\\\" \"\n \"function from PE module instead.\");", " compiler->last_result = yr_parser_emit(\n yyscanner, OP_ENTRYPOINT, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n | _INTEGER_FUNCTION_ '(' primary_expression ')'\n {\n CHECK_TYPE($3, EXPRESSION_TYPE_INTEGER, \"intXXXX or uintXXXX\");", " // _INTEGER_FUNCTION_ could be any of int8, int16, int32, uint8,\n // uint32, etc. $1 contains an index that added to OP_READ_INT results\n // in the proper OP_INTXX opcode.", " compiler->last_result = yr_parser_emit(\n yyscanner, (uint8_t) (OP_READ_INT + $1), NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n | _NUMBER_\n {\n compiler->last_result = yr_parser_emit_with_arg(\n yyscanner, OP_PUSH, $1, NULL, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = $1;\n }\n | _DOUBLE_\n {\n compiler->last_result = yr_parser_emit_with_arg_double(\n yyscanner, OP_PUSH, $1, NULL, NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_FLOAT;\n }\n | _TEXT_STRING_\n {\n SIZED_STRING* sized_string;", " compiler->last_result = yr_arena_write_data(\n compiler->sz_arena,\n $1,\n $1->length + sizeof(SIZED_STRING),\n (void**) &sized_string);", " yr_free($1);", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_parser_emit_with_arg_reloc(\n yyscanner,\n OP_PUSH,\n sized_string,\n NULL,\n NULL);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_STRING;\n $$.value.sized_string = sized_string;\n }\n | _STRING_COUNT_\n {\n compiler->last_result = yr_parser_reduce_string_identifier(\n yyscanner, $1, OP_COUNT, UNDEFINED);", " yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n | _STRING_OFFSET_ '[' primary_expression ']'\n {\n compiler->last_result = yr_parser_reduce_string_identifier(\n yyscanner, $1, OP_OFFSET, UNDEFINED);", " yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n | _STRING_OFFSET_\n {\n compiler->last_result = yr_parser_emit_with_arg(\n yyscanner, OP_PUSH, 1, NULL, NULL);", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_parser_reduce_string_identifier(\n yyscanner, $1, OP_OFFSET, UNDEFINED);", " yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n | _STRING_LENGTH_ '[' primary_expression ']'\n {\n compiler->last_result = yr_parser_reduce_string_identifier(\n yyscanner, $1, OP_LENGTH, UNDEFINED);", " yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n | _STRING_LENGTH_\n {\n compiler->last_result = yr_parser_emit_with_arg(\n yyscanner, OP_PUSH, 1, NULL, NULL);", " if (compiler->last_result == ERROR_SUCCESS)\n compiler->last_result = yr_parser_reduce_string_identifier(\n yyscanner, $1, OP_LENGTH, UNDEFINED);", " yr_free($1);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n | identifier\n {\n if ($1.type == EXPRESSION_TYPE_INTEGER) // loop identifier\n {\n $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n }\n else if ($1.type == EXPRESSION_TYPE_BOOLEAN) // rule identifier\n {\n $$.type = EXPRESSION_TYPE_BOOLEAN;\n $$.value.integer = UNDEFINED;\n }\n else if ($1.type == EXPRESSION_TYPE_OBJECT)\n {\n compiler->last_result = yr_parser_emit(\n yyscanner, OP_OBJ_VALUE, NULL);", " switch($1.value.object->type)\n {\n case OBJECT_TYPE_INTEGER:\n $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = UNDEFINED;\n break;\n case OBJECT_TYPE_FLOAT:\n $$.type = EXPRESSION_TYPE_FLOAT;\n break;\n case OBJECT_TYPE_STRING:\n $$.type = EXPRESSION_TYPE_STRING;\n $$.value.sized_string = NULL;\n break;\n default:\n yr_compiler_set_error_extra_info_fmt(\n compiler,\n \"wrong usage of identifier \\\"%s\\\"\",\n $1.identifier);\n compiler->last_result = ERROR_WRONG_TYPE;\n }\n }\n else\n {\n assert(FALSE);\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n | '-' primary_expression %prec UNARY_MINUS\n {\n CHECK_TYPE($2, EXPRESSION_TYPE_INTEGER | EXPRESSION_TYPE_FLOAT, \"-\");", " if ($2.type == EXPRESSION_TYPE_INTEGER)\n {\n $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = ($2.value.integer == UNDEFINED) ?\n UNDEFINED : -($2.value.integer);\n compiler->last_result = yr_parser_emit(yyscanner, OP_INT_MINUS, NULL);\n }\n else if ($2.type == EXPRESSION_TYPE_FLOAT)\n {\n $$.type = EXPRESSION_TYPE_FLOAT;\n compiler->last_result = yr_parser_emit(yyscanner, OP_DBL_MINUS, NULL);\n }", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n | primary_expression '+' primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \"+\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " if ($1.type == EXPRESSION_TYPE_INTEGER &&\n $3.type == EXPRESSION_TYPE_INTEGER)\n {\n $$.value.integer = OPERATION(+, $1.value.integer, $3.value.integer);\n $$.type = EXPRESSION_TYPE_INTEGER;\n }\n else\n {\n $$.type = EXPRESSION_TYPE_FLOAT;\n }\n }\n | primary_expression '-' primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \"-\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " if ($1.type == EXPRESSION_TYPE_INTEGER &&\n $3.type == EXPRESSION_TYPE_INTEGER)\n {\n $$.value.integer = OPERATION(-, $1.value.integer, $3.value.integer);\n $$.type = EXPRESSION_TYPE_INTEGER;\n }\n else\n {\n $$.type = EXPRESSION_TYPE_FLOAT;\n }\n }\n | primary_expression '*' primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \"*\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " if ($1.type == EXPRESSION_TYPE_INTEGER &&\n $3.type == EXPRESSION_TYPE_INTEGER)\n {\n $$.value.integer = OPERATION(*, $1.value.integer, $3.value.integer);\n $$.type = EXPRESSION_TYPE_INTEGER;\n }\n else\n {\n $$.type = EXPRESSION_TYPE_FLOAT;\n }\n }\n | primary_expression '\\\\' primary_expression\n {\n compiler->last_result = yr_parser_reduce_operation(\n yyscanner, \"\\\\\", $1, $3);", " ERROR_IF(compiler->last_result != ERROR_SUCCESS);", " if ($1.type == EXPRESSION_TYPE_INTEGER &&\n $3.type == EXPRESSION_TYPE_INTEGER)\n {\n if ($3.value.integer != 0)\n {\n $$.value.integer = OPERATION(/, $1.value.integer, $3.value.integer);\n $$.type = EXPRESSION_TYPE_INTEGER;\n }\n else\n {\n compiler->last_result = ERROR_DIVISION_BY_ZERO;\n ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n }\n else\n {\n $$.type = EXPRESSION_TYPE_FLOAT;\n }\n }\n | primary_expression '%' primary_expression\n {\n CHECK_TYPE($1, EXPRESSION_TYPE_INTEGER, \"%\");\n CHECK_TYPE($3, EXPRESSION_TYPE_INTEGER, \"%\");", " yr_parser_emit(yyscanner, OP_MOD, NULL);", " if ($3.value.integer != 0)\n {\n $$.value.integer = OPERATION(%, $1.value.integer, $3.value.integer);\n $$.type = EXPRESSION_TYPE_INTEGER;\n }\n else\n {\n compiler->last_result = ERROR_DIVISION_BY_ZERO;\n ERROR_IF(compiler->last_result != ERROR_SUCCESS);\n }\n }\n | primary_expression '^' primary_expression\n {\n CHECK_TYPE($1, EXPRESSION_TYPE_INTEGER, \"^\");\n CHECK_TYPE($3, EXPRESSION_TYPE_INTEGER, \"^\");", " yr_parser_emit(yyscanner, OP_BITWISE_XOR, NULL);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = OPERATION(^, $1.value.integer, $3.value.integer);\n }\n | primary_expression '&' primary_expression\n {\n CHECK_TYPE($1, EXPRESSION_TYPE_INTEGER, \"^\");\n CHECK_TYPE($3, EXPRESSION_TYPE_INTEGER, \"^\");", " yr_parser_emit(yyscanner, OP_BITWISE_AND, NULL);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = OPERATION(&, $1.value.integer, $3.value.integer);\n }\n | primary_expression '|' primary_expression\n {\n CHECK_TYPE($1, EXPRESSION_TYPE_INTEGER, \"|\");\n CHECK_TYPE($3, EXPRESSION_TYPE_INTEGER, \"|\");", " yr_parser_emit(yyscanner, OP_BITWISE_OR, NULL);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = OPERATION(|, $1.value.integer, $3.value.integer);\n }\n | '~' primary_expression\n {\n CHECK_TYPE($2, EXPRESSION_TYPE_INTEGER, \"~\");", " yr_parser_emit(yyscanner, OP_BITWISE_NOT, NULL);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = ($2.value.integer == UNDEFINED) ?\n UNDEFINED : ~($2.value.integer);\n }\n | primary_expression _SHIFT_LEFT_ primary_expression\n {\n CHECK_TYPE($1, EXPRESSION_TYPE_INTEGER, \"<<\");\n CHECK_TYPE($3, EXPRESSION_TYPE_INTEGER, \"<<\");", " yr_parser_emit(yyscanner, OP_SHL, NULL);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = OPERATION(<<, $1.value.integer, $3.value.integer);\n }\n | primary_expression _SHIFT_RIGHT_ primary_expression\n {\n CHECK_TYPE($1, EXPRESSION_TYPE_INTEGER, \">>\");\n CHECK_TYPE($3, EXPRESSION_TYPE_INTEGER, \">>\");", " yr_parser_emit(yyscanner, OP_SHR, NULL);", " $$.type = EXPRESSION_TYPE_INTEGER;\n $$.value.integer = OPERATION(>>, $1.value.integer, $3.value.integer);\n }\n | regexp\n {\n $$ = $1;\n }\n ;", "%%" ]
[ 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, 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, 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, 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, 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, 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1022], "buggy_code_start_loc": [1020], "filenames": ["libyara/grammar.y"], "fixing_code_end_loc": [1025], "fixing_code_start_loc": [1020], "message": "libyara/grammar.y in YARA 3.5.0 allows remote attackers to cause a denial of service (use-after-free and application crash) via a crafted rule that is mishandled in the yr_compiler_destroy function.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:virustotal:yara:3.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "0254F781-4B89-4557-8F17-1F228A3A8216", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "libyara/grammar.y in YARA 3.5.0 allows remote attackers to cause a denial of service (use-after-free and application crash) via a crafted rule that is mishandled in the yr_compiler_destroy function."}, {"lang": "es", "value": "libyara/grammar.y en YARA 3.5.0 permite a atacantes remotos provocar una denegaci\u00f3n de servicio (uso despu\u00e9s de liberaci\u00f3n de memoria y ca\u00edda de la aplicaci\u00f3n) a trav\u00e9s de una regla manipulada que no se maneja correctamente en la funci\u00f3n yr_compiler_destroy."}], "evaluatorComment": null, "id": "CVE-2017-5924", "lastModified": "2017-05-02T01:59:02.937", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-04-03T05:59:00.737", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/98075"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/VirusTotal/yara/commit/7f02eca670f29c00a1d2c305e96febae6ce5d37b"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Patch"], "url": "https://github.com/VirusTotal/yara/issues/593"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-416"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/VirusTotal/yara/commit/7f02eca670f29c00a1d2c305e96febae6ce5d37b"}, "type": "CWE-416"}
189
Determine whether the {function_name} code is vulnerable or not.
[ "/* vi:set ts=8 sts=4 sw=4 noet:\n *\n * VIM - Vi IMproved\tby Bram Moolenaar\n *\n * Do \":help uganda\" in Vim to read copying and usage conditions.\n * Do \":help credits\" in Vim to see a list of people who contributed.\n * See README.txt for an overview of the Vim source code.\n */", "/*\n * eval.c: Expression evaluation.\n */\n#define USING_FLOAT_STUFF", "#include \"vim.h\"", "#if defined(FEAT_EVAL) || defined(PROTO)", "#ifdef VMS\n# include <float.h>\n#endif", "#define NAMESPACE_CHAR\t(char_u *)\"abglstvw\"", "/*\n * When recursively copying lists and dicts we need to remember which ones we\n * have done to avoid endless recursiveness. This unique ID is used for that.\n * The last bit is used for previous_funccal, ignored when comparing.\n */\nstatic int current_copyID = 0;", "static int eval2(char_u **arg, typval_T *rettv, evalarg_T *evalarg);\nstatic int eval3(char_u **arg, typval_T *rettv, evalarg_T *evalarg);\nstatic int eval4(char_u **arg, typval_T *rettv, evalarg_T *evalarg);\nstatic int eval5(char_u **arg, typval_T *rettv, evalarg_T *evalarg);\nstatic int eval6(char_u **arg, typval_T *rettv, evalarg_T *evalarg);\nstatic int eval7(char_u **arg, typval_T *rettv, evalarg_T *evalarg, int want_string);\nstatic int eval8(char_u **arg, typval_T *rettv, evalarg_T *evalarg, int want_string);\nstatic int eval9(char_u **arg, typval_T *rettv, evalarg_T *evalarg, int want_string);\nstatic int eval9_leader(typval_T *rettv, int numeric_only, char_u *start_leader, char_u **end_leaderp);", "static int free_unref_items(int copyID);\nstatic char_u *make_expanded_name(char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end);", "/*\n * Return \"n1\" divided by \"n2\", taking care of dividing by zero.\n * If \"failed\" is not NULL set it to TRUE when dividing by zero fails.\n */\n\tvarnumber_T\nnum_divide(varnumber_T n1, varnumber_T n2, int *failed)\n{\n varnumber_T\tresult;", " if (n2 == 0)\n {\n\tif (in_vim9script())\n\t{\n\t emsg(_(e_divide_by_zero));\n\t if (failed != NULL)\n\t\t*failed = TRUE;\n\t}\n\tif (n1 == 0)\n\t result = VARNUM_MIN; // similar to NaN\n\telse if (n1 < 0)\n\t result = -VARNUM_MAX;\n\telse\n\t result = VARNUM_MAX;\n }\n else if (n1 == VARNUM_MIN && n2 == -1)\n {\n\t// specific case: trying to do VARNUM_MIN / -1 results in a positive\n\t// number that doesn't fit in varnumber_T and causes an FPE\n\tresult = VARNUM_MAX;\n }\n else\n\tresult = n1 / n2;", " return result;\n}", "/*\n * Return \"n1\" modulus \"n2\", taking care of dividing by zero.\n * If \"failed\" is not NULL set it to TRUE when dividing by zero fails.\n */\n\tvarnumber_T\nnum_modulus(varnumber_T n1, varnumber_T n2, int *failed)\n{\n if (n2 == 0 && in_vim9script())\n {\n\temsg(_(e_divide_by_zero));\n\tif (failed != NULL)\n\t *failed = TRUE;\n }\n return (n2 == 0) ? 0 : (n1 % n2);\n}", "/*\n * Initialize the global and v: variables.\n */\n void\neval_init(void)\n{\n evalvars_init();\n func_init();\n}", "#if defined(EXITFREE) || defined(PROTO)\n void\neval_clear(void)\n{\n evalvars_clear();\n free_scriptnames(); // must come after evalvars_clear().\n free_locales();", " // autoloaded script names\n free_autoload_scriptnames();", " // unreferenced lists and dicts\n (void)garbage_collect(FALSE);", " // functions not garbage collected\n free_all_functions();\n}\n#endif", " void\nfill_evalarg_from_eap(evalarg_T *evalarg, exarg_T *eap, int skip)\n{\n init_evalarg(evalarg);\n evalarg->eval_flags = skip ? 0 : EVAL_EVALUATE;", " if (eap == NULL)\n\treturn;", " evalarg->eval_cstack = eap->cstack;\n if (sourcing_a_script(eap) || eap->getline == get_list_line)\n {\n\tevalarg->eval_getline = eap->getline;\n\tevalarg->eval_cookie = eap->cookie;\n }\n}", "/*\n * Top level evaluation function, returning a boolean.\n * Sets \"error\" to TRUE if there was an error.\n * Return TRUE or FALSE.\n */\n int\neval_to_bool(\n char_u\t*arg,\n int\t\t*error,\n exarg_T\t*eap,\n int\t\tskip,\t // only parse, don't execute\n int\t\tuse_simple_function)\n{\n typval_T\ttv;\n varnumber_T\tretval = FALSE;\n evalarg_T\tevalarg;\n int\t\tr;", " fill_evalarg_from_eap(&evalarg, eap, skip);", " if (skip)\n\t++emsg_skip;\n if (use_simple_function)\n\tr = eval0_simple_funccal(arg, &tv, eap, &evalarg);\n else\n\tr = eval0(arg, &tv, eap, &evalarg);\n if (r == FAIL)\n\t*error = TRUE;\n else\n {\n\t*error = FALSE;\n\tif (!skip)\n\t{\n\t if (in_vim9script())\n\t\tretval = tv_get_bool_chk(&tv, error);\n\t else\n\t\tretval = (tv_get_number_chk(&tv, error) != 0);\n\t clear_tv(&tv);\n\t}\n }\n if (skip)\n\t--emsg_skip;\n clear_evalarg(&evalarg, eap);", " return (int)retval;\n}", "/*\n * Call eval1() and give an error message if not done at a lower level.\n */\n static int\neval1_emsg(char_u **arg, typval_T *rettv, exarg_T *eap)\n{\n char_u\t*start = *arg;\n int\t\tret;\n int\t\tdid_emsg_before = did_emsg;\n int\t\tcalled_emsg_before = called_emsg;\n evalarg_T\tevalarg;", " fill_evalarg_from_eap(&evalarg, eap, eap != NULL && eap->skip);", " ret = eval1(arg, rettv, &evalarg);\n if (ret == FAIL)\n {\n\t// Report the invalid expression unless the expression evaluation has\n\t// been cancelled due to an aborting error, an interrupt, or an\n\t// exception, or we already gave a more specific error.\n\t// Also check called_emsg for when using assert_fails().\n\tif (!aborting() && did_emsg == did_emsg_before\n\t\t\t\t\t && called_emsg == called_emsg_before)\n\t semsg(_(e_invalid_expression_str), start);\n }\n clear_evalarg(&evalarg, eap);\n return ret;\n}", "/*\n * Return whether a typval is a valid expression to pass to eval_expr_typval()\n * or eval_expr_to_bool(). An empty string returns FALSE;\n */\n int\neval_expr_valid_arg(typval_T *tv)\n{\n return tv->v_type != VAR_UNKNOWN\n\t && (tv->v_type != VAR_STRING\n\t\t || (tv->vval.v_string != NULL && *tv->vval.v_string != NUL));\n}", "/*\n * When calling eval_expr_typval() many times we only need one funccall_T.\n * Returns NULL when no funccall_T is to be used.\n * When returning non-NULL remove_funccal() must be called later.\n */\n funccall_T *\neval_expr_get_funccal(typval_T *expr, typval_T *rettv)\n{\n if (expr->v_type != VAR_PARTIAL)\n\treturn NULL;", " partial_T *partial = expr->vval.v_partial;\n if (partial == NULL)\n\treturn NULL;\n if (partial->pt_func == NULL\n\t || partial->pt_func->uf_def_status == UF_NOT_COMPILED)\n\treturn NULL;", " return create_funccal(partial->pt_func, rettv);\n}", "/*\n * Evaluate an expression, which can be a function, partial or string.\n * Pass arguments \"argv[argc]\".\n * \"fc_arg\" is from eval_expr_get_funccal() or NULL;\n * Return the result in \"rettv\" and OK or FAIL.\n */\n int\neval_expr_typval(\n\ttypval_T *expr,\n\ttypval_T *argv,\n\tint\t argc,\n\tfunccall_T *fc_arg,\n\ttypval_T *rettv)\n{\n char_u\t*s;\n char_u\tbuf[NUMBUFLEN];\n funcexe_T\tfuncexe;", " if (expr->v_type == VAR_FUNC)\n {\n\ts = expr->vval.v_string;\n\tif (s == NULL || *s == NUL)\n\t return FAIL;\n\tCLEAR_FIELD(funcexe);\n\tfuncexe.fe_evaluate = TRUE;\n\tif (call_func(s, -1, rettv, argc, argv, &funcexe) == FAIL)\n\t return FAIL;\n }\n else if (expr->v_type == VAR_PARTIAL)\n {\n\tpartial_T *partial = expr->vval.v_partial;", "\tif (partial == NULL)\n\t return FAIL;", "\tif (partial->pt_func != NULL\n\t\t\t && partial->pt_func->uf_def_status != UF_NOT_COMPILED)\n\t{\n\t funccall_T\t*fc = fc_arg != NULL ? fc_arg\n\t\t\t\t : create_funccal(partial->pt_func, rettv);\n\t int\t\tr;", "\t if (fc == NULL)\n\t\treturn FAIL;", "\t // Shortcut to call a compiled function with minimal overhead.\n\t r = call_def_function(partial->pt_func, argc, argv,\n\t\t\t\t DEF_USE_PT_ARGV, partial, NULL, fc, rettv);\n\t if (fc_arg == NULL)\n\t\tremove_funccal();\n\t if (r == FAIL)\n\t\treturn FAIL;\n\t}\n\telse\n\t{\n\t s = partial_name(partial);\n\t if (s == NULL || *s == NUL)\n\t\treturn FAIL;\n\t CLEAR_FIELD(funcexe);\n\t funcexe.fe_evaluate = TRUE;\n\t funcexe.fe_partial = partial;\n\t if (call_func(s, -1, rettv, argc, argv, &funcexe) == FAIL)\n\t\treturn FAIL;\n\t}\n }\n else if (expr->v_type == VAR_INSTR)\n {\n\treturn exe_typval_instr(expr, rettv);\n }\n else\n {\n\ts = tv_get_string_buf_chk_strict(expr, buf, in_vim9script());\n\tif (s == NULL)\n\t return FAIL;\n\ts = skipwhite(s);\n\tif (eval1_emsg(&s, rettv, NULL) == FAIL)\n\t return FAIL;\n\tif (*skipwhite(s) != NUL) // check for trailing chars after expr\n\t{\n\t clear_tv(rettv);\n\t semsg(_(e_invalid_expression_str), s);\n\t return FAIL;\n\t}\n }\n return OK;\n}", "/*\n * Like eval_to_bool() but using a typval_T instead of a string.\n * Works for string, funcref and partial.\n */\n int\neval_expr_to_bool(typval_T *expr, int *error)\n{\n typval_T\trettv;\n int\t\tres;", " if (eval_expr_typval(expr, NULL, 0, NULL, &rettv) == FAIL)\n {\n\t*error = TRUE;\n\treturn FALSE;\n }\n res = (tv_get_bool_chk(&rettv, error) != 0);\n clear_tv(&rettv);\n return res;\n}", "/*\n * Top level evaluation function, returning a string. If \"skip\" is TRUE,\n * only parsing to \"nextcmd\" is done, without reporting errors. Return\n * pointer to allocated memory, or NULL for failure or when \"skip\" is TRUE.\n */\n char_u *\neval_to_string_skip(\n char_u\t*arg,\n exarg_T\t*eap,\n int\t\tskip)\t // only parse, don't execute\n{\n typval_T\ttv;\n char_u\t*retval;\n evalarg_T\tevalarg;", " fill_evalarg_from_eap(&evalarg, eap, skip);\n if (skip)\n\t++emsg_skip;\n if (eval0(arg, &tv, eap, &evalarg) == FAIL || skip)\n\tretval = NULL;\n else\n {\n\tretval = vim_strsave(tv_get_string(&tv));\n\tclear_tv(&tv);\n }\n if (skip)\n\t--emsg_skip;\n clear_evalarg(&evalarg, eap);", " return retval;\n}", "/*\n * Initialize \"evalarg\" for use.\n */\n void\ninit_evalarg(evalarg_T *evalarg)\n{\n CLEAR_POINTER(evalarg);\n ga_init2(&evalarg->eval_tofree_ga, sizeof(char_u *), 20);\n}", "/*\n * If \"evalarg->eval_tofree\" is not NULL free it later.\n * Caller is expected to overwrite \"evalarg->eval_tofree\" next.\n */\n static void\nfree_eval_tofree_later(evalarg_T *evalarg)\n{\n if (evalarg->eval_tofree == NULL)\n\treturn;", " if (ga_grow(&evalarg->eval_tofree_ga, 1) == OK)\n\t((char_u **)evalarg->eval_tofree_ga.ga_data)\n\t [evalarg->eval_tofree_ga.ga_len++]\n\t = evalarg->eval_tofree;\n else\n\tvim_free(evalarg->eval_tofree);\n}", "/*\n * After using \"evalarg\" filled from \"eap\": free the memory.\n */\n void\nclear_evalarg(evalarg_T *evalarg, exarg_T *eap)\n{\n if (evalarg == NULL)\n\treturn;", " garray_T *etga = &evalarg->eval_tofree_ga;", " if (evalarg->eval_tofree != NULL || evalarg->eval_using_cmdline)\n {\n\tif (eap != NULL)\n\t{\n\t // We may need to keep the original command line, e.g. for\n\t // \":let\" it has the variable names. But we may also need\n\t // the new one, \"nextcmd\" points into it. Keep both.\n\t vim_free(eap->cmdline_tofree);\n\t eap->cmdline_tofree = *eap->cmdlinep;", "\t if (evalarg->eval_using_cmdline && etga->ga_len > 0)\n\t {\n\t\t// \"nextcmd\" points into the last line in eval_tofree_ga,\n\t\t// need to keep it around.\n\t\t--etga->ga_len;\n\t\t*eap->cmdlinep = ((char_u **)etga->ga_data)[etga->ga_len];\n\t\tvim_free(evalarg->eval_tofree);\n\t }\n\t else\n\t\t*eap->cmdlinep = evalarg->eval_tofree;\n\t}\n\telse\n\t vim_free(evalarg->eval_tofree);\n\tevalarg->eval_tofree = NULL;\n }", " ga_clear_strings(etga);\n VIM_CLEAR(evalarg->eval_tofree_lambda);\n}", "/*\n * Skip over an expression at \"*pp\".\n * Return FAIL for an error, OK otherwise.\n */\n int\nskip_expr(char_u **pp, evalarg_T *evalarg)\n{\n typval_T\trettv;", " *pp = skipwhite(*pp);\n return eval1(pp, &rettv, evalarg);\n}", "/*\n * Skip over an expression at \"*arg\".\n * If in Vim9 script and line breaks are encountered, the lines are\n * concatenated. \"evalarg->eval_tofree\" will be set accordingly.\n * \"arg\" is advanced to just after the expression.\n * \"start\" is set to the start of the expression, \"end\" to just after the end.\n * Also when the expression is copied to allocated memory.\n * Return FAIL for an error, OK otherwise.\n */\n int\nskip_expr_concatenate(\n\tchar_u\t **arg,\n\tchar_u\t **start,\n\tchar_u\t **end,\n\tevalarg_T *evalarg)\n{\n typval_T\trettv;\n int\t\tres;\n int\t\tvim9script = in_vim9script();\n garray_T *gap = evalarg == NULL ? NULL : &evalarg->eval_ga;\n garray_T *freegap = evalarg == NULL ? NULL : &evalarg->eval_freega;\n int\t\tsave_flags = evalarg == NULL ? 0 : evalarg->eval_flags;\n int\t\tevaluate = evalarg == NULL\n\t\t\t ? FALSE : (evalarg->eval_flags & EVAL_EVALUATE);", " if (vim9script && evaluate\n\t && (evalarg->eval_cookie != NULL || evalarg->eval_cctx != NULL))\n {\n\tga_init2(gap, sizeof(char_u *), 10);\n\t// leave room for \"start\"\n\tif (ga_grow(gap, 1) == OK)\n\t ++gap->ga_len;\n\tga_init2(freegap, sizeof(char_u *), 10);\n }\n *start = *arg;", " // Don't evaluate the expression.\n if (evalarg != NULL)\n\tevalarg->eval_flags &= ~EVAL_EVALUATE;\n *arg = skipwhite(*arg);\n res = eval1(arg, &rettv, evalarg);\n *end = *arg;\n if (evalarg != NULL)\n\tevalarg->eval_flags = save_flags;", " if (vim9script && evaluate\n\t && (evalarg->eval_cookie != NULL || evalarg->eval_cctx != NULL))\n {\n\tif (evalarg->eval_ga.ga_len == 1)\n\t{\n\t // just the one line, no need to concatenate\n\t ga_clear(gap);\n\t gap->ga_itemsize = 0;\n\t}\n\telse\n\t{\n\t char_u\t *p;\n\t size_t\t endoff = STRLEN(*arg);", "\t // Line breaks encountered, concatenate all the lines.\n\t *((char_u **)gap->ga_data) = *start;\n\t p = ga_concat_strings(gap, \" \");", "\t // free the lines only when using getsourceline()\n\t if (evalarg->eval_cookie != NULL)\n\t {\n\t\t// Do not free the first line, the caller can still use it.\n\t\t*((char_u **)gap->ga_data) = NULL;\n\t\t// Do not free the last line, \"arg\" points into it, free it\n\t\t// later. Also free \"eval_tofree\" later if needed.\n\t\tfree_eval_tofree_later(evalarg);\n\t\tevalarg->eval_tofree =\n\t\t\t\t ((char_u **)gap->ga_data)[gap->ga_len - 1];\n\t\t((char_u **)gap->ga_data)[gap->ga_len - 1] = NULL;\n\t\tga_clear_strings(gap);\n\t }\n\t else\n\t {\n\t\tga_clear(gap);", "\t\t// free lines that were explicitly marked for freeing\n\t\tga_clear_strings(freegap);\n\t }", "\t gap->ga_itemsize = 0;\n\t if (p == NULL)\n\t\treturn FAIL;\n\t *start = p;\n\t vim_free(evalarg->eval_tofree_lambda);\n\t evalarg->eval_tofree_lambda = p;\n\t // Compute \"end\" relative to the end.\n\t *end = *start + STRLEN(*start) - endoff;\n\t}\n }", " return res;\n}", "/*\n * Convert \"tv\" to a string.\n * When \"convert\" is TRUE convert a List into a sequence of lines and convert\n * a Float to a String.\n * Returns an allocated string (NULL when out of memory).\n */\n char_u *\ntypval2string(typval_T *tv, int convert)\n{\n garray_T\tga;\n char_u\t*retval;\n char_u\tnumbuf[NUMBUFLEN];", " if (convert && tv->v_type == VAR_LIST)\n {\n\tga_init2(&ga, sizeof(char), 80);\n\tif (tv->vval.v_list != NULL)\n\t{\n\t list_join(&ga, tv->vval.v_list, (char_u *)\"\\n\", TRUE, FALSE, 0);\n\t if (tv->vval.v_list->lv_len > 0)\n\t\tga_append(&ga, NL);\n\t}\n\tga_append(&ga, NUL);\n\tretval = (char_u *)ga.ga_data;\n }\n else if (convert && tv->v_type == VAR_FLOAT)\n {\n\tvim_snprintf((char *)numbuf, NUMBUFLEN, \"%g\", tv->vval.v_float);\n\tretval = vim_strsave(numbuf);\n }\n else\n\tretval = vim_strsave(tv_get_string(tv));\n return retval;\n}", "/*\n * Top level evaluation function, returning a string. Does not handle line\n * breaks.\n * When \"convert\" is TRUE convert a List into a sequence of lines and convert\n * a Float to a String.\n * Return pointer to allocated memory, or NULL for failure.\n */\n char_u *\neval_to_string_eap(\n char_u\t*arg,\n int\t\tconvert,\n exarg_T\t*eap,\n int\t\tuse_simple_function)\n{\n typval_T\ttv;\n char_u\t*retval;\n evalarg_T\tevalarg;\n int\t\tr;", " fill_evalarg_from_eap(&evalarg, eap, eap != NULL && eap->skip);\n if (use_simple_function)\n\tr = eval0_simple_funccal(arg, &tv, NULL, &evalarg);\n else\n\tr = eval0(arg, &tv, NULL, &evalarg);\n if (r == FAIL)\n\tretval = NULL;\n else\n {\n\tretval = typval2string(&tv, convert);\n\tclear_tv(&tv);\n }\n clear_evalarg(&evalarg, NULL);", " return retval;\n}", " char_u *\neval_to_string(\n char_u\t*arg,\n int\t\tconvert,\n int\t\tuse_simple_function)\n{\n return eval_to_string_eap(arg, convert, NULL, use_simple_function);\n}", "/*\n * Call eval_to_string() without using current local variables and using\n * textlock. When \"use_sandbox\" is TRUE use the sandbox.\n * Use legacy Vim script syntax.\n */\n char_u *\neval_to_string_safe(\n char_u\t*arg,\n int\t\tuse_sandbox,\n int\t\tkeep_script_version,\n int\t\tuse_simple_function)\n{\n char_u\t*retval;\n funccal_entry_T funccal_entry;\n int\t\tsave_sc_version = current_sctx.sc_version;\n int\t\tsave_garbage = may_garbage_collect;", " if (!keep_script_version)\n\tcurrent_sctx.sc_version = 1;\n save_funccal(&funccal_entry);\n if (use_sandbox)\n\t++sandbox;\n ++textlock;\n may_garbage_collect = FALSE;\n retval = eval_to_string(arg, FALSE, use_simple_function);\n if (use_sandbox)\n\t--sandbox;\n --textlock;\n may_garbage_collect = save_garbage;\n restore_funccal();\n current_sctx.sc_version = save_sc_version;\n return retval;\n}", "/*\n * Top level evaluation function, returning a number.\n * Evaluates \"expr\" silently.\n * Returns -1 for an error.\n */\n varnumber_T\neval_to_number(char_u *expr, int use_simple_function)\n{\n typval_T\trettv;\n varnumber_T\tretval;\n char_u\t*p = skipwhite(expr);\n int\t\tr = NOTDONE;", " ++emsg_off;", " if (use_simple_function)\n\tr = may_call_simple_func(expr, &rettv);\n if (r == NOTDONE)\n\tr = eval1(&p, &rettv, &EVALARG_EVALUATE);\n if (r == FAIL)\n\tretval = -1;\n else\n {\n\tretval = tv_get_number_chk(&rettv, NULL);\n\tclear_tv(&rettv);\n }\n --emsg_off;", " return retval;\n}", "/*\n * Top level evaluation function.\n * Returns an allocated typval_T with the result.\n * Returns NULL when there is an error.\n */\n typval_T *\neval_expr(char_u *arg, exarg_T *eap)\n{\n return eval_expr_ext(arg, eap, FALSE);\n}", " typval_T *\neval_expr_ext(char_u *arg, exarg_T *eap, int use_simple_function)\n{\n typval_T\t*tv;\n evalarg_T\tevalarg;", " fill_evalarg_from_eap(&evalarg, eap, eap != NULL && eap->skip);", " tv = ALLOC_ONE(typval_T);\n if (tv != NULL)\n {\n\tint\tr = NOTDONE;", "\tif (use_simple_function)\n\t r = eval0_simple_funccal(arg, tv, eap, &evalarg);\n\tif (r == NOTDONE)\n\t r = eval0(arg, tv, eap, &evalarg);", "\tif (r == FAIL)\n\t VIM_CLEAR(tv);\n }", " clear_evalarg(&evalarg, eap);\n return tv;\n}", "/*\n * \"*arg\" points to what can be a function name in the form of \"import.Name\" or\n * \"Funcref\". Return the name of the function. Set \"tofree\" to something that\n * was allocated.\n * If \"verbose\" is FALSE no errors are given.\n * Return NULL for any failure.\n */\n static char_u *\nderef_function_name(\n\t char_u\t**arg,\n\t char_u\t**tofree,\n\t evalarg_T\t*evalarg,\n\t int\t\tverbose)\n{\n typval_T\tref;\n char_u\t*name = *arg;\n int\t\tsave_flags = 0;", " ref.v_type = VAR_UNKNOWN;\n if (evalarg != NULL)\n {\n\t// need to evaluate this to get an import, like in \"a.Func\"\n\tsave_flags = evalarg->eval_flags;\n\tevalarg->eval_flags |= EVAL_EVALUATE;\n }\n if (eval9(arg, &ref, evalarg, FALSE) == FAIL)\n {\n\tdictitem_T\t*v;", "\t// If <SID>VarName was used it would not be found, try another way.\n\tv = find_var_also_in_script(name, NULL, FALSE);\n\tif (v == NULL)\n\t{\n\t name = NULL;\n\t goto theend;\n\t}\n\tcopy_tv(&v->di_tv, &ref);\n }\n if (*skipwhite(*arg) != NUL)\n {\n\tif (verbose)\n\t semsg(_(e_trailing_characters_str), *arg);\n\tname = NULL;\n }\n else if (ref.v_type == VAR_FUNC && ref.vval.v_string != NULL)\n {\n\tname = ref.vval.v_string;\n\tref.vval.v_string = NULL;\n\t*tofree = name;\n }\n else if (ref.v_type == VAR_PARTIAL && ref.vval.v_partial != NULL)\n {\n\tif (ref.vval.v_partial->pt_argc > 0\n\t\t|| ref.vval.v_partial->pt_dict != NULL)\n\t{\n\t if (verbose)\n\t\temsg(_(e_cannot_use_partial_here));\n\t name = NULL;\n\t}\n\telse\n\t{\n\t name = vim_strsave(partial_name(ref.vval.v_partial));\n\t *tofree = name;\n\t}\n }\n else\n {\n\tif (verbose)\n\t semsg(_(e_not_callable_type_str), name);\n\tname = NULL;\n }", "theend:\n clear_tv(&ref);\n if (evalarg != NULL)\n\tevalarg->eval_flags = save_flags;\n return name;\n}", "/*\n * Call some Vim script function and return the result in \"*rettv\".\n * Uses argv[0] to argv[argc - 1] for the function arguments. argv[argc]\n * should have type VAR_UNKNOWN.\n * Returns OK or FAIL.\n */\n int\ncall_vim_function(\n char_u *func,\n int\t\targc,\n typval_T\t*argv,\n typval_T\t*rettv)\n{\n int\t\tret;\n funcexe_T\tfuncexe;\n char_u\t*arg;\n char_u\t*name;\n char_u\t*tofree = NULL;\n int\t\tignore_errors;", " rettv->v_type = VAR_UNKNOWN;\t\t// clear_tv() uses this\n CLEAR_FIELD(funcexe);\n funcexe.fe_firstline = curwin->w_cursor.lnum;\n funcexe.fe_lastline = curwin->w_cursor.lnum;\n funcexe.fe_evaluate = TRUE;", " // The name might be \"import.Func\" or \"Funcref\". We don't know, we need to\n // ignore errors for an undefined name. But we do want errors when an\n // autoload script has errors. Guess that when there is a dot in the name\n // showing errors is the right choice.\n ignore_errors = vim_strchr(func, '.') == NULL;\n arg = func;\n if (ignore_errors)\n\t++emsg_off;\n name = deref_function_name(&arg, &tofree, &EVALARG_EVALUATE, FALSE);\n if (ignore_errors)\n\t--emsg_off;\n if (name == NULL)\n\tname = func;", " ret = call_func(name, -1, rettv, argc, argv, &funcexe);", " if (ret == FAIL)\n\tclear_tv(rettv);\n vim_free(tofree);", " return ret;\n}", "/*\n * Call Vim script function \"func\" and return the result as a string.\n * Uses \"argv[0]\" to \"argv[argc - 1]\" for the function arguments. \"argv[argc]\"\n * should have type VAR_UNKNOWN.\n * Returns NULL when calling the function fails.\n */\n void *\ncall_func_retstr(\n char_u *func,\n int\t\targc,\n typval_T\t*argv)\n{\n typval_T\trettv;\n char_u\t*retval;", " if (call_vim_function(func, argc, argv, &rettv) == FAIL)\n\treturn NULL;", " retval = vim_strsave(tv_get_string(&rettv));\n clear_tv(&rettv);\n return retval;\n}", "/*\n * Call Vim script function \"func\" and return the result as a List.\n * Uses \"argv\" and \"argc\" as call_func_retstr().\n * Returns NULL when there is something wrong.\n * Gives an error when the returned value is not a list.\n */\n void *\ncall_func_retlist(\n char_u *func,\n int\t\targc,\n typval_T\t*argv)\n{\n typval_T\trettv;", " if (call_vim_function(func, argc, argv, &rettv) == FAIL)\n\treturn NULL;", " if (rettv.v_type != VAR_LIST)\n {\n\tsemsg(_(e_custom_list_completion_function_does_not_return_list_but_str),\n\t\tvartype_name(rettv.v_type));\n\tclear_tv(&rettv);\n\treturn NULL;\n }", " return rettv.vval.v_list;\n}", "#if defined(FEAT_FOLDING) || defined(PROTO)\n/*\n * Evaluate \"arg\", which is 'foldexpr'.\n * Note: caller must set \"curwin\" to match \"arg\".\n * Returns the foldlevel, and any character preceding it in \"*cp\". Doesn't\n * give error messages.\n */\n int\neval_foldexpr(win_T *wp, int *cp)\n{\n char_u\t*arg;\n typval_T\ttv;\n varnumber_T\tretval;\n char_u\t*s;\n sctx_T\tsaved_sctx = current_sctx;\n int\t\tuse_sandbox = was_set_insecurely((char_u *)\"foldexpr\",\n\t\t\t\t\t\t\t\t OPT_LOCAL);", " arg = skipwhite(wp->w_p_fde);\n current_sctx = wp->w_p_script_ctx[WV_FDE];", " ++emsg_off;\n if (use_sandbox)\n\t++sandbox;\n ++textlock;\n *cp = NUL;", " // Evaluate the expression. If the expression is \"FuncName()\" call the\n // function directly.\n if (eval0_simple_funccal(arg, &tv, NULL, &EVALARG_EVALUATE) == FAIL)\n\tretval = 0;\n else\n {\n\t// If the result is a number, just return the number.\n\tif (tv.v_type == VAR_NUMBER)\n\t retval = tv.vval.v_number;\n\telse if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)\n\t retval = 0;\n\telse\n\t{\n\t // If the result is a string, check if there is a non-digit before\n\t // the number.\n\t s = tv.vval.v_string;\n\t if (!VIM_ISDIGIT(*s) && *s != '-')\n\t\t*cp = *s++;\n\t retval = atol((char *)s);\n\t}\n\tclear_tv(&tv);\n }\n --emsg_off;\n if (use_sandbox)\n\t--sandbox;\n --textlock;\n clear_evalarg(&EVALARG_EVALUATE, NULL);\n current_sctx = saved_sctx;", " return (int)retval;\n}\n#endif", "/*\n * Get an lval: variable, Dict item or List item that can be assigned a value\n * to: \"name\", \"na{me}\", \"name[expr]\", \"name[expr:expr]\", \"name[expr][expr]\",\n * \"name.key\", \"name.key[expr]\" etc.\n * Indexing only works if \"name\" is an existing List or Dictionary.\n * \"name\" points to the start of the name.\n * If \"rettv\" is not NULL it points to the value to be assigned.\n * \"unlet\" is TRUE for \":unlet\": slightly different behavior when something is\n * wrong; must end in space or cmd separator.\n *\n * flags:\n * GLV_QUIET: do not give error messages\n * GLV_READ_ONLY: will not change the variable\n * GLV_NO_AUTOLOAD: do not use script autoloading\n *\n * Returns a pointer to just after the name, including indexes.\n * When an evaluation error occurs \"lp->ll_name\" is NULL;\n * Returns NULL for a parsing error. Still need to free items in \"lp\"!\n */\n char_u *\nget_lval(\n char_u\t*name,\n typval_T\t*rettv,\n lval_T\t*lp,\n int\t\tunlet,\n int\t\tskip,\n int\t\tflags,\t // GLV_ values\n int\t\tfne_flags) // flags for find_name_end()\n{\n char_u\t*p;\n char_u\t*expr_start, *expr_end;\n int\t\tcc;\n dictitem_T\t*v;\n typval_T\tvar1;\n typval_T\tvar2;\n int\t\tempty1 = FALSE;\n char_u\t*key = NULL;\n int\t\tlen;\n hashtab_T\t*ht = NULL;\n int\t\tquiet = flags & GLV_QUIET;\n int\t\twriting;\n int\t\tvim9script = in_vim9script();", " // Clear everything in \"lp\".\n CLEAR_POINTER(lp);", " if (skip || (flags & GLV_COMPILING))\n {\n\t// When skipping or compiling just find the end of the name.\n\tlp->ll_name = name;\n\tlp->ll_name_end = find_name_end(name, NULL, NULL,\n\t\t\t\t\t\t FNE_INCL_BR | fne_flags);\n\treturn lp->ll_name_end;\n }", " // Cannot use \"s:var\" at the Vim9 script level. \"s: type\" is OK.\n if (vim9script && at_script_level()\n\t\t && name[0] == 's' && name[1] == ':' && !VIM_ISWHITE(name[2]))\n {\n\tsemsg(_(e_cannot_use_s_colon_in_vim9_script_str), name);\n\treturn NULL;\n }", " // Find the end of the name.\n p = find_name_end(name, &expr_start, &expr_end, fne_flags);\n lp->ll_name_end = p;\n if (expr_start != NULL)\n {\n\t// Don't expand the name when we already know there is an error.\n\tif (unlet && !VIM_ISWHITE(*p) && !ends_excmd(*p)\n\t\t\t\t\t\t && *p != '[' && *p != '.')\n\t{\n\t semsg(_(e_trailing_characters_str), p);\n\t return NULL;\n\t}", "\tlp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);\n\tif (lp->ll_exp_name == NULL)\n\t{\n\t // Report an invalid expression in braces, unless the\n\t // expression evaluation has been cancelled due to an\n\t // aborting error, an interrupt, or an exception.\n\t if (!aborting() && !quiet)\n\t {\n\t\temsg_severe = TRUE;\n\t\tsemsg(_(e_invalid_argument_str), name);\n\t\treturn NULL;\n\t }\n\t}\n\tlp->ll_name = lp->ll_exp_name;\n }\n else\n {\n\tlp->ll_name = name;", "\tif (vim9script)\n\t{\n\t // \"a: type\" is declaring variable \"a\" with a type, not \"a:\".\n\t // However, \"g:[key]\" is indexing a dictionary.\n\t if (p == name + 2 && p[-1] == ':' && *p != '[')\n\t {\n\t\t--p;\n\t\tlp->ll_name_end = p;\n\t }\n\t if (*p == ':')\n\t {\n\t\tchar_u\t *tp = skipwhite(p + 1);", "\t\tif (is_scoped_variable(name))\n\t\t{\n\t\t semsg(_(e_cannot_use_type_with_this_variable_str), name);\n\t\t return NULL;\n\t\t}\n\t\tif (tp == p + 1 && !quiet)\n\t\t{\n\t\t semsg(_(e_white_space_required_after_str_str), \":\", p);\n\t\t return NULL;\n\t\t}\n\t\tif (!SCRIPT_ID_VALID(current_sctx.sc_sid))\n\t\t{\n\t\t semsg(_(e_using_type_not_in_script_context_str), p);\n\t\t return NULL;\n\t\t}", "\t\t// parse the type after the name\n\t\tlp->ll_type = parse_type(&tp,\n\t\t\t &SCRIPT_ITEM(current_sctx.sc_sid)->sn_type_list,\n\t\t\t !quiet);\n\t\tif (lp->ll_type == NULL && !quiet)\n\t\t return NULL;\n\t\tlp->ll_name_end = tp;\n\t }\n\t}\n }\n if (lp->ll_name == NULL)\n\treturn p;", " if (*p == '.')\n {\n\timported_T *import = find_imported(lp->ll_name, p - lp->ll_name, TRUE);", "\tif (import != NULL)\n\t{\n\t ufunc_T *ufunc;\n\t type_T *type;", "\t import_check_sourced_sid(&import->imp_sid);\n\t lp->ll_sid = import->imp_sid;\n\t lp->ll_name = skipwhite(p + 1);\n\t p = find_name_end(lp->ll_name, NULL, NULL, fne_flags);\n\t lp->ll_name_end = p;", "\t // check the item is exported\n\t cc = *p;\n\t *p = NUL;\n\t if (find_exported(import->imp_sid, lp->ll_name, &ufunc, &type,\n\t\t\t\t\t\t NULL, NULL, TRUE) == -1)\n\t {\n\t\t*p = cc;\n\t\treturn NULL;\n\t }\n\t *p = cc;\n\t}\n }", " // Without [idx] or .key we are done.\n if ((*p != '[' && *p != '.'))\n\treturn p;", " if (vim9script && lval_root != NULL)\n {\n\t// using local variable\n\tlp->ll_tv = lval_root;\n\tv = NULL;\n }\n else\n {\n\tcc = *p;\n\t*p = NUL;\n\t// When we would write to the variable pass &ht and prevent autoload.\n\twriting = !(flags & GLV_READ_ONLY);\n\tv = find_var(lp->ll_name, writing ? &ht : NULL,\n\t\t\t\t\t (flags & GLV_NO_AUTOLOAD) || writing);\n\tif (v == NULL && !quiet)\n\t semsg(_(e_undefined_variable_str), lp->ll_name);\n\t*p = cc;\n\tif (v == NULL)\n\t return NULL;\n\tlp->ll_tv = &v->di_tv;\n }", " if (vim9script && (flags & GLV_NO_DECL) == 0)\n {\n\tif (!quiet)\n\t semsg(_(e_variable_already_declared_str), lp->ll_name);\n\treturn NULL;\n }", " /*\n * Loop until no more [idx] or .key is following.\n */\n var1.v_type = VAR_UNKNOWN;\n var2.v_type = VAR_UNKNOWN;\n while (*p == '[' || (*p == '.' && p[1] != '=' && p[1] != '.'))\n {\n\tvartype_T v_type = lp->ll_tv->v_type;", "\tif (*p == '.' && v_type != VAR_DICT\n\t\t && v_type != VAR_OBJECT\n\t\t && v_type != VAR_CLASS)\n\t{\n\t if (!quiet)\n\t\tsemsg(_(e_dot_can_only_be_used_on_dictionary_str), name);\n\t return NULL;\n\t}\n\tif (v_type != VAR_LIST\n\t\t&& v_type != VAR_DICT\n\t\t&& v_type != VAR_BLOB\n\t\t&& v_type != VAR_OBJECT\n\t\t&& v_type != VAR_CLASS)\n\t{\n\t if (!quiet)\n\t\temsg(_(e_can_only_index_list_dictionary_or_blob));\n\t return NULL;\n\t}", "\t// A NULL list/blob works like an empty list/blob, allocate one now.\n\tint r = OK;\n\tif (v_type == VAR_LIST && lp->ll_tv->vval.v_list == NULL)\n\t r = rettv_list_alloc(lp->ll_tv);\n\telse if (v_type == VAR_BLOB\n\t\t\t\t\t && lp->ll_tv->vval.v_blob == NULL)\n\t r = rettv_blob_alloc(lp->ll_tv);\n\tif (r == FAIL)\n\t return NULL;", "\tif (lp->ll_range)\n\t{\n\t if (!quiet)\n\t\temsg(_(e_slice_must_come_last));\n\t return NULL;\n\t}", "\tif (vim9script && lp->ll_valtype == NULL\n\t\t&& v != NULL\n\t\t&& lp->ll_tv == &v->di_tv\n\t\t&& ht != NULL && ht == get_script_local_ht())\n\t{\n\t svar_T *sv = find_typval_in_script(lp->ll_tv, 0, TRUE);", "\t // Vim9 script local variable: get the type\n\t if (sv != NULL)\n\t\tlp->ll_valtype = sv->sv_type;\n\t}", "\tlen = -1;\n\tif (*p == '.')\n\t{\n\t key = p + 1;\n\t for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)\n\t\t;\n\t if (len == 0)\n\t {\n\t\tif (!quiet)\n\t\t emsg(_(e_cannot_use_empty_key_for_dictionary));\n\t\treturn NULL;\n\t }\n\t p = key + len;\n\t}\n\telse\n\t{\n\t // Get the index [expr] or the first index [expr: ].\n\t p = skipwhite(p + 1);\n\t if (*p == ':')\n\t\tempty1 = TRUE;\n\t else\n\t {\n\t\tempty1 = FALSE;\n\t\tif (eval1(&p, &var1, &EVALARG_EVALUATE) == FAIL) // recursive!\n\t\t return NULL;\n\t\tif (tv_get_string_chk(&var1) == NULL)\n\t\t{\n\t\t // not a number or string\n\t\t clear_tv(&var1);\n\t\t return NULL;\n\t\t}\n\t\tp = skipwhite(p);\n\t }", "\t // Optionally get the second index [ :expr].\n\t if (*p == ':')\n\t {\n\t\tif (v_type == VAR_DICT)\n\t\t{\n\t\t if (!quiet)\n\t\t\temsg(_(e_cannot_slice_dictionary));\n\t\t clear_tv(&var1);\n\t\t return NULL;\n\t\t}\n\t\tif (rettv != NULL\n\t\t\t&& !(rettv->v_type == VAR_LIST\n\t\t\t\t\t\t && rettv->vval.v_list != NULL)\n\t\t\t&& !(rettv->v_type == VAR_BLOB\n\t\t\t\t\t\t&& rettv->vval.v_blob != NULL))\n\t\t{\n\t\t if (!quiet)\n\t\t\temsg(_(e_slice_requires_list_or_blob_value));\n\t\t clear_tv(&var1);\n\t\t return NULL;\n\t\t}\n\t\tp = skipwhite(p + 1);\n\t\tif (*p == ']')\n\t\t lp->ll_empty2 = TRUE;\n\t\telse\n\t\t{\n\t\t lp->ll_empty2 = FALSE;\n\t\t // recursive!\n\t\t if (eval1(&p, &var2, &EVALARG_EVALUATE) == FAIL)\n\t\t {\n\t\t\tclear_tv(&var1);\n\t\t\treturn NULL;\n\t\t }\n\t\t if (tv_get_string_chk(&var2) == NULL)\n\t\t {\n\t\t\t// not a number or string\n\t\t\tclear_tv(&var1);\n\t\t\tclear_tv(&var2);\n\t\t\treturn NULL;\n\t\t }\n\t\t}\n\t\tlp->ll_range = TRUE;\n\t }\n\t else\n\t\tlp->ll_range = FALSE;", "\t if (*p != ']')\n\t {\n\t\tif (!quiet)\n\t\t emsg(_(e_missing_closing_square_brace));\n\t\tclear_tv(&var1);\n\t\tclear_tv(&var2);\n\t\treturn NULL;\n\t }", "\t // Skip to past ']'.\n\t ++p;\n\t}", "\tif (v_type == VAR_DICT)\n\t{\n\t if (len == -1)\n\t {\n\t\t// \"[key]\": get key from \"var1\"\n\t\tkey = tv_get_string_chk(&var1);\t// is number or string\n\t\tif (key == NULL)\n\t\t{\n\t\t clear_tv(&var1);\n\t\t return NULL;\n\t\t}\n\t }\n\t lp->ll_list = NULL;", "\t // a NULL dict is equivalent with an empty dict\n\t if (lp->ll_tv->vval.v_dict == NULL)\n\t {\n\t\tlp->ll_tv->vval.v_dict = dict_alloc();\n\t\tif (lp->ll_tv->vval.v_dict == NULL)\n\t\t{\n\t\t clear_tv(&var1);\n\t\t return NULL;\n\t\t}\n\t\t++lp->ll_tv->vval.v_dict->dv_refcount;\n\t }\n\t lp->ll_dict = lp->ll_tv->vval.v_dict;", "\t lp->ll_di = dict_find(lp->ll_dict, key, len);", "\t // When assigning to a scope dictionary check that a function and\n\t // variable name is valid (only variable name unless it is l: or\n\t // g: dictionary). Disallow overwriting a builtin function.\n\t if (rettv != NULL && lp->ll_dict->dv_scope != 0)\n\t {\n\t\tint prevval;", "\t\tif (len != -1)\n\t\t{\n\t\t prevval = key[len];\n\t\t key[len] = NUL;\n\t\t}\n\t\telse\n\t\t prevval = 0; // avoid compiler warning\n\t\tint wrong = (lp->ll_dict->dv_scope == VAR_DEF_SCOPE\n\t\t\t && (rettv->v_type == VAR_FUNC\n\t\t\t\t\t || rettv->v_type == VAR_PARTIAL)\n\t\t\t && var_wrong_func_name(key, lp->ll_di == NULL))\n\t\t\t|| !valid_varname(key, -1, TRUE);\n\t\tif (len != -1)\n\t\t key[len] = prevval;\n\t\tif (wrong)\n\t\t{\n\t\t clear_tv(&var1);\n\t\t return NULL;\n\t\t}\n\t }", "\t if (lp->ll_valtype != NULL)\n\t\t// use the type of the member\n\t\tlp->ll_valtype = lp->ll_valtype->tt_member;", "\t if (lp->ll_di == NULL)\n\t {\n\t\t// Can't add \"v:\" or \"a:\" variable.\n\t\tif (lp->ll_dict == get_vimvar_dict()\n\t\t\t || &lp->ll_dict->dv_hashtab == get_funccal_args_ht())\n\t\t{\n\t\t semsg(_(e_illegal_variable_name_str), name);\n\t\t clear_tv(&var1);\n\t\t return NULL;\n\t\t}", "\t\t// Key does not exist in dict: may need to add it.\n\t\tif (*p == '[' || *p == '.' || unlet)\n\t\t{\n\t\t if (!quiet)\n\t\t\tsemsg(_(e_key_not_present_in_dictionary_str), key);\n\t\t clear_tv(&var1);\n\t\t return NULL;\n\t\t}\n\t\tif (len == -1)\n\t\t lp->ll_newkey = vim_strsave(key);\n\t\telse\n\t\t lp->ll_newkey = vim_strnsave(key, len);\n\t\tclear_tv(&var1);\n\t\tif (lp->ll_newkey == NULL)\n\t\t p = NULL;\n\t\tbreak;\n\t }\n\t // existing variable, need to check if it can be changed\n\t else if ((flags & GLV_READ_ONLY) == 0\n\t\t\t&& (var_check_ro(lp->ll_di->di_flags, name, FALSE)\n\t\t\t || var_check_lock(lp->ll_di->di_flags, name, FALSE)))\n\t {\n\t\tclear_tv(&var1);\n\t\treturn NULL;\n\t }", "\t clear_tv(&var1);\n\t lp->ll_tv = &lp->ll_di->di_tv;\n\t}\n\telse if (v_type == VAR_BLOB)\n\t{\n\t long bloblen = blob_len(lp->ll_tv->vval.v_blob);", "\t /*\n\t * Get the number and item for the only or first index of the List.\n\t */\n\t if (empty1)\n\t\tlp->ll_n1 = 0;\n\t else\n\t\t// is number or string\n\t\tlp->ll_n1 = (long)tv_get_number(&var1);\n\t clear_tv(&var1);", "\t if (check_blob_index(bloblen, lp->ll_n1, quiet) == FAIL)\n\t {\n\t\tclear_tv(&var2);\n\t\treturn NULL;\n\t }\n\t if (lp->ll_range && !lp->ll_empty2)\n\t {\n\t\tlp->ll_n2 = (long)tv_get_number(&var2);\n\t\tclear_tv(&var2);\n\t\tif (check_blob_range(bloblen, lp->ll_n1, lp->ll_n2, quiet)\n\t\t\t\t\t\t\t\t == FAIL)\n\t\t return NULL;\n\t }\n\t lp->ll_blob = lp->ll_tv->vval.v_blob;\n\t lp->ll_tv = NULL;\n\t break;\n\t}\n\telse if (v_type == VAR_LIST)\n\t{\n\t /*\n\t * Get the number and item for the only or first index of the List.\n\t */\n\t if (empty1)\n\t\tlp->ll_n1 = 0;\n\t else\n\t\t// is number or string\n\t\tlp->ll_n1 = (long)tv_get_number(&var1);\n\t clear_tv(&var1);", "\t lp->ll_dict = NULL;\n\t lp->ll_list = lp->ll_tv->vval.v_list;\n\t lp->ll_li = check_range_index_one(lp->ll_list, &lp->ll_n1,\n\t\t\t\t (flags & GLV_ASSIGN_WITH_OP) == 0, quiet);\n\t if (lp->ll_li == NULL)\n\t {\n\t\tclear_tv(&var2);\n\t\treturn NULL;\n\t }", "\t if (lp->ll_valtype != NULL)\n\t\t// use the type of the member\n\t\tlp->ll_valtype = lp->ll_valtype->tt_member;", "\t /*\n\t * May need to find the item or absolute index for the second\n\t * index of a range.\n\t * When no index given: \"lp->ll_empty2\" is TRUE.\n\t * Otherwise \"lp->ll_n2\" is set to the second index.\n\t */\n\t if (lp->ll_range && !lp->ll_empty2)\n\t {\n\t\tlp->ll_n2 = (long)tv_get_number(&var2);\n\t\t\t\t\t\t // is number or string\n\t\tclear_tv(&var2);\n\t\tif (check_range_index_two(lp->ll_list,\n\t\t\t\t\t &lp->ll_n1, lp->ll_li,\n\t\t\t\t\t &lp->ll_n2, quiet) == FAIL)\n\t\t return NULL;\n\t }", "\t lp->ll_tv = &lp->ll_li->li_tv;\n\t}\n\telse // v_type == VAR_CLASS || v_type == VAR_OBJECT\n\t{\n\t class_T *cl = (v_type == VAR_OBJECT\n\t\t\t\t\t && lp->ll_tv->vval.v_object != NULL)\n\t\t\t ? lp->ll_tv->vval.v_object->obj_class\n\t\t\t : lp->ll_tv->vval.v_class;\n\t // TODO: what if class is NULL?\n\t if (cl != NULL)\n\t {\n\t\tlp->ll_valtype = NULL;\n\t\tint count = v_type == VAR_OBJECT ? cl->class_obj_member_count\n\t\t\t\t\t\t: cl->class_class_member_count;\n\t\tocmember_T *members = v_type == VAR_OBJECT\n\t\t\t\t\t\t ? cl->class_obj_members\n\t\t\t\t\t\t : cl->class_class_members;\n\t\tfor (int i = 0; i < count; ++i)\n\t\t{\n\t\t ocmember_T *om = members + i;\n\t\t if (STRNCMP(om->ocm_name, key, p - key) == 0\n\t\t\t\t\t && om->ocm_name[p - key] == NUL)\n\t\t {\n\t\t\tswitch (om->ocm_access)\n\t\t\t{\n\t\t\t case ACCESS_PRIVATE:\n\t\t\t\t semsg(_(e_cannot_access_private_member_str),\n\t\t\t\t\t\t\t\t om->ocm_name);\n\t\t\t\t return NULL;\n\t\t\t case ACCESS_READ:\n\t\t\t\t if (!(flags & GLV_READ_ONLY))\n\t\t\t\t {\n\t\t\t\t\tsemsg(_(e_member_is_not_writable_str),\n\t\t\t\t\t\t\t\t om->ocm_name);\n\t\t\t\t\treturn NULL;\n\t\t\t\t }\n\t\t\t\t break;\n\t\t\t case ACCESS_ALL:\n\t\t\t\t break;\n\t\t\t}", "\t\t\tlp->ll_valtype = om->ocm_type;", "\t\t\tif (v_type == VAR_OBJECT)\n\t\t\t lp->ll_tv = ((typval_T *)(\n\t\t\t\t\t lp->ll_tv->vval.v_object + 1)) + i;\n\t\t\telse\n\t\t\t lp->ll_tv = &cl->class_members_tv[i];\n\t\t\tbreak;\n\t\t }\n\t\t}\n\t\tif (lp->ll_valtype == NULL)\n\t\t{\n\t\t if (v_type == VAR_OBJECT)\n\t\t\tsemsg(_(e_object_member_not_found_str), key);\n\t\t else\n\t\t\tsemsg(_(e_class_member_not_found_str), key);\n\t\t return NULL;\n\t\t}\n\t }\n\t}\n }", " clear_tv(&var1);\n lp->ll_name_end = p;\n return p;\n}", "/*\n * Clear lval \"lp\" that was filled by get_lval().\n */\n void\nclear_lval(lval_T *lp)\n{\n vim_free(lp->ll_exp_name);\n vim_free(lp->ll_newkey);\n}", "/*\n * Set a variable that was parsed by get_lval() to \"rettv\".\n * \"endp\" points to just after the parsed name.\n * \"op\" is NULL, \"+\" for \"+=\", \"-\" for \"-=\", \"*\" for \"*=\", \"/\" for \"/=\",\n * \"%\" for \"%=\", \".\" for \".=\" or \"=\" for \"=\".\n */\n void\nset_var_lval(\n lval_T\t*lp,\n char_u\t*endp,\n typval_T\t*rettv,\n int\t\tcopy,\n int\t\tflags,\t // ASSIGN_CONST, ASSIGN_NO_DECL\n char_u\t*op,\n int\t\tvar_idx) // index for \"let [a, b] = list\"\n{\n int\t\tcc;\n dictitem_T\t*di;", " if (lp->ll_tv == NULL)\n {\n\tcc = *endp;\n\t*endp = NUL;\n\tif (in_vim9script() && check_reserved_name(lp->ll_name, NULL) == FAIL)\n\t return;", "\tif (lp->ll_blob != NULL)\n\t{\n\t int\t error = FALSE, val;", "\t if (op != NULL && *op != '=')\n\t {\n\t\tsemsg(_(e_wrong_variable_type_for_str_equal), op);\n\t\treturn;\n\t }\n\t if (value_check_lock(lp->ll_blob->bv_lock, lp->ll_name, FALSE))\n\t\treturn;", "\t if (lp->ll_range && rettv->v_type == VAR_BLOB)\n\t {\n\t\tif (lp->ll_empty2)\n\t\t lp->ll_n2 = blob_len(lp->ll_blob) - 1;", "\t\tif (blob_set_range(lp->ll_blob, lp->ll_n1, lp->ll_n2,\n\t\t\t\t\t\t\t\trettv) == FAIL)\n\t\t return;\n\t }\n\t else\n\t {\n\t\tval = (int)tv_get_number_chk(rettv, &error);\n\t\tif (!error)\n\t\t blob_set_append(lp->ll_blob, lp->ll_n1, val);\n\t }\n\t}\n\telse if (op != NULL && *op != '=')\n\t{\n\t typval_T tv;", "\t if ((flags & (ASSIGN_CONST | ASSIGN_FINAL))\n\t\t\t\t\t && (flags & ASSIGN_FOR_LOOP) == 0)\n\t {\n\t\temsg(_(e_cannot_modify_existing_variable));\n\t\t*endp = cc;\n\t\treturn;\n\t }", "\t // handle +=, -=, *=, /=, %= and .=\n\t di = NULL;\n\t if (eval_variable(lp->ll_name, (int)STRLEN(lp->ll_name),\n\t\t\t\t lp->ll_sid, &tv, &di, EVAL_VAR_VERBOSE) == OK)\n\t {\n\t\tif ((di == NULL\n\t\t\t || (!var_check_ro(di->di_flags, lp->ll_name, FALSE)\n\t\t\t && !tv_check_lock(&di->di_tv, lp->ll_name, FALSE)))\n\t\t\t&& tv_op(&tv, rettv, op) == OK)\n\t\t set_var_const(lp->ll_name, lp->ll_sid, NULL, &tv, FALSE,\n\t\t\t\t\t\t\t ASSIGN_NO_DECL, 0);\n\t\tclear_tv(&tv);\n\t }\n\t}\n\telse\n\t{\n\t if (lp->ll_type != NULL && check_typval_arg_type(lp->ll_type, rettv,\n\t\t\t\t\t\t\t NULL, 0) == FAIL)\n\t\treturn;\n\t set_var_const(lp->ll_name, lp->ll_sid, lp->ll_type, rettv, copy,\n\t\t\t\t\t\t\t flags, var_idx);\n\t}\n\t*endp = cc;\n }\n else if (value_check_lock(lp->ll_newkey == NULL\n\t\t? lp->ll_tv->v_lock\n\t\t: lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name, FALSE))\n\t;\n else if (lp->ll_range)\n {\n\tif ((flags & (ASSIGN_CONST | ASSIGN_FINAL))\n\t\t\t\t\t && (flags & ASSIGN_FOR_LOOP) == 0)\n\t{\n\t emsg(_(e_cannot_lock_range));\n\t return;\n\t}", "\t(void)list_assign_range(lp->ll_list, rettv->vval.v_list,\n\t\t\t lp->ll_n1, lp->ll_n2, lp->ll_empty2, op, lp->ll_name);\n }\n else\n {\n\t/*\n\t * Assign to a List, Dictionary or Object item.\n\t */\n\tif ((flags & (ASSIGN_CONST | ASSIGN_FINAL))\n\t\t\t\t\t && (flags & ASSIGN_FOR_LOOP) == 0)\n\t{\n\t emsg(_(e_cannot_lock_list_or_dict));\n\t return;\n\t}", "\tif (lp->ll_valtype != NULL\n\t\t && check_typval_arg_type(lp->ll_valtype, rettv,\n\t\t\t\t\t\t\t NULL, 0) == FAIL)\n\t return;", "\tif (lp->ll_newkey != NULL)\n\t{\n\t if (op != NULL && *op != '=')\n\t {\n\t\tsemsg(_(e_key_not_present_in_dictionary_str), lp->ll_newkey);\n\t\treturn;\n\t }\n\t if (dict_wrong_func_name(lp->ll_tv->vval.v_dict, rettv,\n\t\t\t\t\t\t\t\tlp->ll_newkey))\n\t\treturn;", "\t // Need to add an item to the Dictionary.\n\t di = dictitem_alloc(lp->ll_newkey);\n\t if (di == NULL)\n\t\treturn;\n\t if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)\n\t {\n\t\tvim_free(di);\n\t\treturn;\n\t }\n\t lp->ll_tv = &di->di_tv;\n\t}\n\telse if (op != NULL && *op != '=')\n\t{\n\t tv_op(lp->ll_tv, rettv, op);\n\t return;\n\t}\n\telse\n\t clear_tv(lp->ll_tv);", "\t/*\n\t * Assign the value to the variable or list item.\n\t */\n\tif (copy)\n\t copy_tv(rettv, lp->ll_tv);\n\telse\n\t{\n\t *lp->ll_tv = *rettv;\n\t lp->ll_tv->v_lock = 0;\n\t init_tv(rettv);\n\t}\n }\n}", "/*\n * Handle \"tv1 += tv2\", \"tv1 -= tv2\", \"tv1 *= tv2\", \"tv1 /= tv2\", \"tv1 %= tv2\"\n * and \"tv1 .= tv2\"\n * Returns OK or FAIL.\n */\n int\ntv_op(typval_T *tv1, typval_T *tv2, char_u *op)\n{\n varnumber_T\tn;\n char_u\tnumbuf[NUMBUFLEN];\n char_u\t*s;\n int\t\tfailed = FALSE;", " // Can't do anything with a Funcref or Dict on the right.\n // v:true and friends only work with \"..=\".\n if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT\n\t\t && ((tv2->v_type != VAR_BOOL && tv2->v_type != VAR_SPECIAL)\n\t\t\t\t\t\t\t\t|| *op == '.'))\n {\n\tswitch (tv1->v_type)\n\t{\n\t case VAR_UNKNOWN:\n\t case VAR_ANY:\n\t case VAR_VOID:\n\t case VAR_DICT:\n\t case VAR_FUNC:\n\t case VAR_PARTIAL:\n\t case VAR_BOOL:\n\t case VAR_SPECIAL:\n\t case VAR_JOB:\n\t case VAR_CHANNEL:\n\t case VAR_INSTR:\n\t case VAR_CLASS:\n\t case VAR_OBJECT:\n\t\tbreak;", "\t case VAR_BLOB:\n\t\tif (*op != '+' || tv2->v_type != VAR_BLOB)\n\t\t break;\n\t\t// BLOB += BLOB\n\t\tif (tv1->vval.v_blob != NULL && tv2->vval.v_blob != NULL)\n\t\t{\n\t\t blob_T *b1 = tv1->vval.v_blob;\n\t\t blob_T *b2 = tv2->vval.v_blob;\n\t\t int\ti, len = blob_len(b2);\n\t\t for (i = 0; i < len; i++)\n\t\t\tga_append(&b1->bv_ga, blob_get(b2, i));\n\t\t}\n\t\treturn OK;", "\t case VAR_LIST:\n\t\tif (*op != '+' || tv2->v_type != VAR_LIST)\n\t\t break;\n\t\t// List += List\n\t\tif (tv2->vval.v_list != NULL)\n\t\t{\n\t\t if (tv1->vval.v_list == NULL)\n\t\t {\n\t\t\ttv1->vval.v_list = tv2->vval.v_list;\n\t\t\t++tv1->vval.v_list->lv_refcount;\n\t\t }\n\t\t else\n\t\t\tlist_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);\n\t\t}\n\t\treturn OK;", "\t case VAR_NUMBER:\n\t case VAR_STRING:\n\t\tif (tv2->v_type == VAR_LIST)\n\t\t break;\n\t\tif (vim_strchr((char_u *)\"+-*/%\", *op) != NULL)\n\t\t{\n\t\t // nr += nr , nr -= nr , nr *=nr , nr /= nr , nr %= nr\n\t\t n = tv_get_number(tv1);\n\t\t if (tv2->v_type == VAR_FLOAT)\n\t\t {\n\t\t\tfloat_T f = n;", "\t\t\tif (*op == '%')\n\t\t\t break;\n\t\t\tswitch (*op)\n\t\t\t{\n\t\t\t case '+': f += tv2->vval.v_float; break;\n\t\t\t case '-': f -= tv2->vval.v_float; break;\n\t\t\t case '*': f *= tv2->vval.v_float; break;\n\t\t\t case '/': f /= tv2->vval.v_float; break;\n\t\t\t}\n\t\t\tclear_tv(tv1);\n\t\t\ttv1->v_type = VAR_FLOAT;\n\t\t\ttv1->vval.v_float = f;\n\t\t }\n\t\t else\n\t\t {\n\t\t\tswitch (*op)\n\t\t\t{\n\t\t\t case '+': n += tv_get_number(tv2); break;\n\t\t\t case '-': n -= tv_get_number(tv2); break;\n\t\t\t case '*': n *= tv_get_number(tv2); break;\n\t\t\t case '/': n = num_divide(n, tv_get_number(tv2),\n\t\t\t\t\t\t\t &failed); break;\n\t\t\t case '%': n = num_modulus(n, tv_get_number(tv2),\n\t\t\t\t\t\t\t &failed); break;\n\t\t\t}\n\t\t\tclear_tv(tv1);\n\t\t\ttv1->v_type = VAR_NUMBER;\n\t\t\ttv1->vval.v_number = n;\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t\t if (tv2->v_type == VAR_FLOAT)\n\t\t\tbreak;", "\t\t // str .= str\n\t\t s = tv_get_string(tv1);\n\t\t s = concat_str(s, tv_get_string_buf(tv2, numbuf));\n\t\t clear_tv(tv1);\n\t\t tv1->v_type = VAR_STRING;\n\t\t tv1->vval.v_string = s;\n\t\t}\n\t\treturn failed ? FAIL : OK;", "\t case VAR_FLOAT:\n\t\t{\n\t\t float_T f;", "\t\t if (*op == '%' || *op == '.'\n\t\t\t\t || (tv2->v_type != VAR_FLOAT\n\t\t\t\t && tv2->v_type != VAR_NUMBER\n\t\t\t\t && tv2->v_type != VAR_STRING))\n\t\t\tbreak;\n\t\t if (tv2->v_type == VAR_FLOAT)\n\t\t\tf = tv2->vval.v_float;\n\t\t else\n\t\t\tf = tv_get_number(tv2);\n\t\t switch (*op)\n\t\t {\n\t\t\tcase '+': tv1->vval.v_float += f; break;\n\t\t\tcase '-': tv1->vval.v_float -= f; break;\n\t\t\tcase '*': tv1->vval.v_float *= f; break;\n\t\t\tcase '/': tv1->vval.v_float /= f; break;\n\t\t }\n\t\t}\n\t\treturn OK;\n\t}\n }", " semsg(_(e_wrong_variable_type_for_str_equal), op);\n return FAIL;\n}", "/*\n * Evaluate the expression used in a \":for var in expr\" command.\n * \"arg\" points to \"var\".\n * Set \"*errp\" to TRUE for an error, FALSE otherwise;\n * Return a pointer that holds the info. Null when there is an error.\n */\n void *\neval_for_line(\n char_u\t*arg,\n int\t\t*errp,\n exarg_T\t*eap,\n evalarg_T\t*evalarg)\n{\n forinfo_T\t*fi;\n char_u\t*var_list_end;\n char_u\t*expr;\n typval_T\ttv;\n list_T\t*l;\n int\t\tskip = !(evalarg->eval_flags & EVAL_EVALUATE);", " *errp = TRUE;\t// default: there is an error", " fi = ALLOC_CLEAR_ONE(forinfo_T);\n if (fi == NULL)\n\treturn NULL;", " var_list_end = skip_var_list(arg, TRUE, &fi->fi_varcount,\n\t\t\t\t\t\t &fi->fi_semicolon, FALSE);\n if (var_list_end == NULL)\n\treturn fi;", " expr = skipwhite_and_linebreak(var_list_end, evalarg);\n if (expr[0] != 'i' || expr[1] != 'n'\n\t\t\t\t || !(expr[2] == NUL || VIM_ISWHITE(expr[2])))\n {\n\tif (in_vim9script() && *expr == ':' && expr != var_list_end)\n\t semsg(_(e_no_white_space_allowed_before_colon_str), expr);\n\telse\n\t emsg(_(e_missing_in_after_for));\n\treturn fi;\n }", " if (skip)\n\t++emsg_skip;\n expr = skipwhite_and_linebreak(expr + 2, evalarg);\n if (eval0(expr, &tv, eap, evalarg) == OK)\n {\n\t*errp = FALSE;\n\tif (!skip)\n\t{\n\t if (tv.v_type == VAR_LIST)\n\t {\n\t\tl = tv.vval.v_list;\n\t\tif (l == NULL)\n\t\t{\n\t\t // a null list is like an empty list: do nothing\n\t\t clear_tv(&tv);\n\t\t}\n\t\telse\n\t\t{\n\t\t // Need a real list here.\n\t\t CHECK_LIST_MATERIALIZE(l);", "\t\t // No need to increment the refcount, it's already set for\n\t\t // the list being used in \"tv\".\n\t\t fi->fi_list = l;\n\t\t list_add_watch(l, &fi->fi_lw);\n\t\t fi->fi_lw.lw_item = l->lv_first;\n\t\t}\n\t }\n\t else if (tv.v_type == VAR_BLOB)\n\t {\n\t\tfi->fi_bi = 0;\n\t\tif (tv.vval.v_blob != NULL)\n\t\t{\n\t\t typval_T btv;", "\t\t // Make a copy, so that the iteration still works when the\n\t\t // blob is changed.\n\t\t blob_copy(tv.vval.v_blob, &btv);\n\t\t fi->fi_blob = btv.vval.v_blob;\n\t\t}\n\t\tclear_tv(&tv);\n\t }\n\t else if (tv.v_type == VAR_STRING)\n\t {\n\t\tfi->fi_byte_idx = 0;\n\t\tfi->fi_string = tv.vval.v_string;\n\t\ttv.vval.v_string = NULL;\n\t\tif (fi->fi_string == NULL)\n\t\t fi->fi_string = vim_strsave((char_u *)\"\");\n\t }\n\t else\n\t {\n\t\temsg(_(e_string_list_or_blob_required));\n\t\tclear_tv(&tv);\n\t }\n\t}\n }\n if (skip)\n\t--emsg_skip;\n fi->fi_break_count = evalarg->eval_break_count;", " return fi;\n}", "/*\n * Used when looping over a :for line, skip the \"in expr\" part.\n */\n void\nskip_for_lines(void *fi_void, evalarg_T *evalarg)\n{\n forinfo_T\t*fi = (forinfo_T *)fi_void;\n int\t\ti;", " for (i = 0; i < fi->fi_break_count; ++i)\n\teval_next_line(NULL, evalarg);\n}", "/*\n * Use the first item in a \":for\" list. Advance to the next.\n * Assign the values to the variable (list). \"arg\" points to the first one.\n * Return TRUE when a valid item was found, FALSE when at end of list or\n * something wrong.\n */\n int\nnext_for_item(void *fi_void, char_u *arg)\n{\n forinfo_T\t*fi = (forinfo_T *)fi_void;\n int\t\tresult;\n int\t\tflag = ASSIGN_FOR_LOOP | (in_vim9script()\n\t\t\t ? (ASSIGN_FINAL\n\t\t\t // first round: error if variable exists\n\t\t\t | (fi->fi_bi == 0 ? 0 : ASSIGN_DECL)\n\t\t\t | ASSIGN_NO_MEMBER_TYPE\n\t\t\t | ASSIGN_UPDATE_BLOCK_ID)\n\t\t\t : 0);\n listitem_T\t*item;\n int\t\tskip_assign = in_vim9script() && arg[0] == '_'\n\t\t\t\t\t\t && !eval_isnamec(arg[1]);", " if (fi->fi_blob != NULL)\n {\n\ttypval_T\ttv;", "\tif (fi->fi_bi >= blob_len(fi->fi_blob))\n\t return FALSE;\n\ttv.v_type = VAR_NUMBER;\n\ttv.v_lock = VAR_FIXED;\n\ttv.vval.v_number = blob_get(fi->fi_blob, fi->fi_bi);\n\t++fi->fi_bi;\n\tif (skip_assign)\n\t return TRUE;\n\treturn ex_let_vars(arg, &tv, TRUE, fi->fi_semicolon,\n\t\t\t\t\t fi->fi_varcount, flag, NULL) == OK;\n }", " if (fi->fi_string != NULL)\n {\n\ttypval_T\ttv;\n\tint\t\tlen;", "\tlen = mb_ptr2len(fi->fi_string + fi->fi_byte_idx);\n\tif (len == 0)\n\t return FALSE;\n\ttv.v_type = VAR_STRING;\n\ttv.v_lock = VAR_FIXED;\n\ttv.vval.v_string = vim_strnsave(fi->fi_string + fi->fi_byte_idx, len);\n\tfi->fi_byte_idx += len;\n\t++fi->fi_bi;\n\tif (skip_assign)\n\t result = TRUE;\n\telse\n\t result = ex_let_vars(arg, &tv, TRUE, fi->fi_semicolon,\n\t\t\t\t\t fi->fi_varcount, flag, NULL) == OK;\n\tvim_free(tv.vval.v_string);\n\treturn result;\n }", " item = fi->fi_lw.lw_item;\n if (item == NULL)\n\tresult = FALSE;\n else\n {\n\tfi->fi_lw.lw_item = item->li_next;\n\t++fi->fi_bi;\n\tif (skip_assign)\n\t result = TRUE;\n\telse\n\t result = (ex_let_vars(arg, &item->li_tv, TRUE, fi->fi_semicolon,\n\t\t\t\t\t fi->fi_varcount, flag, NULL) == OK);\n }\n return result;\n}", "/*\n * Free the structure used to store info used by \":for\".\n */\n void\nfree_for_info(void *fi_void)\n{\n forinfo_T *fi = (forinfo_T *)fi_void;", " if (fi == NULL)\n\treturn;\n if (fi->fi_list != NULL)\n {\n\tlist_rem_watch(fi->fi_list, &fi->fi_lw);\n\tlist_unref(fi->fi_list);\n }\n else if (fi->fi_blob != NULL)\n\tblob_unref(fi->fi_blob);\n else\n\tvim_free(fi->fi_string);\n vim_free(fi);\n}", " void\nset_context_for_expression(\n expand_T\t*xp,\n char_u\t*arg,\n cmdidx_T\tcmdidx)\n{\n int\t\thas_expr = cmdidx != CMD_let && cmdidx != CMD_var;\n int\t\tc;\n char_u\t*p;", " if (cmdidx == CMD_let || cmdidx == CMD_var\n\t\t\t\t || cmdidx == CMD_const || cmdidx == CMD_final)\n {\n\txp->xp_context = EXPAND_USER_VARS;\n\tif (vim_strpbrk(arg, (char_u *)\"\\\"'+-*/%.=!?~|&$([<>,#\") == NULL)\n\t{\n\t // \":let var1 var2 ...\": find last space.\n\t for (p = arg + STRLEN(arg); p >= arg; )\n\t {\n\t\txp->xp_pattern = p;\n\t\tMB_PTR_BACK(arg, p);\n\t\tif (VIM_ISWHITE(*p))\n\t\t break;\n\t }\n\t return;\n\t}\n }\n else\n\txp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS\n\t\t\t\t\t\t\t : EXPAND_EXPRESSION;\n while ((xp->xp_pattern = vim_strpbrk(arg,\n\t\t\t\t (char_u *)\"\\\"'+-*/%.=!?~|&$([<>,#\")) != NULL)\n {\n\tc = *xp->xp_pattern;\n\tif (c == '&')\n\t{\n\t c = xp->xp_pattern[1];\n\t if (c == '&')\n\t {\n\t\t++xp->xp_pattern;\n\t\txp->xp_context = has_expr ? EXPAND_EXPRESSION : EXPAND_NOTHING;\n\t }\n\t else if (c != ' ')\n\t {\n\t\txp->xp_context = EXPAND_SETTINGS;\n\t\tif ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')\n\t\t xp->xp_pattern += 2;", "\t }\n\t}\n\telse if (c == '$')\n\t{\n\t // environment variable\n\t xp->xp_context = EXPAND_ENV_VARS;\n\t}\n\telse if (c == '=')\n\t{\n\t has_expr = TRUE;\n\t xp->xp_context = EXPAND_EXPRESSION;\n\t}\n\telse if (c == '#'\n\t\t&& xp->xp_context == EXPAND_EXPRESSION)\n\t{\n\t // Autoload function/variable contains '#'.\n\t break;\n\t}\n\telse if ((c == '<' || c == '#')\n\t\t&& xp->xp_context == EXPAND_FUNCTIONS\n\t\t&& vim_strchr(xp->xp_pattern, '(') == NULL)\n\t{\n\t // Function name can start with \"<SNR>\" and contain '#'.\n\t break;\n\t}\n\telse if (has_expr)\n\t{\n\t if (c == '\"')\t // string\n\t {\n\t\twhile ((c = *++xp->xp_pattern) != NUL && c != '\"')\n\t\t if (c == '\\\\' && xp->xp_pattern[1] != NUL)\n\t\t\t++xp->xp_pattern;\n\t\txp->xp_context = EXPAND_NOTHING;\n\t }\n\t else if (c == '\\'')\t // literal string\n\t {\n\t\t// Trick: '' is like stopping and starting a literal string.\n\t\twhile ((c = *++xp->xp_pattern) != NUL && c != '\\'')\n\t\t /* skip */ ;\n\t\txp->xp_context = EXPAND_NOTHING;\n\t }\n\t else if (c == '|')\n\t {\n\t\tif (xp->xp_pattern[1] == '|')\n\t\t{\n\t\t ++xp->xp_pattern;\n\t\t xp->xp_context = EXPAND_EXPRESSION;\n\t\t}\n\t\telse\n\t\t xp->xp_context = EXPAND_COMMANDS;\n\t }\n\t else\n\t\txp->xp_context = EXPAND_EXPRESSION;\n\t}\n\telse\n\t // Doesn't look like something valid, expand as an expression\n\t // anyway.\n\t xp->xp_context = EXPAND_EXPRESSION;\n\targ = xp->xp_pattern;\n\tif (*arg != NUL)\n\t while ((c = *++arg) != NUL && (c == ' ' || c == '\\t'))\n\t\t/* skip */ ;\n }", " // \":exe one two\" completes \"two\"\n if ((cmdidx == CMD_execute\n\t\t|| cmdidx == CMD_echo\n\t\t|| cmdidx == CMD_echon\n\t\t|| cmdidx == CMD_echomsg\n\t\t|| cmdidx == CMD_echowindow)\n\t && xp->xp_context == EXPAND_EXPRESSION)\n {\n\tfor (;;)\n\t{\n\t char_u *n = skiptowhite(arg);", "\t if (n == arg || IS_WHITE_OR_NUL(*skipwhite(n)))\n\t\tbreak;\n\t arg = skipwhite(n);\n\t}\n }", " xp->xp_pattern = arg;\n}", "/*\n * Return TRUE if \"pat\" matches \"text\".\n * Does not use 'cpo' and always uses 'magic'.\n */\n int\npattern_match(char_u *pat, char_u *text, int ic)\n{\n int\t\tmatches = FALSE;\n char_u\t*save_cpo;\n regmatch_T\tregmatch;", " // avoid 'l' flag in 'cpoptions'\n save_cpo = p_cpo;\n p_cpo = empty_option;\n regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);\n if (regmatch.regprog != NULL)\n {\n\tregmatch.rm_ic = ic;\n\tmatches = vim_regexec_nl(&regmatch, text, (colnr_T)0);\n\tvim_regfree(regmatch.regprog);\n }\n p_cpo = save_cpo;\n return matches;\n}", "/*\n * Handle a name followed by \"(\". Both for just \"name(arg)\" and for\n * \"expr->name(arg)\".\n * Returns OK or FAIL.\n */\n static int\neval_func(\n\tchar_u\t **arg,\t// points to \"(\", will be advanced\n\tevalarg_T *evalarg,\n\tchar_u\t *name,\n\tint\t name_len,\n\ttypval_T *rettv,\n\tint\t flags,\n\ttypval_T *basetv)\t// \"expr\" for \"expr->name(arg)\"\n{\n int\t\tevaluate = flags & EVAL_EVALUATE;\n char_u\t*s = name;\n int\t\tlen = name_len;\n partial_T\t*partial;\n int\t\tret = OK;\n type_T\t*type = NULL;\n int\t\tfound_var = FALSE;", " if (!evaluate)\n\tcheck_vars(s, len);", " // If \"s\" is the name of a variable of type VAR_FUNC\n // use its contents.\n s = deref_func_name(s, &len, &partial,\n\t\t in_vim9script() ? &type : NULL, !evaluate, FALSE, &found_var);", " // Need to make a copy, in case evaluating the arguments makes\n // the name invalid.\n s = vim_strsave(s);\n if (s == NULL || (evaluate && (*s == NUL || (flags & EVAL_CONSTANT))))\n\tret = FAIL;\n else\n {\n\tfuncexe_T funcexe;", "\t// Invoke the function.\n\tCLEAR_FIELD(funcexe);\n\tfuncexe.fe_firstline = curwin->w_cursor.lnum;\n\tfuncexe.fe_lastline = curwin->w_cursor.lnum;\n\tfuncexe.fe_evaluate = evaluate;\n\tfuncexe.fe_partial = partial;\n\tfuncexe.fe_basetv = basetv;\n\tfuncexe.fe_check_type = type;\n\tfuncexe.fe_found_var = found_var;\n\tret = get_func_tv(s, len, rettv, arg, evalarg, &funcexe);\n }\n vim_free(s);", " // If evaluate is FALSE rettv->v_type was not set in\n // get_func_tv, but it's needed in handle_subscript() to parse\n // what follows. So set it here.\n if (rettv->v_type == VAR_UNKNOWN && !evaluate && **arg == '(')\n {\n\trettv->vval.v_string = NULL;\n\trettv->v_type = VAR_FUNC;\n }", " // Stop the expression evaluation when immediately\n // aborting on error, or when an interrupt occurred or\n // an exception was thrown but not caught.\n if (evaluate && aborting())\n {\n\tif (ret == OK)\n\t clear_tv(rettv);\n\tret = FAIL;\n }\n return ret;\n}", "/*\n * After a NL, skip over empty lines and comment-only lines.\n */\n static char_u *\nnewline_skip_comments(char_u *arg)\n{\n char_u *p = arg + 1;", " for (;;)\n {\n\tp = skipwhite(p);", "\tif (*p == NUL)\n\t break;\n\tif (vim9_comment_start(p))\n\t{\n\t char_u *nl = vim_strchr(p, NL);", "\t if (nl == NULL)\n\t\t break;\n\t p = nl;\n\t}\n\tif (*p != NL)\n\t break;\n\t++p; // skip another NL\n }\n return p;\n}", "/*\n * Get the next line source line without advancing. But do skip over comment\n * lines.\n * Only called for Vim9 script.\n */\n static char_u *\ngetline_peek_skip_comments(evalarg_T *evalarg)\n{\n for (;;)\n {\n\tchar_u *next = getline_peek(evalarg->eval_getline,\n\t\t\t\t\t\t\t evalarg->eval_cookie);\n\tchar_u *p;", "\tif (next == NULL)\n\t break;\n\tp = skipwhite(next);\n\tif (*p != NUL && !vim9_comment_start(p))\n\t return next;\n\tif (eval_next_line(NULL, evalarg) == NULL)\n\t break;\n }\n return NULL;\n}", "/*\n * If inside Vim9 script, \"arg\" points to the end of a line (ignoring a #\n * comment) and there is a next line, return the next line (skipping blanks)\n * and set \"getnext\".\n * Otherwise return the next non-white at or after \"arg\" and set \"getnext\" to\n * FALSE.\n * \"arg\" must point somewhere inside a line, not at the start.\n */\n char_u *\neval_next_non_blank(char_u *arg, evalarg_T *evalarg, int *getnext)\n{\n char_u *p = skipwhite(arg);", " *getnext = FALSE;\n if (in_vim9script()\n\t && evalarg != NULL\n\t && (evalarg->eval_cookie != NULL || evalarg->eval_cctx != NULL\n\t\t\t\t\t\t\t\t || *p == NL)\n\t && (*p == NUL || *p == NL\n\t\t\t || (vim9_comment_start(p) && VIM_ISWHITE(p[-1]))))\n {\n\tchar_u *next;", "\tif (*p == NL)\n\t next = newline_skip_comments(p);\n\telse if (evalarg->eval_cookie != NULL)\n\t next = getline_peek_skip_comments(evalarg);\n\telse\n\t next = peek_next_line_from_context(evalarg->eval_cctx);", "\tif (next != NULL)\n\t{\n\t *getnext = *p != NL;\n\t return skipwhite(next);\n\t}\n }\n return p;\n}", "/*\n * To be called after eval_next_non_blank() sets \"getnext\" to TRUE.\n * Only called for Vim9 script.\n */\n char_u *\neval_next_line(char_u *arg, evalarg_T *evalarg)\n{\n garray_T\t*gap = &evalarg->eval_ga;\n char_u\t*line;", " if (arg != NULL)\n {\n\tif (*arg == NL)\n\t return newline_skip_comments(arg);\n\t// Truncate before a trailing comment, so that concatenating the lines\n\t// won't turn the rest into a comment.\n\tif (*skipwhite(arg) == '#')\n\t *arg = NUL;\n }", " if (evalarg->eval_cookie != NULL)\n\tline = evalarg->eval_getline(0, evalarg->eval_cookie, 0,\n\t\t\t\t\t\t\t GETLINE_CONCAT_ALL);\n else\n\tline = next_line_from_context(evalarg->eval_cctx, TRUE);\n if (line == NULL)\n\treturn NULL;", " ++evalarg->eval_break_count;\n if (gap->ga_itemsize > 0 && ga_grow(gap, 1) == OK)\n {\n\tchar_u *p = skipwhite(line);", "\t// Going to concatenate the lines after parsing. For an empty or\n\t// comment line use an empty string.\n\tif (*p == NUL || vim9_comment_start(p))\n\t{\n\t vim_free(line);\n\t line = vim_strsave((char_u *)\"\");\n\t}", "\t((char_u **)gap->ga_data)[gap->ga_len] = line;\n\t++gap->ga_len;\n }\n else if (evalarg->eval_cookie != NULL)\n {\n\tfree_eval_tofree_later(evalarg);\n\tevalarg->eval_tofree = line;\n }", " // Advanced to the next line, \"arg\" no longer points into the previous\n // line.\n evalarg->eval_using_cmdline = FALSE;\n return skipwhite(line);\n}", "/*\n * Call eval_next_non_blank() and get the next line if needed.\n */\n char_u *\nskipwhite_and_linebreak(char_u *arg, evalarg_T *evalarg)\n{\n int\t getnext;\n char_u *p = skipwhite_and_nl(arg);", " if (evalarg == NULL)\n\treturn skipwhite(arg);\n eval_next_non_blank(p, evalarg, &getnext);\n if (getnext)\n\treturn eval_next_line(arg, evalarg);\n return p;\n}", "/*\n * The \"eval\" functions have an \"evalarg\" argument: When NULL or\n * \"evalarg->eval_flags\" does not have EVAL_EVALUATE, then the argument is only\n * parsed but not executed. The functions may return OK, but the rettv will be\n * of type VAR_UNKNOWN. The functions still returns FAIL for a syntax error.\n */", "/*\n * Handle zero level expression.\n * This calls eval1() and handles error message and nextcmd.\n * Put the result in \"rettv\" when returning OK and \"evaluate\" is TRUE.\n * Note: \"rettv.v_lock\" is not set.\n * \"evalarg\" can be NULL, EVALARG_EVALUATE or a pointer.\n * Return OK or FAIL.\n */\n int\neval0(\n char_u\t*arg,\n typval_T\t*rettv,\n exarg_T\t*eap,\n evalarg_T\t*evalarg)\n{\n return eval0_retarg(arg, rettv, eap, evalarg, NULL);\n}", "/*\n * If \"arg\" is a simple function call without arguments then call it and return\n * the result. Otherwise return NOTDONE.\n */\n int\nmay_call_simple_func(\n char_u\t*arg,\n typval_T\t*rettv)\n{\n char_u *parens = (char_u *)strstr((char *)arg, \"()\");\n int\t r = NOTDONE;", " // If the expression is \"FuncName()\" then we can skip a lot of overhead.\n if (parens != NULL && *skipwhite(parens + 2) == NUL)\n {\n\tchar_u *p = STRNCMP(arg, \"<SNR>\", 5) == 0 ? skipdigits(arg + 5) : arg;", "\tif (to_name_end(p, TRUE) == parens)\n\t r = call_simple_func(arg, (int)(parens - arg), rettv);\n }\n return r;\n}", "/*\n * Handle zero level expression with optimization for a simple function call.\n * Same arguments and return value as eval0().\n */\n int\neval0_simple_funccal(\n char_u\t*arg,\n typval_T\t*rettv,\n exarg_T\t*eap,\n evalarg_T\t*evalarg)\n{\n int\t r = may_call_simple_func(arg, rettv);", " if (r == NOTDONE)\n\tr = eval0_retarg(arg, rettv, eap, evalarg, NULL);\n return r;\n}", "/*\n * Like eval0() but when \"retarg\" is not NULL store the pointer to after the\n * expression and don't check what comes after the expression.\n */\n int\neval0_retarg(\n char_u\t*arg,\n typval_T\t*rettv,\n exarg_T\t*eap,\n evalarg_T\t*evalarg,\n char_u\t**retarg)\n{\n int\t\tret;\n char_u\t*p;\n char_u\t*expr_end;\n int\t\tdid_emsg_before = did_emsg;\n int\t\tcalled_emsg_before = called_emsg;\n int\t\tflags = evalarg == NULL ? 0 : evalarg->eval_flags;\n int\t\tcheck_for_end = retarg == NULL;\n int\t\tend_error = FALSE;", " p = skipwhite(arg);\n ret = eval1(&p, rettv, evalarg);", " if (ret != FAIL)\n {\n\texpr_end = p;\n\tp = skipwhite(p);", "\t// In Vim9 script a command block is not split at NL characters for\n\t// commands using an expression argument. Skip over a '#' comment to\n\t// check for a following NL. Require white space before the '#'.\n\tif (in_vim9script() && p > expr_end && retarg == NULL)\n\t while (*p == '#')\n\t {\n\t\tchar_u *nl = vim_strchr(p, NL);", "\t\tif (nl == NULL)\n\t\t break;\n\t\tp = skipwhite(nl + 1);\n\t\tif (eap != NULL && *p != NUL)\n\t\t eap->nextcmd = p;\n\t\tcheck_for_end = FALSE;\n\t }", "\tif (check_for_end)\n\t end_error = !ends_excmd2(arg, p);\n }", " if (ret == FAIL || end_error)\n {\n\tif (ret != FAIL)\n\t clear_tv(rettv);\n\t/*\n\t * Report the invalid expression unless the expression evaluation has\n\t * been cancelled due to an aborting error, an interrupt, or an\n\t * exception, or we already gave a more specific error.\n\t * Also check called_emsg for when using assert_fails().\n\t */\n\tif (!aborting()\n\t\t&& did_emsg == did_emsg_before\n\t\t&& called_emsg == called_emsg_before\n\t\t&& (flags & EVAL_CONSTANT) == 0\n\t\t&& (!in_vim9script() || !vim9_bad_comment(p)))\n\t{\n\t if (end_error)\n\t\tsemsg(_(e_trailing_characters_str), p);\n\t else\n\t\tsemsg(_(e_invalid_expression_str), arg);\n\t}", "\t// Some of the expression may not have been consumed. Do not check for\n\t// a next command to avoid more errors, unless \"|\" is following, which\n\t// could only be a command separator.\n\tif (eap != NULL && p != NULL\n\t\t\t && skipwhite(p)[0] == '|' && skipwhite(p)[1] != '|')\n\t eap->nextcmd = check_nextcmd(p);\n\treturn FAIL;\n }", " if (retarg != NULL)\n\t*retarg = p;\n else if (check_for_end && eap != NULL)\n\tset_nextcmd(eap, p);", " return ret;\n}", "/*\n * Handle top level expression:\n *\texpr2 ? expr1 : expr1\n *\texpr2 ?? expr1\n *\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n *\n * Note: \"rettv.v_lock\" is not set.\n *\n * Return OK or FAIL.\n */\n int\neval1(char_u **arg, typval_T *rettv, evalarg_T *evalarg)\n{\n char_u *p;\n int\t getnext;", " CLEAR_POINTER(rettv);", " /*\n * Get the first variable.\n */\n if (eval2(arg, rettv, evalarg) == FAIL)\n\treturn FAIL;", " p = eval_next_non_blank(*arg, evalarg, &getnext);\n if (*p == '?')\n {\n\tint\t\top_falsy = p[1] == '?';\n\tint\t\tresult;\n\ttypval_T\tvar2;\n\tevalarg_T\t*evalarg_used = evalarg;\n\tevalarg_T\tlocal_evalarg;\n\tint\t\torig_flags;\n\tint\t\tevaluate;\n\tint\t\tvim9script = in_vim9script();", "\tif (evalarg == NULL)\n\t{\n\t init_evalarg(&local_evalarg);\n\t evalarg_used = &local_evalarg;\n\t}\n\torig_flags = evalarg_used->eval_flags;\n\tevaluate = evalarg_used->eval_flags & EVAL_EVALUATE;", "\tif (getnext)\n\t *arg = eval_next_line(*arg, evalarg_used);\n\telse\n\t{\n\t if (evaluate && vim9script && !VIM_ISWHITE(p[-1]))\n\t {\n\t\terror_white_both(p, op_falsy ? 2 : 1);\n\t\tclear_tv(rettv);\n\t\treturn FAIL;\n\t }\n\t *arg = p;\n\t}", "\tresult = FALSE;\n\tif (evaluate)\n\t{\n\t int\t\terror = FALSE;", "\t if (op_falsy)\n\t\tresult = tv2bool(rettv);\n\t else if (vim9script)\n\t\tresult = tv_get_bool_chk(rettv, &error);\n\t else if (tv_get_number_chk(rettv, &error) != 0)\n\t\tresult = TRUE;\n\t if (error || !op_falsy || !result)\n\t\tclear_tv(rettv);\n\t if (error)\n\t\treturn FAIL;\n\t}", "\t/*\n\t * Get the second variable. Recursive!\n\t */\n\tif (op_falsy)\n\t ++*arg;\n\tif (evaluate && vim9script && !IS_WHITE_OR_NUL((*arg)[1]))\n\t{\n\t error_white_both(*arg - (op_falsy ? 1 : 0), op_falsy ? 2 : 1);\n\t clear_tv(rettv);\n\t return FAIL;\n\t}\n\t*arg = skipwhite_and_linebreak(*arg + 1, evalarg_used);\n\tevalarg_used->eval_flags = (op_falsy ? !result : result)\n\t\t\t\t ? orig_flags : orig_flags & ~EVAL_EVALUATE;\n\tif (eval1(arg, &var2, evalarg_used) == FAIL)\n\t{\n\t evalarg_used->eval_flags = orig_flags;\n\t return FAIL;\n\t}\n\tif (!op_falsy || !result)\n\t *rettv = var2;", "\tif (!op_falsy)\n\t{\n\t /*\n\t * Check for the \":\".\n\t */\n\t p = eval_next_non_blank(*arg, evalarg_used, &getnext);\n\t if (*p != ':')\n\t {\n\t\temsg(_(e_missing_colon_after_questionmark));\n\t\tif (evaluate && result)\n\t\t clear_tv(rettv);\n\t\tevalarg_used->eval_flags = orig_flags;\n\t\treturn FAIL;\n\t }\n\t if (getnext)\n\t\t*arg = eval_next_line(*arg, evalarg_used);\n\t else\n\t {\n\t\tif (evaluate && vim9script && !VIM_ISWHITE(p[-1]))\n\t\t{\n\t\t error_white_both(p, 1);\n\t\t clear_tv(rettv);\n\t\t evalarg_used->eval_flags = orig_flags;\n\t\t return FAIL;\n\t\t}\n\t\t*arg = p;\n\t }", "\t /*\n\t * Get the third variable. Recursive!\n\t */\n\t if (evaluate && vim9script && !IS_WHITE_OR_NUL((*arg)[1]))\n\t {\n\t\terror_white_both(*arg, 1);\n\t\tclear_tv(rettv);\n\t\tevalarg_used->eval_flags = orig_flags;\n\t\treturn FAIL;\n\t }\n\t *arg = skipwhite_and_linebreak(*arg + 1, evalarg_used);\n\t evalarg_used->eval_flags = !result ? orig_flags\n\t\t\t\t\t\t : orig_flags & ~EVAL_EVALUATE;\n\t if (eval1(arg, &var2, evalarg_used) == FAIL)\n\t {\n\t\tif (evaluate && result)\n\t\t clear_tv(rettv);\n\t\tevalarg_used->eval_flags = orig_flags;\n\t\treturn FAIL;\n\t }\n\t if (evaluate && !result)\n\t\t*rettv = var2;\n\t}", "\tif (evalarg == NULL)\n\t clear_evalarg(&local_evalarg, NULL);\n\telse\n\t evalarg->eval_flags = orig_flags;\n }", " return OK;\n}", "/*\n * Handle first level expression:\n *\texpr2 || expr2 || expr2\t logical OR\n *\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n *\n * Return OK or FAIL.\n */\n static int\neval2(char_u **arg, typval_T *rettv, evalarg_T *evalarg)\n{\n char_u\t*p;\n int\t\tgetnext;", " /*\n * Get the first expression.\n */\n if (eval3(arg, rettv, evalarg) == FAIL)\n\treturn FAIL;", " /*\n * Handle the \"||\" operator.\n */\n p = eval_next_non_blank(*arg, evalarg, &getnext);\n if (p[0] == '|' && p[1] == '|')\n {\n\tevalarg_T *evalarg_used = evalarg;\n\tevalarg_T local_evalarg;\n\tint\t evaluate;\n\tint\t orig_flags;\n\tlong\t result = FALSE;\n\ttypval_T var2;\n\tint\t error = FALSE;\n\tint\t vim9script = in_vim9script();", "\tif (evalarg == NULL)\n\t{\n\t init_evalarg(&local_evalarg);\n\t evalarg_used = &local_evalarg;\n\t}\n\torig_flags = evalarg_used->eval_flags;\n\tevaluate = orig_flags & EVAL_EVALUATE;\n\tif (evaluate)\n\t{\n\t if (vim9script)\n\t\tresult = tv_get_bool_chk(rettv, &error);\n\t else if (tv_get_number_chk(rettv, &error) != 0)\n\t\tresult = TRUE;\n\t clear_tv(rettv);\n\t if (error)\n\t\treturn FAIL;\n\t}", "\t/*\n\t * Repeat until there is no following \"||\".\n\t */\n\twhile (p[0] == '|' && p[1] == '|')\n\t{\n\t if (getnext)\n\t\t*arg = eval_next_line(*arg, evalarg_used);\n\t else\n\t {\n\t\tif (evaluate && vim9script && !VIM_ISWHITE(p[-1]))\n\t\t{\n\t\t error_white_both(p, 2);\n\t\t clear_tv(rettv);\n\t\t return FAIL;\n\t\t}\n\t\t*arg = p;\n\t }", "\t /*\n\t * Get the second variable.\n\t */\n\t if (evaluate && vim9script && !IS_WHITE_OR_NUL((*arg)[2]))\n\t {\n\t\terror_white_both(*arg, 2);\n\t\tclear_tv(rettv);\n\t\treturn FAIL;\n\t }\n\t *arg = skipwhite_and_linebreak(*arg + 2, evalarg_used);\n\t evalarg_used->eval_flags = !result ? orig_flags\n\t\t\t\t\t\t : orig_flags & ~EVAL_EVALUATE;\n\t if (eval3(arg, &var2, evalarg_used) == FAIL)\n\t\treturn FAIL;", "\t /*\n\t * Compute the result.\n\t */\n\t if (evaluate && !result)\n\t {\n\t\tif (vim9script)\n\t\t result = tv_get_bool_chk(&var2, &error);\n\t\telse if (tv_get_number_chk(&var2, &error) != 0)\n\t\t result = TRUE;\n\t\tclear_tv(&var2);\n\t\tif (error)\n\t\t return FAIL;\n\t }\n\t if (evaluate)\n\t {\n\t\tif (vim9script)\n\t\t{\n\t\t rettv->v_type = VAR_BOOL;\n\t\t rettv->vval.v_number = result ? VVAL_TRUE : VVAL_FALSE;\n\t\t}\n\t\telse\n\t\t{\n\t\t rettv->v_type = VAR_NUMBER;\n\t\t rettv->vval.v_number = result;\n\t\t}\n\t }", "\t p = eval_next_non_blank(*arg, evalarg_used, &getnext);\n\t}", "\tif (evalarg == NULL)\n\t clear_evalarg(&local_evalarg, NULL);\n\telse\n\t evalarg->eval_flags = orig_flags;\n }", " return OK;\n}", "/*\n * Handle second level expression:\n *\texpr3 && expr3 && expr3\t logical AND\n *\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n *\n * Return OK or FAIL.\n */\n static int\neval3(char_u **arg, typval_T *rettv, evalarg_T *evalarg)\n{\n char_u\t*p;\n int\t\tgetnext;", " /*\n * Get the first expression.\n */\n if (eval4(arg, rettv, evalarg) == FAIL)\n\treturn FAIL;", " /*\n * Handle the \"&&\" operator.\n */\n p = eval_next_non_blank(*arg, evalarg, &getnext);\n if (p[0] == '&' && p[1] == '&')\n {\n\tevalarg_T *evalarg_used = evalarg;\n\tevalarg_T local_evalarg;\n\tint\t orig_flags;\n\tint\t evaluate;\n\tlong\t result = TRUE;\n\ttypval_T var2;\n\tint\t error = FALSE;\n\tint\t vim9script = in_vim9script();", "\tif (evalarg == NULL)\n\t{\n\t init_evalarg(&local_evalarg);\n\t evalarg_used = &local_evalarg;\n\t}\n\torig_flags = evalarg_used->eval_flags;\n\tevaluate = orig_flags & EVAL_EVALUATE;\n\tif (evaluate)\n\t{\n\t if (vim9script)\n\t\tresult = tv_get_bool_chk(rettv, &error);\n\t else if (tv_get_number_chk(rettv, &error) == 0)\n\t\tresult = FALSE;\n\t clear_tv(rettv);\n\t if (error)\n\t\treturn FAIL;\n\t}", "\t/*\n\t * Repeat until there is no following \"&&\".\n\t */\n\twhile (p[0] == '&' && p[1] == '&')\n\t{\n\t if (getnext)\n\t\t*arg = eval_next_line(*arg, evalarg_used);\n\t else\n\t {\n\t\tif (evaluate && vim9script && !VIM_ISWHITE(p[-1]))\n\t\t{\n\t\t error_white_both(p, 2);\n\t\t clear_tv(rettv);\n\t\t return FAIL;\n\t\t}\n\t\t*arg = p;\n\t }", "\t /*\n\t * Get the second variable.\n\t */\n\t if (evaluate && vim9script && !IS_WHITE_OR_NUL((*arg)[2]))\n\t {\n\t\terror_white_both(*arg, 2);\n\t\tclear_tv(rettv);\n\t\treturn FAIL;\n\t }\n\t *arg = skipwhite_and_linebreak(*arg + 2, evalarg_used);\n\t evalarg_used->eval_flags = result ? orig_flags\n\t\t\t\t\t\t : orig_flags & ~EVAL_EVALUATE;\n\t CLEAR_FIELD(var2);\n\t if (eval4(arg, &var2, evalarg_used) == FAIL)\n\t\treturn FAIL;", "\t /*\n\t * Compute the result.\n\t */\n\t if (evaluate && result)\n\t {\n\t\tif (vim9script)\n\t\t result = tv_get_bool_chk(&var2, &error);\n\t\telse if (tv_get_number_chk(&var2, &error) == 0)\n\t\t result = FALSE;\n\t\tclear_tv(&var2);\n\t\tif (error)\n\t\t return FAIL;\n\t }\n\t if (evaluate)\n\t {\n\t\tif (vim9script)\n\t\t{\n\t\t rettv->v_type = VAR_BOOL;\n\t\t rettv->vval.v_number = result ? VVAL_TRUE : VVAL_FALSE;\n\t\t}\n\t\telse\n\t\t{\n\t\t rettv->v_type = VAR_NUMBER;\n\t\t rettv->vval.v_number = result;\n\t\t}\n\t }", "\t p = eval_next_non_blank(*arg, evalarg_used, &getnext);\n\t}", "\tif (evalarg == NULL)\n\t clear_evalarg(&local_evalarg, NULL);\n\telse\n\t evalarg->eval_flags = orig_flags;\n }", " return OK;\n}", "/*\n * Handle third level expression:\n *\tvar1 == var2\n *\tvar1 =~ var2\n *\tvar1 != var2\n *\tvar1 !~ var2\n *\tvar1 > var2\n *\tvar1 >= var2\n *\tvar1 < var2\n *\tvar1 <= var2\n *\tvar1 is var2\n *\tvar1 isnot var2\n *\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n *\n * Return OK or FAIL.\n */\n static int\neval4(char_u **arg, typval_T *rettv, evalarg_T *evalarg)\n{\n char_u\t*p;\n int\t\tgetnext;\n exprtype_T\ttype = EXPR_UNKNOWN;\n int\t\tlen = 2;\n int\t\ttype_is = FALSE;", " /*\n * Get the first expression.\n */\n if (eval5(arg, rettv, evalarg) == FAIL)\n\treturn FAIL;", " p = eval_next_non_blank(*arg, evalarg, &getnext);", " type = get_compare_type(p, &len, &type_is);", " /*\n * If there is a comparative operator, use it.\n */\n if (type != EXPR_UNKNOWN)\n {\n\ttypval_T var2;\n\tint\t ic;\n\tint\t vim9script = in_vim9script();\n\tint\t evaluate = evalarg == NULL\n\t\t\t\t ? 0 : (evalarg->eval_flags & EVAL_EVALUATE);\n\tlong\t comp_lnum = SOURCING_LNUM;", "\tif (getnext)\n\t{\n\t *arg = eval_next_line(*arg, evalarg);\n\t p = *arg;\n\t}\n\telse if (evaluate && vim9script && !VIM_ISWHITE(**arg))\n\t{\n\t error_white_both(*arg, len);\n\t clear_tv(rettv);\n\t return FAIL;\n\t}", "\tif (vim9script && type_is && (p[len] == '?' || p[len] == '#'))\n\t{\n\t semsg(_(e_invalid_expression_str), p);\n\t clear_tv(rettv);\n\t return FAIL;\n\t}", "\t// extra question mark appended: ignore case\n\tif (p[len] == '?')\n\t{\n\t ic = TRUE;\n\t ++len;\n\t}\n\t// extra '#' appended: match case\n\telse if (p[len] == '#')\n\t{\n\t ic = FALSE;\n\t ++len;\n\t}\n\t// nothing appended: use 'ignorecase' if not in Vim script\n\telse\n\t ic = vim9script ? FALSE : p_ic;", "\t/*\n\t * Get the second variable.\n\t */\n\tif (evaluate && vim9script && !IS_WHITE_OR_NUL(p[len]))\n\t{\n\t error_white_both(p, len);\n\t clear_tv(rettv);\n\t return FAIL;\n\t}\n\t*arg = skipwhite_and_linebreak(p + len, evalarg);\n\tif (eval5(arg, &var2, evalarg) == FAIL)\n\t{\n\t clear_tv(rettv);\n\t return FAIL;\n\t}\n\tif (evaluate)\n\t{\n\t int ret;", "\t // use the line of the comparison for messages\n\t SOURCING_LNUM = comp_lnum;\n\t if (vim9script && check_compare_types(type, rettv, &var2) == FAIL)\n\t {\n\t\tret = FAIL;\n\t\tclear_tv(rettv);\n\t }\n\t else\n\t\tret = typval_compare(rettv, &var2, type, ic);\n\t clear_tv(&var2);\n\t return ret;\n\t}\n }", " return OK;\n}", "/*\n * Make a copy of blob \"tv1\" and append blob \"tv2\".\n */\n void\neval_addblob(typval_T *tv1, typval_T *tv2)\n{\n blob_T *b1 = tv1->vval.v_blob;\n blob_T *b2 = tv2->vval.v_blob;\n blob_T *b = blob_alloc();\n int\t i;", " if (b == NULL)\n\treturn;", " for (i = 0; i < blob_len(b1); i++)\n\tga_append(&b->bv_ga, blob_get(b1, i));\n for (i = 0; i < blob_len(b2); i++)\n\tga_append(&b->bv_ga, blob_get(b2, i));", " clear_tv(tv1);\n rettv_blob_set(tv1, b);\n}", "/*\n * Make a copy of list \"tv1\" and append list \"tv2\".\n */\n int\neval_addlist(typval_T *tv1, typval_T *tv2)\n{\n typval_T var3;", " // concatenate Lists\n if (list_concat(tv1->vval.v_list, tv2->vval.v_list, &var3) == FAIL)\n {\n\tclear_tv(tv1);\n\tclear_tv(tv2);\n\treturn FAIL;\n }\n clear_tv(tv1);\n *tv1 = var3;\n return OK;\n}", "/*\n * Handle the bitwise left/right shift operator expression:\n *\tvar1 << var2\n *\tvar1 >> var2\n *\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n *\n * Return OK or FAIL.\n */\n static int\neval5(char_u **arg, typval_T *rettv, evalarg_T *evalarg)\n{\n /*\n * Get the first expression.\n */\n if (eval6(arg, rettv, evalarg) == FAIL)\n\treturn FAIL;", " /*\n * Repeat computing, until no '<<' or '>>' is following.\n */\n for (;;)\n {\n\tchar_u\t\t*p;\n\tint\t\tgetnext;\n\texprtype_T\ttype;\n\tint\t\tevaluate;\n\ttypval_T\tvar2;\n\tint\t\tvim9script;", "\tp = eval_next_non_blank(*arg, evalarg, &getnext);\n\tif (p[0] == '<' && p[1] == '<')\n\t type = EXPR_LSHIFT;\n\telse if (p[0] == '>' && p[1] == '>')\n\t type = EXPR_RSHIFT;\n\telse\n\t return OK;", "\t// Handle a bitwise left or right shift operator\n\tif (rettv->v_type != VAR_NUMBER)\n\t{\n\t // left operand should be a number\n\t emsg(_(e_bitshift_ops_must_be_number));\n\t clear_tv(rettv);\n\t return FAIL;\n\t}", "\tevaluate = evalarg == NULL ? 0 : (evalarg->eval_flags & EVAL_EVALUATE);\n\tvim9script = in_vim9script();\n\tif (getnext)\n\t{\n\t *arg = eval_next_line(*arg, evalarg);\n\t p = *arg;\n\t}\n\telse if (evaluate && vim9script && !VIM_ISWHITE(**arg))\n\t{\n\t error_white_both(*arg, 2);\n\t clear_tv(rettv);\n\t return FAIL;\n\t}", "\t/*\n\t * Get the second variable.\n\t */\n\tif (evaluate && vim9script && !IS_WHITE_OR_NUL(p[2]))\n\t{\n\t error_white_both(p, 2);\n\t clear_tv(rettv);\n\t return FAIL;\n\t}\n\t*arg = skipwhite_and_linebreak(p + 2, evalarg);\n\tif (eval6(arg, &var2, evalarg) == FAIL)\n\t{\n\t clear_tv(rettv);\n\t return FAIL;\n\t}", "\tif (var2.v_type != VAR_NUMBER || var2.vval.v_number < 0)\n\t{\n\t // right operand should be a positive number\n\t if (var2.v_type != VAR_NUMBER)\n\t\temsg(_(e_bitshift_ops_must_be_number));\n\t else\n\t\temsg(_(e_bitshift_ops_must_be_positive));\n\t clear_tv(rettv);\n\t clear_tv(&var2);\n\t return FAIL;\n\t}", "\tif (evaluate)\n\t{\n\t if (var2.vval.v_number > MAX_LSHIFT_BITS)\n\t\t// shifting more bits than we have always results in zero\n\t\trettv->vval.v_number = 0;\n\t else if (type == EXPR_LSHIFT)\n\t\trettv->vval.v_number =\n\t\t (uvarnumber_T)rettv->vval.v_number << var2.vval.v_number;\n\t else\n\t\trettv->vval.v_number =\n\t\t (uvarnumber_T)rettv->vval.v_number >> var2.vval.v_number;\n\t}", "\tclear_tv(&var2);\n }", " return OK;\n}", "/*\n * Handle fifth level expression:\n *\t+\tnumber addition, concatenation of list or blob\n *\t-\tnumber subtraction\n *\t.\tstring concatenation (if script version is 1)\n *\t..\tstring concatenation\n *\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n *\n * Return OK or FAIL.\n */\n static int\neval6(char_u **arg, typval_T *rettv, evalarg_T *evalarg)\n{\n /*\n * Get the first expression.\n */\n if (eval7(arg, rettv, evalarg, FALSE) == FAIL)\n\treturn FAIL;", " /*\n * Repeat computing, until no '+', '-' or '.' is following.\n */\n for (;;)\n {\n\tint\t evaluate;\n\tint\t getnext;\n\tchar_u\t *p;\n\tint\t op;\n\tint\t oplen;\n\tint\t concat;\n\ttypval_T var2;\n\tint\t vim9script = in_vim9script();", "\t// \".\" is only string concatenation when scriptversion is 1\n\t// \"+=\", \"-=\" and \"..=\" are assignments\n\t// \"++\" and \"--\" on the next line are a separate command.\n\tp = eval_next_non_blank(*arg, evalarg, &getnext);\n\top = *p;\n\tconcat = op == '.' && (*(p + 1) == '.' || in_old_script(2));\n\tif ((op != '+' && op != '-' && !concat) || p[1] == '='\n\t\t\t\t\t || (p[1] == '.' && p[2] == '='))\n\t break;\n\tif (getnext && (op == '+' || op == '-') && p[0] == p[1])\n\t break;", "\tevaluate = evalarg == NULL ? 0 : (evalarg->eval_flags & EVAL_EVALUATE);\n\toplen = (concat && p[1] == '.') ? 2 : 1;\n\tif (getnext)\n\t *arg = eval_next_line(*arg, evalarg);\n\telse\n\t{\n\t if (evaluate && vim9script && !VIM_ISWHITE(**arg))\n\t {\n\t\terror_white_both(*arg, oplen);\n\t\tclear_tv(rettv);\n\t\treturn FAIL;\n\t }\n\t *arg = p;\n\t}\n\tif ((op != '+' || (rettv->v_type != VAR_LIST\n\t\t\t\t\t\t && rettv->v_type != VAR_BLOB))\n\t\t&& (op == '.' || rettv->v_type != VAR_FLOAT)\n\t\t&& evaluate)\n\t{\n\t int\t\terror = FALSE;", "\t // For \"list + ...\", an illegal use of the first operand as\n\t // a number cannot be determined before evaluating the 2nd\n\t // operand: if this is also a list, all is ok.\n\t // For \"something . ...\", \"something - ...\" or \"non-list + ...\",\n\t // we know that the first operand needs to be a string or number\n\t // without evaluating the 2nd operand. So check before to avoid\n\t // side effects after an error.\n\t if (op != '.')\n\t\ttv_get_number_chk(rettv, &error);\n\t if ((op == '.' && tv_get_string_chk(rettv) == NULL) || error)\n\t {\n\t\tclear_tv(rettv);\n\t\treturn FAIL;\n\t }\n\t}", "\t/*\n\t * Get the second variable.\n\t */\n\tif (evaluate && vim9script && !IS_WHITE_OR_NUL((*arg)[oplen]))\n\t{\n\t error_white_both(*arg, oplen);\n\t clear_tv(rettv);\n\t return FAIL;\n\t}\n\t*arg = skipwhite_and_linebreak(*arg + oplen, evalarg);\n\tif (eval7(arg, &var2, evalarg, !vim9script && op == '.') == FAIL)\n\t{\n\t clear_tv(rettv);\n\t return FAIL;\n\t}", "\tif (evaluate)\n\t{\n\t /*\n\t * Compute the result.\n\t */\n\t if (op == '.')\n\t {\n\t\tchar_u\tbuf1[NUMBUFLEN], buf2[NUMBUFLEN];\n\t\tchar_u\t*s1 = tv_get_string_buf(rettv, buf1);\n\t\tchar_u\t*s2 = NULL;", "\t\tif (vim9script && (var2.v_type == VAR_VOID\n\t\t\t|| var2.v_type == VAR_CHANNEL\n\t\t\t|| var2.v_type == VAR_JOB))\n\t\t semsg(_(e_using_invalid_value_as_string_str),\n\t\t\t\t\t\t vartype_name(var2.v_type));\n\t\telse if (vim9script && var2.v_type == VAR_FLOAT)\n\t\t{\n\t\t vim_snprintf((char *)buf2, NUMBUFLEN, \"%g\",\n\t\t\t\t\t\t\t var2.vval.v_float);\n\t\t s2 = buf2;\n\t\t}\n\t\telse\n\t\t s2 = tv_get_string_buf_chk(&var2, buf2);\n\t\tif (s2 == NULL)\t\t// type error ?\n\t\t{\n\t\t clear_tv(rettv);\n\t\t clear_tv(&var2);\n\t\t return FAIL;\n\t\t}\n\t\tp = concat_str(s1, s2);\n\t\tclear_tv(rettv);\n\t\trettv->v_type = VAR_STRING;\n\t\trettv->vval.v_string = p;\n\t }\n\t else if (op == '+' && rettv->v_type == VAR_BLOB\n\t\t\t\t\t\t && var2.v_type == VAR_BLOB)\n\t\teval_addblob(rettv, &var2);\n\t else if (op == '+' && rettv->v_type == VAR_LIST\n\t\t\t\t\t\t && var2.v_type == VAR_LIST)\n\t {\n\t\tif (eval_addlist(rettv, &var2) == FAIL)\n\t\t return FAIL;\n\t }\n\t else\n\t {\n\t\tint\t\terror = FALSE;\n\t\tvarnumber_T\tn1, n2;\n\t\tfloat_T\t\tf1 = 0, f2 = 0;", "\t\tif (rettv->v_type == VAR_FLOAT)\n\t\t{\n\t\t f1 = rettv->vval.v_float;\n\t\t n1 = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t n1 = tv_get_number_chk(rettv, &error);\n\t\t if (error)\n\t\t {\n\t\t\t// This can only happen for \"list + non-list\" or\n\t\t\t// \"blob + non-blob\". For \"non-list + ...\" or\n\t\t\t// \"something - ...\", we returned before evaluating the\n\t\t\t// 2nd operand.\n\t\t\tclear_tv(rettv);\n\t\t\tclear_tv(&var2);\n\t\t\treturn FAIL;\n\t\t }\n\t\t if (var2.v_type == VAR_FLOAT)\n\t\t\tf1 = n1;\n\t\t}\n\t\tif (var2.v_type == VAR_FLOAT)\n\t\t{\n\t\t f2 = var2.vval.v_float;\n\t\t n2 = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t n2 = tv_get_number_chk(&var2, &error);\n\t\t if (error)\n\t\t {\n\t\t\tclear_tv(rettv);\n\t\t\tclear_tv(&var2);\n\t\t\treturn FAIL;\n\t\t }\n\t\t if (rettv->v_type == VAR_FLOAT)\n\t\t\tf2 = n2;\n\t\t}\n\t\tclear_tv(rettv);", "\t\t// If there is a float on either side the result is a float.\n\t\tif (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)\n\t\t{\n\t\t if (op == '+')\n\t\t\tf1 = f1 + f2;\n\t\t else\n\t\t\tf1 = f1 - f2;\n\t\t rettv->v_type = VAR_FLOAT;\n\t\t rettv->vval.v_float = f1;\n\t\t}\n\t\telse\n\t\t{\n\t\t if (op == '+')\n\t\t\tn1 = n1 + n2;\n\t\t else\n\t\t\tn1 = n1 - n2;\n\t\t rettv->v_type = VAR_NUMBER;\n\t\t rettv->vval.v_number = n1;\n\t\t}\n\t }\n\t clear_tv(&var2);\n\t}\n }\n return OK;\n}", "/*\n * Handle sixth level expression:\n *\t*\tnumber multiplication\n *\t/\tnumber division\n *\t%\tnumber modulo\n *\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n *\n * Return OK or FAIL.\n */\n static int\neval7(\n char_u\t**arg,\n typval_T\t*rettv,\n evalarg_T\t*evalarg,\n int\t\twant_string) // after \".\" operator\n{\n int\t use_float = FALSE;", " /*\n * Get the first expression.\n */\n if (eval8(arg, rettv, evalarg, want_string) == FAIL)\n\treturn FAIL;", " /*\n * Repeat computing, until no '*', '/' or '%' is following.\n */\n for (;;)\n {\n\tint\t evaluate;\n\tint\t getnext;\n\ttypval_T var2;\n\tchar_u\t *p;\n\tint\t op;\n\tvarnumber_T n1, n2;\n\tfloat_T\t f1, f2;\n\tint\t error;", "\t// \"*=\", \"/=\" and \"%=\" are assignments\n\tp = eval_next_non_blank(*arg, evalarg, &getnext);\n\top = *p;\n\tif ((op != '*' && op != '/' && op != '%') || p[1] == '=')\n\t break;", "\tevaluate = evalarg == NULL ? 0 : (evalarg->eval_flags & EVAL_EVALUATE);\n\tif (getnext)\n\t *arg = eval_next_line(*arg, evalarg);\n\telse\n\t{\n\t if (evaluate && in_vim9script() && !VIM_ISWHITE(**arg))\n\t {\n\t\terror_white_both(*arg, 1);\n\t\tclear_tv(rettv);\n\t\treturn FAIL;\n\t }\n\t *arg = p;\n\t}", "\tf1 = 0;\n\tf2 = 0;\n\terror = FALSE;\n\tif (evaluate)\n\t{\n\t if (rettv->v_type == VAR_FLOAT)\n\t {\n\t\tf1 = rettv->vval.v_float;\n\t\tuse_float = TRUE;\n\t\tn1 = 0;\n\t }\n\t else\n\t\tn1 = tv_get_number_chk(rettv, &error);\n\t clear_tv(rettv);\n\t if (error)\n\t\treturn FAIL;\n\t}\n\telse\n\t n1 = 0;", "\t/*\n\t * Get the second variable.\n\t */\n\tif (evaluate && in_vim9script() && !IS_WHITE_OR_NUL((*arg)[1]))\n\t{\n\t error_white_both(*arg, 1);\n\t clear_tv(rettv);\n\t return FAIL;\n\t}\n\t*arg = skipwhite_and_linebreak(*arg + 1, evalarg);\n\tif (eval8(arg, &var2, evalarg, FALSE) == FAIL)\n\t return FAIL;", "\tif (evaluate)\n\t{\n\t if (var2.v_type == VAR_FLOAT)\n\t {\n\t\tif (!use_float)\n\t\t{\n\t\t f1 = n1;\n\t\t use_float = TRUE;\n\t\t}\n\t\tf2 = var2.vval.v_float;\n\t\tn2 = 0;\n\t }\n\t else\n\t {\n\t\tn2 = tv_get_number_chk(&var2, &error);\n\t\tclear_tv(&var2);\n\t\tif (error)\n\t\t return FAIL;\n\t\tif (use_float)\n\t\t f2 = n2;\n\t }", "\t /*\n\t * Compute the result.\n\t * When either side is a float the result is a float.\n\t */\n\t if (use_float)\n\t {\n\t\tif (op == '*')\n\t\t f1 = f1 * f2;\n\t\telse if (op == '/')\n\t\t{\n#ifdef VMS\n\t\t // VMS crashes on divide by zero, work around it\n\t\t if (f2 == 0.0)\n\t\t {\n\t\t\tif (f1 == 0)\n\t\t\t f1 = -1 * __F_FLT_MAX - 1L; // similar to NaN\n\t\t\telse if (f1 < 0)\n\t\t\t f1 = -1 * __F_FLT_MAX;\n\t\t\telse\n\t\t\t f1 = __F_FLT_MAX;\n\t\t }\n\t\t else\n\t\t\tf1 = f1 / f2;\n#else\n\t\t // We rely on the floating point library to handle divide\n\t\t // by zero to result in \"inf\" and not a crash.\n\t\t f1 = f1 / f2;\n#endif\n\t\t}\n\t\telse\n\t\t{\n\t\t emsg(_(e_cannot_use_percent_with_float));\n\t\t return FAIL;\n\t\t}\n\t\trettv->v_type = VAR_FLOAT;\n\t\trettv->vval.v_float = f1;\n\t }\n\t else\n\t {\n\t\tint\t failed = FALSE;", "\t\tif (op == '*')\n\t\t n1 = n1 * n2;\n\t\telse if (op == '/')\n\t\t n1 = num_divide(n1, n2, &failed);\n\t\telse\n\t\t n1 = num_modulus(n1, n2, &failed);\n\t\tif (failed)\n\t\t return FAIL;", "\t\trettv->v_type = VAR_NUMBER;\n\t\trettv->vval.v_number = n1;\n\t }\n\t}\n }", " return OK;\n}", "/*\n * Handle a type cast before a base level expression.\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n * Return OK or FAIL.\n */\n static int\neval8(\n char_u\t**arg,\n typval_T\t*rettv,\n evalarg_T\t*evalarg,\n int\t\twant_string)\t// after \".\" operator\n{\n type_T\t*want_type = NULL;\n garray_T\ttype_list;\t // list of pointers to allocated types\n int\t\tres;\n int\t\tevaluate = evalarg == NULL ? 0\n\t\t\t\t : (evalarg->eval_flags & EVAL_EVALUATE);", " // Recognize <type> in Vim9 script only.\n if (in_vim9script() && **arg == '<' && eval_isnamec1((*arg)[1])\n\t\t\t\t\t && STRNCMP(*arg, \"<SNR>\", 5) != 0)\n {\n\t++*arg;\n\tga_init2(&type_list, sizeof(type_T *), 10);\n\twant_type = parse_type(arg, &type_list, TRUE);\n\tif (want_type == NULL && (evaluate || **arg != '>'))\n\t{\n\t clear_type_list(&type_list);\n\t return FAIL;\n\t}", "\tif (**arg != '>')\n\t{\n\t if (*skipwhite(*arg) == '>')\n\t\tsemsg(_(e_no_white_space_allowed_before_str_str), \">\", *arg);\n\t else\n\t\temsg(_(e_missing_gt));\n\t clear_type_list(&type_list);\n\t return FAIL;\n\t}\n\t++*arg;\n\t*arg = skipwhite_and_linebreak(*arg, evalarg);\n }", " res = eval9(arg, rettv, evalarg, want_string);", " if (want_type != NULL && evaluate)\n {\n\tif (res == OK)\n\t{\n\t type_T *actual = typval2type(rettv, get_copyID(), &type_list,\n\t\t\t\t\t\t\t TVTT_DO_MEMBER);", "\t if (!equal_type(want_type, actual, 0))\n\t {\n\t\tif (want_type == &t_bool && actual != &t_bool\n\t\t\t\t\t&& (actual->tt_flags & TTFLAG_BOOL_OK))\n\t\t{\n\t\t int n = tv2bool(rettv);", "\t\t // can use \"0\" and \"1\" for boolean in some places\n\t\t clear_tv(rettv);\n\t\t rettv->v_type = VAR_BOOL;\n\t\t rettv->vval.v_number = n ? VVAL_TRUE : VVAL_FALSE;\n\t\t}\n\t\telse\n\t\t{\n\t\t where_T where = WHERE_INIT;", "\t\t where.wt_variable = TRUE;\n\t\t res = check_type(want_type, actual, TRUE, where);\n\t\t}\n\t }\n\t}\n\tclear_type_list(&type_list);\n }", " return res;\n}", " int\neval_leader(char_u **arg, int vim9)\n{\n char_u\t*s = *arg;\n char_u\t*p = *arg;", " while (*p == '!' || *p == '-' || *p == '+')\n {\n\tchar_u *n = skipwhite(p + 1);", "\t// ++, --, -+ and +- are not accepted in Vim9 script\n\tif (vim9 && (*p == '-' || *p == '+') && (*n == '-' || *n == '+'))\n\t{\n\t semsg(_(e_invalid_expression_str), s);\n\t return FAIL;\n\t}\n\tp = n;\n }\n *arg = p;\n return OK;\n}", "/*\n * Check for a predefined value \"true\", \"false\" and \"null.*\".\n * Return OK when recognized.\n */\n int\nhandle_predefined(char_u *s, int len, typval_T *rettv)\n{\n switch (len)\n {\n\tcase 4: if (STRNCMP(s, \"true\", 4) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_BOOL;\n\t\t rettv->vval.v_number = VVAL_TRUE;\n\t\t return OK;\n\t\t}\n\t\tif (STRNCMP(s, \"null\", 4) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_SPECIAL;\n\t\t rettv->vval.v_number = VVAL_NULL;\n\t\t return OK;\n\t\t}\n\t\tbreak;\n\tcase 5: if (STRNCMP(s, \"false\", 5) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_BOOL;\n\t\t rettv->vval.v_number = VVAL_FALSE;\n\t\t return OK;\n\t\t}\n\t\tbreak;\n\tcase 8: if (STRNCMP(s, \"null_job\", 8) == 0)\n\t\t{\n#ifdef FEAT_JOB_CHANNEL\n\t\t rettv->v_type = VAR_JOB;\n\t\t rettv->vval.v_job = NULL;\n#else\n\t\t rettv->v_type = VAR_SPECIAL;\n\t\t rettv->vval.v_number = VVAL_NULL;\n#endif\n\t\t return OK;\n\t\t}\n\t\tbreak;\n\tcase 9:\n\t\tif (STRNCMP(s, \"null_\", 5) != 0)\n\t\t break;\n\t\tif (STRNCMP(s + 5, \"list\", 4) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_LIST;\n\t\t rettv->vval.v_list = NULL;\n\t\t return OK;\n\t\t}\n\t\tif (STRNCMP(s + 5, \"dict\", 4) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_DICT;\n\t\t rettv->vval.v_dict = NULL;\n\t\t return OK;\n\t\t}\n\t\tif (STRNCMP(s + 5, \"blob\", 4) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_BLOB;\n\t\t rettv->vval.v_blob = NULL;\n\t\t return OK;\n\t\t}\n\t\tbreak;\n\tcase 10: if (STRNCMP(s, \"null_class\", 10) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_CLASS;\n\t\t rettv->vval.v_class = NULL;\n\t\t return OK;\n\t\t}\n\t\t break;\n\tcase 11: if (STRNCMP(s, \"null_string\", 11) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_STRING;\n\t\t rettv->vval.v_string = NULL;\n\t\t return OK;\n\t\t}\n\t\tif (STRNCMP(s, \"null_object\", 11) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_OBJECT;\n\t\t rettv->vval.v_object = NULL;\n\t\t return OK;\n\t\t}\n\t\tbreak;\n\tcase 12:\n\t\tif (STRNCMP(s, \"null_channel\", 12) == 0)\n\t\t{\n#ifdef FEAT_JOB_CHANNEL\n\t\t rettv->v_type = VAR_CHANNEL;\n\t\t rettv->vval.v_channel = NULL;\n#else\n\t\t rettv->v_type = VAR_SPECIAL;\n\t\t rettv->vval.v_number = VVAL_NULL;\n#endif\n\t\t return OK;\n\t\t}\n\t\tif (STRNCMP(s, \"null_partial\", 12) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_PARTIAL;\n\t\t rettv->vval.v_partial = NULL;\n\t\t return OK;\n\t\t}\n\t\tbreak;\n\tcase 13: if (STRNCMP(s, \"null_function\", 13) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_FUNC;\n\t\t rettv->vval.v_string = NULL;\n\t\t return OK;\n\t\t}\n\t\tbreak;\n }\n return FAIL;\n}", "/*\n * Handle sixth level expression:\n * number\t\tnumber constant\n * 0zFFFFFFFF\t\tBlob constant\n * \"string\"\t\tstring constant\n * 'string'\t\tliteral string constant\n * &option-name\toption value\n * @r\t\t\tregister contents\n * identifier\t\tvariable value\n * function()\t\tfunction call\n * $VAR\t\tenvironment variable\n * (expression)\tnested expression\n * [expr, expr]\tList\n * {arg, arg -> expr}\tLambda\n * {key: val, key: val} Dictionary\n * #{key: val, key: val} Dictionary with literal keys\n *\n * Also handle:\n * ! in front\t\tlogical NOT\n * - in front\t\tunary minus\n * + in front\t\tunary plus (ignored)\n * trailing []\t\tsubscript in String or List\n * trailing .name\tentry in Dictionary\n * trailing ->name()\tmethod call\n *\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n *\n * Return OK or FAIL.\n */\n static int\neval9(\n char_u\t**arg,\n typval_T\t*rettv,\n evalarg_T\t*evalarg,\n int\t\twant_string)\t// after \".\" operator\n{\n int\t\tevaluate = evalarg != NULL\n\t\t\t\t && (evalarg->eval_flags & EVAL_EVALUATE);\n int\t\tlen;\n char_u\t*s;\n char_u\t*name_start = NULL;\n char_u\t*start_leader, *end_leader;\n int\t\tret = OK;\n char_u\t*alias;\n static int\trecurse = 0;\n int\t\tvim9script = in_vim9script();", " /*\n * Initialise variable so that clear_tv() can't mistake this for a\n * string and free a string that isn't there.\n */\n rettv->v_type = VAR_UNKNOWN;", " /*\n * Skip '!', '-' and '+' characters. They are handled later.\n */\n start_leader = *arg;\n if (eval_leader(arg, vim9script) == FAIL)\n\treturn FAIL;\n end_leader = *arg;", " if (**arg == '.' && (!isdigit(*(*arg + 1)) || in_old_script(2)))\n {\n\tsemsg(_(e_invalid_expression_str), *arg);\n\t++*arg;\n\treturn FAIL;\n }", " // Limit recursion to 1000 levels. At least at 10000 we run out of stack\n // and crash. With MSVC the stack is smaller.\n if (recurse ==\n#ifdef _MSC_VER\n\t\t 300\n#else\n\t\t 1000\n#endif\n\t\t )\n {\n\tsemsg(_(e_expression_too_recursive_str), *arg);\n\treturn FAIL;\n }\n ++recurse;", " switch (**arg)\n {\n /*\n * Number constant.\n */\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n case '.':\tret = eval_number(arg, rettv, evaluate, want_string);", "\t\t// Apply prefixed \"-\" and \"+\" now. Matters especially when\n\t\t// \"->\" follows.\n\t\tif (ret == OK && evaluate && end_leader > start_leader\n\t\t\t\t\t\t && rettv->v_type != VAR_BLOB)\n\t\t ret = eval9_leader(rettv, TRUE, start_leader, &end_leader);\n\t\tbreak;", " /*\n * String constant: \"string\".\n */\n case '\"':\tret = eval_string(arg, rettv, evaluate, FALSE);\n\t\tbreak;", " /*\n * Literal string constant: 'str''ing'.\n */\n case '\\'':\tret = eval_lit_string(arg, rettv, evaluate, FALSE);\n\t\tbreak;", " /*\n * List: [expr, expr]\n */\n case '[':\tret = eval_list(arg, rettv, evalarg, TRUE);\n\t\tbreak;", " /*\n * Dictionary: #{key: val, key: val}\n */\n case '#':\tif (vim9script)\n\t\t{\n\t\t ret = vim9_bad_comment(*arg) ? FAIL : NOTDONE;\n\t\t}\n\t\telse if ((*arg)[1] == '{')\n\t\t{\n\t\t ++*arg;\n\t\t ret = eval_dict(arg, rettv, evalarg, TRUE);\n\t\t}\n\t\telse\n\t\t ret = NOTDONE;\n\t\tbreak;", " /*\n * Lambda: {arg, arg -> expr}\n * Dictionary: {'key': val, 'key': val}\n */\n case '{':\tif (vim9script)\n\t\t ret = NOTDONE;\n\t\telse\n\t\t ret = get_lambda_tv(arg, rettv, vim9script, evalarg);\n\t\tif (ret == NOTDONE)\n\t\t ret = eval_dict(arg, rettv, evalarg, FALSE);\n\t\tbreak;", " /*\n * Option value: &name\n */\n case '&':\tret = eval_option(arg, rettv, evaluate);\n\t\tbreak;", " /*\n * Environment variable: $VAR.\n * Interpolated string: $\"string\" or $'string'.\n */\n case '$':\tif ((*arg)[1] == '\"' || (*arg)[1] == '\\'')\n\t\t ret = eval_interp_string(arg, rettv, evaluate);\n\t\telse\n\t\t ret = eval_env_var(arg, rettv, evaluate);\n\t\tbreak;", " /*\n * Register contents: @r.\n */\n case '@':\t++*arg;\n\t\tif (evaluate)\n\t\t{\n\t\t if (vim9script && IS_WHITE_OR_NUL(**arg))\n\t\t\tsemsg(_(e_syntax_error_at_str), *arg);\n\t\t else if (vim9script && !valid_yank_reg(**arg, FALSE))\n\t\t\temsg_invreg(**arg);\n\t\t else\n\t\t {\n\t\t\trettv->v_type = VAR_STRING;\n\t\t\trettv->vval.v_string = get_reg_contents(**arg,\n\t\t\t\t\t\t\t\tGREG_EXPR_SRC);\n\t\t }\n\t\t}\n\t\tif (**arg != NUL)\n\t\t ++*arg;\n\t\tbreak;", " /*\n * nested expression: (expression).\n * or lambda: (arg) => expr\n */\n case '(':\tret = NOTDONE;\n\t\tif (vim9script)\n\t\t{\n\t\t ret = get_lambda_tv(arg, rettv, TRUE, evalarg);\n\t\t if (ret == OK && evaluate)\n\t\t {\n\t\t\tufunc_T *ufunc = rettv->vval.v_partial->pt_func;", "\t\t\t// Compile it here to get the return type. The return\n\t\t\t// type is optional, when it's missing use t_unknown.\n\t\t\t// This is recognized in compile_return().\n\t\t\tif (ufunc->uf_ret_type->tt_type == VAR_VOID)\n\t\t\t ufunc->uf_ret_type = &t_unknown;\n\t\t\tif (compile_def_function(ufunc, FALSE,\n\t\t\t\t\tget_compile_type(ufunc), NULL) == FAIL)\n\t\t\t{\n\t\t\t clear_tv(rettv);\n\t\t\t ret = FAIL;\n\t\t\t}\n\t\t }\n\t\t}\n\t\tif (ret == NOTDONE)\n\t\t{\n\t\t *arg = skipwhite_and_linebreak(*arg + 1, evalarg);\n\t\t ret = eval1(arg, rettv, evalarg);\t// recursive!", "\t\t *arg = skipwhite_and_linebreak(*arg, evalarg);\n\t\t if (**arg == ')')\n\t\t\t++*arg;\n\t\t else if (ret == OK)\n\t\t {\n\t\t\temsg(_(e_missing_closing_paren));\n\t\t\tclear_tv(rettv);\n\t\t\tret = FAIL;\n\t\t }\n\t\t}\n\t\tbreak;", " default:\tret = NOTDONE;\n\t\tbreak;\n }", " if (ret == NOTDONE)\n {\n\t/*\n\t * Must be a variable or function name.\n\t * Can also be a curly-braces kind of name: {expr}.\n\t */\n\ts = *arg;\n\tlen = get_name_len(arg, &alias, evaluate, TRUE);\n\tif (alias != NULL)\n\t s = alias;", "\tif (len <= 0)\n\t ret = FAIL;\n\telse\n\t{\n\t int\t flags = evalarg == NULL ? 0 : evalarg->eval_flags;", "\t if (evaluate && vim9script && len == 1 && *s == '_')\n\t {\n\t\temsg(_(e_cannot_use_underscore_here));\n\t\tret = FAIL;\n\t }\n\t else if (evaluate && vim9script && len > 2\n\t\t\t\t\t\t && s[0] == 's' && s[1] == ':')\n\t {\n\t\tsemsg(_(e_cannot_use_s_colon_in_vim9_script_str), s);\n\t\tret = FAIL;\n\t }\n\t else if ((vim9script ? **arg : *skipwhite(*arg)) == '(')\n\t {\n\t\t// \"name(...\" recursive!\n\t\t*arg = skipwhite(*arg);\n\t\tret = eval_func(arg, evalarg, s, len, rettv, flags, NULL);\n\t }\n\t else if (flags & EVAL_CONSTANT)\n\t\tret = FAIL;\n\t else if (evaluate)\n\t {\n\t\t// get the value of \"true\", \"false\", etc. or a variable\n\t\tret = FAIL;\n\t\tif (vim9script)\n\t\t ret = handle_predefined(s, len, rettv);\n\t\tif (ret == FAIL)\n\t\t{\n\t\t name_start = s;\n\t\t ret = eval_variable(s, len, 0, rettv, NULL,\n\t\t\t\t\t EVAL_VAR_VERBOSE + EVAL_VAR_IMPORT);\n\t\t}\n\t }\n\t else\n\t {\n\t\t// skip the name\n\t\tcheck_vars(s, len);\n\t\tret = OK;\n\t }\n\t}\n\tvim_free(alias);\n }", " // Handle following '[', '(' and '.' for expr[expr], expr.name,\n // expr(expr), expr->name(expr)\n if (ret == OK)\n\tret = handle_subscript(arg, name_start, rettv, evalarg, evaluate);", " /*\n * Apply logical NOT and unary '-', from right to left, ignore '+'.\n */\n if (ret == OK && evaluate && end_leader > start_leader)\n\tret = eval9_leader(rettv, FALSE, start_leader, &end_leader);", " --recurse;\n return ret;\n}", "/*\n * Apply the leading \"!\" and \"-\" before an eval9 expression to \"rettv\".\n * When \"numeric_only\" is TRUE only handle \"+\" and \"-\".\n * Adjusts \"end_leaderp\" until it is at \"start_leader\".\n */\n static int\neval9_leader(\n\ttypval_T *rettv,\n\tint\t numeric_only,\n\tchar_u\t *start_leader,\n\tchar_u\t **end_leaderp)\n{\n char_u\t*end_leader = *end_leaderp;\n int\t\tret = OK;\n int\t\terror = FALSE;\n varnumber_T val = 0;\n vartype_T\ttype = rettv->v_type;\n int\t\tvim9script = in_vim9script();\n float_T\t f = 0.0;", " if (rettv->v_type == VAR_FLOAT)\n\tf = rettv->vval.v_float;\n else\n {\n\twhile (VIM_ISWHITE(end_leader[-1]))\n\t --end_leader;\n\tif (vim9script && end_leader[-1] == '!')\n\t val = tv2bool(rettv);\n\telse\n\t val = tv_get_number_chk(rettv, &error);\n }\n if (error)\n {\n\tclear_tv(rettv);\n\tret = FAIL;\n }\n else\n {\n\twhile (end_leader > start_leader)\n\t{\n\t --end_leader;\n\t if (*end_leader == '!')\n\t {\n\t\tif (numeric_only)\n\t\t{\n\t\t ++end_leader;\n\t\t break;\n\t\t}\n\t\tif (rettv->v_type == VAR_FLOAT)\n\t\t{\n\t\t if (vim9script)\n\t\t {\n\t\t\trettv->v_type = VAR_BOOL;\n\t\t\tval = f == 0.0 ? VVAL_TRUE : VVAL_FALSE;\n\t\t }\n\t\t else\n\t\t\tf = !f;\n\t\t}\n\t\telse\n\t\t{\n\t\t val = !val;\n\t\t type = VAR_BOOL;\n\t\t}\n\t }\n\t else if (*end_leader == '-')\n\t {\n\t\tif (rettv->v_type == VAR_FLOAT)\n\t\t f = -f;\n\t\telse\n\t\t{\n\t\t val = -val;\n\t\t type = VAR_NUMBER;\n\t\t}\n\t }\n\t}\n\tif (rettv->v_type == VAR_FLOAT)\n\t{\n\t clear_tv(rettv);\n\t rettv->vval.v_float = f;\n\t}\n\telse\n\t{\n\t clear_tv(rettv);\n\t if (vim9script)\n\t\trettv->v_type = type;\n\t else\n\t\trettv->v_type = VAR_NUMBER;\n\t rettv->vval.v_number = val;\n\t}\n }\n *end_leaderp = end_leader;\n return ret;\n}", "/*\n * Call the function referred to in \"rettv\".\n */\n static int\ncall_func_rettv(\n\tchar_u\t **arg,\n\tevalarg_T *evalarg,\n\ttypval_T *rettv,\n\tint\t evaluate,\n\tdict_T\t *selfdict,\n\ttypval_T *basetv)\n{\n partial_T\t*pt = NULL;\n funcexe_T\tfuncexe;\n typval_T\tfunctv;\n char_u\t*s;\n int\t\tret;", " // need to copy the funcref so that we can clear rettv\n if (evaluate)\n {\n\tfunctv = *rettv;\n\trettv->v_type = VAR_UNKNOWN;", "\t// Invoke the function. Recursive!\n\tif (functv.v_type == VAR_PARTIAL)\n\t{\n\t pt = functv.vval.v_partial;\n\t s = partial_name(pt);\n\t}\n\telse\n\t{\n\t s = functv.vval.v_string;\n\t if (s == NULL || *s == NUL)\n\t {\n\t\temsg(_(e_empty_function_name));\n\t\tret = FAIL;\n\t\tgoto theend;\n\t }\n\t}\n }\n else\n\ts = (char_u *)\"\";", " CLEAR_FIELD(funcexe);\n funcexe.fe_firstline = curwin->w_cursor.lnum;\n funcexe.fe_lastline = curwin->w_cursor.lnum;\n funcexe.fe_evaluate = evaluate;\n funcexe.fe_partial = pt;\n funcexe.fe_selfdict = selfdict;\n funcexe.fe_basetv = basetv;\n ret = get_func_tv(s, -1, rettv, arg, evalarg, &funcexe);", "theend:\n // Clear the funcref afterwards, so that deleting it while\n // evaluating the arguments is possible (see test55).\n if (evaluate)\n\tclear_tv(&functv);", " return ret;\n}", "/*\n * Evaluate \"->method()\".\n * \"*arg\" points to \"method\".\n * Returns FAIL or OK. \"*arg\" is advanced to after the ')'.\n */\n static int\neval_lambda(\n char_u\t**arg,\n typval_T\t*rettv,\n evalarg_T\t*evalarg,\n int\t\tverbose)\t// give error messages\n{\n int\t\tevaluate = evalarg != NULL\n\t\t\t\t && (evalarg->eval_flags & EVAL_EVALUATE);\n typval_T\tbase = *rettv;\n int\t\tret;", " rettv->v_type = VAR_UNKNOWN;", " if (**arg == '{')\n {\n\t// ->{lambda}()\n\tret = get_lambda_tv(arg, rettv, FALSE, evalarg);\n }\n else\n {\n\t// ->(lambda)()\n\t++*arg;\n\tret = eval1(arg, rettv, evalarg);\n\t*arg = skipwhite_and_linebreak(*arg, evalarg);\n\tif (**arg != ')')\n\t{\n\t emsg(_(e_missing_closing_paren));\n\t return FAIL;\n\t}\n\tif (rettv->v_type != VAR_STRING && rettv->v_type != VAR_FUNC\n\t\t\t\t\t && rettv->v_type != VAR_PARTIAL)\n\t{\n\t emsg(_(e_string_or_function_required_for_arrow_parens_expr));\n\t return FAIL;\n\t}\n\t++*arg;\n }\n if (ret != OK)\n\treturn FAIL;", " if (**arg != '(')\n {\n\tif (verbose)\n\t{\n\t if (*skipwhite(*arg) == '(')\n\t\temsg(_(e_no_white_space_allowed_before_parenthesis));\n\t else\n\t\tsemsg(_(e_missing_parenthesis_str), \"lambda\");\n\t}\n\tclear_tv(rettv);\n\tret = FAIL;\n }\n else\n\tret = call_func_rettv(arg, evalarg, rettv, evaluate, NULL, &base);", " // Clear the funcref afterwards, so that deleting it while\n // evaluating the arguments is possible (see test55).\n if (evaluate)\n\tclear_tv(&base);", " return ret;\n}", "/*\n * Evaluate \"->method()\".\n * \"*arg\" points to \"method\".\n * Returns FAIL or OK. \"*arg\" is advanced to after the ')'.\n */\n static int\neval_method(\n char_u\t**arg,\n typval_T\t*rettv,\n evalarg_T\t*evalarg,\n int\t\tverbose)\t// give error messages\n{\n char_u\t*name;\n long\tlen;\n char_u\t*alias;\n char_u\t*tofree = NULL;\n typval_T\tbase = *rettv;\n int\t\tret = OK;\n int\t\tevaluate = evalarg != NULL\n\t\t\t\t && (evalarg->eval_flags & EVAL_EVALUATE);", " rettv->v_type = VAR_UNKNOWN;", " name = *arg;\n len = get_name_len(arg, &alias, evaluate, evaluate);\n if (alias != NULL)\n\tname = alias;", " if (len <= 0)\n {\n\tif (verbose)\n\t emsg(_(e_missing_name_after_method));\n\tret = FAIL;\n }\n else\n {\n\tchar_u *paren;", "\t// If there is no \"(\" immediately following, but there is further on,\n\t// it can be \"import.Func()\", \"dict.Func()\", \"list[nr]\", etc.\n\t// Does not handle anything where \"(\" is part of the expression.\n\t*arg = skipwhite(*arg);", "\tif (**arg != '(' && alias == NULL\n\t\t\t\t && (paren = vim_strchr(*arg, '(')) != NULL)\n\t{\n\t *arg = name;", "\t // Truncate the name a the \"(\". Avoid trying to get another line\n\t // by making \"getline\" NULL.\n\t *paren = NUL;\n\t char_u\t*(*getline)(int, void *, int, getline_opt_T) = NULL;\n\t if (evalarg != NULL)\n\t {\n\t\tgetline = evalarg->eval_getline;\n\t\tevalarg->eval_getline = NULL;\n\t }", "\t char_u *deref = deref_function_name(arg, &tofree, evalarg, verbose);\n\t if (deref == NULL)\n\t {\n\t\t*arg = name + len;\n\t\tret = FAIL;\n\t }\n\t else\n\t {\n\t\tname = deref;\n\t\tlen = (long)STRLEN(name);\n\t }", "\t *paren = '(';\n\t if (getline != NULL)\n\t\tevalarg->eval_getline = getline;\n\t}", "\tif (ret == OK)\n\t{\n\t *arg = skipwhite(*arg);", "\t if (**arg != '(')\n\t {\n\t\tif (verbose)\n\t\t semsg(_(e_missing_parenthesis_str), name);\n\t\tret = FAIL;\n\t }\n\t else if (VIM_ISWHITE((*arg)[-1]))\n\t {\n\t\tif (verbose)\n\t\t emsg(_(e_no_white_space_allowed_before_parenthesis));\n\t\tret = FAIL;\n\t }\n\t else\n\t\tret = eval_func(arg, evalarg, name, len, rettv,\n\t\t\t\t\t evaluate ? EVAL_EVALUATE : 0, &base);\n\t}\n }", " // Clear the funcref afterwards, so that deleting it while\n // evaluating the arguments is possible (see test55).\n if (evaluate)\n\tclear_tv(&base);\n vim_free(tofree);", " return ret;\n}", "/*\n * Evaluate an \"[expr]\" or \"[expr:expr]\" index. Also \"dict.key\".\n * \"*arg\" points to the '[' or '.'.\n * Returns FAIL or OK. \"*arg\" is advanced to after the ']'.\n */\n static int\neval_index(\n char_u\t**arg,\n typval_T\t*rettv,\n evalarg_T\t*evalarg,\n int\t\tverbose)\t// give error messages\n{\n int\t\tevaluate = evalarg != NULL\n\t\t\t\t && (evalarg->eval_flags & EVAL_EVALUATE);\n int\t\tempty1 = FALSE, empty2 = FALSE;\n typval_T\tvar1, var2;\n int\t\trange = FALSE;\n char_u\t*key = NULL;\n int\t\tkeylen = -1;\n int\t\tvim9script = in_vim9script();", " if (check_can_index(rettv, evaluate, verbose) == FAIL)\n\treturn FAIL;", " init_tv(&var1);\n init_tv(&var2);\n if (**arg == '.')\n {\n\t/*\n\t * dict.name\n\t */\n\tkey = *arg + 1;\n\tfor (keylen = 0; eval_isdictc(key[keylen]); ++keylen)\n\t ;\n\tif (keylen == 0)\n\t return FAIL;\n\t*arg = key + keylen;\n }\n else\n {\n\t/*\n\t * something[idx]\n\t *\n\t * Get the (first) variable from inside the [].\n\t */\n\t*arg = skipwhite_and_linebreak(*arg + 1, evalarg);\n\tif (**arg == ':')\n\t empty1 = TRUE;\n\telse if (eval1(arg, &var1, evalarg) == FAIL)\t// recursive!\n\t return FAIL;\n\telse if (vim9script && **arg == ':')\n\t{\n\t semsg(_(e_white_space_required_before_and_after_str_at_str),\n\t\t\t\t\t\t\t\t \":\", *arg);\n\t clear_tv(&var1);\n\t return FAIL;\n\t}\n\telse if (evaluate)\n\t{\n\t int error = FALSE;", "\t // allow for indexing with float\n\t if (vim9script && rettv->v_type == VAR_DICT\n\t\t\t\t\t\t && var1.v_type == VAR_FLOAT)\n\t {\n\t\tvar1.vval.v_string = typval_tostring(&var1, TRUE);\n\t\tvar1.v_type = VAR_STRING;\n\t }", "\t if (vim9script && rettv->v_type == VAR_LIST)\n\t\ttv_get_number_chk(&var1, &error);\n\t else\n\t\terror = tv_get_string_chk(&var1) == NULL;\n\t if (error)\n\t {\n\t\t// not a number or string\n\t\tclear_tv(&var1);\n\t\treturn FAIL;\n\t }\n\t}", "\t/*\n\t * Get the second variable from inside the [:].\n\t */\n\t*arg = skipwhite_and_linebreak(*arg, evalarg);\n\tif (**arg == ':')\n\t{\n\t range = TRUE;\n\t ++*arg;\n\t if (vim9script && !IS_WHITE_OR_NUL(**arg) && **arg != ']')\n\t {\n\t\tsemsg(_(e_white_space_required_before_and_after_str_at_str),\n\t\t\t\t\t\t\t\t\":\", *arg - 1);\n\t\tif (!empty1)\n\t\t clear_tv(&var1);\n\t\treturn FAIL;\n\t }\n\t *arg = skipwhite_and_linebreak(*arg, evalarg);\n\t if (**arg == ']')\n\t\tempty2 = TRUE;\n\t else if (eval1(arg, &var2, evalarg) == FAIL)\t// recursive!\n\t {\n\t\tif (!empty1)\n\t\t clear_tv(&var1);\n\t\treturn FAIL;\n\t }\n\t else if (evaluate && tv_get_string_chk(&var2) == NULL)\n\t {\n\t\t// not a number or string\n\t\tif (!empty1)\n\t\t clear_tv(&var1);\n\t\tclear_tv(&var2);\n\t\treturn FAIL;\n\t }\n\t}", "\t// Check for the ']'.\n\t*arg = skipwhite_and_linebreak(*arg, evalarg);\n\tif (**arg != ']')\n\t{\n\t if (verbose)\n\t\temsg(_(e_missing_closing_square_brace));\n\t clear_tv(&var1);\n\t if (range)\n\t\tclear_tv(&var2);\n\t return FAIL;\n\t}\n\t*arg = *arg + 1;\t// skip over the ']'\n }", " if (evaluate)\n {\n\tint res = eval_index_inner(rettv, range,\n\t\tempty1 ? NULL : &var1, empty2 ? NULL : &var2, FALSE,\n\t\tkey, keylen, verbose);", "\tif (!empty1)\n\t clear_tv(&var1);\n\tif (range)\n\t clear_tv(&var2);\n\treturn res;\n }\n return OK;\n}", "/*\n * Check if \"rettv\" can have an [index] or [sli:ce]\n */\n int\ncheck_can_index(typval_T *rettv, int evaluate, int verbose)\n{\n switch (rettv->v_type)\n {\n\tcase VAR_FUNC:\n\tcase VAR_PARTIAL:\n\t if (verbose)\n\t\temsg(_(e_cannot_index_a_funcref));\n\t return FAIL;\n\tcase VAR_FLOAT:\n\t if (verbose)\n\t\temsg(_(e_using_float_as_string));\n\t return FAIL;\n\tcase VAR_BOOL:\n\tcase VAR_SPECIAL:\n\tcase VAR_JOB:\n\tcase VAR_CHANNEL:\n\tcase VAR_INSTR:\n\tcase VAR_CLASS:\n\tcase VAR_OBJECT:\n\t if (verbose)\n\t\temsg(_(e_cannot_index_special_variable));\n\t return FAIL;\n\tcase VAR_UNKNOWN:\n\tcase VAR_ANY:\n\tcase VAR_VOID:\n\t if (evaluate)\n\t {\n\t\temsg(_(e_cannot_index_special_variable));\n\t\treturn FAIL;\n\t }\n\t // FALLTHROUGH", "\tcase VAR_STRING:\n\tcase VAR_LIST:\n\tcase VAR_DICT:\n\tcase VAR_BLOB:\n\t break;\n\tcase VAR_NUMBER:\n\t if (in_vim9script())\n\t\temsg(_(e_cannot_index_number));\n\t break;\n }\n return OK;\n}", "/*\n * slice() function\n */\n void\nf_slice(typval_T *argvars, typval_T *rettv)\n{\n if (in_vim9script()\n\t && ((argvars[0].v_type != VAR_STRING\n\t\t && argvars[0].v_type != VAR_LIST\n\t\t && argvars[0].v_type != VAR_BLOB\n\t\t && check_for_list_arg(argvars, 0) == FAIL)\n\t\t|| check_for_number_arg(argvars, 1) == FAIL\n\t\t|| check_for_opt_number_arg(argvars, 2) == FAIL))\n\treturn;", " if (check_can_index(argvars, TRUE, FALSE) != OK)\n\treturn;", " copy_tv(argvars, rettv);\n eval_index_inner(rettv, TRUE, argvars + 1,\n\t argvars[2].v_type == VAR_UNKNOWN ? NULL : argvars + 2,\n\t TRUE, NULL, 0, FALSE);\n}", "/*\n * Apply index or range to \"rettv\".\n * \"var1\" is the first index, NULL for [:expr].\n * \"var2\" is the second index, NULL for [expr] and [expr: ]\n * \"exclusive\" is TRUE for slice(): second index is exclusive, use character\n * index for string.\n * Alternatively, \"key\" is not NULL, then key[keylen] is the dict index.\n */\n int\neval_index_inner(\n\ttypval_T *rettv,\n\tint\t is_range,\n\ttypval_T *var1,\n\ttypval_T *var2,\n\tint\t exclusive,\n\tchar_u\t *key,\n\tint\t keylen,\n\tint\t verbose)\n{\n varnumber_T\t n1, n2 = 0;\n long\t len;", " n1 = 0;\n if (var1 != NULL && rettv->v_type != VAR_DICT)\n\tn1 = tv_get_number(var1);", " if (is_range)\n {\n\tif (rettv->v_type == VAR_DICT)\n\t{\n\t if (verbose)\n\t\temsg(_(e_cannot_slice_dictionary));\n\t return FAIL;\n\t}\n\tif (var2 != NULL)\n\t n2 = tv_get_number(var2);\n\telse\n\t n2 = VARNUM_MAX;\n }", " switch (rettv->v_type)\n {\n\tcase VAR_UNKNOWN:\n\tcase VAR_ANY:\n\tcase VAR_VOID:\n\tcase VAR_FUNC:\n\tcase VAR_PARTIAL:\n\tcase VAR_FLOAT:\n\tcase VAR_BOOL:\n\tcase VAR_SPECIAL:\n\tcase VAR_JOB:\n\tcase VAR_CHANNEL:\n\tcase VAR_INSTR:\n\tcase VAR_CLASS:\n\tcase VAR_OBJECT:\n\t break; // not evaluating, skipping over subscript", "\tcase VAR_NUMBER:\n\tcase VAR_STRING:\n\t {\n\t\tchar_u\t*s = tv_get_string(rettv);", "\t\tlen = (long)STRLEN(s);\n\t\tif (in_vim9script() || exclusive)\n\t\t{\n\t\t if (is_range)\n\t\t\ts = string_slice(s, n1, n2, exclusive);\n\t\t else\n\t\t\ts = char_from_string(s, n1);\n\t\t}\n\t\telse if (is_range)\n\t\t{\n\t\t // The resulting variable is a substring. If the indexes\n\t\t // are out of range the result is empty.\n\t\t if (n1 < 0)\n\t\t {\n\t\t\tn1 = len + n1;\n\t\t\tif (n1 < 0)\n\t\t\t n1 = 0;\n\t\t }\n\t\t if (n2 < 0)\n\t\t\tn2 = len + n2;\n\t\t else if (n2 >= len)\n\t\t\tn2 = len;\n\t\t if (n1 >= len || n2 < 0 || n1 > n2)\n\t\t\ts = NULL;\n\t\t else\n\t\t\ts = vim_strnsave(s + n1, n2 - n1 + 1);\n\t\t}\n\t\telse\n\t\t{\n\t\t // The resulting variable is a string of a single\n\t\t // character. If the index is too big or negative the\n\t\t // result is empty.\n\t\t if (n1 >= len || n1 < 0)\n\t\t\ts = NULL;\n\t\t else\n\t\t\ts = vim_strnsave(s + n1, 1);\n\t\t}\n\t\tclear_tv(rettv);\n\t\trettv->v_type = VAR_STRING;\n\t\trettv->vval.v_string = s;\n\t }\n\t break;", "\tcase VAR_BLOB:\n\t blob_slice_or_index(rettv->vval.v_blob, is_range, n1, n2,\n\t\t\t\t\t\t\t exclusive, rettv);\n\t break;", "\tcase VAR_LIST:\n\t if (var1 == NULL)\n\t\tn1 = 0;\n\t if (var2 == NULL)\n\t\tn2 = VARNUM_MAX;\n\t if (list_slice_or_index(rettv->vval.v_list,\n\t\t\t is_range, n1, n2, exclusive, rettv, verbose) == FAIL)\n\t\treturn FAIL;\n\t break;", "\tcase VAR_DICT:\n\t {\n\t\tdictitem_T\t*item;\n\t\ttypval_T\ttmp;", "\t\tif (key == NULL)\n\t\t{\n\t\t key = tv_get_string_chk(var1);\n\t\t if (key == NULL)\n\t\t\treturn FAIL;\n\t\t}", "\t\titem = dict_find(rettv->vval.v_dict, key, keylen);", "\t\tif (item == NULL)\n\t\t{\n\t\t if (verbose)\n\t\t {\n\t\t\tif (keylen > 0)\n\t\t\t key[keylen] = NUL;\n\t\t\tsemsg(_(e_key_not_present_in_dictionary_str), key);\n\t\t }\n\t\t return FAIL;\n\t\t}", "\t\tcopy_tv(&item->di_tv, &tmp);\n\t\tclear_tv(rettv);\n\t\t*rettv = tmp;\n\t }\n\t break;\n }\n return OK;\n}", "/*\n * Return the function name of partial \"pt\".\n */\n char_u *\npartial_name(partial_T *pt)\n{\n if (pt != NULL)\n {\n\tif (pt->pt_name != NULL)\n\t return pt->pt_name;\n\tif (pt->pt_func != NULL)\n\t return pt->pt_func->uf_name;\n }\n return (char_u *)\"\";\n}", " static void\npartial_free(partial_T *pt)\n{\n int i;", " for (i = 0; i < pt->pt_argc; ++i)\n\tclear_tv(&pt->pt_argv[i]);\n vim_free(pt->pt_argv);\n dict_unref(pt->pt_dict);\n if (pt->pt_name != NULL)\n {\n\tfunc_unref(pt->pt_name);\n\tvim_free(pt->pt_name);\n }\n else\n\tfunc_ptr_unref(pt->pt_func);", " // \"out_up\" is no longer used, decrement refcount on partial that owns it.\n partial_unref(pt->pt_outer.out_up_partial);", " // Using pt_outer from another partial.\n partial_unref(pt->pt_outer_partial);", " // Decrease the reference count for the context of a closure. If down\n // to the minimum it may be time to free it.\n if (pt->pt_funcstack != NULL)\n {\n\t--pt->pt_funcstack->fs_refcount;\n\tfuncstack_check_refcount(pt->pt_funcstack);\n }\n // Similarly for loop variables.\n for (i = 0; i < MAX_LOOP_DEPTH; ++i)\n\tif (pt->pt_loopvars[i] != NULL)\n\t{\n\t --pt->pt_loopvars[i]->lvs_refcount;\n\t loopvars_check_refcount(pt->pt_loopvars[i]);\n\t}", " vim_free(pt);\n}", "/*\n * Unreference a closure: decrement the reference count and free it when it\n * becomes zero.\n */\n void\npartial_unref(partial_T *pt)\n{\n if (pt == NULL)\n\treturn;", " int\tdone = FALSE;", " if (--pt->pt_refcount <= 0)\n\tpartial_free(pt);", " // If the reference count goes down to one, the funcstack may be the\n // only reference and can be freed if no other partials reference it.\n else if (pt->pt_refcount == 1)\n {\n\t// careful: if the funcstack is freed it may contain this partial\n\t// and it gets freed as well\n\tif (pt->pt_funcstack != NULL)\n\t done = funcstack_check_refcount(pt->pt_funcstack);", "\tif (!done)\n\t{\n\t int\tdepth;", "\t for (depth = 0; depth < MAX_LOOP_DEPTH; ++depth)\n\t\tif (pt->pt_loopvars[depth] != NULL\n\t\t\t&& loopvars_check_refcount(pt->pt_loopvars[depth]))\n\t\t break;\n\t}\n }\n}", "/*\n * Return the next (unique) copy ID.\n * Used for serializing nested structures.\n */\n int\nget_copyID(void)\n{\n current_copyID += COPYID_INC;\n return current_copyID;\n}", "/*\n * Garbage collection for lists and dictionaries.\n *\n * We use reference counts to be able to free most items right away when they\n * are no longer used. But for composite items it's possible that it becomes\n * unused while the reference count is > 0: When there is a recursive\n * reference. Example:\n *\t:let l = [1, 2, 3]\n *\t:let d = {9: l}\n *\t:let l[1] = d\n *\n * Since this is quite unusual we handle this with garbage collection: every\n * once in a while find out which lists and dicts are not referenced from any\n * variable.\n *\n * Here is a good reference text about garbage collection (refers to Python\n * but it applies to all reference-counting mechanisms):\n *\thttp://python.ca/nas/python/gc/\n */", "/*\n * Do garbage collection for lists and dicts.\n * When \"testing\" is TRUE this is called from test_garbagecollect_now().\n * Return TRUE if some memory was freed.\n */\n int\ngarbage_collect(int testing)\n{\n int\t\tcopyID;\n int\t\tabort = FALSE;\n buf_T\t*buf;\n win_T\t*wp;\n int\t\tdid_free = FALSE;\n tabpage_T\t*tp;", " if (!testing)\n {\n\t// Only do this once.\n\twant_garbage_collect = FALSE;\n\tmay_garbage_collect = FALSE;\n\tgarbage_collect_at_exit = FALSE;\n }", " // The execution stack can grow big, limit the size.\n if (exestack.ga_maxlen - exestack.ga_len > 500)\n {\n\tsize_t\tnew_len;\n\tchar_u\t*pp;\n\tint\tn;", "\t// Keep 150% of the current size, with a minimum of the growth size.\n\tn = exestack.ga_len / 2;\n\tif (n < exestack.ga_growsize)\n\t n = exestack.ga_growsize;", "\t// Don't make it bigger though.\n\tif (exestack.ga_len + n < exestack.ga_maxlen)\n\t{\n\t new_len = (size_t)exestack.ga_itemsize * (exestack.ga_len + n);\n\t pp = vim_realloc(exestack.ga_data, new_len);\n\t if (pp == NULL)\n\t\treturn FAIL;\n\t exestack.ga_maxlen = exestack.ga_len + n;\n\t exestack.ga_data = pp;\n\t}\n }", " // We advance by two because we add one for items referenced through\n // previous_funccal.\n copyID = get_copyID();", " /*\n * 1. Go through all accessible variables and mark all lists and dicts\n * with copyID.\n */", " // Don't free variables in the previous_funccal list unless they are only\n // referenced through previous_funccal. This must be first, because if\n // the item is referenced elsewhere the funccal must not be freed.\n abort = abort || set_ref_in_previous_funccal(copyID);", " // script-local variables\n abort = abort || garbage_collect_scriptvars(copyID);", " // buffer-local variables\n FOR_ALL_BUFFERS(buf)\n\tabort = abort || set_ref_in_item(&buf->b_bufvar.di_tv, copyID,\n\t\t\t\t\t\t\t\t NULL, NULL);", " // window-local variables\n FOR_ALL_TAB_WINDOWS(tp, wp)\n\tabort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,\n\t\t\t\t\t\t\t\t NULL, NULL);\n // window-local variables in autocmd windows\n for (int i = 0; i < AUCMD_WIN_COUNT; ++i)\n\tif (aucmd_win[i].auc_win != NULL)\n\t abort = abort || set_ref_in_item(\n\t\t &aucmd_win[i].auc_win->w_winvar.di_tv, copyID, NULL, NULL);\n#ifdef FEAT_PROP_POPUP\n FOR_ALL_POPUPWINS(wp)\n\tabort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,\n\t\t\t\t\t\t\t\t NULL, NULL);\n FOR_ALL_TABPAGES(tp)\n\tFOR_ALL_POPUPWINS_IN_TAB(tp, wp)\n\t\tabort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,\n\t\t\t\t\t\t\t\t NULL, NULL);\n#endif", " // tabpage-local variables\n FOR_ALL_TABPAGES(tp)\n\tabort = abort || set_ref_in_item(&tp->tp_winvar.di_tv, copyID,\n\t\t\t\t\t\t\t\t NULL, NULL);\n // global variables\n abort = abort || garbage_collect_globvars(copyID);", " // function-local variables\n abort = abort || set_ref_in_call_stack(copyID);", " // named functions (matters for closures)\n abort = abort || set_ref_in_functions(copyID);", " // function call arguments, if v:testing is set.\n abort = abort || set_ref_in_func_args(copyID);", " // funcstacks keep variables for closures\n abort = abort || set_ref_in_funcstacks(copyID);", " // loopvars keep variables for loop blocks\n abort = abort || set_ref_in_loopvars(copyID);", " // v: vars\n abort = abort || garbage_collect_vimvars(copyID);", " // callbacks in buffers\n abort = abort || set_ref_in_buffers(copyID);", " // 'completefunc', 'omnifunc' and 'thesaurusfunc' callbacks\n abort = abort || set_ref_in_insexpand_funcs(copyID);", " // 'operatorfunc' callback\n abort = abort || set_ref_in_opfunc(copyID);", " // 'tagfunc' callback\n abort = abort || set_ref_in_tagfunc(copyID);", " // 'imactivatefunc' and 'imstatusfunc' callbacks\n abort = abort || set_ref_in_im_funcs(copyID);", "#ifdef FEAT_LUA\n abort = abort || set_ref_in_lua(copyID);\n#endif", "#ifdef FEAT_PYTHON\n abort = abort || set_ref_in_python(copyID);\n#endif", "#ifdef FEAT_PYTHON3\n abort = abort || set_ref_in_python3(copyID);\n#endif", "#ifdef FEAT_JOB_CHANNEL\n abort = abort || set_ref_in_channel(copyID);\n abort = abort || set_ref_in_job(copyID);\n#endif\n#ifdef FEAT_NETBEANS_INTG\n abort = abort || set_ref_in_nb_channel(copyID);\n#endif", "#ifdef FEAT_TIMERS\n abort = abort || set_ref_in_timer(copyID);\n#endif", "#ifdef FEAT_QUICKFIX\n abort = abort || set_ref_in_quickfix(copyID);\n#endif", "#ifdef FEAT_TERMINAL\n abort = abort || set_ref_in_term(copyID);\n#endif", "#ifdef FEAT_PROP_POPUP\n abort = abort || set_ref_in_popups(copyID);\n#endif", " if (!abort)\n {\n\t/*\n\t * 2. Free lists and dictionaries that are not referenced.\n\t */\n\tdid_free = free_unref_items(copyID);", "\t/*\n\t * 3. Check if any funccal can be freed now.\n\t * This may call us back recursively.\n\t */\n\tfree_unref_funccal(copyID, testing);\n }\n else if (p_verbose > 0)\n {\n\tverb_msg(_(\"Not enough memory to set references, garbage collection aborted!\"));\n }", " return did_free;\n}", "/*\n * Free lists, dictionaries, channels and jobs that are no longer referenced.\n */\n static int\nfree_unref_items(int copyID)\n{\n int\t\tdid_free = FALSE;", " // Let all \"free\" functions know that we are here. This means no\n // dictionaries, lists, channels or jobs are to be freed, because we will\n // do that here.\n in_free_unref_items = TRUE;", " /*\n * PASS 1: free the contents of the items. We don't free the items\n * themselves yet, so that it is possible to decrement refcount counters\n */", " // Go through the list of dicts and free items without this copyID.\n did_free |= dict_free_nonref(copyID);", " // Go through the list of lists and free items without this copyID.\n did_free |= list_free_nonref(copyID);", " // Go through the list of objects and free items without this copyID.\n did_free |= object_free_nonref(copyID);", "#ifdef FEAT_JOB_CHANNEL\n // Go through the list of jobs and free items without the copyID. This\n // must happen before doing channels, because jobs refer to channels, but\n // the reference from the channel to the job isn't tracked.\n did_free |= free_unused_jobs_contents(copyID, COPYID_MASK);", " // Go through the list of channels and free items without the copyID.\n did_free |= free_unused_channels_contents(copyID, COPYID_MASK);\n#endif", " /*\n * PASS 2: free the items themselves.\n */\n dict_free_items(copyID);\n list_free_items(copyID);", "#ifdef FEAT_JOB_CHANNEL\n // Go through the list of jobs and free items without the copyID. This\n // must happen before doing channels, because jobs refer to channels, but\n // the reference from the channel to the job isn't tracked.\n free_unused_jobs(copyID, COPYID_MASK);", " // Go through the list of channels and free items without the copyID.\n free_unused_channels(copyID, COPYID_MASK);\n#endif", " in_free_unref_items = FALSE;", " return did_free;\n}", "/*\n * Mark all lists and dicts referenced through hashtab \"ht\" with \"copyID\".\n * \"list_stack\" is used to add lists to be marked. Can be NULL.\n *\n * Returns TRUE if setting references failed somehow.\n */\n int\nset_ref_in_ht(hashtab_T *ht, int copyID, list_stack_T **list_stack)\n{\n int\t\ttodo;\n int\t\tabort = FALSE;\n hashitem_T\t*hi;\n hashtab_T\t*cur_ht;\n ht_stack_T\t*ht_stack = NULL;\n ht_stack_T\t*tempitem;", " cur_ht = ht;\n for (;;)\n {\n\tif (!abort)\n\t{\n\t // Mark each item in the hashtab. If the item contains a hashtab\n\t // it is added to ht_stack, if it contains a list it is added to\n\t // list_stack.\n\t todo = (int)cur_ht->ht_used;\n\t for (hi = cur_ht->ht_array; todo > 0; ++hi)\n\t\tif (!HASHITEM_EMPTY(hi))\n\t\t{\n\t\t --todo;\n\t\t abort = abort || set_ref_in_item(&HI2DI(hi)->di_tv, copyID,\n\t\t\t\t\t\t &ht_stack, list_stack);\n\t\t}\n\t}", "\tif (ht_stack == NULL)\n\t break;", "\t// take an item from the stack\n\tcur_ht = ht_stack->ht;\n\ttempitem = ht_stack;\n\tht_stack = ht_stack->prev;\n\tfree(tempitem);\n }", " return abort;\n}", "#if defined(FEAT_LUA) || defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) \\\n\t\t\t\t\t\t\t|| defined(PROTO)\n/*\n * Mark a dict and its items with \"copyID\".\n * Returns TRUE if setting references failed somehow.\n */\n int\nset_ref_in_dict(dict_T *d, int copyID)\n{\n if (d != NULL && d->dv_copyID != copyID)\n {\n\td->dv_copyID = copyID;\n\treturn set_ref_in_ht(&d->dv_hashtab, copyID, NULL);\n }\n return FALSE;\n}\n#endif", "/*\n * Mark a list and its items with \"copyID\".\n * Returns TRUE if setting references failed somehow.\n */\n int\nset_ref_in_list(list_T *ll, int copyID)\n{\n if (ll != NULL && ll->lv_copyID != copyID)\n {\n\tll->lv_copyID = copyID;\n\treturn set_ref_in_list_items(ll, copyID, NULL);\n }\n return FALSE;\n}", "/*\n * Mark all lists and dicts referenced through list \"l\" with \"copyID\".\n * \"ht_stack\" is used to add hashtabs to be marked. Can be NULL.\n *\n * Returns TRUE if setting references failed somehow.\n */\n int\nset_ref_in_list_items(list_T *l, int copyID, ht_stack_T **ht_stack)\n{\n listitem_T\t *li;\n int\t\t abort = FALSE;\n list_T\t *cur_l;\n list_stack_T *list_stack = NULL;\n list_stack_T *tempitem;", " cur_l = l;\n for (;;)\n {\n\tif (!abort && cur_l->lv_first != &range_list_item)\n\t // Mark each item in the list. If the item contains a hashtab\n\t // it is added to ht_stack, if it contains a list it is added to\n\t // list_stack.\n\t for (li = cur_l->lv_first; !abort && li != NULL; li = li->li_next)\n\t\tabort = abort || set_ref_in_item(&li->li_tv, copyID,\n\t\t\t\t\t\t ht_stack, &list_stack);\n\tif (list_stack == NULL)\n\t break;", "\t// take an item from the stack\n\tcur_l = list_stack->list;\n\ttempitem = list_stack;\n\tlist_stack = list_stack->prev;\n\tfree(tempitem);\n }", " return abort;\n}", "/*\n * Mark the partial in callback 'cb' with \"copyID\".\n */\n int\nset_ref_in_callback(callback_T *cb, int copyID)\n{\n typval_T tv;", " if (cb->cb_name == NULL || *cb->cb_name == NUL || cb->cb_partial == NULL)\n\treturn FALSE;", " tv.v_type = VAR_PARTIAL;\n tv.vval.v_partial = cb->cb_partial;\n return set_ref_in_item(&tv, copyID, NULL, NULL);\n}", "/*\n * Mark all lists, dicts and other container types referenced through typval\n * \"tv\" with \"copyID\".\n * \"list_stack\" is used to add lists to be marked. Can be NULL.\n * \"ht_stack\" is used to add hashtabs to be marked. Can be NULL.\n *\n * Returns TRUE if setting references failed somehow.\n */\n int\nset_ref_in_item(\n typval_T\t *tv,\n int\t\t copyID,\n ht_stack_T\t **ht_stack,\n list_stack_T **list_stack)\n{\n int\t\tabort = FALSE;", " switch (tv->v_type)\n {\n\tcase VAR_DICT:\n\t{\n\t dict_T\t*dd = tv->vval.v_dict;", "\t if (dd != NULL && dd->dv_copyID != copyID)\n\t {\n\t\t// Didn't see this dict yet.\n\t\tdd->dv_copyID = copyID;\n\t\tif (ht_stack == NULL)\n\t\t{\n\t\t abort = set_ref_in_ht(&dd->dv_hashtab, copyID, list_stack);\n\t\t}\n\t\telse\n\t\t{\n\t\t ht_stack_T *newitem = ALLOC_ONE(ht_stack_T);", "\t\t if (newitem == NULL)\n\t\t\tabort = TRUE;\n\t\t else\n\t\t {\n\t\t\tnewitem->ht = &dd->dv_hashtab;\n\t\t\tnewitem->prev = *ht_stack;\n\t\t\t*ht_stack = newitem;\n\t\t }\n\t\t}\n\t }\n\t break;\n\t}", "\tcase VAR_LIST:\n\t{\n\t list_T\t*ll = tv->vval.v_list;", "\t if (ll != NULL && ll->lv_copyID != copyID)\n\t {\n\t\t// Didn't see this list yet.\n\t\tll->lv_copyID = copyID;\n\t\tif (list_stack == NULL)\n\t\t{\n\t\t abort = set_ref_in_list_items(ll, copyID, ht_stack);\n\t\t}\n\t\telse\n\t\t{\n\t\t list_stack_T *newitem = ALLOC_ONE(list_stack_T);", "\t\t if (newitem == NULL)\n\t\t\tabort = TRUE;\n\t\t else\n\t\t {\n\t\t\tnewitem->list = ll;\n\t\t\tnewitem->prev = *list_stack;\n\t\t\t*list_stack = newitem;\n\t\t }\n\t\t}\n\t }\n\t break;\n\t}", "\tcase VAR_FUNC:\n\t{\n\t abort = set_ref_in_func(tv->vval.v_string, NULL, copyID);\n\t break;\n\t}", "\tcase VAR_PARTIAL:\n\t{\n\t partial_T\t*pt = tv->vval.v_partial;\n\t int\t\ti;", "\t if (pt != NULL && pt->pt_copyID != copyID)\n\t {\n\t\t// Didn't see this partial yet.\n\t\tpt->pt_copyID = copyID;", "\t\tabort = set_ref_in_func(pt->pt_name, pt->pt_func, copyID);", "\t\tif (pt->pt_dict != NULL)\n\t\t{\n\t\t typval_T dtv;", "\t\t dtv.v_type = VAR_DICT;\n\t\t dtv.vval.v_dict = pt->pt_dict;\n\t\t set_ref_in_item(&dtv, copyID, ht_stack, list_stack);\n\t\t}", "\t\tfor (i = 0; i < pt->pt_argc; ++i)\n\t\t abort = abort || set_ref_in_item(&pt->pt_argv[i], copyID,\n\t\t\t\t\t\t\t ht_stack, list_stack);\n\t\t// pt_funcstack is handled in set_ref_in_funcstacks()\n\t\t// pt_loopvars is handled in set_ref_in_loopvars()\n\t }\n\t break;\n\t}", "\tcase VAR_JOB:\n\t{\n#ifdef FEAT_JOB_CHANNEL\n\t job_T\t *job = tv->vval.v_job;\n\t typval_T dtv;", "\t if (job != NULL && job->jv_copyID != copyID)\n\t {\n\t\tjob->jv_copyID = copyID;\n\t\tif (job->jv_channel != NULL)\n\t\t{\n\t\t dtv.v_type = VAR_CHANNEL;\n\t\t dtv.vval.v_channel = job->jv_channel;\n\t\t set_ref_in_item(&dtv, copyID, ht_stack, list_stack);\n\t\t}\n\t\tif (job->jv_exit_cb.cb_partial != NULL)\n\t\t{\n\t\t dtv.v_type = VAR_PARTIAL;\n\t\t dtv.vval.v_partial = job->jv_exit_cb.cb_partial;\n\t\t set_ref_in_item(&dtv, copyID, ht_stack, list_stack);\n\t\t}\n\t }\n#endif\n\t break;\n\t}", "\tcase VAR_CHANNEL:\n\t{\n#ifdef FEAT_JOB_CHANNEL\n\t channel_T *ch = tv->vval.v_channel;\n\t ch_part_T part;\n\t typval_T dtv;\n\t jsonq_T\t*jq;\n\t cbq_T\t*cq;", "\t if (ch != NULL && ch->ch_copyID != copyID)\n\t {\n\t\tch->ch_copyID = copyID;\n\t\tfor (part = PART_SOCK; part < PART_COUNT; ++part)\n\t\t{\n\t\t for (jq = ch->ch_part[part].ch_json_head.jq_next;\n\t\t\t\t\t\t jq != NULL; jq = jq->jq_next)\n\t\t\tset_ref_in_item(jq->jq_value, copyID,\n\t\t\t\t\t\t\t ht_stack, list_stack);\n\t\t for (cq = ch->ch_part[part].ch_cb_head.cq_next; cq != NULL;\n\t\t\t\t\t\t\t cq = cq->cq_next)\n\t\t\tif (cq->cq_callback.cb_partial != NULL)\n\t\t\t{\n\t\t\t dtv.v_type = VAR_PARTIAL;\n\t\t\t dtv.vval.v_partial = cq->cq_callback.cb_partial;\n\t\t\t set_ref_in_item(&dtv, copyID, ht_stack, list_stack);\n\t\t\t}\n\t\t if (ch->ch_part[part].ch_callback.cb_partial != NULL)\n\t\t {\n\t\t\tdtv.v_type = VAR_PARTIAL;\n\t\t\tdtv.vval.v_partial =\n\t\t\t\t ch->ch_part[part].ch_callback.cb_partial;\n\t\t\tset_ref_in_item(&dtv, copyID, ht_stack, list_stack);\n\t\t }\n\t\t}\n\t\tif (ch->ch_callback.cb_partial != NULL)\n\t\t{\n\t\t dtv.v_type = VAR_PARTIAL;\n\t\t dtv.vval.v_partial = ch->ch_callback.cb_partial;\n\t\t set_ref_in_item(&dtv, copyID, ht_stack, list_stack);\n\t\t}\n\t\tif (ch->ch_close_cb.cb_partial != NULL)\n\t\t{\n\t\t dtv.v_type = VAR_PARTIAL;\n\t\t dtv.vval.v_partial = ch->ch_close_cb.cb_partial;\n\t\t set_ref_in_item(&dtv, copyID, ht_stack, list_stack);\n\t\t}\n\t }\n#endif\n\t break;\n\t}", "\tcase VAR_CLASS:\n\t // TODO: Mark methods in class_obj_methods ?\n\t // Mark initializer expressions?\n\t break;", "\tcase VAR_OBJECT:\n\t {\n\t\tobject_T *obj = tv->vval.v_object;\n\t\tif (obj != NULL && obj->obj_copyID != copyID)\n\t\t{\n\t\t obj->obj_copyID = copyID;", "\t\t // The typval_T array is right after the object_T.\n\t\t typval_T *mtv = (typval_T *)(obj + 1);\n\t\t for (int i = 0; !abort\n\t\t\t && i < obj->obj_class->class_obj_member_count; ++i)\n\t\t\tabort = abort || set_ref_in_item(mtv + i, copyID,\n\t\t\t\t\t\t\t ht_stack, list_stack);\n\t\t}\n\t\tbreak;\n\t }", "\tcase VAR_UNKNOWN:\n\tcase VAR_ANY:\n\tcase VAR_VOID:\n\tcase VAR_BOOL:\n\tcase VAR_SPECIAL:\n\tcase VAR_NUMBER:\n\tcase VAR_FLOAT:\n\tcase VAR_STRING:\n\tcase VAR_BLOB:\n\tcase VAR_INSTR:\n\t // Types that do not contain any other item\n\t break;\n }", " return abort;\n}", "/*\n * Return a string with the string representation of a variable.\n * If the memory is allocated \"tofree\" is set to it, otherwise NULL.\n * \"numbuf\" is used for a number.\n * When \"copyID\" is not NULL replace recursive lists and dicts with \"...\".\n * When both \"echo_style\" and \"composite_val\" are FALSE, put quotes around\n * strings as \"string()\", otherwise does not put quotes around strings, as\n * \":echo\" displays values.\n * When \"restore_copyID\" is FALSE, repeated items in dictionaries and lists\n * are replaced with \"...\".\n * May return NULL.\n */\n char_u *\necho_string_core(\n typval_T\t*tv,\n char_u\t**tofree,\n char_u\t*numbuf,\n int\t\tcopyID,\n int\t\techo_style,\n int\t\trestore_copyID,\n int\t\tcomposite_val)\n{\n static int\trecurse = 0;\n char_u\t*r = NULL;", " if (recurse >= DICT_MAXNEST)\n {\n\tif (!did_echo_string_emsg)\n\t{\n\t // Only give this message once for a recursive call to avoid\n\t // flooding the user with errors. And stop iterating over lists\n\t // and dicts.\n\t did_echo_string_emsg = TRUE;\n\t emsg(_(e_variable_nested_too_deep_for_displaying));\n\t}\n\t*tofree = NULL;\n\treturn (char_u *)\"{E724}\";\n }\n ++recurse;", " switch (tv->v_type)\n {\n\tcase VAR_STRING:\n\t if (echo_style && !composite_val)\n\t {\n\t\t*tofree = NULL;\n\t\tr = tv->vval.v_string;\n\t\tif (r == NULL)\n\t\t r = (char_u *)\"\";\n\t }\n\t else\n\t {\n\t\t*tofree = string_quote(tv->vval.v_string, FALSE);\n\t\tr = *tofree;\n\t }\n\t break;", "\tcase VAR_FUNC:\n\t {\n\t\tchar_u buf[MAX_FUNC_NAME_LEN];", "\t\tif (echo_style)\n\t\t{\n\t\t r = tv->vval.v_string == NULL ? (char_u *)\"function()\"\n\t\t\t\t : make_ufunc_name_readable(tv->vval.v_string,\n\t\t\t\t\t\t buf, MAX_FUNC_NAME_LEN);\n\t\t if (r == buf)\n\t\t {\n\t\t\tr = vim_strsave(buf);\n\t\t\t*tofree = r;\n\t\t }\n\t\t else\n\t\t\t*tofree = NULL;\n\t\t}\n\t\telse\n\t\t{\n\t\t *tofree = string_quote(tv->vval.v_string == NULL ? NULL\n\t\t\t : make_ufunc_name_readable(\n\t\t\t\ttv->vval.v_string, buf, MAX_FUNC_NAME_LEN),\n\t\t\t\t\t\t\t\t\t TRUE);\n\t\t r = *tofree;\n\t\t}\n\t }\n\t break;", "\tcase VAR_PARTIAL:\n\t {\n\t\tpartial_T *pt = tv->vval.v_partial;\n\t\tchar_u\t *fname = string_quote(pt == NULL ? NULL\n\t\t\t\t\t\t : partial_name(pt), FALSE);\n\t\tgarray_T ga;\n\t\tint\t i;\n\t\tchar_u\t *tf;", "\t\tga_init2(&ga, 1, 100);\n\t\tga_concat(&ga, (char_u *)\"function(\");\n\t\tif (fname != NULL)\n\t\t{\n\t\t // When using uf_name prepend \"g:\" for a global function.\n\t\t if (pt != NULL && pt->pt_name == NULL && fname[0] == '\\''\n\t\t\t\t\t\t && vim_isupper(fname[1]))\n\t\t {\n\t\t\tga_concat(&ga, (char_u *)\"'g:\");\n\t\t\tga_concat(&ga, fname + 1);\n\t\t }\n\t\t else\n\t\t\tga_concat(&ga, fname);\n\t\t vim_free(fname);\n\t\t}\n\t\tif (pt != NULL && pt->pt_argc > 0)\n\t\t{\n\t\t ga_concat(&ga, (char_u *)\", [\");\n\t\t for (i = 0; i < pt->pt_argc; ++i)\n\t\t {\n\t\t\tif (i > 0)\n\t\t\t ga_concat(&ga, (char_u *)\", \");\n\t\t\tga_concat(&ga,\n\t\t\t tv2string(&pt->pt_argv[i], &tf, numbuf, copyID));\n\t\t\tvim_free(tf);\n\t\t }\n\t\t ga_concat(&ga, (char_u *)\"]\");\n\t\t}\n\t\tif (pt != NULL && pt->pt_dict != NULL)\n\t\t{\n\t\t typval_T dtv;", "\t\t ga_concat(&ga, (char_u *)\", \");\n\t\t dtv.v_type = VAR_DICT;\n\t\t dtv.vval.v_dict = pt->pt_dict;\n\t\t ga_concat(&ga, tv2string(&dtv, &tf, numbuf, copyID));\n\t\t vim_free(tf);\n\t\t}\n\t\t// terminate with ')' and a NUL\n\t\tga_concat_len(&ga, (char_u *)\")\", 2);", "\t\t*tofree = ga.ga_data;\n\t\tr = *tofree;\n\t\tbreak;\n\t }", "\tcase VAR_BLOB:\n\t r = blob2string(tv->vval.v_blob, tofree, numbuf);\n\t break;", "\tcase VAR_LIST:\n\t if (tv->vval.v_list == NULL)\n\t {\n\t\t// NULL list is equivalent to empty list.\n\t\t*tofree = NULL;\n\t\tr = (char_u *)\"[]\";\n\t }\n\t else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID\n\t\t && tv->vval.v_list->lv_len > 0)\n\t {\n\t\t*tofree = NULL;\n\t\tr = (char_u *)\"[...]\";\n\t }\n\t else\n\t {\n\t\tint old_copyID = tv->vval.v_list->lv_copyID;", "\t\ttv->vval.v_list->lv_copyID = copyID;\n\t\t*tofree = list2string(tv, copyID, restore_copyID);\n\t\tif (restore_copyID)\n\t\t tv->vval.v_list->lv_copyID = old_copyID;\n\t\tr = *tofree;\n\t }\n\t break;", "\tcase VAR_DICT:\n\t if (tv->vval.v_dict == NULL)\n\t {\n\t\t// NULL dict is equivalent to empty dict.\n\t\t*tofree = NULL;\n\t\tr = (char_u *)\"{}\";\n\t }\n\t else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID\n\t\t && tv->vval.v_dict->dv_hashtab.ht_used != 0)\n\t {\n\t\t*tofree = NULL;\n\t\tr = (char_u *)\"{...}\";\n\t }\n\t else\n\t {\n\t\tint old_copyID = tv->vval.v_dict->dv_copyID;", "\t\ttv->vval.v_dict->dv_copyID = copyID;\n\t\t*tofree = dict2string(tv, copyID, restore_copyID);\n\t\tif (restore_copyID)\n\t\t tv->vval.v_dict->dv_copyID = old_copyID;\n\t\tr = *tofree;\n\t }\n\t break;", "\tcase VAR_NUMBER:\n\tcase VAR_UNKNOWN:\n\tcase VAR_ANY:\n\tcase VAR_VOID:\n\t *tofree = NULL;\n\t r = tv_get_string_buf(tv, numbuf);\n\t break;", "\tcase VAR_JOB:\n\tcase VAR_CHANNEL:\n#ifdef FEAT_JOB_CHANNEL\n\t *tofree = NULL;\n\t r = tv->v_type == VAR_JOB ? job_to_string_buf(tv, numbuf)\n\t\t\t\t\t : channel_to_string_buf(tv, numbuf);\n\t if (composite_val)\n\t {\n\t\t*tofree = string_quote(r, FALSE);\n\t\tr = *tofree;\n\t }\n#endif\n\t break;", "\tcase VAR_INSTR:\n\t *tofree = NULL;\n\t r = (char_u *)\"instructions\";\n\t break;", "\tcase VAR_CLASS:\n\t {\n\t\tclass_T *cl = tv->vval.v_class;\n\t\tsize_t len = 6 + (cl == NULL ? 9 : STRLEN(cl->class_name)) + 1;\n\t\tr = *tofree = alloc(len);\n\t\tvim_snprintf((char *)r, len, \"class %s\",\n\t\t\t cl == NULL ? \"[unknown]\" : (char *)cl->class_name);\n\t }\n\t break;", "\tcase VAR_OBJECT:\n\t {\n\t\tgarray_T ga;\n\t\tga_init2(&ga, 1, 50);\n\t\tga_concat(&ga, (char_u *)\"object of \");\n\t\tobject_T *obj = tv->vval.v_object;\n\t\tclass_T *cl = obj == NULL ? NULL : obj->obj_class;\n\t\tga_concat(&ga, cl == NULL ? (char_u *)\"[unknown]\"\n\t\t\t\t\t\t\t : cl->class_name);\n\t\tif (cl != NULL)\n\t\t{\n\t\t ga_concat(&ga, (char_u *)\" {\");\n\t\t for (int i = 0; i < cl->class_obj_member_count; ++i)\n\t\t {\n\t\t\tif (i > 0)\n\t\t\t ga_concat(&ga, (char_u *)\", \");\n\t\t\tocmember_T *m = &cl->class_obj_members[i];\n\t\t\tga_concat(&ga, m->ocm_name);\n\t\t\tga_concat(&ga, (char_u *)\": \");\n\t\t\tchar_u *tf = NULL;\n\t\t\tga_concat(&ga, echo_string_core(\n\t\t\t\t\t (typval_T *)(obj + 1) + i,\n\t\t\t\t\t &tf, numbuf, copyID, echo_style,\n\t\t\t\t\t restore_copyID, composite_val));\n\t\t\tvim_free(tf);\n\t\t }\n\t\t ga_concat(&ga, (char_u *)\"}\");\n\t\t}", "\t\t*tofree = r = ga.ga_data;\n\t }\n\t break;", "\tcase VAR_FLOAT:\n\t *tofree = NULL;\n\t vim_snprintf((char *)numbuf, NUMBUFLEN, \"%g\", tv->vval.v_float);\n\t r = numbuf;\n\t break;", "\tcase VAR_BOOL:\n\tcase VAR_SPECIAL:\n\t *tofree = NULL;\n\t r = (char_u *)get_var_special_name(tv->vval.v_number);\n\t break;\n }", " if (--recurse == 0)\n\tdid_echo_string_emsg = FALSE;\n return r;\n}", "/*\n * Return a string with the string representation of a variable.\n * If the memory is allocated \"tofree\" is set to it, otherwise NULL.\n * \"numbuf\" is used for a number.\n * Does not put quotes around strings, as \":echo\" displays values.\n * When \"copyID\" is not NULL replace recursive lists and dicts with \"...\".\n * May return NULL.\n */\n char_u *\necho_string(\n typval_T\t*tv,\n char_u\t**tofree,\n char_u\t*numbuf,\n int\t\tcopyID)\n{\n return echo_string_core(tv, tofree, numbuf, copyID, TRUE, FALSE, FALSE);\n}", "/*\n * Convert the specified byte index of line 'lnum' in buffer 'buf' to a\n * character index. Works only for loaded buffers. Returns -1 on failure.\n * The index of the first byte and the first character is zero.\n */\n int\nbuf_byteidx_to_charidx(buf_T *buf, int lnum, int byteidx)\n{\n char_u\t*str;\n char_u\t*t;\n int\t\tcount;", " if (buf == NULL || buf->b_ml.ml_mfp == NULL)\n\treturn -1;", " if (lnum > buf->b_ml.ml_line_count)\n\tlnum = buf->b_ml.ml_line_count;", " str = ml_get_buf(buf, lnum, FALSE);\n if (str == NULL)\n\treturn -1;", " if (*str == NUL)\n\treturn 0;", " // count the number of characters\n t = str;\n for (count = 0; *t != NUL && t <= str + byteidx; count++)\n\tt += mb_ptr2len(t);", " // In insert mode, when the cursor is at the end of a non-empty line,\n // byteidx points to the NUL character immediately past the end of the\n // string. In this case, add one to the character count.\n if (*t == NUL && byteidx != 0 && t == str + byteidx)\n\tcount++;", " return count - 1;\n}", "/*\n * Convert the specified character index of line 'lnum' in buffer 'buf' to a\n * byte index. Works only for loaded buffers. Returns -1 on failure.\n * The index of the first byte and the first character is zero.\n */\n int\nbuf_charidx_to_byteidx(buf_T *buf, int lnum, int charidx)\n{\n char_u\t*str;\n char_u\t*t;", " if (buf == NULL || buf->b_ml.ml_mfp == NULL)\n\treturn -1;", " if (lnum > buf->b_ml.ml_line_count)\n\tlnum = buf->b_ml.ml_line_count;", " str = ml_get_buf(buf, lnum, FALSE);\n if (str == NULL)\n\treturn -1;", " // Convert the character offset to a byte offset\n t = str;\n while (*t != NUL && --charidx > 0)\n\tt += mb_ptr2len(t);", " return t - str;\n}", "/*\n * Translate a String variable into a position.\n * Returns NULL when there is an error.\n */\n pos_T *\nvar2fpos(\n typval_T\t*varp,\n int\t\tdollar_lnum,\t// TRUE when $ is last line\n int\t\t*fnum,\t\t// set to fnum for '0, 'A, etc.\n int\t\tcharcol)\t// return character column\n{\n char_u\t\t*name;\n static pos_T\tpos;\n pos_T\t\t*pp;", " // Argument can be [lnum, col, coladd].\n if (varp->v_type == VAR_LIST)\n {\n\tlist_T\t\t*l;\n\tint\t\tlen;\n\tint\t\terror = FALSE;\n\tlistitem_T\t*li;", "\tl = varp->vval.v_list;\n\tif (l == NULL)\n\t return NULL;", "\t// Get the line number\n\tpos.lnum = list_find_nr(l, 0L, &error);\n\tif (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)\n\t return NULL;\t// invalid line number\n\tif (charcol)\n\t len = (long)mb_charlen(ml_get(pos.lnum));\n\telse\n\t len = (long)STRLEN(ml_get(pos.lnum));", "\t// Get the column number\n\t// We accept \"$\" for the column number: last column.\n\tli = list_find(l, 1L);\n\tif (li != NULL && li->li_tv.v_type == VAR_STRING\n\t\t&& li->li_tv.vval.v_string != NULL\n\t\t&& STRCMP(li->li_tv.vval.v_string, \"$\") == 0)\n\t{\n\t pos.col = len + 1;\n\t}\n\telse\n\t{\n\t pos.col = list_find_nr(l, 1L, &error);\n\t if (error)\n\t\treturn NULL;\n\t}", "\t// Accept a position up to the NUL after the line.\n\tif (pos.col == 0 || (int)pos.col > len + 1)\n\t return NULL;\t// invalid column number\n\t--pos.col;", "\t// Get the virtual offset. Defaults to zero.\n\tpos.coladd = list_find_nr(l, 2L, &error);\n\tif (error)\n\t pos.coladd = 0;", "\treturn &pos;\n }", " if (in_vim9script() && check_for_string_arg(varp, 0) == FAIL)\n\treturn NULL;", " name = tv_get_string_chk(varp);\n if (name == NULL)\n\treturn NULL;", " pos.lnum = 0;\n if (name[0] == '.' && (!in_vim9script() || name[1] == NUL))\n {\n\t// cursor\n\tpos = curwin->w_cursor;\n }\n else if (name[0] == 'v' && name[1] == NUL)\n {\n\t// Visual start\n\tif (VIsual_active)\n\t pos = VIsual;\n\telse\n\t pos = curwin->w_cursor;\n }\n else if (name[0] == '\\'' && (!in_vim9script()\n\t\t\t\t\t|| (name[1] != NUL && name[2] == NUL)))\n {\n\t// mark\n\tpp = getmark_buf_fnum(curbuf, name[1], FALSE, fnum);\n\tif (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)\n\t return NULL;\n\tpos = *pp;\n }\n if (pos.lnum != 0)\n {\n\tif (charcol)\n\t pos.col = buf_byteidx_to_charidx(curbuf, pos.lnum, pos.col);\n\treturn &pos;\n }", " pos.coladd = 0;", " if (name[0] == 'w' && dollar_lnum)\n {\n\tpos.col = 0;\n\tif (name[1] == '0')\t\t// \"w0\": first visible line\n\t{\n\t update_topline();\n\t // In silent Ex mode topline is zero, but that's not a valid line\n\t // number; use one instead.\n\t pos.lnum = curwin->w_topline > 0 ? curwin->w_topline : 1;\n\t return &pos;\n\t}\n\telse if (name[1] == '$')\t// \"w$\": last visible line\n\t{\n\t validate_botline();\n\t // In silent Ex mode botline is zero, return zero then.\n\t pos.lnum = curwin->w_botline > 0 ? curwin->w_botline - 1 : 0;\n\t return &pos;\n\t}\n }\n else if (name[0] == '$')\t\t// last column or line\n {\n\tif (dollar_lnum)\n\t{\n\t pos.lnum = curbuf->b_ml.ml_line_count;\n\t pos.col = 0;\n\t}\n\telse\n\t{\n\t pos.lnum = curwin->w_cursor.lnum;\n\t if (charcol)\n\t\tpos.col = (colnr_T)mb_charlen(ml_get_curline());\n\t else\n\t\tpos.col = (colnr_T)STRLEN(ml_get_curline());\n\t}\n\treturn &pos;\n }\n if (in_vim9script())\n\tsemsg(_(e_invalid_value_for_line_number_str), name);\n return NULL;\n}", "/*\n * Convert list in \"arg\" into position \"posp\" and optional file number \"fnump\".\n * When \"fnump\" is NULL there is no file number, only 3 items: [lnum, col, off]\n * Note that the column is passed on as-is, the caller may want to decrement\n * it to use 1 for the first column.\n * If \"charcol\" is TRUE use the column as the character index instead of the\n * byte index.\n * Return FAIL when conversion is not possible, doesn't check the position for\n * validity.\n */\n int\nlist2fpos(\n typval_T\t*arg,\n pos_T\t*posp,\n int\t\t*fnump,\n colnr_T\t*curswantp,\n int\t\tcharcol)\n{\n list_T\t*l = arg->vval.v_list;\n long\ti = 0;\n long\tn;", " // List must be: [fnum, lnum, col, coladd, curswant], where \"fnum\" is only\n // there when \"fnump\" isn't NULL; \"coladd\" and \"curswant\" are optional.\n if (arg->v_type != VAR_LIST\n\t || l == NULL\n\t || l->lv_len < (fnump == NULL ? 2 : 3)\n\t || l->lv_len > (fnump == NULL ? 4 : 5))\n\treturn FAIL;", " if (fnump != NULL)\n {\n\tn = list_find_nr(l, i++, NULL);\t// fnum\n\tif (n < 0)\n\t return FAIL;\n\tif (n == 0)\n\t n = curbuf->b_fnum;\t\t// current buffer\n\t*fnump = n;\n }", " n = list_find_nr(l, i++, NULL);\t// lnum\n if (n < 0)\n\treturn FAIL;\n posp->lnum = n;", " n = list_find_nr(l, i++, NULL);\t// col\n if (n < 0)\n\treturn FAIL;\n // If character position is specified, then convert to byte position\n // If the line number is zero use the cursor line.\n if (charcol)\n {\n\tbuf_T\t*buf;", "\t// Get the text for the specified line in a loaded buffer\n\tbuf = buflist_findnr(fnump == NULL ? curbuf->b_fnum : *fnump);\n\tif (buf == NULL || buf->b_ml.ml_mfp == NULL)\n\t return FAIL;", "\tn = buf_charidx_to_byteidx(buf,\n\t\t posp->lnum == 0 ? curwin->w_cursor.lnum : posp->lnum, n) + 1;\n }\n posp->col = n;", " n = list_find_nr(l, i, NULL);\t// off\n if (n < 0)\n\tposp->coladd = 0;\n else\n\tposp->coladd = n;", " if (curswantp != NULL)\n\t*curswantp = list_find_nr(l, i + 1, NULL); // curswant", " return OK;\n}", "/*\n * Get the length of an environment variable name.\n * Advance \"arg\" to the first character after the name.\n * Return 0 for error.\n */\n int\nget_env_len(char_u **arg)\n{\n char_u\t*p;\n int\t\tlen;", " for (p = *arg; vim_isIDc(*p); ++p)\n\t;\n if (p == *arg)\t // no name found\n\treturn 0;", " len = (int)(p - *arg);\n *arg = p;\n return len;\n}", "/*\n * Get the length of the name of a function or internal variable.\n * \"arg\" is advanced to after the name.\n * Return 0 if something is wrong.\n */\n int\nget_id_len(char_u **arg)\n{\n char_u\t*p;\n int\t\tlen;", " // Find the end of the name.\n for (p = *arg; eval_isnamec(*p); ++p)\n {\n\tif (*p == ':')\n\t{\n\t // \"s:\" is start of \"s:var\", but \"n:\" is not and can be used in\n\t // slice \"[n:]\". Also \"xx:\" is not a namespace.\n\t len = (int)(p - *arg);\n\t if ((len == 1 && vim_strchr(NAMESPACE_CHAR, **arg) == NULL)\n\t\t || len > 1)\n\t\tbreak;\n\t}\n }\n if (p == *arg)\t // no name found\n\treturn 0;", " len = (int)(p - *arg);\n *arg = p;", " return len;\n}", "/*\n * Get the length of the name of a variable or function.\n * Only the name is recognized, does not handle \".key\" or \"[idx]\".\n * \"arg\" is advanced to the first non-white character after the name.\n * Return -1 if curly braces expansion failed.\n * Return 0 if something else is wrong.\n * If the name contains 'magic' {}'s, expand them and return the\n * expanded name in an allocated string via 'alias' - caller must free.\n */\n int\nget_name_len(\n char_u\t**arg,\n char_u\t**alias,\n int\t\tevaluate,\n int\t\tverbose)\n{\n int\t\tlen;\n char_u\t*p;\n char_u\t*expr_start;\n char_u\t*expr_end;", " *alias = NULL; // default to no alias", " if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA\n\t\t\t\t\t\t && (*arg)[2] == (int)KE_SNR)\n {\n\t// hard coded <SNR>, already translated\n\t*arg += 3;\n\treturn get_id_len(arg) + 3;\n }\n len = eval_fname_script(*arg);\n if (len > 0)\n {\n\t// literal \"<SID>\", \"s:\" or \"<SNR>\"\n\t*arg += len;\n }", " /*\n * Find the end of the name; check for {} construction.\n */\n p = find_name_end(*arg, &expr_start, &expr_end,\n\t\t\t\t\t len > 0 ? 0 : FNE_CHECK_START);\n if (expr_start != NULL)\n {\n\tchar_u\t*temp_string;", "\tif (!evaluate)\n\t{\n\t len += (int)(p - *arg);\n\t *arg = skipwhite(p);\n\t return len;\n\t}", "\t/*\n\t * Include any <SID> etc in the expanded string:\n\t * Thus the -len here.\n\t */\n\ttemp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);\n\tif (temp_string == NULL)\n\t return -1;\n\t*alias = temp_string;\n\t*arg = skipwhite(p);\n\treturn (int)STRLEN(temp_string);\n }", " len += get_id_len(arg);\n // Only give an error when there is something, otherwise it will be\n // reported at a higher level.\n if (len == 0 && verbose && **arg != NUL)\n\tsemsg(_(e_invalid_expression_str), *arg);", " return len;\n}", "/*\n * Find the end of a variable or function name, taking care of magic braces.\n * If \"expr_start\" is not NULL then \"expr_start\" and \"expr_end\" are set to the\n * start and end of the first magic braces item.\n * \"flags\" can have FNE_INCL_BR and FNE_CHECK_START.\n * Return a pointer to just after the name. Equal to \"arg\" if there is no\n * valid name.\n */\n char_u *\nfind_name_end(\n char_u\t*arg,\n char_u\t**expr_start,\n char_u\t**expr_end,\n int\t\tflags)\n{\n int\t\tmb_nest = 0;\n int\t\tbr_nest = 0;\n char_u\t*p;\n int\t\tlen;\n int\t\tvim9script = in_vim9script();", " if (expr_start != NULL)\n {\n\t*expr_start = NULL;\n\t*expr_end = NULL;\n }", " // Quick check for valid starting character.\n if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg)\n\t\t\t\t\t\t&& (*arg != '{' || vim9script))\n\treturn arg;", " for (p = arg; *p != NUL\n\t\t && (eval_isnamec(*p)\n\t\t\t|| (*p == '{' && !vim9script)\n\t\t\t|| ((flags & FNE_INCL_BR) && (*p == '['\n\t\t\t\t\t || (*p == '.' && eval_isdictc(p[1]))))\n\t\t\t|| mb_nest != 0\n\t\t\t|| br_nest != 0); MB_PTR_ADV(p))\n {\n\tif (*p == '\\'')\n\t{\n\t // skip over 'string' to avoid counting [ and ] inside it.\n\t for (p = p + 1; *p != NUL && *p != '\\''; MB_PTR_ADV(p))\n\t\t;\n\t if (*p == NUL)\n\t\tbreak;\n\t}\n\telse if (*p == '\"')\n\t{\n\t // skip over \"str\\\"ing\" to avoid counting [ and ] inside it.\n\t for (p = p + 1; *p != NUL && *p != '\"'; MB_PTR_ADV(p))\n\t\tif (*p == '\\\\' && p[1] != NUL)\n\t\t ++p;\n\t if (*p == NUL)\n\t\tbreak;\n\t}\n\telse if (br_nest == 0 && mb_nest == 0 && *p == ':')\n\t{\n\t // \"s:\" is start of \"s:var\", but \"n:\" is not and can be used in\n\t // slice \"[n:]\". Also \"xx:\" is not a namespace. But {ns}: is.\n\t len = (int)(p - arg);\n\t if ((len == 1 && vim_strchr(NAMESPACE_CHAR, *arg) == NULL)\n\t\t || (len > 1 && p[-1] != '}'))\n\t\tbreak;\n\t}", "\tif (mb_nest == 0)\n\t{\n\t if (*p == '[')\n\t\t++br_nest;\n\t else if (*p == ']')\n\t\t--br_nest;\n\t}", "\tif (br_nest == 0 && !vim9script)\n\t{\n\t if (*p == '{')\n\t {\n\t\tmb_nest++;\n\t\tif (expr_start != NULL && *expr_start == NULL)\n\t\t *expr_start = p;\n\t }\n\t else if (*p == '}')\n\t {\n\t\tmb_nest--;\n\t\tif (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)\n\t\t *expr_end = p;\n\t }\n\t}\n }", " return p;\n}", "/*\n * Expands out the 'magic' {}'s in a variable/function name.\n * Note that this can call itself recursively, to deal with\n * constructs like foo{bar}{baz}{bam}\n * The four pointer arguments point to \"foo{expre}ss{ion}bar\"\n *\t\t\t\"in_start\" ^\n *\t\t\t\"expr_start\"\t ^\n *\t\t\t\"expr_end\"\t\t ^\n *\t\t\t\"in_end\"\t\t\t ^\n *\n * Returns a new allocated string, which the caller must free.\n * Returns NULL for failure.\n */\n static char_u *\nmake_expanded_name(\n char_u\t*in_start,\n char_u\t*expr_start,\n char_u\t*expr_end,\n char_u\t*in_end)\n{\n char_u\tc1;\n char_u\t*retval = NULL;\n char_u\t*temp_result;", " if (expr_end == NULL || in_end == NULL)\n\treturn NULL;\n *expr_start\t= NUL;\n *expr_end = NUL;\n c1 = *in_end;\n *in_end = NUL;", " temp_result = eval_to_string(expr_start + 1, FALSE, FALSE);\n if (temp_result != NULL)\n {\n\tretval = alloc(STRLEN(temp_result) + (expr_start - in_start)\n\t\t\t\t\t\t + (in_end - expr_end) + 1);\n\tif (retval != NULL)\n\t{\n\t STRCPY(retval, in_start);\n\t STRCAT(retval, temp_result);\n\t STRCAT(retval, expr_end + 1);\n\t}\n }\n vim_free(temp_result);", " *in_end = c1;\t\t// put char back for error messages\n *expr_start = '{';\n *expr_end = '}';", " if (retval != NULL)\n {\n\ttemp_result = find_name_end(retval, &expr_start, &expr_end, 0);\n\tif (expr_start != NULL)\n\t{\n\t // Further expansion!\n\t temp_result = make_expanded_name(retval, expr_start,\n\t\t\t\t\t\t expr_end, temp_result);\n\t vim_free(retval);\n\t retval = temp_result;\n\t}\n }", " return retval;\n}", "/*\n * Return TRUE if character \"c\" can be used in a variable or function name.\n * Does not include '{' or '}' for magic braces.\n */\n int\neval_isnamec(int c)\n{\n return ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR;\n}", "/*\n * Return TRUE if character \"c\" can be used as the first character in a\n * variable or function name (excluding '{' and '}').\n */\n int\neval_isnamec1(int c)\n{\n return ASCII_ISALPHA(c) || c == '_';\n}", "/*\n * Return TRUE if character \"c\" can be used as the first character of a\n * dictionary key.\n */\n int\neval_isdictc(int c)\n{\n return ASCII_ISALNUM(c) || c == '_';\n}", "/*\n * Handle:\n * - expr[expr], expr[expr:expr] subscript\n * - \".name\" lookup\n * - function call with Funcref variable: func(expr)\n * - method call: var->method()\n *\n * Can all be combined in any order: dict.func(expr)[idx]['func'](expr)->len()\n * \"name_start\" points to a variable before the subscript or is NULL.\n */\n int\nhandle_subscript(\n char_u\t**arg,\n char_u\t*name_start,\n typval_T\t*rettv,\n evalarg_T\t*evalarg,\n int\t\tverbose)\t// give error messages\n{\n int\t\tevaluate = evalarg != NULL\n\t\t\t\t && (evalarg->eval_flags & EVAL_EVALUATE);\n int\t\tret = OK;\n dict_T\t*selfdict = NULL;\n int\t\tcheck_white = TRUE;\n int\t\tgetnext;\n char_u\t*p;", " while (ret == OK)\n {\n\t// When at the end of the line and \".name\" or \"->{\" or \"->X\" follows in\n\t// the next line then consume the line break.\n\tp = eval_next_non_blank(*arg, evalarg, &getnext);\n\tif (getnext\n\t && ((rettv->v_type == VAR_DICT && *p == '.' && eval_isdictc(p[1]))\n\t\t|| (p[0] == '-' && p[1] == '>' && (p[2] == '{'\n\t\t\t|| ASCII_ISALPHA(in_vim9script() ? *skipwhite(p + 2)\n\t\t\t\t\t\t\t\t : p[2])))))\n\t{\n\t *arg = eval_next_line(*arg, evalarg);\n\t p = *arg;\n\t check_white = FALSE;\n\t}", "\tif (rettv->v_type == VAR_ANY)\n\t{\n\t char_u\t*exp_name;\n\t int\t\tcc;\n\t int\t\tidx;\n\t ufunc_T\t*ufunc;\n\t type_T\t*type;", "\t // Found script from \"import {name} as name\", script item name must\n\t // follow. \"rettv->vval.v_number\" has the script ID.\n\t if (**arg != '.')\n\t {\n\t\tif (verbose)\n\t\t semsg(_(e_expected_dot_after_name_str),\n\t\t\t\t\tname_start != NULL ? name_start: *arg);\n\t\tret = FAIL;\n\t\tbreak;\n\t }\n\t ++*arg;\n\t if (IS_WHITE_OR_NUL(**arg))\n\t {\n\t\tif (verbose)\n\t\t emsg(_(e_no_white_space_allowed_after_dot));\n\t\tret = FAIL;\n\t\tbreak;\n\t }", "\t // isolate the name\n\t exp_name = *arg;\n\t while (eval_isnamec(**arg))\n\t\t++*arg;\n\t cc = **arg;\n\t **arg = NUL;", "\t idx = find_exported(rettv->vval.v_number, exp_name, &ufunc, &type,\n\t\t evalarg == NULL ? NULL : evalarg->eval_cctx,\n\t\t evalarg == NULL ? NULL : evalarg->eval_cstack, verbose);\n\t **arg = cc;", "\t if (idx < 0 && ufunc == NULL)\n\t {\n\t\tret = FAIL;\n\t\tbreak;\n\t }\n\t if (idx >= 0)\n\t {\n\t\tscriptitem_T *si = SCRIPT_ITEM(rettv->vval.v_number);\n\t\tsvar_T\t\t*sv = ((svar_T *)si->sn_var_vals.ga_data) + idx;", "\t\tcopy_tv(sv->sv_tv, rettv);\n\t }\n\t else\n\t {\n\t\trettv->v_type = VAR_FUNC;\n\t\trettv->vval.v_string = vim_strsave(ufunc->uf_name);\n\t }\n\t continue;\n\t}", "\tif ((**arg == '(' && (!evaluate || rettv->v_type == VAR_FUNC\n\t\t\t || rettv->v_type == VAR_PARTIAL))\n\t\t && (!check_white || !VIM_ISWHITE(*(*arg - 1))))\n\t{\n\t ret = call_func_rettv(arg, evalarg, rettv, evaluate,\n\t\t\t\t\t\t\t selfdict, NULL);", "\t // Stop the expression evaluation when immediately aborting on\n\t // error, or when an interrupt occurred or an exception was thrown\n\t // but not caught.\n\t if (aborting())\n\t {\n\t\tif (ret == OK)\n\t\t clear_tv(rettv);\n\t\tret = FAIL;\n\t }\n\t dict_unref(selfdict);\n\t selfdict = NULL;\n\t}\n\telse if (p[0] == '-' && p[1] == '>')\n\t{\n\t if (in_vim9script())\n\t\t*arg = skipwhite(p + 2);\n\t else\n\t\t*arg = p + 2;\n\t if (ret == OK)\n\t {\n\t\tif (VIM_ISWHITE(**arg))\n\t\t{\n\t\t emsg(_(e_no_white_space_allowed_before_parenthesis));\n\t\t ret = FAIL;\n\t\t}\n\t\telse if ((**arg == '{' && !in_vim9script()) || **arg == '(')\n\t\t // expr->{lambda}() or expr->(lambda)()\n\t\t ret = eval_lambda(arg, rettv, evalarg, verbose);\n\t\telse\n\t\t // expr->name()\n\t\t ret = eval_method(arg, rettv, evalarg, verbose);\n\t }\n\t}\n\t// \".\" is \".name\" lookup when we found a dict or when evaluating and\n\t// scriptversion is at least 2, where string concatenation is \"..\".\n\telse if (**arg == '['\n\t\t|| (**arg == '.' && (rettv->v_type == VAR_DICT\n\t\t\t|| (!evaluate\n\t\t\t && (*arg)[1] != '.'\n\t\t\t && !in_old_script(2)))))\n\t{\n\t dict_unref(selfdict);\n\t if (rettv->v_type == VAR_DICT)\n\t {\n\t\tselfdict = rettv->vval.v_dict;\n\t\tif (selfdict != NULL)\n\t\t ++selfdict->dv_refcount;\n\t }\n\t else\n\t\tselfdict = NULL;\n\t if (eval_index(arg, rettv, evalarg, verbose) == FAIL)\n\t {\n\t\tclear_tv(rettv);\n\t\tret = FAIL;\n\t }\n\t}\n\telse if (**arg == '.' && (rettv->v_type == VAR_CLASS\n\t\t\t\t\t || rettv->v_type == VAR_OBJECT))\n\t{\n\t // class member: SomeClass.varname\n\t // class method: SomeClass.SomeMethod()\n\t // class constructor: SomeClass.new()\n\t // object member: someObject.varname\n\t // object method: someObject.SomeMethod()\n\t if (class_object_index(arg, rettv, evalarg, verbose) == FAIL)\n\t {\n\t\tclear_tv(rettv);\n\t\tret = FAIL;\n\t }\n\t}\n\telse\n\t break;\n }", " // Turn \"dict.Func\" into a partial for \"Func\" bound to \"dict\".\n // Don't do this when \"Func\" is already a partial that was bound\n // explicitly (pt_auto is FALSE).\n if (selfdict != NULL\n\t && (rettv->v_type == VAR_FUNC\n\t\t|| (rettv->v_type == VAR_PARTIAL\n\t\t && (rettv->vval.v_partial->pt_auto\n\t\t\t|| rettv->vval.v_partial->pt_dict == NULL))))\n\tselfdict = make_partial(selfdict, rettv);", " dict_unref(selfdict);\n return ret;\n}", "/*\n * Make a copy of an item.\n * Lists and Dictionaries are also copied. A deep copy if \"deep\" is set.\n * \"top\" is TRUE for the toplevel of copy().\n * For deepcopy() \"copyID\" is zero for a full copy or the ID for when a\n * reference to an already copied list/dict can be used.\n * Returns FAIL or OK.\n */\n int\nitem_copy(\n typval_T\t*from,\n typval_T\t*to,\n int\t\tdeep,\n int\t\ttop,\n int\t\tcopyID)\n{\n static int\trecurse = 0;\n int\t\tret = OK;", " if (recurse >= DICT_MAXNEST)\n {\n\temsg(_(e_variable_nested_too_deep_for_making_copy));\n\treturn FAIL;\n }\n ++recurse;", " switch (from->v_type)\n {\n\tcase VAR_NUMBER:\n\tcase VAR_FLOAT:\n\tcase VAR_STRING:\n\tcase VAR_FUNC:\n\tcase VAR_PARTIAL:\n\tcase VAR_BOOL:\n\tcase VAR_SPECIAL:\n\tcase VAR_JOB:\n\tcase VAR_CHANNEL:\n\tcase VAR_INSTR:\n\tcase VAR_CLASS:\n\tcase VAR_OBJECT:\n\t copy_tv(from, to);\n\t break;\n\tcase VAR_LIST:\n\t to->v_type = VAR_LIST;\n\t to->v_lock = 0;\n\t if (from->vval.v_list == NULL)\n\t\tto->vval.v_list = NULL;\n\t else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)\n\t {\n\t\t// use the copy made earlier\n\t\tto->vval.v_list = from->vval.v_list->lv_copylist;\n\t\t++to->vval.v_list->lv_refcount;\n\t }\n\t else\n\t\tto->vval.v_list = list_copy(from->vval.v_list,\n\t\t\t\t\t\t\t deep, top, copyID);\n\t if (to->vval.v_list == NULL)\n\t\tret = FAIL;\n\t break;\n\tcase VAR_BLOB:\n\t ret = blob_copy(from->vval.v_blob, to);\n\t break;\n\tcase VAR_DICT:\n\t to->v_type = VAR_DICT;\n\t to->v_lock = 0;\n\t if (from->vval.v_dict == NULL)\n\t\tto->vval.v_dict = NULL;\n\t else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)\n\t {\n\t\t// use the copy made earlier\n\t\tto->vval.v_dict = from->vval.v_dict->dv_copydict;\n\t\t++to->vval.v_dict->dv_refcount;\n\t }\n\t else\n\t\tto->vval.v_dict = dict_copy(from->vval.v_dict,\n\t\t\t\t\t\t\t deep, top, copyID);\n\t if (to->vval.v_dict == NULL)\n\t\tret = FAIL;\n\t break;\n\tcase VAR_UNKNOWN:\n\tcase VAR_ANY:\n\tcase VAR_VOID:\n\t internal_error_no_abort(\"item_copy(UNKNOWN)\");\n\t ret = FAIL;\n }\n --recurse;\n return ret;\n}", " void\necho_one(typval_T *rettv, int with_space, int *atstart, int *needclr)\n{\n char_u\t*tofree;\n char_u\tnumbuf[NUMBUFLEN];\n char_u\t*p = echo_string(rettv, &tofree, numbuf, get_copyID());", " if (*atstart)\n {\n\t*atstart = FALSE;\n\t// Call msg_start() after eval1(), evaluating the expression\n\t// may cause a message to appear.\n\tif (with_space)\n\t{\n\t // Mark the saved text as finishing the line, so that what\n\t // follows is displayed on a new line when scrolling back\n\t // at the more prompt.\n\t msg_sb_eol();\n\t msg_start();\n\t}\n }\n else if (with_space)\n\tmsg_puts_attr(\" \", echo_attr);", " if (p != NULL)\n\tfor ( ; *p != NUL && !got_int; ++p)\n\t{\n\t if (*p == '\\n' || *p == '\\r' || *p == TAB)\n\t {\n\t\tif (*p != TAB && *needclr)\n\t\t{\n\t\t // remove any text still there from the command\n\t\t msg_clr_eos();\n\t\t *needclr = FALSE;\n\t\t}\n\t\tmsg_putchar_attr(*p, echo_attr);\n\t }\n\t else\n\t {\n\t\tif (has_mbyte)\n\t\t{\n\t\t int i = (*mb_ptr2len)(p);", "\t\t (void)msg_outtrans_len_attr(p, i, echo_attr);\n\t\t p += i - 1;\n\t\t}\n\t\telse\n\t\t (void)msg_outtrans_len_attr(p, 1, echo_attr);\n\t }\n\t}\n vim_free(tofree);\n}", "/*\n * \":echo expr1 ...\"\tprint each argument separated with a space, add a\n *\t\t\tnewline at the end.\n * \":echon expr1 ...\"\tprint each argument plain.\n */\n void\nex_echo(exarg_T *eap)\n{\n char_u\t*arg = eap->arg;\n typval_T\trettv;\n char_u\t*arg_start;\n int\t\tneedclr = TRUE;\n int\t\tatstart = TRUE;\n int\t\tdid_emsg_before = did_emsg;\n int\t\tcalled_emsg_before = called_emsg;\n evalarg_T\tevalarg;", " fill_evalarg_from_eap(&evalarg, eap, eap->skip);", " if (eap->skip)\n\t++emsg_skip;\n while ((!ends_excmd2(eap->cmd, arg) || *arg == '\"') && !got_int)\n {\n\t// If eval1() causes an error message the text from the command may\n\t// still need to be cleared. E.g., \"echo 22,44\".\n\tneed_clr_eos = needclr;", "\targ_start = arg;\n\tif (eval1(&arg, &rettv, &evalarg) == FAIL)\n\t{\n\t /*\n\t * Report the invalid expression unless the expression evaluation\n\t * has been cancelled due to an aborting error, an interrupt, or an\n\t * exception.\n\t */\n\t if (!aborting() && did_emsg == did_emsg_before\n\t\t\t\t\t && called_emsg == called_emsg_before)\n\t\tsemsg(_(e_invalid_expression_str), arg_start);\n\t need_clr_eos = FALSE;\n\t break;\n\t}\n\tneed_clr_eos = FALSE;", "\tif (!eap->skip)\n\t{\n\t if (rettv.v_type == VAR_VOID)\n\t {\n\t\tsemsg(_(e_expression_does_not_result_in_value_str), arg_start);\n\t\tbreak;\n\t }\n\t echo_one(&rettv, eap->cmdidx == CMD_echo, &atstart, &needclr);\n\t}", "\tclear_tv(&rettv);\n\targ = skipwhite(arg);\n }\n set_nextcmd(eap, arg);\n clear_evalarg(&evalarg, eap);", " if (eap->skip)\n\t--emsg_skip;\n else\n {\n\t// remove text that may still be there from the command\n\tif (needclr)\n\t msg_clr_eos();\n\tif (eap->cmdidx == CMD_echo)\n\t msg_end();\n }\n}", "/*\n * \":echohl {name}\".\n */\n void\nex_echohl(exarg_T *eap)\n{\n echo_attr = syn_name2attr(eap->arg);\n}", "/*\n * Returns the :echo attribute\n */\n int\nget_echo_attr(void)\n{\n return echo_attr;\n}", "/*\n * \":execute expr1 ...\"\texecute the result of an expression.\n * \":echomsg expr1 ...\"\tPrint a message\n * \":echowindow expr1 ...\" Print a message in the messages window\n * \":echoerr expr1 ...\"\tPrint an error\n * \":echoconsole expr1 ...\" Print a message on stdout\n * Each gets spaces around each argument and a newline at the end for\n * echo commands\n */\n void\nex_execute(exarg_T *eap)\n{\n char_u\t*arg = eap->arg;\n typval_T\trettv;\n int\t\tret = OK;\n char_u\t*p;\n garray_T\tga;\n int\t\tlen;\n long\tstart_lnum = SOURCING_LNUM;", " ga_init2(&ga, 1, 80);", " if (eap->skip)\n\t++emsg_skip;\n while (!ends_excmd2(eap->cmd, arg) || *arg == '\"')\n {\n\tret = eval1_emsg(&arg, &rettv, eap);\n\tif (ret == FAIL)\n\t break;", "\tif (!eap->skip)\n\t{\n\t char_u buf[NUMBUFLEN];", "\t if (eap->cmdidx == CMD_execute)\n\t {\n\t\tif (rettv.v_type == VAR_CHANNEL || rettv.v_type == VAR_JOB)\n\t\t{\n\t\t semsg(_(e_using_invalid_value_as_string_str),\n\t\t\t\t\t\t vartype_name(rettv.v_type));\n\t\t p = NULL;\n\t\t}\n\t\telse\n\t\t p = tv_get_string_buf(&rettv, buf);\n\t }\n\t else\n\t\tp = tv_stringify(&rettv, buf);\n\t if (p == NULL)\n\t {\n\t\tclear_tv(&rettv);\n\t\tret = FAIL;\n\t\tbreak;\n\t }\n\t len = (int)STRLEN(p);\n\t if (ga_grow(&ga, len + 2) == FAIL)\n\t {\n\t\tclear_tv(&rettv);\n\t\tret = FAIL;\n\t\tbreak;\n\t }\n\t if (ga.ga_len)\n\t\t((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';\n\t STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);\n\t ga.ga_len += len;\n\t}", "\tclear_tv(&rettv);\n\targ = skipwhite(arg);\n }", " if (ret != FAIL && ga.ga_data != NULL)\n {\n\t// use the first line of continuation lines for messages\n\tSOURCING_LNUM = start_lnum;", "\tif (eap->cmdidx == CMD_echomsg\n\t\t|| eap->cmdidx == CMD_echowindow\n\t\t|| eap->cmdidx == CMD_echoerr)\n\t{\n\t // Mark the already saved text as finishing the line, so that what\n\t // follows is displayed on a new line when scrolling back at the\n\t // more prompt.\n\t msg_sb_eol();\n\t}", "\tif (eap->cmdidx == CMD_echomsg)\n\t{\n\t msg_attr(ga.ga_data, echo_attr);\n\t out_flush();\n\t}\n\telse if (eap->cmdidx == CMD_echowindow)\n\t{\n#ifdef HAS_MESSAGE_WINDOW\n\t start_echowindow(eap->addr_count > 0 ? eap->line2 : 0);\n#endif\n\t msg_attr(ga.ga_data, echo_attr);\n#ifdef HAS_MESSAGE_WINDOW\n\t end_echowindow();\n#endif\n\t}\n\telse if (eap->cmdidx == CMD_echoconsole)\n\t{\n\t ui_write(ga.ga_data, (int)STRLEN(ga.ga_data), TRUE);\n\t ui_write((char_u *)\"\\r\\n\", 2, TRUE);\n\t}\n\telse if (eap->cmdidx == CMD_echoerr)\n\t{\n\t int\t\tsave_did_emsg = did_emsg;", "\t // We don't want to abort following commands, restore did_emsg.\n\t emsg(ga.ga_data);\n\t if (!force_abort)\n\t\tdid_emsg = save_did_emsg;\n\t}\n\telse if (eap->cmdidx == CMD_execute)\n\t{\n\t int save_sticky_cmdmod_flags = sticky_cmdmod_flags;", "\t // \"legacy exe cmd\" and \"vim9cmd exe cmd\" applies to \"cmd\".\n\t sticky_cmdmod_flags = cmdmod.cmod_flags\n\t\t\t\t\t\t& (CMOD_LEGACY | CMOD_VIM9CMD);\n\t do_cmdline((char_u *)ga.ga_data,\n\t\t eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);\n\t sticky_cmdmod_flags = save_sticky_cmdmod_flags;\n\t}\n }", " ga_clear(&ga);", " if (eap->skip)\n\t--emsg_skip;\n set_nextcmd(eap, arg);\n}", "/*\n * Skip over the name of an option: \"&option\", \"&g:option\" or \"&l:option\".\n * \"arg\" points to the \"&\" or '+' when called, to \"option\" when returning.\n * Returns NULL when no option name found. Otherwise pointer to the char\n * after the option name.\n */\n char_u *\nfind_option_end(char_u **arg, int *scope)\n{\n char_u\t*p = *arg;", " ++p;\n if (*p == 'g' && p[1] == ':')\n {\n\t*scope = OPT_GLOBAL;\n\tp += 2;\n }\n else if (*p == 'l' && p[1] == ':')\n {\n\t*scope = OPT_LOCAL;\n\tp += 2;\n }\n else\n\t*scope = 0;", " if (!ASCII_ISALPHA(*p))\n\treturn NULL;\n *arg = p;", " if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)\n\tp += 4;\t // termcap option\n else\n\twhile (ASCII_ISALPHA(*p))\n\t ++p;\n return p;\n}", "/*\n * Display script name where an item was last set.\n * Should only be invoked when 'verbose' is non-zero.\n */\n void\nlast_set_msg(sctx_T script_ctx)\n{\n char_u *p;", " if (script_ctx.sc_sid == 0)\n\treturn;", " p = home_replace_save(NULL, get_scriptname(script_ctx.sc_sid));\n if (p == NULL)\n\treturn;", " verbose_enter();\n msg_puts(_(\"\\n\\tLast set from \"));\n msg_puts((char *)p);\n if (script_ctx.sc_lnum > 0)\n {\n\tmsg_puts(_(line_msg));\n\tmsg_outnum((long)script_ctx.sc_lnum);\n }\n verbose_leave();\n vim_free(p);\n}", "#endif // FEAT_EVAL", "/*\n * Perform a substitution on \"str\" with pattern \"pat\" and substitute \"sub\".\n * When \"sub\" is NULL \"expr\" is used, must be a VAR_FUNC or VAR_PARTIAL.\n * \"flags\" can be \"g\" to do a global substitute.\n * Returns an allocated string, NULL for error.\n */\n char_u *\ndo_string_sub(\n char_u\t*str,\n char_u\t*pat,\n char_u\t*sub,\n typval_T\t*expr,\n char_u\t*flags)\n{\n int\t\tsublen;\n regmatch_T\tregmatch;\n int\t\ti;\n int\t\tdo_all;\n char_u\t*tail;\n char_u\t*end;\n garray_T\tga;\n char_u\t*ret;\n char_u\t*save_cpo;\n char_u\t*zero_width = NULL;", " // Make 'cpoptions' empty, so that the 'l' flag doesn't work here\n save_cpo = p_cpo;\n p_cpo = empty_option;", " ga_init2(&ga, 1, 200);", " do_all = (flags[0] == 'g');", " regmatch.rm_ic = p_ic;\n regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);\n if (regmatch.regprog != NULL)\n {\n\ttail = str;\n\tend = str + STRLEN(str);\n\twhile (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))\n\t{\n\t // Skip empty match except for first match.\n\t if (regmatch.startp[0] == regmatch.endp[0])\n\t {\n\t\tif (zero_width == regmatch.startp[0])\n\t\t{\n\t\t // avoid getting stuck on a match with an empty string\n\t\t i = mb_ptr2len(tail);\n\t\t mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail,\n\t\t\t\t\t\t\t\t (size_t)i);\n\t\t ga.ga_len += i;\n\t\t tail += i;\n\t\t continue;\n\t\t}\n\t\tzero_width = regmatch.startp[0];\n\t }", "\t /*\n\t * Get some space for a temporary buffer to do the substitution\n\t * into. It will contain:\n\t * - The text up to where the match is.\n\t * - The substituted text.\n\t * - The text after the match.\n\t */\n\t sublen = vim_regsub(&regmatch, sub, expr, tail, 0, REGSUB_MAGIC);", "", "\t if (ga_grow(&ga, (int)((end - tail) + sublen -\n\t\t\t (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)\n\t {\n\t\tga_clear(&ga);\n\t\tbreak;\n\t }", "\t // copy the text up to where the match is\n\t i = (int)(regmatch.startp[0] - tail);\n\t mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);\n\t // add the substituted text\n\t (void)vim_regsub(&regmatch, sub, expr,\n\t\t\t\t (char_u *)ga.ga_data + ga.ga_len + i, sublen,\n\t\t\t\t REGSUB_COPY | REGSUB_MAGIC);\n\t ga.ga_len += i + sublen - 1;\n\t tail = regmatch.endp[0];\n\t if (*tail == NUL)\n\t\tbreak;\n\t if (!do_all)\n\t\tbreak;\n\t}", "\tif (ga.ga_data != NULL)\n\t STRCPY((char *)ga.ga_data + ga.ga_len, tail);", "\tvim_regfree(regmatch.regprog);\n }", " ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);\n ga_clear(&ga);\n if (p_cpo == empty_option)\n\tp_cpo = save_cpo;\n else\n {\n\t// Darn, evaluating {sub} expression or {expr} changed the value.\n\t// If it's still empty it was changed and restored, need to restore in\n\t// the complicated way.\n\tif (*p_cpo == NUL)\n\t set_option_value_give_err((char_u *)\"cpo\", 0L, save_cpo, 0);\n\tfree_string_option(save_cpo);\n }", " return ret;\n}" ]
[ 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [7314, 1117, 697], "buggy_code_start_loc": [7314, 883, 697], "filenames": ["src/eval.c", "src/testdir/test_substitute.vim", "src/version.c"], "fixing_code_end_loc": [7320, 1134, 700], "fixing_code_start_loc": [7315, 883, 698], "message": "Out-of-bounds Write in GitHub repository vim/vim prior to 9.0.1145.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "7A64F3DA-66B5-4F73-A776-7457E9CBCE52", "versionEndExcluding": "9.0.1145", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Out-of-bounds Write in GitHub repository vim/vim prior to 9.0.1145."}], "evaluatorComment": null, "id": "CVE-2023-0054", "lastModified": "2023-05-03T12:16:43.723", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.3, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-04T19:15:09.573", "references": [{"source": "security@huntr.dev", "tags": null, "url": "http://seclists.org/fulldisclosure/2023/Mar/17"}, {"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/3ac1d97a1d9353490493d30088256360435f7731"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Third Party Advisory"], "url": "https://huntr.dev/bounties/b289ee0f-fd16-4147-bd01-c6289c45e49d"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}, {"source": "security@huntr.dev", "tags": null, "url": "https://support.apple.com/kb/HT213670"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-787"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/3ac1d97a1d9353490493d30088256360435f7731"}, "type": "CWE-787"}
190
Determine whether the {function_name} code is vulnerable or not.
[ "/* vi:set ts=8 sts=4 sw=4 noet:\n *\n * VIM - Vi IMproved\tby Bram Moolenaar\n *\n * Do \":help uganda\" in Vim to read copying and usage conditions.\n * Do \":help credits\" in Vim to see a list of people who contributed.\n * See README.txt for an overview of the Vim source code.\n */", "/*\n * eval.c: Expression evaluation.\n */\n#define USING_FLOAT_STUFF", "#include \"vim.h\"", "#if defined(FEAT_EVAL) || defined(PROTO)", "#ifdef VMS\n# include <float.h>\n#endif", "#define NAMESPACE_CHAR\t(char_u *)\"abglstvw\"", "/*\n * When recursively copying lists and dicts we need to remember which ones we\n * have done to avoid endless recursiveness. This unique ID is used for that.\n * The last bit is used for previous_funccal, ignored when comparing.\n */\nstatic int current_copyID = 0;", "static int eval2(char_u **arg, typval_T *rettv, evalarg_T *evalarg);\nstatic int eval3(char_u **arg, typval_T *rettv, evalarg_T *evalarg);\nstatic int eval4(char_u **arg, typval_T *rettv, evalarg_T *evalarg);\nstatic int eval5(char_u **arg, typval_T *rettv, evalarg_T *evalarg);\nstatic int eval6(char_u **arg, typval_T *rettv, evalarg_T *evalarg);\nstatic int eval7(char_u **arg, typval_T *rettv, evalarg_T *evalarg, int want_string);\nstatic int eval8(char_u **arg, typval_T *rettv, evalarg_T *evalarg, int want_string);\nstatic int eval9(char_u **arg, typval_T *rettv, evalarg_T *evalarg, int want_string);\nstatic int eval9_leader(typval_T *rettv, int numeric_only, char_u *start_leader, char_u **end_leaderp);", "static int free_unref_items(int copyID);\nstatic char_u *make_expanded_name(char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end);", "/*\n * Return \"n1\" divided by \"n2\", taking care of dividing by zero.\n * If \"failed\" is not NULL set it to TRUE when dividing by zero fails.\n */\n\tvarnumber_T\nnum_divide(varnumber_T n1, varnumber_T n2, int *failed)\n{\n varnumber_T\tresult;", " if (n2 == 0)\n {\n\tif (in_vim9script())\n\t{\n\t emsg(_(e_divide_by_zero));\n\t if (failed != NULL)\n\t\t*failed = TRUE;\n\t}\n\tif (n1 == 0)\n\t result = VARNUM_MIN; // similar to NaN\n\telse if (n1 < 0)\n\t result = -VARNUM_MAX;\n\telse\n\t result = VARNUM_MAX;\n }\n else if (n1 == VARNUM_MIN && n2 == -1)\n {\n\t// specific case: trying to do VARNUM_MIN / -1 results in a positive\n\t// number that doesn't fit in varnumber_T and causes an FPE\n\tresult = VARNUM_MAX;\n }\n else\n\tresult = n1 / n2;", " return result;\n}", "/*\n * Return \"n1\" modulus \"n2\", taking care of dividing by zero.\n * If \"failed\" is not NULL set it to TRUE when dividing by zero fails.\n */\n\tvarnumber_T\nnum_modulus(varnumber_T n1, varnumber_T n2, int *failed)\n{\n if (n2 == 0 && in_vim9script())\n {\n\temsg(_(e_divide_by_zero));\n\tif (failed != NULL)\n\t *failed = TRUE;\n }\n return (n2 == 0) ? 0 : (n1 % n2);\n}", "/*\n * Initialize the global and v: variables.\n */\n void\neval_init(void)\n{\n evalvars_init();\n func_init();\n}", "#if defined(EXITFREE) || defined(PROTO)\n void\neval_clear(void)\n{\n evalvars_clear();\n free_scriptnames(); // must come after evalvars_clear().\n free_locales();", " // autoloaded script names\n free_autoload_scriptnames();", " // unreferenced lists and dicts\n (void)garbage_collect(FALSE);", " // functions not garbage collected\n free_all_functions();\n}\n#endif", " void\nfill_evalarg_from_eap(evalarg_T *evalarg, exarg_T *eap, int skip)\n{\n init_evalarg(evalarg);\n evalarg->eval_flags = skip ? 0 : EVAL_EVALUATE;", " if (eap == NULL)\n\treturn;", " evalarg->eval_cstack = eap->cstack;\n if (sourcing_a_script(eap) || eap->getline == get_list_line)\n {\n\tevalarg->eval_getline = eap->getline;\n\tevalarg->eval_cookie = eap->cookie;\n }\n}", "/*\n * Top level evaluation function, returning a boolean.\n * Sets \"error\" to TRUE if there was an error.\n * Return TRUE or FALSE.\n */\n int\neval_to_bool(\n char_u\t*arg,\n int\t\t*error,\n exarg_T\t*eap,\n int\t\tskip,\t // only parse, don't execute\n int\t\tuse_simple_function)\n{\n typval_T\ttv;\n varnumber_T\tretval = FALSE;\n evalarg_T\tevalarg;\n int\t\tr;", " fill_evalarg_from_eap(&evalarg, eap, skip);", " if (skip)\n\t++emsg_skip;\n if (use_simple_function)\n\tr = eval0_simple_funccal(arg, &tv, eap, &evalarg);\n else\n\tr = eval0(arg, &tv, eap, &evalarg);\n if (r == FAIL)\n\t*error = TRUE;\n else\n {\n\t*error = FALSE;\n\tif (!skip)\n\t{\n\t if (in_vim9script())\n\t\tretval = tv_get_bool_chk(&tv, error);\n\t else\n\t\tretval = (tv_get_number_chk(&tv, error) != 0);\n\t clear_tv(&tv);\n\t}\n }\n if (skip)\n\t--emsg_skip;\n clear_evalarg(&evalarg, eap);", " return (int)retval;\n}", "/*\n * Call eval1() and give an error message if not done at a lower level.\n */\n static int\neval1_emsg(char_u **arg, typval_T *rettv, exarg_T *eap)\n{\n char_u\t*start = *arg;\n int\t\tret;\n int\t\tdid_emsg_before = did_emsg;\n int\t\tcalled_emsg_before = called_emsg;\n evalarg_T\tevalarg;", " fill_evalarg_from_eap(&evalarg, eap, eap != NULL && eap->skip);", " ret = eval1(arg, rettv, &evalarg);\n if (ret == FAIL)\n {\n\t// Report the invalid expression unless the expression evaluation has\n\t// been cancelled due to an aborting error, an interrupt, or an\n\t// exception, or we already gave a more specific error.\n\t// Also check called_emsg for when using assert_fails().\n\tif (!aborting() && did_emsg == did_emsg_before\n\t\t\t\t\t && called_emsg == called_emsg_before)\n\t semsg(_(e_invalid_expression_str), start);\n }\n clear_evalarg(&evalarg, eap);\n return ret;\n}", "/*\n * Return whether a typval is a valid expression to pass to eval_expr_typval()\n * or eval_expr_to_bool(). An empty string returns FALSE;\n */\n int\neval_expr_valid_arg(typval_T *tv)\n{\n return tv->v_type != VAR_UNKNOWN\n\t && (tv->v_type != VAR_STRING\n\t\t || (tv->vval.v_string != NULL && *tv->vval.v_string != NUL));\n}", "/*\n * When calling eval_expr_typval() many times we only need one funccall_T.\n * Returns NULL when no funccall_T is to be used.\n * When returning non-NULL remove_funccal() must be called later.\n */\n funccall_T *\neval_expr_get_funccal(typval_T *expr, typval_T *rettv)\n{\n if (expr->v_type != VAR_PARTIAL)\n\treturn NULL;", " partial_T *partial = expr->vval.v_partial;\n if (partial == NULL)\n\treturn NULL;\n if (partial->pt_func == NULL\n\t || partial->pt_func->uf_def_status == UF_NOT_COMPILED)\n\treturn NULL;", " return create_funccal(partial->pt_func, rettv);\n}", "/*\n * Evaluate an expression, which can be a function, partial or string.\n * Pass arguments \"argv[argc]\".\n * \"fc_arg\" is from eval_expr_get_funccal() or NULL;\n * Return the result in \"rettv\" and OK or FAIL.\n */\n int\neval_expr_typval(\n\ttypval_T *expr,\n\ttypval_T *argv,\n\tint\t argc,\n\tfunccall_T *fc_arg,\n\ttypval_T *rettv)\n{\n char_u\t*s;\n char_u\tbuf[NUMBUFLEN];\n funcexe_T\tfuncexe;", " if (expr->v_type == VAR_FUNC)\n {\n\ts = expr->vval.v_string;\n\tif (s == NULL || *s == NUL)\n\t return FAIL;\n\tCLEAR_FIELD(funcexe);\n\tfuncexe.fe_evaluate = TRUE;\n\tif (call_func(s, -1, rettv, argc, argv, &funcexe) == FAIL)\n\t return FAIL;\n }\n else if (expr->v_type == VAR_PARTIAL)\n {\n\tpartial_T *partial = expr->vval.v_partial;", "\tif (partial == NULL)\n\t return FAIL;", "\tif (partial->pt_func != NULL\n\t\t\t && partial->pt_func->uf_def_status != UF_NOT_COMPILED)\n\t{\n\t funccall_T\t*fc = fc_arg != NULL ? fc_arg\n\t\t\t\t : create_funccal(partial->pt_func, rettv);\n\t int\t\tr;", "\t if (fc == NULL)\n\t\treturn FAIL;", "\t // Shortcut to call a compiled function with minimal overhead.\n\t r = call_def_function(partial->pt_func, argc, argv,\n\t\t\t\t DEF_USE_PT_ARGV, partial, NULL, fc, rettv);\n\t if (fc_arg == NULL)\n\t\tremove_funccal();\n\t if (r == FAIL)\n\t\treturn FAIL;\n\t}\n\telse\n\t{\n\t s = partial_name(partial);\n\t if (s == NULL || *s == NUL)\n\t\treturn FAIL;\n\t CLEAR_FIELD(funcexe);\n\t funcexe.fe_evaluate = TRUE;\n\t funcexe.fe_partial = partial;\n\t if (call_func(s, -1, rettv, argc, argv, &funcexe) == FAIL)\n\t\treturn FAIL;\n\t}\n }\n else if (expr->v_type == VAR_INSTR)\n {\n\treturn exe_typval_instr(expr, rettv);\n }\n else\n {\n\ts = tv_get_string_buf_chk_strict(expr, buf, in_vim9script());\n\tif (s == NULL)\n\t return FAIL;\n\ts = skipwhite(s);\n\tif (eval1_emsg(&s, rettv, NULL) == FAIL)\n\t return FAIL;\n\tif (*skipwhite(s) != NUL) // check for trailing chars after expr\n\t{\n\t clear_tv(rettv);\n\t semsg(_(e_invalid_expression_str), s);\n\t return FAIL;\n\t}\n }\n return OK;\n}", "/*\n * Like eval_to_bool() but using a typval_T instead of a string.\n * Works for string, funcref and partial.\n */\n int\neval_expr_to_bool(typval_T *expr, int *error)\n{\n typval_T\trettv;\n int\t\tres;", " if (eval_expr_typval(expr, NULL, 0, NULL, &rettv) == FAIL)\n {\n\t*error = TRUE;\n\treturn FALSE;\n }\n res = (tv_get_bool_chk(&rettv, error) != 0);\n clear_tv(&rettv);\n return res;\n}", "/*\n * Top level evaluation function, returning a string. If \"skip\" is TRUE,\n * only parsing to \"nextcmd\" is done, without reporting errors. Return\n * pointer to allocated memory, or NULL for failure or when \"skip\" is TRUE.\n */\n char_u *\neval_to_string_skip(\n char_u\t*arg,\n exarg_T\t*eap,\n int\t\tskip)\t // only parse, don't execute\n{\n typval_T\ttv;\n char_u\t*retval;\n evalarg_T\tevalarg;", " fill_evalarg_from_eap(&evalarg, eap, skip);\n if (skip)\n\t++emsg_skip;\n if (eval0(arg, &tv, eap, &evalarg) == FAIL || skip)\n\tretval = NULL;\n else\n {\n\tretval = vim_strsave(tv_get_string(&tv));\n\tclear_tv(&tv);\n }\n if (skip)\n\t--emsg_skip;\n clear_evalarg(&evalarg, eap);", " return retval;\n}", "/*\n * Initialize \"evalarg\" for use.\n */\n void\ninit_evalarg(evalarg_T *evalarg)\n{\n CLEAR_POINTER(evalarg);\n ga_init2(&evalarg->eval_tofree_ga, sizeof(char_u *), 20);\n}", "/*\n * If \"evalarg->eval_tofree\" is not NULL free it later.\n * Caller is expected to overwrite \"evalarg->eval_tofree\" next.\n */\n static void\nfree_eval_tofree_later(evalarg_T *evalarg)\n{\n if (evalarg->eval_tofree == NULL)\n\treturn;", " if (ga_grow(&evalarg->eval_tofree_ga, 1) == OK)\n\t((char_u **)evalarg->eval_tofree_ga.ga_data)\n\t [evalarg->eval_tofree_ga.ga_len++]\n\t = evalarg->eval_tofree;\n else\n\tvim_free(evalarg->eval_tofree);\n}", "/*\n * After using \"evalarg\" filled from \"eap\": free the memory.\n */\n void\nclear_evalarg(evalarg_T *evalarg, exarg_T *eap)\n{\n if (evalarg == NULL)\n\treturn;", " garray_T *etga = &evalarg->eval_tofree_ga;", " if (evalarg->eval_tofree != NULL || evalarg->eval_using_cmdline)\n {\n\tif (eap != NULL)\n\t{\n\t // We may need to keep the original command line, e.g. for\n\t // \":let\" it has the variable names. But we may also need\n\t // the new one, \"nextcmd\" points into it. Keep both.\n\t vim_free(eap->cmdline_tofree);\n\t eap->cmdline_tofree = *eap->cmdlinep;", "\t if (evalarg->eval_using_cmdline && etga->ga_len > 0)\n\t {\n\t\t// \"nextcmd\" points into the last line in eval_tofree_ga,\n\t\t// need to keep it around.\n\t\t--etga->ga_len;\n\t\t*eap->cmdlinep = ((char_u **)etga->ga_data)[etga->ga_len];\n\t\tvim_free(evalarg->eval_tofree);\n\t }\n\t else\n\t\t*eap->cmdlinep = evalarg->eval_tofree;\n\t}\n\telse\n\t vim_free(evalarg->eval_tofree);\n\tevalarg->eval_tofree = NULL;\n }", " ga_clear_strings(etga);\n VIM_CLEAR(evalarg->eval_tofree_lambda);\n}", "/*\n * Skip over an expression at \"*pp\".\n * Return FAIL for an error, OK otherwise.\n */\n int\nskip_expr(char_u **pp, evalarg_T *evalarg)\n{\n typval_T\trettv;", " *pp = skipwhite(*pp);\n return eval1(pp, &rettv, evalarg);\n}", "/*\n * Skip over an expression at \"*arg\".\n * If in Vim9 script and line breaks are encountered, the lines are\n * concatenated. \"evalarg->eval_tofree\" will be set accordingly.\n * \"arg\" is advanced to just after the expression.\n * \"start\" is set to the start of the expression, \"end\" to just after the end.\n * Also when the expression is copied to allocated memory.\n * Return FAIL for an error, OK otherwise.\n */\n int\nskip_expr_concatenate(\n\tchar_u\t **arg,\n\tchar_u\t **start,\n\tchar_u\t **end,\n\tevalarg_T *evalarg)\n{\n typval_T\trettv;\n int\t\tres;\n int\t\tvim9script = in_vim9script();\n garray_T *gap = evalarg == NULL ? NULL : &evalarg->eval_ga;\n garray_T *freegap = evalarg == NULL ? NULL : &evalarg->eval_freega;\n int\t\tsave_flags = evalarg == NULL ? 0 : evalarg->eval_flags;\n int\t\tevaluate = evalarg == NULL\n\t\t\t ? FALSE : (evalarg->eval_flags & EVAL_EVALUATE);", " if (vim9script && evaluate\n\t && (evalarg->eval_cookie != NULL || evalarg->eval_cctx != NULL))\n {\n\tga_init2(gap, sizeof(char_u *), 10);\n\t// leave room for \"start\"\n\tif (ga_grow(gap, 1) == OK)\n\t ++gap->ga_len;\n\tga_init2(freegap, sizeof(char_u *), 10);\n }\n *start = *arg;", " // Don't evaluate the expression.\n if (evalarg != NULL)\n\tevalarg->eval_flags &= ~EVAL_EVALUATE;\n *arg = skipwhite(*arg);\n res = eval1(arg, &rettv, evalarg);\n *end = *arg;\n if (evalarg != NULL)\n\tevalarg->eval_flags = save_flags;", " if (vim9script && evaluate\n\t && (evalarg->eval_cookie != NULL || evalarg->eval_cctx != NULL))\n {\n\tif (evalarg->eval_ga.ga_len == 1)\n\t{\n\t // just the one line, no need to concatenate\n\t ga_clear(gap);\n\t gap->ga_itemsize = 0;\n\t}\n\telse\n\t{\n\t char_u\t *p;\n\t size_t\t endoff = STRLEN(*arg);", "\t // Line breaks encountered, concatenate all the lines.\n\t *((char_u **)gap->ga_data) = *start;\n\t p = ga_concat_strings(gap, \" \");", "\t // free the lines only when using getsourceline()\n\t if (evalarg->eval_cookie != NULL)\n\t {\n\t\t// Do not free the first line, the caller can still use it.\n\t\t*((char_u **)gap->ga_data) = NULL;\n\t\t// Do not free the last line, \"arg\" points into it, free it\n\t\t// later. Also free \"eval_tofree\" later if needed.\n\t\tfree_eval_tofree_later(evalarg);\n\t\tevalarg->eval_tofree =\n\t\t\t\t ((char_u **)gap->ga_data)[gap->ga_len - 1];\n\t\t((char_u **)gap->ga_data)[gap->ga_len - 1] = NULL;\n\t\tga_clear_strings(gap);\n\t }\n\t else\n\t {\n\t\tga_clear(gap);", "\t\t// free lines that were explicitly marked for freeing\n\t\tga_clear_strings(freegap);\n\t }", "\t gap->ga_itemsize = 0;\n\t if (p == NULL)\n\t\treturn FAIL;\n\t *start = p;\n\t vim_free(evalarg->eval_tofree_lambda);\n\t evalarg->eval_tofree_lambda = p;\n\t // Compute \"end\" relative to the end.\n\t *end = *start + STRLEN(*start) - endoff;\n\t}\n }", " return res;\n}", "/*\n * Convert \"tv\" to a string.\n * When \"convert\" is TRUE convert a List into a sequence of lines and convert\n * a Float to a String.\n * Returns an allocated string (NULL when out of memory).\n */\n char_u *\ntypval2string(typval_T *tv, int convert)\n{\n garray_T\tga;\n char_u\t*retval;\n char_u\tnumbuf[NUMBUFLEN];", " if (convert && tv->v_type == VAR_LIST)\n {\n\tga_init2(&ga, sizeof(char), 80);\n\tif (tv->vval.v_list != NULL)\n\t{\n\t list_join(&ga, tv->vval.v_list, (char_u *)\"\\n\", TRUE, FALSE, 0);\n\t if (tv->vval.v_list->lv_len > 0)\n\t\tga_append(&ga, NL);\n\t}\n\tga_append(&ga, NUL);\n\tretval = (char_u *)ga.ga_data;\n }\n else if (convert && tv->v_type == VAR_FLOAT)\n {\n\tvim_snprintf((char *)numbuf, NUMBUFLEN, \"%g\", tv->vval.v_float);\n\tretval = vim_strsave(numbuf);\n }\n else\n\tretval = vim_strsave(tv_get_string(tv));\n return retval;\n}", "/*\n * Top level evaluation function, returning a string. Does not handle line\n * breaks.\n * When \"convert\" is TRUE convert a List into a sequence of lines and convert\n * a Float to a String.\n * Return pointer to allocated memory, or NULL for failure.\n */\n char_u *\neval_to_string_eap(\n char_u\t*arg,\n int\t\tconvert,\n exarg_T\t*eap,\n int\t\tuse_simple_function)\n{\n typval_T\ttv;\n char_u\t*retval;\n evalarg_T\tevalarg;\n int\t\tr;", " fill_evalarg_from_eap(&evalarg, eap, eap != NULL && eap->skip);\n if (use_simple_function)\n\tr = eval0_simple_funccal(arg, &tv, NULL, &evalarg);\n else\n\tr = eval0(arg, &tv, NULL, &evalarg);\n if (r == FAIL)\n\tretval = NULL;\n else\n {\n\tretval = typval2string(&tv, convert);\n\tclear_tv(&tv);\n }\n clear_evalarg(&evalarg, NULL);", " return retval;\n}", " char_u *\neval_to_string(\n char_u\t*arg,\n int\t\tconvert,\n int\t\tuse_simple_function)\n{\n return eval_to_string_eap(arg, convert, NULL, use_simple_function);\n}", "/*\n * Call eval_to_string() without using current local variables and using\n * textlock. When \"use_sandbox\" is TRUE use the sandbox.\n * Use legacy Vim script syntax.\n */\n char_u *\neval_to_string_safe(\n char_u\t*arg,\n int\t\tuse_sandbox,\n int\t\tkeep_script_version,\n int\t\tuse_simple_function)\n{\n char_u\t*retval;\n funccal_entry_T funccal_entry;\n int\t\tsave_sc_version = current_sctx.sc_version;\n int\t\tsave_garbage = may_garbage_collect;", " if (!keep_script_version)\n\tcurrent_sctx.sc_version = 1;\n save_funccal(&funccal_entry);\n if (use_sandbox)\n\t++sandbox;\n ++textlock;\n may_garbage_collect = FALSE;\n retval = eval_to_string(arg, FALSE, use_simple_function);\n if (use_sandbox)\n\t--sandbox;\n --textlock;\n may_garbage_collect = save_garbage;\n restore_funccal();\n current_sctx.sc_version = save_sc_version;\n return retval;\n}", "/*\n * Top level evaluation function, returning a number.\n * Evaluates \"expr\" silently.\n * Returns -1 for an error.\n */\n varnumber_T\neval_to_number(char_u *expr, int use_simple_function)\n{\n typval_T\trettv;\n varnumber_T\tretval;\n char_u\t*p = skipwhite(expr);\n int\t\tr = NOTDONE;", " ++emsg_off;", " if (use_simple_function)\n\tr = may_call_simple_func(expr, &rettv);\n if (r == NOTDONE)\n\tr = eval1(&p, &rettv, &EVALARG_EVALUATE);\n if (r == FAIL)\n\tretval = -1;\n else\n {\n\tretval = tv_get_number_chk(&rettv, NULL);\n\tclear_tv(&rettv);\n }\n --emsg_off;", " return retval;\n}", "/*\n * Top level evaluation function.\n * Returns an allocated typval_T with the result.\n * Returns NULL when there is an error.\n */\n typval_T *\neval_expr(char_u *arg, exarg_T *eap)\n{\n return eval_expr_ext(arg, eap, FALSE);\n}", " typval_T *\neval_expr_ext(char_u *arg, exarg_T *eap, int use_simple_function)\n{\n typval_T\t*tv;\n evalarg_T\tevalarg;", " fill_evalarg_from_eap(&evalarg, eap, eap != NULL && eap->skip);", " tv = ALLOC_ONE(typval_T);\n if (tv != NULL)\n {\n\tint\tr = NOTDONE;", "\tif (use_simple_function)\n\t r = eval0_simple_funccal(arg, tv, eap, &evalarg);\n\tif (r == NOTDONE)\n\t r = eval0(arg, tv, eap, &evalarg);", "\tif (r == FAIL)\n\t VIM_CLEAR(tv);\n }", " clear_evalarg(&evalarg, eap);\n return tv;\n}", "/*\n * \"*arg\" points to what can be a function name in the form of \"import.Name\" or\n * \"Funcref\". Return the name of the function. Set \"tofree\" to something that\n * was allocated.\n * If \"verbose\" is FALSE no errors are given.\n * Return NULL for any failure.\n */\n static char_u *\nderef_function_name(\n\t char_u\t**arg,\n\t char_u\t**tofree,\n\t evalarg_T\t*evalarg,\n\t int\t\tverbose)\n{\n typval_T\tref;\n char_u\t*name = *arg;\n int\t\tsave_flags = 0;", " ref.v_type = VAR_UNKNOWN;\n if (evalarg != NULL)\n {\n\t// need to evaluate this to get an import, like in \"a.Func\"\n\tsave_flags = evalarg->eval_flags;\n\tevalarg->eval_flags |= EVAL_EVALUATE;\n }\n if (eval9(arg, &ref, evalarg, FALSE) == FAIL)\n {\n\tdictitem_T\t*v;", "\t// If <SID>VarName was used it would not be found, try another way.\n\tv = find_var_also_in_script(name, NULL, FALSE);\n\tif (v == NULL)\n\t{\n\t name = NULL;\n\t goto theend;\n\t}\n\tcopy_tv(&v->di_tv, &ref);\n }\n if (*skipwhite(*arg) != NUL)\n {\n\tif (verbose)\n\t semsg(_(e_trailing_characters_str), *arg);\n\tname = NULL;\n }\n else if (ref.v_type == VAR_FUNC && ref.vval.v_string != NULL)\n {\n\tname = ref.vval.v_string;\n\tref.vval.v_string = NULL;\n\t*tofree = name;\n }\n else if (ref.v_type == VAR_PARTIAL && ref.vval.v_partial != NULL)\n {\n\tif (ref.vval.v_partial->pt_argc > 0\n\t\t|| ref.vval.v_partial->pt_dict != NULL)\n\t{\n\t if (verbose)\n\t\temsg(_(e_cannot_use_partial_here));\n\t name = NULL;\n\t}\n\telse\n\t{\n\t name = vim_strsave(partial_name(ref.vval.v_partial));\n\t *tofree = name;\n\t}\n }\n else\n {\n\tif (verbose)\n\t semsg(_(e_not_callable_type_str), name);\n\tname = NULL;\n }", "theend:\n clear_tv(&ref);\n if (evalarg != NULL)\n\tevalarg->eval_flags = save_flags;\n return name;\n}", "/*\n * Call some Vim script function and return the result in \"*rettv\".\n * Uses argv[0] to argv[argc - 1] for the function arguments. argv[argc]\n * should have type VAR_UNKNOWN.\n * Returns OK or FAIL.\n */\n int\ncall_vim_function(\n char_u *func,\n int\t\targc,\n typval_T\t*argv,\n typval_T\t*rettv)\n{\n int\t\tret;\n funcexe_T\tfuncexe;\n char_u\t*arg;\n char_u\t*name;\n char_u\t*tofree = NULL;\n int\t\tignore_errors;", " rettv->v_type = VAR_UNKNOWN;\t\t// clear_tv() uses this\n CLEAR_FIELD(funcexe);\n funcexe.fe_firstline = curwin->w_cursor.lnum;\n funcexe.fe_lastline = curwin->w_cursor.lnum;\n funcexe.fe_evaluate = TRUE;", " // The name might be \"import.Func\" or \"Funcref\". We don't know, we need to\n // ignore errors for an undefined name. But we do want errors when an\n // autoload script has errors. Guess that when there is a dot in the name\n // showing errors is the right choice.\n ignore_errors = vim_strchr(func, '.') == NULL;\n arg = func;\n if (ignore_errors)\n\t++emsg_off;\n name = deref_function_name(&arg, &tofree, &EVALARG_EVALUATE, FALSE);\n if (ignore_errors)\n\t--emsg_off;\n if (name == NULL)\n\tname = func;", " ret = call_func(name, -1, rettv, argc, argv, &funcexe);", " if (ret == FAIL)\n\tclear_tv(rettv);\n vim_free(tofree);", " return ret;\n}", "/*\n * Call Vim script function \"func\" and return the result as a string.\n * Uses \"argv[0]\" to \"argv[argc - 1]\" for the function arguments. \"argv[argc]\"\n * should have type VAR_UNKNOWN.\n * Returns NULL when calling the function fails.\n */\n void *\ncall_func_retstr(\n char_u *func,\n int\t\targc,\n typval_T\t*argv)\n{\n typval_T\trettv;\n char_u\t*retval;", " if (call_vim_function(func, argc, argv, &rettv) == FAIL)\n\treturn NULL;", " retval = vim_strsave(tv_get_string(&rettv));\n clear_tv(&rettv);\n return retval;\n}", "/*\n * Call Vim script function \"func\" and return the result as a List.\n * Uses \"argv\" and \"argc\" as call_func_retstr().\n * Returns NULL when there is something wrong.\n * Gives an error when the returned value is not a list.\n */\n void *\ncall_func_retlist(\n char_u *func,\n int\t\targc,\n typval_T\t*argv)\n{\n typval_T\trettv;", " if (call_vim_function(func, argc, argv, &rettv) == FAIL)\n\treturn NULL;", " if (rettv.v_type != VAR_LIST)\n {\n\tsemsg(_(e_custom_list_completion_function_does_not_return_list_but_str),\n\t\tvartype_name(rettv.v_type));\n\tclear_tv(&rettv);\n\treturn NULL;\n }", " return rettv.vval.v_list;\n}", "#if defined(FEAT_FOLDING) || defined(PROTO)\n/*\n * Evaluate \"arg\", which is 'foldexpr'.\n * Note: caller must set \"curwin\" to match \"arg\".\n * Returns the foldlevel, and any character preceding it in \"*cp\". Doesn't\n * give error messages.\n */\n int\neval_foldexpr(win_T *wp, int *cp)\n{\n char_u\t*arg;\n typval_T\ttv;\n varnumber_T\tretval;\n char_u\t*s;\n sctx_T\tsaved_sctx = current_sctx;\n int\t\tuse_sandbox = was_set_insecurely((char_u *)\"foldexpr\",\n\t\t\t\t\t\t\t\t OPT_LOCAL);", " arg = skipwhite(wp->w_p_fde);\n current_sctx = wp->w_p_script_ctx[WV_FDE];", " ++emsg_off;\n if (use_sandbox)\n\t++sandbox;\n ++textlock;\n *cp = NUL;", " // Evaluate the expression. If the expression is \"FuncName()\" call the\n // function directly.\n if (eval0_simple_funccal(arg, &tv, NULL, &EVALARG_EVALUATE) == FAIL)\n\tretval = 0;\n else\n {\n\t// If the result is a number, just return the number.\n\tif (tv.v_type == VAR_NUMBER)\n\t retval = tv.vval.v_number;\n\telse if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)\n\t retval = 0;\n\telse\n\t{\n\t // If the result is a string, check if there is a non-digit before\n\t // the number.\n\t s = tv.vval.v_string;\n\t if (!VIM_ISDIGIT(*s) && *s != '-')\n\t\t*cp = *s++;\n\t retval = atol((char *)s);\n\t}\n\tclear_tv(&tv);\n }\n --emsg_off;\n if (use_sandbox)\n\t--sandbox;\n --textlock;\n clear_evalarg(&EVALARG_EVALUATE, NULL);\n current_sctx = saved_sctx;", " return (int)retval;\n}\n#endif", "/*\n * Get an lval: variable, Dict item or List item that can be assigned a value\n * to: \"name\", \"na{me}\", \"name[expr]\", \"name[expr:expr]\", \"name[expr][expr]\",\n * \"name.key\", \"name.key[expr]\" etc.\n * Indexing only works if \"name\" is an existing List or Dictionary.\n * \"name\" points to the start of the name.\n * If \"rettv\" is not NULL it points to the value to be assigned.\n * \"unlet\" is TRUE for \":unlet\": slightly different behavior when something is\n * wrong; must end in space or cmd separator.\n *\n * flags:\n * GLV_QUIET: do not give error messages\n * GLV_READ_ONLY: will not change the variable\n * GLV_NO_AUTOLOAD: do not use script autoloading\n *\n * Returns a pointer to just after the name, including indexes.\n * When an evaluation error occurs \"lp->ll_name\" is NULL;\n * Returns NULL for a parsing error. Still need to free items in \"lp\"!\n */\n char_u *\nget_lval(\n char_u\t*name,\n typval_T\t*rettv,\n lval_T\t*lp,\n int\t\tunlet,\n int\t\tskip,\n int\t\tflags,\t // GLV_ values\n int\t\tfne_flags) // flags for find_name_end()\n{\n char_u\t*p;\n char_u\t*expr_start, *expr_end;\n int\t\tcc;\n dictitem_T\t*v;\n typval_T\tvar1;\n typval_T\tvar2;\n int\t\tempty1 = FALSE;\n char_u\t*key = NULL;\n int\t\tlen;\n hashtab_T\t*ht = NULL;\n int\t\tquiet = flags & GLV_QUIET;\n int\t\twriting;\n int\t\tvim9script = in_vim9script();", " // Clear everything in \"lp\".\n CLEAR_POINTER(lp);", " if (skip || (flags & GLV_COMPILING))\n {\n\t// When skipping or compiling just find the end of the name.\n\tlp->ll_name = name;\n\tlp->ll_name_end = find_name_end(name, NULL, NULL,\n\t\t\t\t\t\t FNE_INCL_BR | fne_flags);\n\treturn lp->ll_name_end;\n }", " // Cannot use \"s:var\" at the Vim9 script level. \"s: type\" is OK.\n if (vim9script && at_script_level()\n\t\t && name[0] == 's' && name[1] == ':' && !VIM_ISWHITE(name[2]))\n {\n\tsemsg(_(e_cannot_use_s_colon_in_vim9_script_str), name);\n\treturn NULL;\n }", " // Find the end of the name.\n p = find_name_end(name, &expr_start, &expr_end, fne_flags);\n lp->ll_name_end = p;\n if (expr_start != NULL)\n {\n\t// Don't expand the name when we already know there is an error.\n\tif (unlet && !VIM_ISWHITE(*p) && !ends_excmd(*p)\n\t\t\t\t\t\t && *p != '[' && *p != '.')\n\t{\n\t semsg(_(e_trailing_characters_str), p);\n\t return NULL;\n\t}", "\tlp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);\n\tif (lp->ll_exp_name == NULL)\n\t{\n\t // Report an invalid expression in braces, unless the\n\t // expression evaluation has been cancelled due to an\n\t // aborting error, an interrupt, or an exception.\n\t if (!aborting() && !quiet)\n\t {\n\t\temsg_severe = TRUE;\n\t\tsemsg(_(e_invalid_argument_str), name);\n\t\treturn NULL;\n\t }\n\t}\n\tlp->ll_name = lp->ll_exp_name;\n }\n else\n {\n\tlp->ll_name = name;", "\tif (vim9script)\n\t{\n\t // \"a: type\" is declaring variable \"a\" with a type, not \"a:\".\n\t // However, \"g:[key]\" is indexing a dictionary.\n\t if (p == name + 2 && p[-1] == ':' && *p != '[')\n\t {\n\t\t--p;\n\t\tlp->ll_name_end = p;\n\t }\n\t if (*p == ':')\n\t {\n\t\tchar_u\t *tp = skipwhite(p + 1);", "\t\tif (is_scoped_variable(name))\n\t\t{\n\t\t semsg(_(e_cannot_use_type_with_this_variable_str), name);\n\t\t return NULL;\n\t\t}\n\t\tif (tp == p + 1 && !quiet)\n\t\t{\n\t\t semsg(_(e_white_space_required_after_str_str), \":\", p);\n\t\t return NULL;\n\t\t}\n\t\tif (!SCRIPT_ID_VALID(current_sctx.sc_sid))\n\t\t{\n\t\t semsg(_(e_using_type_not_in_script_context_str), p);\n\t\t return NULL;\n\t\t}", "\t\t// parse the type after the name\n\t\tlp->ll_type = parse_type(&tp,\n\t\t\t &SCRIPT_ITEM(current_sctx.sc_sid)->sn_type_list,\n\t\t\t !quiet);\n\t\tif (lp->ll_type == NULL && !quiet)\n\t\t return NULL;\n\t\tlp->ll_name_end = tp;\n\t }\n\t}\n }\n if (lp->ll_name == NULL)\n\treturn p;", " if (*p == '.')\n {\n\timported_T *import = find_imported(lp->ll_name, p - lp->ll_name, TRUE);", "\tif (import != NULL)\n\t{\n\t ufunc_T *ufunc;\n\t type_T *type;", "\t import_check_sourced_sid(&import->imp_sid);\n\t lp->ll_sid = import->imp_sid;\n\t lp->ll_name = skipwhite(p + 1);\n\t p = find_name_end(lp->ll_name, NULL, NULL, fne_flags);\n\t lp->ll_name_end = p;", "\t // check the item is exported\n\t cc = *p;\n\t *p = NUL;\n\t if (find_exported(import->imp_sid, lp->ll_name, &ufunc, &type,\n\t\t\t\t\t\t NULL, NULL, TRUE) == -1)\n\t {\n\t\t*p = cc;\n\t\treturn NULL;\n\t }\n\t *p = cc;\n\t}\n }", " // Without [idx] or .key we are done.\n if ((*p != '[' && *p != '.'))\n\treturn p;", " if (vim9script && lval_root != NULL)\n {\n\t// using local variable\n\tlp->ll_tv = lval_root;\n\tv = NULL;\n }\n else\n {\n\tcc = *p;\n\t*p = NUL;\n\t// When we would write to the variable pass &ht and prevent autoload.\n\twriting = !(flags & GLV_READ_ONLY);\n\tv = find_var(lp->ll_name, writing ? &ht : NULL,\n\t\t\t\t\t (flags & GLV_NO_AUTOLOAD) || writing);\n\tif (v == NULL && !quiet)\n\t semsg(_(e_undefined_variable_str), lp->ll_name);\n\t*p = cc;\n\tif (v == NULL)\n\t return NULL;\n\tlp->ll_tv = &v->di_tv;\n }", " if (vim9script && (flags & GLV_NO_DECL) == 0)\n {\n\tif (!quiet)\n\t semsg(_(e_variable_already_declared_str), lp->ll_name);\n\treturn NULL;\n }", " /*\n * Loop until no more [idx] or .key is following.\n */\n var1.v_type = VAR_UNKNOWN;\n var2.v_type = VAR_UNKNOWN;\n while (*p == '[' || (*p == '.' && p[1] != '=' && p[1] != '.'))\n {\n\tvartype_T v_type = lp->ll_tv->v_type;", "\tif (*p == '.' && v_type != VAR_DICT\n\t\t && v_type != VAR_OBJECT\n\t\t && v_type != VAR_CLASS)\n\t{\n\t if (!quiet)\n\t\tsemsg(_(e_dot_can_only_be_used_on_dictionary_str), name);\n\t return NULL;\n\t}\n\tif (v_type != VAR_LIST\n\t\t&& v_type != VAR_DICT\n\t\t&& v_type != VAR_BLOB\n\t\t&& v_type != VAR_OBJECT\n\t\t&& v_type != VAR_CLASS)\n\t{\n\t if (!quiet)\n\t\temsg(_(e_can_only_index_list_dictionary_or_blob));\n\t return NULL;\n\t}", "\t// A NULL list/blob works like an empty list/blob, allocate one now.\n\tint r = OK;\n\tif (v_type == VAR_LIST && lp->ll_tv->vval.v_list == NULL)\n\t r = rettv_list_alloc(lp->ll_tv);\n\telse if (v_type == VAR_BLOB\n\t\t\t\t\t && lp->ll_tv->vval.v_blob == NULL)\n\t r = rettv_blob_alloc(lp->ll_tv);\n\tif (r == FAIL)\n\t return NULL;", "\tif (lp->ll_range)\n\t{\n\t if (!quiet)\n\t\temsg(_(e_slice_must_come_last));\n\t return NULL;\n\t}", "\tif (vim9script && lp->ll_valtype == NULL\n\t\t&& v != NULL\n\t\t&& lp->ll_tv == &v->di_tv\n\t\t&& ht != NULL && ht == get_script_local_ht())\n\t{\n\t svar_T *sv = find_typval_in_script(lp->ll_tv, 0, TRUE);", "\t // Vim9 script local variable: get the type\n\t if (sv != NULL)\n\t\tlp->ll_valtype = sv->sv_type;\n\t}", "\tlen = -1;\n\tif (*p == '.')\n\t{\n\t key = p + 1;\n\t for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)\n\t\t;\n\t if (len == 0)\n\t {\n\t\tif (!quiet)\n\t\t emsg(_(e_cannot_use_empty_key_for_dictionary));\n\t\treturn NULL;\n\t }\n\t p = key + len;\n\t}\n\telse\n\t{\n\t // Get the index [expr] or the first index [expr: ].\n\t p = skipwhite(p + 1);\n\t if (*p == ':')\n\t\tempty1 = TRUE;\n\t else\n\t {\n\t\tempty1 = FALSE;\n\t\tif (eval1(&p, &var1, &EVALARG_EVALUATE) == FAIL) // recursive!\n\t\t return NULL;\n\t\tif (tv_get_string_chk(&var1) == NULL)\n\t\t{\n\t\t // not a number or string\n\t\t clear_tv(&var1);\n\t\t return NULL;\n\t\t}\n\t\tp = skipwhite(p);\n\t }", "\t // Optionally get the second index [ :expr].\n\t if (*p == ':')\n\t {\n\t\tif (v_type == VAR_DICT)\n\t\t{\n\t\t if (!quiet)\n\t\t\temsg(_(e_cannot_slice_dictionary));\n\t\t clear_tv(&var1);\n\t\t return NULL;\n\t\t}\n\t\tif (rettv != NULL\n\t\t\t&& !(rettv->v_type == VAR_LIST\n\t\t\t\t\t\t && rettv->vval.v_list != NULL)\n\t\t\t&& !(rettv->v_type == VAR_BLOB\n\t\t\t\t\t\t&& rettv->vval.v_blob != NULL))\n\t\t{\n\t\t if (!quiet)\n\t\t\temsg(_(e_slice_requires_list_or_blob_value));\n\t\t clear_tv(&var1);\n\t\t return NULL;\n\t\t}\n\t\tp = skipwhite(p + 1);\n\t\tif (*p == ']')\n\t\t lp->ll_empty2 = TRUE;\n\t\telse\n\t\t{\n\t\t lp->ll_empty2 = FALSE;\n\t\t // recursive!\n\t\t if (eval1(&p, &var2, &EVALARG_EVALUATE) == FAIL)\n\t\t {\n\t\t\tclear_tv(&var1);\n\t\t\treturn NULL;\n\t\t }\n\t\t if (tv_get_string_chk(&var2) == NULL)\n\t\t {\n\t\t\t// not a number or string\n\t\t\tclear_tv(&var1);\n\t\t\tclear_tv(&var2);\n\t\t\treturn NULL;\n\t\t }\n\t\t}\n\t\tlp->ll_range = TRUE;\n\t }\n\t else\n\t\tlp->ll_range = FALSE;", "\t if (*p != ']')\n\t {\n\t\tif (!quiet)\n\t\t emsg(_(e_missing_closing_square_brace));\n\t\tclear_tv(&var1);\n\t\tclear_tv(&var2);\n\t\treturn NULL;\n\t }", "\t // Skip to past ']'.\n\t ++p;\n\t}", "\tif (v_type == VAR_DICT)\n\t{\n\t if (len == -1)\n\t {\n\t\t// \"[key]\": get key from \"var1\"\n\t\tkey = tv_get_string_chk(&var1);\t// is number or string\n\t\tif (key == NULL)\n\t\t{\n\t\t clear_tv(&var1);\n\t\t return NULL;\n\t\t}\n\t }\n\t lp->ll_list = NULL;", "\t // a NULL dict is equivalent with an empty dict\n\t if (lp->ll_tv->vval.v_dict == NULL)\n\t {\n\t\tlp->ll_tv->vval.v_dict = dict_alloc();\n\t\tif (lp->ll_tv->vval.v_dict == NULL)\n\t\t{\n\t\t clear_tv(&var1);\n\t\t return NULL;\n\t\t}\n\t\t++lp->ll_tv->vval.v_dict->dv_refcount;\n\t }\n\t lp->ll_dict = lp->ll_tv->vval.v_dict;", "\t lp->ll_di = dict_find(lp->ll_dict, key, len);", "\t // When assigning to a scope dictionary check that a function and\n\t // variable name is valid (only variable name unless it is l: or\n\t // g: dictionary). Disallow overwriting a builtin function.\n\t if (rettv != NULL && lp->ll_dict->dv_scope != 0)\n\t {\n\t\tint prevval;", "\t\tif (len != -1)\n\t\t{\n\t\t prevval = key[len];\n\t\t key[len] = NUL;\n\t\t}\n\t\telse\n\t\t prevval = 0; // avoid compiler warning\n\t\tint wrong = (lp->ll_dict->dv_scope == VAR_DEF_SCOPE\n\t\t\t && (rettv->v_type == VAR_FUNC\n\t\t\t\t\t || rettv->v_type == VAR_PARTIAL)\n\t\t\t && var_wrong_func_name(key, lp->ll_di == NULL))\n\t\t\t|| !valid_varname(key, -1, TRUE);\n\t\tif (len != -1)\n\t\t key[len] = prevval;\n\t\tif (wrong)\n\t\t{\n\t\t clear_tv(&var1);\n\t\t return NULL;\n\t\t}\n\t }", "\t if (lp->ll_valtype != NULL)\n\t\t// use the type of the member\n\t\tlp->ll_valtype = lp->ll_valtype->tt_member;", "\t if (lp->ll_di == NULL)\n\t {\n\t\t// Can't add \"v:\" or \"a:\" variable.\n\t\tif (lp->ll_dict == get_vimvar_dict()\n\t\t\t || &lp->ll_dict->dv_hashtab == get_funccal_args_ht())\n\t\t{\n\t\t semsg(_(e_illegal_variable_name_str), name);\n\t\t clear_tv(&var1);\n\t\t return NULL;\n\t\t}", "\t\t// Key does not exist in dict: may need to add it.\n\t\tif (*p == '[' || *p == '.' || unlet)\n\t\t{\n\t\t if (!quiet)\n\t\t\tsemsg(_(e_key_not_present_in_dictionary_str), key);\n\t\t clear_tv(&var1);\n\t\t return NULL;\n\t\t}\n\t\tif (len == -1)\n\t\t lp->ll_newkey = vim_strsave(key);\n\t\telse\n\t\t lp->ll_newkey = vim_strnsave(key, len);\n\t\tclear_tv(&var1);\n\t\tif (lp->ll_newkey == NULL)\n\t\t p = NULL;\n\t\tbreak;\n\t }\n\t // existing variable, need to check if it can be changed\n\t else if ((flags & GLV_READ_ONLY) == 0\n\t\t\t&& (var_check_ro(lp->ll_di->di_flags, name, FALSE)\n\t\t\t || var_check_lock(lp->ll_di->di_flags, name, FALSE)))\n\t {\n\t\tclear_tv(&var1);\n\t\treturn NULL;\n\t }", "\t clear_tv(&var1);\n\t lp->ll_tv = &lp->ll_di->di_tv;\n\t}\n\telse if (v_type == VAR_BLOB)\n\t{\n\t long bloblen = blob_len(lp->ll_tv->vval.v_blob);", "\t /*\n\t * Get the number and item for the only or first index of the List.\n\t */\n\t if (empty1)\n\t\tlp->ll_n1 = 0;\n\t else\n\t\t// is number or string\n\t\tlp->ll_n1 = (long)tv_get_number(&var1);\n\t clear_tv(&var1);", "\t if (check_blob_index(bloblen, lp->ll_n1, quiet) == FAIL)\n\t {\n\t\tclear_tv(&var2);\n\t\treturn NULL;\n\t }\n\t if (lp->ll_range && !lp->ll_empty2)\n\t {\n\t\tlp->ll_n2 = (long)tv_get_number(&var2);\n\t\tclear_tv(&var2);\n\t\tif (check_blob_range(bloblen, lp->ll_n1, lp->ll_n2, quiet)\n\t\t\t\t\t\t\t\t == FAIL)\n\t\t return NULL;\n\t }\n\t lp->ll_blob = lp->ll_tv->vval.v_blob;\n\t lp->ll_tv = NULL;\n\t break;\n\t}\n\telse if (v_type == VAR_LIST)\n\t{\n\t /*\n\t * Get the number and item for the only or first index of the List.\n\t */\n\t if (empty1)\n\t\tlp->ll_n1 = 0;\n\t else\n\t\t// is number or string\n\t\tlp->ll_n1 = (long)tv_get_number(&var1);\n\t clear_tv(&var1);", "\t lp->ll_dict = NULL;\n\t lp->ll_list = lp->ll_tv->vval.v_list;\n\t lp->ll_li = check_range_index_one(lp->ll_list, &lp->ll_n1,\n\t\t\t\t (flags & GLV_ASSIGN_WITH_OP) == 0, quiet);\n\t if (lp->ll_li == NULL)\n\t {\n\t\tclear_tv(&var2);\n\t\treturn NULL;\n\t }", "\t if (lp->ll_valtype != NULL)\n\t\t// use the type of the member\n\t\tlp->ll_valtype = lp->ll_valtype->tt_member;", "\t /*\n\t * May need to find the item or absolute index for the second\n\t * index of a range.\n\t * When no index given: \"lp->ll_empty2\" is TRUE.\n\t * Otherwise \"lp->ll_n2\" is set to the second index.\n\t */\n\t if (lp->ll_range && !lp->ll_empty2)\n\t {\n\t\tlp->ll_n2 = (long)tv_get_number(&var2);\n\t\t\t\t\t\t // is number or string\n\t\tclear_tv(&var2);\n\t\tif (check_range_index_two(lp->ll_list,\n\t\t\t\t\t &lp->ll_n1, lp->ll_li,\n\t\t\t\t\t &lp->ll_n2, quiet) == FAIL)\n\t\t return NULL;\n\t }", "\t lp->ll_tv = &lp->ll_li->li_tv;\n\t}\n\telse // v_type == VAR_CLASS || v_type == VAR_OBJECT\n\t{\n\t class_T *cl = (v_type == VAR_OBJECT\n\t\t\t\t\t && lp->ll_tv->vval.v_object != NULL)\n\t\t\t ? lp->ll_tv->vval.v_object->obj_class\n\t\t\t : lp->ll_tv->vval.v_class;\n\t // TODO: what if class is NULL?\n\t if (cl != NULL)\n\t {\n\t\tlp->ll_valtype = NULL;\n\t\tint count = v_type == VAR_OBJECT ? cl->class_obj_member_count\n\t\t\t\t\t\t: cl->class_class_member_count;\n\t\tocmember_T *members = v_type == VAR_OBJECT\n\t\t\t\t\t\t ? cl->class_obj_members\n\t\t\t\t\t\t : cl->class_class_members;\n\t\tfor (int i = 0; i < count; ++i)\n\t\t{\n\t\t ocmember_T *om = members + i;\n\t\t if (STRNCMP(om->ocm_name, key, p - key) == 0\n\t\t\t\t\t && om->ocm_name[p - key] == NUL)\n\t\t {\n\t\t\tswitch (om->ocm_access)\n\t\t\t{\n\t\t\t case ACCESS_PRIVATE:\n\t\t\t\t semsg(_(e_cannot_access_private_member_str),\n\t\t\t\t\t\t\t\t om->ocm_name);\n\t\t\t\t return NULL;\n\t\t\t case ACCESS_READ:\n\t\t\t\t if (!(flags & GLV_READ_ONLY))\n\t\t\t\t {\n\t\t\t\t\tsemsg(_(e_member_is_not_writable_str),\n\t\t\t\t\t\t\t\t om->ocm_name);\n\t\t\t\t\treturn NULL;\n\t\t\t\t }\n\t\t\t\t break;\n\t\t\t case ACCESS_ALL:\n\t\t\t\t break;\n\t\t\t}", "\t\t\tlp->ll_valtype = om->ocm_type;", "\t\t\tif (v_type == VAR_OBJECT)\n\t\t\t lp->ll_tv = ((typval_T *)(\n\t\t\t\t\t lp->ll_tv->vval.v_object + 1)) + i;\n\t\t\telse\n\t\t\t lp->ll_tv = &cl->class_members_tv[i];\n\t\t\tbreak;\n\t\t }\n\t\t}\n\t\tif (lp->ll_valtype == NULL)\n\t\t{\n\t\t if (v_type == VAR_OBJECT)\n\t\t\tsemsg(_(e_object_member_not_found_str), key);\n\t\t else\n\t\t\tsemsg(_(e_class_member_not_found_str), key);\n\t\t return NULL;\n\t\t}\n\t }\n\t}\n }", " clear_tv(&var1);\n lp->ll_name_end = p;\n return p;\n}", "/*\n * Clear lval \"lp\" that was filled by get_lval().\n */\n void\nclear_lval(lval_T *lp)\n{\n vim_free(lp->ll_exp_name);\n vim_free(lp->ll_newkey);\n}", "/*\n * Set a variable that was parsed by get_lval() to \"rettv\".\n * \"endp\" points to just after the parsed name.\n * \"op\" is NULL, \"+\" for \"+=\", \"-\" for \"-=\", \"*\" for \"*=\", \"/\" for \"/=\",\n * \"%\" for \"%=\", \".\" for \".=\" or \"=\" for \"=\".\n */\n void\nset_var_lval(\n lval_T\t*lp,\n char_u\t*endp,\n typval_T\t*rettv,\n int\t\tcopy,\n int\t\tflags,\t // ASSIGN_CONST, ASSIGN_NO_DECL\n char_u\t*op,\n int\t\tvar_idx) // index for \"let [a, b] = list\"\n{\n int\t\tcc;\n dictitem_T\t*di;", " if (lp->ll_tv == NULL)\n {\n\tcc = *endp;\n\t*endp = NUL;\n\tif (in_vim9script() && check_reserved_name(lp->ll_name, NULL) == FAIL)\n\t return;", "\tif (lp->ll_blob != NULL)\n\t{\n\t int\t error = FALSE, val;", "\t if (op != NULL && *op != '=')\n\t {\n\t\tsemsg(_(e_wrong_variable_type_for_str_equal), op);\n\t\treturn;\n\t }\n\t if (value_check_lock(lp->ll_blob->bv_lock, lp->ll_name, FALSE))\n\t\treturn;", "\t if (lp->ll_range && rettv->v_type == VAR_BLOB)\n\t {\n\t\tif (lp->ll_empty2)\n\t\t lp->ll_n2 = blob_len(lp->ll_blob) - 1;", "\t\tif (blob_set_range(lp->ll_blob, lp->ll_n1, lp->ll_n2,\n\t\t\t\t\t\t\t\trettv) == FAIL)\n\t\t return;\n\t }\n\t else\n\t {\n\t\tval = (int)tv_get_number_chk(rettv, &error);\n\t\tif (!error)\n\t\t blob_set_append(lp->ll_blob, lp->ll_n1, val);\n\t }\n\t}\n\telse if (op != NULL && *op != '=')\n\t{\n\t typval_T tv;", "\t if ((flags & (ASSIGN_CONST | ASSIGN_FINAL))\n\t\t\t\t\t && (flags & ASSIGN_FOR_LOOP) == 0)\n\t {\n\t\temsg(_(e_cannot_modify_existing_variable));\n\t\t*endp = cc;\n\t\treturn;\n\t }", "\t // handle +=, -=, *=, /=, %= and .=\n\t di = NULL;\n\t if (eval_variable(lp->ll_name, (int)STRLEN(lp->ll_name),\n\t\t\t\t lp->ll_sid, &tv, &di, EVAL_VAR_VERBOSE) == OK)\n\t {\n\t\tif ((di == NULL\n\t\t\t || (!var_check_ro(di->di_flags, lp->ll_name, FALSE)\n\t\t\t && !tv_check_lock(&di->di_tv, lp->ll_name, FALSE)))\n\t\t\t&& tv_op(&tv, rettv, op) == OK)\n\t\t set_var_const(lp->ll_name, lp->ll_sid, NULL, &tv, FALSE,\n\t\t\t\t\t\t\t ASSIGN_NO_DECL, 0);\n\t\tclear_tv(&tv);\n\t }\n\t}\n\telse\n\t{\n\t if (lp->ll_type != NULL && check_typval_arg_type(lp->ll_type, rettv,\n\t\t\t\t\t\t\t NULL, 0) == FAIL)\n\t\treturn;\n\t set_var_const(lp->ll_name, lp->ll_sid, lp->ll_type, rettv, copy,\n\t\t\t\t\t\t\t flags, var_idx);\n\t}\n\t*endp = cc;\n }\n else if (value_check_lock(lp->ll_newkey == NULL\n\t\t? lp->ll_tv->v_lock\n\t\t: lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name, FALSE))\n\t;\n else if (lp->ll_range)\n {\n\tif ((flags & (ASSIGN_CONST | ASSIGN_FINAL))\n\t\t\t\t\t && (flags & ASSIGN_FOR_LOOP) == 0)\n\t{\n\t emsg(_(e_cannot_lock_range));\n\t return;\n\t}", "\t(void)list_assign_range(lp->ll_list, rettv->vval.v_list,\n\t\t\t lp->ll_n1, lp->ll_n2, lp->ll_empty2, op, lp->ll_name);\n }\n else\n {\n\t/*\n\t * Assign to a List, Dictionary or Object item.\n\t */\n\tif ((flags & (ASSIGN_CONST | ASSIGN_FINAL))\n\t\t\t\t\t && (flags & ASSIGN_FOR_LOOP) == 0)\n\t{\n\t emsg(_(e_cannot_lock_list_or_dict));\n\t return;\n\t}", "\tif (lp->ll_valtype != NULL\n\t\t && check_typval_arg_type(lp->ll_valtype, rettv,\n\t\t\t\t\t\t\t NULL, 0) == FAIL)\n\t return;", "\tif (lp->ll_newkey != NULL)\n\t{\n\t if (op != NULL && *op != '=')\n\t {\n\t\tsemsg(_(e_key_not_present_in_dictionary_str), lp->ll_newkey);\n\t\treturn;\n\t }\n\t if (dict_wrong_func_name(lp->ll_tv->vval.v_dict, rettv,\n\t\t\t\t\t\t\t\tlp->ll_newkey))\n\t\treturn;", "\t // Need to add an item to the Dictionary.\n\t di = dictitem_alloc(lp->ll_newkey);\n\t if (di == NULL)\n\t\treturn;\n\t if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)\n\t {\n\t\tvim_free(di);\n\t\treturn;\n\t }\n\t lp->ll_tv = &di->di_tv;\n\t}\n\telse if (op != NULL && *op != '=')\n\t{\n\t tv_op(lp->ll_tv, rettv, op);\n\t return;\n\t}\n\telse\n\t clear_tv(lp->ll_tv);", "\t/*\n\t * Assign the value to the variable or list item.\n\t */\n\tif (copy)\n\t copy_tv(rettv, lp->ll_tv);\n\telse\n\t{\n\t *lp->ll_tv = *rettv;\n\t lp->ll_tv->v_lock = 0;\n\t init_tv(rettv);\n\t}\n }\n}", "/*\n * Handle \"tv1 += tv2\", \"tv1 -= tv2\", \"tv1 *= tv2\", \"tv1 /= tv2\", \"tv1 %= tv2\"\n * and \"tv1 .= tv2\"\n * Returns OK or FAIL.\n */\n int\ntv_op(typval_T *tv1, typval_T *tv2, char_u *op)\n{\n varnumber_T\tn;\n char_u\tnumbuf[NUMBUFLEN];\n char_u\t*s;\n int\t\tfailed = FALSE;", " // Can't do anything with a Funcref or Dict on the right.\n // v:true and friends only work with \"..=\".\n if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT\n\t\t && ((tv2->v_type != VAR_BOOL && tv2->v_type != VAR_SPECIAL)\n\t\t\t\t\t\t\t\t|| *op == '.'))\n {\n\tswitch (tv1->v_type)\n\t{\n\t case VAR_UNKNOWN:\n\t case VAR_ANY:\n\t case VAR_VOID:\n\t case VAR_DICT:\n\t case VAR_FUNC:\n\t case VAR_PARTIAL:\n\t case VAR_BOOL:\n\t case VAR_SPECIAL:\n\t case VAR_JOB:\n\t case VAR_CHANNEL:\n\t case VAR_INSTR:\n\t case VAR_CLASS:\n\t case VAR_OBJECT:\n\t\tbreak;", "\t case VAR_BLOB:\n\t\tif (*op != '+' || tv2->v_type != VAR_BLOB)\n\t\t break;\n\t\t// BLOB += BLOB\n\t\tif (tv1->vval.v_blob != NULL && tv2->vval.v_blob != NULL)\n\t\t{\n\t\t blob_T *b1 = tv1->vval.v_blob;\n\t\t blob_T *b2 = tv2->vval.v_blob;\n\t\t int\ti, len = blob_len(b2);\n\t\t for (i = 0; i < len; i++)\n\t\t\tga_append(&b1->bv_ga, blob_get(b2, i));\n\t\t}\n\t\treturn OK;", "\t case VAR_LIST:\n\t\tif (*op != '+' || tv2->v_type != VAR_LIST)\n\t\t break;\n\t\t// List += List\n\t\tif (tv2->vval.v_list != NULL)\n\t\t{\n\t\t if (tv1->vval.v_list == NULL)\n\t\t {\n\t\t\ttv1->vval.v_list = tv2->vval.v_list;\n\t\t\t++tv1->vval.v_list->lv_refcount;\n\t\t }\n\t\t else\n\t\t\tlist_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);\n\t\t}\n\t\treturn OK;", "\t case VAR_NUMBER:\n\t case VAR_STRING:\n\t\tif (tv2->v_type == VAR_LIST)\n\t\t break;\n\t\tif (vim_strchr((char_u *)\"+-*/%\", *op) != NULL)\n\t\t{\n\t\t // nr += nr , nr -= nr , nr *=nr , nr /= nr , nr %= nr\n\t\t n = tv_get_number(tv1);\n\t\t if (tv2->v_type == VAR_FLOAT)\n\t\t {\n\t\t\tfloat_T f = n;", "\t\t\tif (*op == '%')\n\t\t\t break;\n\t\t\tswitch (*op)\n\t\t\t{\n\t\t\t case '+': f += tv2->vval.v_float; break;\n\t\t\t case '-': f -= tv2->vval.v_float; break;\n\t\t\t case '*': f *= tv2->vval.v_float; break;\n\t\t\t case '/': f /= tv2->vval.v_float; break;\n\t\t\t}\n\t\t\tclear_tv(tv1);\n\t\t\ttv1->v_type = VAR_FLOAT;\n\t\t\ttv1->vval.v_float = f;\n\t\t }\n\t\t else\n\t\t {\n\t\t\tswitch (*op)\n\t\t\t{\n\t\t\t case '+': n += tv_get_number(tv2); break;\n\t\t\t case '-': n -= tv_get_number(tv2); break;\n\t\t\t case '*': n *= tv_get_number(tv2); break;\n\t\t\t case '/': n = num_divide(n, tv_get_number(tv2),\n\t\t\t\t\t\t\t &failed); break;\n\t\t\t case '%': n = num_modulus(n, tv_get_number(tv2),\n\t\t\t\t\t\t\t &failed); break;\n\t\t\t}\n\t\t\tclear_tv(tv1);\n\t\t\ttv1->v_type = VAR_NUMBER;\n\t\t\ttv1->vval.v_number = n;\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t\t if (tv2->v_type == VAR_FLOAT)\n\t\t\tbreak;", "\t\t // str .= str\n\t\t s = tv_get_string(tv1);\n\t\t s = concat_str(s, tv_get_string_buf(tv2, numbuf));\n\t\t clear_tv(tv1);\n\t\t tv1->v_type = VAR_STRING;\n\t\t tv1->vval.v_string = s;\n\t\t}\n\t\treturn failed ? FAIL : OK;", "\t case VAR_FLOAT:\n\t\t{\n\t\t float_T f;", "\t\t if (*op == '%' || *op == '.'\n\t\t\t\t || (tv2->v_type != VAR_FLOAT\n\t\t\t\t && tv2->v_type != VAR_NUMBER\n\t\t\t\t && tv2->v_type != VAR_STRING))\n\t\t\tbreak;\n\t\t if (tv2->v_type == VAR_FLOAT)\n\t\t\tf = tv2->vval.v_float;\n\t\t else\n\t\t\tf = tv_get_number(tv2);\n\t\t switch (*op)\n\t\t {\n\t\t\tcase '+': tv1->vval.v_float += f; break;\n\t\t\tcase '-': tv1->vval.v_float -= f; break;\n\t\t\tcase '*': tv1->vval.v_float *= f; break;\n\t\t\tcase '/': tv1->vval.v_float /= f; break;\n\t\t }\n\t\t}\n\t\treturn OK;\n\t}\n }", " semsg(_(e_wrong_variable_type_for_str_equal), op);\n return FAIL;\n}", "/*\n * Evaluate the expression used in a \":for var in expr\" command.\n * \"arg\" points to \"var\".\n * Set \"*errp\" to TRUE for an error, FALSE otherwise;\n * Return a pointer that holds the info. Null when there is an error.\n */\n void *\neval_for_line(\n char_u\t*arg,\n int\t\t*errp,\n exarg_T\t*eap,\n evalarg_T\t*evalarg)\n{\n forinfo_T\t*fi;\n char_u\t*var_list_end;\n char_u\t*expr;\n typval_T\ttv;\n list_T\t*l;\n int\t\tskip = !(evalarg->eval_flags & EVAL_EVALUATE);", " *errp = TRUE;\t// default: there is an error", " fi = ALLOC_CLEAR_ONE(forinfo_T);\n if (fi == NULL)\n\treturn NULL;", " var_list_end = skip_var_list(arg, TRUE, &fi->fi_varcount,\n\t\t\t\t\t\t &fi->fi_semicolon, FALSE);\n if (var_list_end == NULL)\n\treturn fi;", " expr = skipwhite_and_linebreak(var_list_end, evalarg);\n if (expr[0] != 'i' || expr[1] != 'n'\n\t\t\t\t || !(expr[2] == NUL || VIM_ISWHITE(expr[2])))\n {\n\tif (in_vim9script() && *expr == ':' && expr != var_list_end)\n\t semsg(_(e_no_white_space_allowed_before_colon_str), expr);\n\telse\n\t emsg(_(e_missing_in_after_for));\n\treturn fi;\n }", " if (skip)\n\t++emsg_skip;\n expr = skipwhite_and_linebreak(expr + 2, evalarg);\n if (eval0(expr, &tv, eap, evalarg) == OK)\n {\n\t*errp = FALSE;\n\tif (!skip)\n\t{\n\t if (tv.v_type == VAR_LIST)\n\t {\n\t\tl = tv.vval.v_list;\n\t\tif (l == NULL)\n\t\t{\n\t\t // a null list is like an empty list: do nothing\n\t\t clear_tv(&tv);\n\t\t}\n\t\telse\n\t\t{\n\t\t // Need a real list here.\n\t\t CHECK_LIST_MATERIALIZE(l);", "\t\t // No need to increment the refcount, it's already set for\n\t\t // the list being used in \"tv\".\n\t\t fi->fi_list = l;\n\t\t list_add_watch(l, &fi->fi_lw);\n\t\t fi->fi_lw.lw_item = l->lv_first;\n\t\t}\n\t }\n\t else if (tv.v_type == VAR_BLOB)\n\t {\n\t\tfi->fi_bi = 0;\n\t\tif (tv.vval.v_blob != NULL)\n\t\t{\n\t\t typval_T btv;", "\t\t // Make a copy, so that the iteration still works when the\n\t\t // blob is changed.\n\t\t blob_copy(tv.vval.v_blob, &btv);\n\t\t fi->fi_blob = btv.vval.v_blob;\n\t\t}\n\t\tclear_tv(&tv);\n\t }\n\t else if (tv.v_type == VAR_STRING)\n\t {\n\t\tfi->fi_byte_idx = 0;\n\t\tfi->fi_string = tv.vval.v_string;\n\t\ttv.vval.v_string = NULL;\n\t\tif (fi->fi_string == NULL)\n\t\t fi->fi_string = vim_strsave((char_u *)\"\");\n\t }\n\t else\n\t {\n\t\temsg(_(e_string_list_or_blob_required));\n\t\tclear_tv(&tv);\n\t }\n\t}\n }\n if (skip)\n\t--emsg_skip;\n fi->fi_break_count = evalarg->eval_break_count;", " return fi;\n}", "/*\n * Used when looping over a :for line, skip the \"in expr\" part.\n */\n void\nskip_for_lines(void *fi_void, evalarg_T *evalarg)\n{\n forinfo_T\t*fi = (forinfo_T *)fi_void;\n int\t\ti;", " for (i = 0; i < fi->fi_break_count; ++i)\n\teval_next_line(NULL, evalarg);\n}", "/*\n * Use the first item in a \":for\" list. Advance to the next.\n * Assign the values to the variable (list). \"arg\" points to the first one.\n * Return TRUE when a valid item was found, FALSE when at end of list or\n * something wrong.\n */\n int\nnext_for_item(void *fi_void, char_u *arg)\n{\n forinfo_T\t*fi = (forinfo_T *)fi_void;\n int\t\tresult;\n int\t\tflag = ASSIGN_FOR_LOOP | (in_vim9script()\n\t\t\t ? (ASSIGN_FINAL\n\t\t\t // first round: error if variable exists\n\t\t\t | (fi->fi_bi == 0 ? 0 : ASSIGN_DECL)\n\t\t\t | ASSIGN_NO_MEMBER_TYPE\n\t\t\t | ASSIGN_UPDATE_BLOCK_ID)\n\t\t\t : 0);\n listitem_T\t*item;\n int\t\tskip_assign = in_vim9script() && arg[0] == '_'\n\t\t\t\t\t\t && !eval_isnamec(arg[1]);", " if (fi->fi_blob != NULL)\n {\n\ttypval_T\ttv;", "\tif (fi->fi_bi >= blob_len(fi->fi_blob))\n\t return FALSE;\n\ttv.v_type = VAR_NUMBER;\n\ttv.v_lock = VAR_FIXED;\n\ttv.vval.v_number = blob_get(fi->fi_blob, fi->fi_bi);\n\t++fi->fi_bi;\n\tif (skip_assign)\n\t return TRUE;\n\treturn ex_let_vars(arg, &tv, TRUE, fi->fi_semicolon,\n\t\t\t\t\t fi->fi_varcount, flag, NULL) == OK;\n }", " if (fi->fi_string != NULL)\n {\n\ttypval_T\ttv;\n\tint\t\tlen;", "\tlen = mb_ptr2len(fi->fi_string + fi->fi_byte_idx);\n\tif (len == 0)\n\t return FALSE;\n\ttv.v_type = VAR_STRING;\n\ttv.v_lock = VAR_FIXED;\n\ttv.vval.v_string = vim_strnsave(fi->fi_string + fi->fi_byte_idx, len);\n\tfi->fi_byte_idx += len;\n\t++fi->fi_bi;\n\tif (skip_assign)\n\t result = TRUE;\n\telse\n\t result = ex_let_vars(arg, &tv, TRUE, fi->fi_semicolon,\n\t\t\t\t\t fi->fi_varcount, flag, NULL) == OK;\n\tvim_free(tv.vval.v_string);\n\treturn result;\n }", " item = fi->fi_lw.lw_item;\n if (item == NULL)\n\tresult = FALSE;\n else\n {\n\tfi->fi_lw.lw_item = item->li_next;\n\t++fi->fi_bi;\n\tif (skip_assign)\n\t result = TRUE;\n\telse\n\t result = (ex_let_vars(arg, &item->li_tv, TRUE, fi->fi_semicolon,\n\t\t\t\t\t fi->fi_varcount, flag, NULL) == OK);\n }\n return result;\n}", "/*\n * Free the structure used to store info used by \":for\".\n */\n void\nfree_for_info(void *fi_void)\n{\n forinfo_T *fi = (forinfo_T *)fi_void;", " if (fi == NULL)\n\treturn;\n if (fi->fi_list != NULL)\n {\n\tlist_rem_watch(fi->fi_list, &fi->fi_lw);\n\tlist_unref(fi->fi_list);\n }\n else if (fi->fi_blob != NULL)\n\tblob_unref(fi->fi_blob);\n else\n\tvim_free(fi->fi_string);\n vim_free(fi);\n}", " void\nset_context_for_expression(\n expand_T\t*xp,\n char_u\t*arg,\n cmdidx_T\tcmdidx)\n{\n int\t\thas_expr = cmdidx != CMD_let && cmdidx != CMD_var;\n int\t\tc;\n char_u\t*p;", " if (cmdidx == CMD_let || cmdidx == CMD_var\n\t\t\t\t || cmdidx == CMD_const || cmdidx == CMD_final)\n {\n\txp->xp_context = EXPAND_USER_VARS;\n\tif (vim_strpbrk(arg, (char_u *)\"\\\"'+-*/%.=!?~|&$([<>,#\") == NULL)\n\t{\n\t // \":let var1 var2 ...\": find last space.\n\t for (p = arg + STRLEN(arg); p >= arg; )\n\t {\n\t\txp->xp_pattern = p;\n\t\tMB_PTR_BACK(arg, p);\n\t\tif (VIM_ISWHITE(*p))\n\t\t break;\n\t }\n\t return;\n\t}\n }\n else\n\txp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS\n\t\t\t\t\t\t\t : EXPAND_EXPRESSION;\n while ((xp->xp_pattern = vim_strpbrk(arg,\n\t\t\t\t (char_u *)\"\\\"'+-*/%.=!?~|&$([<>,#\")) != NULL)\n {\n\tc = *xp->xp_pattern;\n\tif (c == '&')\n\t{\n\t c = xp->xp_pattern[1];\n\t if (c == '&')\n\t {\n\t\t++xp->xp_pattern;\n\t\txp->xp_context = has_expr ? EXPAND_EXPRESSION : EXPAND_NOTHING;\n\t }\n\t else if (c != ' ')\n\t {\n\t\txp->xp_context = EXPAND_SETTINGS;\n\t\tif ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')\n\t\t xp->xp_pattern += 2;", "\t }\n\t}\n\telse if (c == '$')\n\t{\n\t // environment variable\n\t xp->xp_context = EXPAND_ENV_VARS;\n\t}\n\telse if (c == '=')\n\t{\n\t has_expr = TRUE;\n\t xp->xp_context = EXPAND_EXPRESSION;\n\t}\n\telse if (c == '#'\n\t\t&& xp->xp_context == EXPAND_EXPRESSION)\n\t{\n\t // Autoload function/variable contains '#'.\n\t break;\n\t}\n\telse if ((c == '<' || c == '#')\n\t\t&& xp->xp_context == EXPAND_FUNCTIONS\n\t\t&& vim_strchr(xp->xp_pattern, '(') == NULL)\n\t{\n\t // Function name can start with \"<SNR>\" and contain '#'.\n\t break;\n\t}\n\telse if (has_expr)\n\t{\n\t if (c == '\"')\t // string\n\t {\n\t\twhile ((c = *++xp->xp_pattern) != NUL && c != '\"')\n\t\t if (c == '\\\\' && xp->xp_pattern[1] != NUL)\n\t\t\t++xp->xp_pattern;\n\t\txp->xp_context = EXPAND_NOTHING;\n\t }\n\t else if (c == '\\'')\t // literal string\n\t {\n\t\t// Trick: '' is like stopping and starting a literal string.\n\t\twhile ((c = *++xp->xp_pattern) != NUL && c != '\\'')\n\t\t /* skip */ ;\n\t\txp->xp_context = EXPAND_NOTHING;\n\t }\n\t else if (c == '|')\n\t {\n\t\tif (xp->xp_pattern[1] == '|')\n\t\t{\n\t\t ++xp->xp_pattern;\n\t\t xp->xp_context = EXPAND_EXPRESSION;\n\t\t}\n\t\telse\n\t\t xp->xp_context = EXPAND_COMMANDS;\n\t }\n\t else\n\t\txp->xp_context = EXPAND_EXPRESSION;\n\t}\n\telse\n\t // Doesn't look like something valid, expand as an expression\n\t // anyway.\n\t xp->xp_context = EXPAND_EXPRESSION;\n\targ = xp->xp_pattern;\n\tif (*arg != NUL)\n\t while ((c = *++arg) != NUL && (c == ' ' || c == '\\t'))\n\t\t/* skip */ ;\n }", " // \":exe one two\" completes \"two\"\n if ((cmdidx == CMD_execute\n\t\t|| cmdidx == CMD_echo\n\t\t|| cmdidx == CMD_echon\n\t\t|| cmdidx == CMD_echomsg\n\t\t|| cmdidx == CMD_echowindow)\n\t && xp->xp_context == EXPAND_EXPRESSION)\n {\n\tfor (;;)\n\t{\n\t char_u *n = skiptowhite(arg);", "\t if (n == arg || IS_WHITE_OR_NUL(*skipwhite(n)))\n\t\tbreak;\n\t arg = skipwhite(n);\n\t}\n }", " xp->xp_pattern = arg;\n}", "/*\n * Return TRUE if \"pat\" matches \"text\".\n * Does not use 'cpo' and always uses 'magic'.\n */\n int\npattern_match(char_u *pat, char_u *text, int ic)\n{\n int\t\tmatches = FALSE;\n char_u\t*save_cpo;\n regmatch_T\tregmatch;", " // avoid 'l' flag in 'cpoptions'\n save_cpo = p_cpo;\n p_cpo = empty_option;\n regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);\n if (regmatch.regprog != NULL)\n {\n\tregmatch.rm_ic = ic;\n\tmatches = vim_regexec_nl(&regmatch, text, (colnr_T)0);\n\tvim_regfree(regmatch.regprog);\n }\n p_cpo = save_cpo;\n return matches;\n}", "/*\n * Handle a name followed by \"(\". Both for just \"name(arg)\" and for\n * \"expr->name(arg)\".\n * Returns OK or FAIL.\n */\n static int\neval_func(\n\tchar_u\t **arg,\t// points to \"(\", will be advanced\n\tevalarg_T *evalarg,\n\tchar_u\t *name,\n\tint\t name_len,\n\ttypval_T *rettv,\n\tint\t flags,\n\ttypval_T *basetv)\t// \"expr\" for \"expr->name(arg)\"\n{\n int\t\tevaluate = flags & EVAL_EVALUATE;\n char_u\t*s = name;\n int\t\tlen = name_len;\n partial_T\t*partial;\n int\t\tret = OK;\n type_T\t*type = NULL;\n int\t\tfound_var = FALSE;", " if (!evaluate)\n\tcheck_vars(s, len);", " // If \"s\" is the name of a variable of type VAR_FUNC\n // use its contents.\n s = deref_func_name(s, &len, &partial,\n\t\t in_vim9script() ? &type : NULL, !evaluate, FALSE, &found_var);", " // Need to make a copy, in case evaluating the arguments makes\n // the name invalid.\n s = vim_strsave(s);\n if (s == NULL || (evaluate && (*s == NUL || (flags & EVAL_CONSTANT))))\n\tret = FAIL;\n else\n {\n\tfuncexe_T funcexe;", "\t// Invoke the function.\n\tCLEAR_FIELD(funcexe);\n\tfuncexe.fe_firstline = curwin->w_cursor.lnum;\n\tfuncexe.fe_lastline = curwin->w_cursor.lnum;\n\tfuncexe.fe_evaluate = evaluate;\n\tfuncexe.fe_partial = partial;\n\tfuncexe.fe_basetv = basetv;\n\tfuncexe.fe_check_type = type;\n\tfuncexe.fe_found_var = found_var;\n\tret = get_func_tv(s, len, rettv, arg, evalarg, &funcexe);\n }\n vim_free(s);", " // If evaluate is FALSE rettv->v_type was not set in\n // get_func_tv, but it's needed in handle_subscript() to parse\n // what follows. So set it here.\n if (rettv->v_type == VAR_UNKNOWN && !evaluate && **arg == '(')\n {\n\trettv->vval.v_string = NULL;\n\trettv->v_type = VAR_FUNC;\n }", " // Stop the expression evaluation when immediately\n // aborting on error, or when an interrupt occurred or\n // an exception was thrown but not caught.\n if (evaluate && aborting())\n {\n\tif (ret == OK)\n\t clear_tv(rettv);\n\tret = FAIL;\n }\n return ret;\n}", "/*\n * After a NL, skip over empty lines and comment-only lines.\n */\n static char_u *\nnewline_skip_comments(char_u *arg)\n{\n char_u *p = arg + 1;", " for (;;)\n {\n\tp = skipwhite(p);", "\tif (*p == NUL)\n\t break;\n\tif (vim9_comment_start(p))\n\t{\n\t char_u *nl = vim_strchr(p, NL);", "\t if (nl == NULL)\n\t\t break;\n\t p = nl;\n\t}\n\tif (*p != NL)\n\t break;\n\t++p; // skip another NL\n }\n return p;\n}", "/*\n * Get the next line source line without advancing. But do skip over comment\n * lines.\n * Only called for Vim9 script.\n */\n static char_u *\ngetline_peek_skip_comments(evalarg_T *evalarg)\n{\n for (;;)\n {\n\tchar_u *next = getline_peek(evalarg->eval_getline,\n\t\t\t\t\t\t\t evalarg->eval_cookie);\n\tchar_u *p;", "\tif (next == NULL)\n\t break;\n\tp = skipwhite(next);\n\tif (*p != NUL && !vim9_comment_start(p))\n\t return next;\n\tif (eval_next_line(NULL, evalarg) == NULL)\n\t break;\n }\n return NULL;\n}", "/*\n * If inside Vim9 script, \"arg\" points to the end of a line (ignoring a #\n * comment) and there is a next line, return the next line (skipping blanks)\n * and set \"getnext\".\n * Otherwise return the next non-white at or after \"arg\" and set \"getnext\" to\n * FALSE.\n * \"arg\" must point somewhere inside a line, not at the start.\n */\n char_u *\neval_next_non_blank(char_u *arg, evalarg_T *evalarg, int *getnext)\n{\n char_u *p = skipwhite(arg);", " *getnext = FALSE;\n if (in_vim9script()\n\t && evalarg != NULL\n\t && (evalarg->eval_cookie != NULL || evalarg->eval_cctx != NULL\n\t\t\t\t\t\t\t\t || *p == NL)\n\t && (*p == NUL || *p == NL\n\t\t\t || (vim9_comment_start(p) && VIM_ISWHITE(p[-1]))))\n {\n\tchar_u *next;", "\tif (*p == NL)\n\t next = newline_skip_comments(p);\n\telse if (evalarg->eval_cookie != NULL)\n\t next = getline_peek_skip_comments(evalarg);\n\telse\n\t next = peek_next_line_from_context(evalarg->eval_cctx);", "\tif (next != NULL)\n\t{\n\t *getnext = *p != NL;\n\t return skipwhite(next);\n\t}\n }\n return p;\n}", "/*\n * To be called after eval_next_non_blank() sets \"getnext\" to TRUE.\n * Only called for Vim9 script.\n */\n char_u *\neval_next_line(char_u *arg, evalarg_T *evalarg)\n{\n garray_T\t*gap = &evalarg->eval_ga;\n char_u\t*line;", " if (arg != NULL)\n {\n\tif (*arg == NL)\n\t return newline_skip_comments(arg);\n\t// Truncate before a trailing comment, so that concatenating the lines\n\t// won't turn the rest into a comment.\n\tif (*skipwhite(arg) == '#')\n\t *arg = NUL;\n }", " if (evalarg->eval_cookie != NULL)\n\tline = evalarg->eval_getline(0, evalarg->eval_cookie, 0,\n\t\t\t\t\t\t\t GETLINE_CONCAT_ALL);\n else\n\tline = next_line_from_context(evalarg->eval_cctx, TRUE);\n if (line == NULL)\n\treturn NULL;", " ++evalarg->eval_break_count;\n if (gap->ga_itemsize > 0 && ga_grow(gap, 1) == OK)\n {\n\tchar_u *p = skipwhite(line);", "\t// Going to concatenate the lines after parsing. For an empty or\n\t// comment line use an empty string.\n\tif (*p == NUL || vim9_comment_start(p))\n\t{\n\t vim_free(line);\n\t line = vim_strsave((char_u *)\"\");\n\t}", "\t((char_u **)gap->ga_data)[gap->ga_len] = line;\n\t++gap->ga_len;\n }\n else if (evalarg->eval_cookie != NULL)\n {\n\tfree_eval_tofree_later(evalarg);\n\tevalarg->eval_tofree = line;\n }", " // Advanced to the next line, \"arg\" no longer points into the previous\n // line.\n evalarg->eval_using_cmdline = FALSE;\n return skipwhite(line);\n}", "/*\n * Call eval_next_non_blank() and get the next line if needed.\n */\n char_u *\nskipwhite_and_linebreak(char_u *arg, evalarg_T *evalarg)\n{\n int\t getnext;\n char_u *p = skipwhite_and_nl(arg);", " if (evalarg == NULL)\n\treturn skipwhite(arg);\n eval_next_non_blank(p, evalarg, &getnext);\n if (getnext)\n\treturn eval_next_line(arg, evalarg);\n return p;\n}", "/*\n * The \"eval\" functions have an \"evalarg\" argument: When NULL or\n * \"evalarg->eval_flags\" does not have EVAL_EVALUATE, then the argument is only\n * parsed but not executed. The functions may return OK, but the rettv will be\n * of type VAR_UNKNOWN. The functions still returns FAIL for a syntax error.\n */", "/*\n * Handle zero level expression.\n * This calls eval1() and handles error message and nextcmd.\n * Put the result in \"rettv\" when returning OK and \"evaluate\" is TRUE.\n * Note: \"rettv.v_lock\" is not set.\n * \"evalarg\" can be NULL, EVALARG_EVALUATE or a pointer.\n * Return OK or FAIL.\n */\n int\neval0(\n char_u\t*arg,\n typval_T\t*rettv,\n exarg_T\t*eap,\n evalarg_T\t*evalarg)\n{\n return eval0_retarg(arg, rettv, eap, evalarg, NULL);\n}", "/*\n * If \"arg\" is a simple function call without arguments then call it and return\n * the result. Otherwise return NOTDONE.\n */\n int\nmay_call_simple_func(\n char_u\t*arg,\n typval_T\t*rettv)\n{\n char_u *parens = (char_u *)strstr((char *)arg, \"()\");\n int\t r = NOTDONE;", " // If the expression is \"FuncName()\" then we can skip a lot of overhead.\n if (parens != NULL && *skipwhite(parens + 2) == NUL)\n {\n\tchar_u *p = STRNCMP(arg, \"<SNR>\", 5) == 0 ? skipdigits(arg + 5) : arg;", "\tif (to_name_end(p, TRUE) == parens)\n\t r = call_simple_func(arg, (int)(parens - arg), rettv);\n }\n return r;\n}", "/*\n * Handle zero level expression with optimization for a simple function call.\n * Same arguments and return value as eval0().\n */\n int\neval0_simple_funccal(\n char_u\t*arg,\n typval_T\t*rettv,\n exarg_T\t*eap,\n evalarg_T\t*evalarg)\n{\n int\t r = may_call_simple_func(arg, rettv);", " if (r == NOTDONE)\n\tr = eval0_retarg(arg, rettv, eap, evalarg, NULL);\n return r;\n}", "/*\n * Like eval0() but when \"retarg\" is not NULL store the pointer to after the\n * expression and don't check what comes after the expression.\n */\n int\neval0_retarg(\n char_u\t*arg,\n typval_T\t*rettv,\n exarg_T\t*eap,\n evalarg_T\t*evalarg,\n char_u\t**retarg)\n{\n int\t\tret;\n char_u\t*p;\n char_u\t*expr_end;\n int\t\tdid_emsg_before = did_emsg;\n int\t\tcalled_emsg_before = called_emsg;\n int\t\tflags = evalarg == NULL ? 0 : evalarg->eval_flags;\n int\t\tcheck_for_end = retarg == NULL;\n int\t\tend_error = FALSE;", " p = skipwhite(arg);\n ret = eval1(&p, rettv, evalarg);", " if (ret != FAIL)\n {\n\texpr_end = p;\n\tp = skipwhite(p);", "\t// In Vim9 script a command block is not split at NL characters for\n\t// commands using an expression argument. Skip over a '#' comment to\n\t// check for a following NL. Require white space before the '#'.\n\tif (in_vim9script() && p > expr_end && retarg == NULL)\n\t while (*p == '#')\n\t {\n\t\tchar_u *nl = vim_strchr(p, NL);", "\t\tif (nl == NULL)\n\t\t break;\n\t\tp = skipwhite(nl + 1);\n\t\tif (eap != NULL && *p != NUL)\n\t\t eap->nextcmd = p;\n\t\tcheck_for_end = FALSE;\n\t }", "\tif (check_for_end)\n\t end_error = !ends_excmd2(arg, p);\n }", " if (ret == FAIL || end_error)\n {\n\tif (ret != FAIL)\n\t clear_tv(rettv);\n\t/*\n\t * Report the invalid expression unless the expression evaluation has\n\t * been cancelled due to an aborting error, an interrupt, or an\n\t * exception, or we already gave a more specific error.\n\t * Also check called_emsg for when using assert_fails().\n\t */\n\tif (!aborting()\n\t\t&& did_emsg == did_emsg_before\n\t\t&& called_emsg == called_emsg_before\n\t\t&& (flags & EVAL_CONSTANT) == 0\n\t\t&& (!in_vim9script() || !vim9_bad_comment(p)))\n\t{\n\t if (end_error)\n\t\tsemsg(_(e_trailing_characters_str), p);\n\t else\n\t\tsemsg(_(e_invalid_expression_str), arg);\n\t}", "\t// Some of the expression may not have been consumed. Do not check for\n\t// a next command to avoid more errors, unless \"|\" is following, which\n\t// could only be a command separator.\n\tif (eap != NULL && p != NULL\n\t\t\t && skipwhite(p)[0] == '|' && skipwhite(p)[1] != '|')\n\t eap->nextcmd = check_nextcmd(p);\n\treturn FAIL;\n }", " if (retarg != NULL)\n\t*retarg = p;\n else if (check_for_end && eap != NULL)\n\tset_nextcmd(eap, p);", " return ret;\n}", "/*\n * Handle top level expression:\n *\texpr2 ? expr1 : expr1\n *\texpr2 ?? expr1\n *\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n *\n * Note: \"rettv.v_lock\" is not set.\n *\n * Return OK or FAIL.\n */\n int\neval1(char_u **arg, typval_T *rettv, evalarg_T *evalarg)\n{\n char_u *p;\n int\t getnext;", " CLEAR_POINTER(rettv);", " /*\n * Get the first variable.\n */\n if (eval2(arg, rettv, evalarg) == FAIL)\n\treturn FAIL;", " p = eval_next_non_blank(*arg, evalarg, &getnext);\n if (*p == '?')\n {\n\tint\t\top_falsy = p[1] == '?';\n\tint\t\tresult;\n\ttypval_T\tvar2;\n\tevalarg_T\t*evalarg_used = evalarg;\n\tevalarg_T\tlocal_evalarg;\n\tint\t\torig_flags;\n\tint\t\tevaluate;\n\tint\t\tvim9script = in_vim9script();", "\tif (evalarg == NULL)\n\t{\n\t init_evalarg(&local_evalarg);\n\t evalarg_used = &local_evalarg;\n\t}\n\torig_flags = evalarg_used->eval_flags;\n\tevaluate = evalarg_used->eval_flags & EVAL_EVALUATE;", "\tif (getnext)\n\t *arg = eval_next_line(*arg, evalarg_used);\n\telse\n\t{\n\t if (evaluate && vim9script && !VIM_ISWHITE(p[-1]))\n\t {\n\t\terror_white_both(p, op_falsy ? 2 : 1);\n\t\tclear_tv(rettv);\n\t\treturn FAIL;\n\t }\n\t *arg = p;\n\t}", "\tresult = FALSE;\n\tif (evaluate)\n\t{\n\t int\t\terror = FALSE;", "\t if (op_falsy)\n\t\tresult = tv2bool(rettv);\n\t else if (vim9script)\n\t\tresult = tv_get_bool_chk(rettv, &error);\n\t else if (tv_get_number_chk(rettv, &error) != 0)\n\t\tresult = TRUE;\n\t if (error || !op_falsy || !result)\n\t\tclear_tv(rettv);\n\t if (error)\n\t\treturn FAIL;\n\t}", "\t/*\n\t * Get the second variable. Recursive!\n\t */\n\tif (op_falsy)\n\t ++*arg;\n\tif (evaluate && vim9script && !IS_WHITE_OR_NUL((*arg)[1]))\n\t{\n\t error_white_both(*arg - (op_falsy ? 1 : 0), op_falsy ? 2 : 1);\n\t clear_tv(rettv);\n\t return FAIL;\n\t}\n\t*arg = skipwhite_and_linebreak(*arg + 1, evalarg_used);\n\tevalarg_used->eval_flags = (op_falsy ? !result : result)\n\t\t\t\t ? orig_flags : orig_flags & ~EVAL_EVALUATE;\n\tif (eval1(arg, &var2, evalarg_used) == FAIL)\n\t{\n\t evalarg_used->eval_flags = orig_flags;\n\t return FAIL;\n\t}\n\tif (!op_falsy || !result)\n\t *rettv = var2;", "\tif (!op_falsy)\n\t{\n\t /*\n\t * Check for the \":\".\n\t */\n\t p = eval_next_non_blank(*arg, evalarg_used, &getnext);\n\t if (*p != ':')\n\t {\n\t\temsg(_(e_missing_colon_after_questionmark));\n\t\tif (evaluate && result)\n\t\t clear_tv(rettv);\n\t\tevalarg_used->eval_flags = orig_flags;\n\t\treturn FAIL;\n\t }\n\t if (getnext)\n\t\t*arg = eval_next_line(*arg, evalarg_used);\n\t else\n\t {\n\t\tif (evaluate && vim9script && !VIM_ISWHITE(p[-1]))\n\t\t{\n\t\t error_white_both(p, 1);\n\t\t clear_tv(rettv);\n\t\t evalarg_used->eval_flags = orig_flags;\n\t\t return FAIL;\n\t\t}\n\t\t*arg = p;\n\t }", "\t /*\n\t * Get the third variable. Recursive!\n\t */\n\t if (evaluate && vim9script && !IS_WHITE_OR_NUL((*arg)[1]))\n\t {\n\t\terror_white_both(*arg, 1);\n\t\tclear_tv(rettv);\n\t\tevalarg_used->eval_flags = orig_flags;\n\t\treturn FAIL;\n\t }\n\t *arg = skipwhite_and_linebreak(*arg + 1, evalarg_used);\n\t evalarg_used->eval_flags = !result ? orig_flags\n\t\t\t\t\t\t : orig_flags & ~EVAL_EVALUATE;\n\t if (eval1(arg, &var2, evalarg_used) == FAIL)\n\t {\n\t\tif (evaluate && result)\n\t\t clear_tv(rettv);\n\t\tevalarg_used->eval_flags = orig_flags;\n\t\treturn FAIL;\n\t }\n\t if (evaluate && !result)\n\t\t*rettv = var2;\n\t}", "\tif (evalarg == NULL)\n\t clear_evalarg(&local_evalarg, NULL);\n\telse\n\t evalarg->eval_flags = orig_flags;\n }", " return OK;\n}", "/*\n * Handle first level expression:\n *\texpr2 || expr2 || expr2\t logical OR\n *\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n *\n * Return OK or FAIL.\n */\n static int\neval2(char_u **arg, typval_T *rettv, evalarg_T *evalarg)\n{\n char_u\t*p;\n int\t\tgetnext;", " /*\n * Get the first expression.\n */\n if (eval3(arg, rettv, evalarg) == FAIL)\n\treturn FAIL;", " /*\n * Handle the \"||\" operator.\n */\n p = eval_next_non_blank(*arg, evalarg, &getnext);\n if (p[0] == '|' && p[1] == '|')\n {\n\tevalarg_T *evalarg_used = evalarg;\n\tevalarg_T local_evalarg;\n\tint\t evaluate;\n\tint\t orig_flags;\n\tlong\t result = FALSE;\n\ttypval_T var2;\n\tint\t error = FALSE;\n\tint\t vim9script = in_vim9script();", "\tif (evalarg == NULL)\n\t{\n\t init_evalarg(&local_evalarg);\n\t evalarg_used = &local_evalarg;\n\t}\n\torig_flags = evalarg_used->eval_flags;\n\tevaluate = orig_flags & EVAL_EVALUATE;\n\tif (evaluate)\n\t{\n\t if (vim9script)\n\t\tresult = tv_get_bool_chk(rettv, &error);\n\t else if (tv_get_number_chk(rettv, &error) != 0)\n\t\tresult = TRUE;\n\t clear_tv(rettv);\n\t if (error)\n\t\treturn FAIL;\n\t}", "\t/*\n\t * Repeat until there is no following \"||\".\n\t */\n\twhile (p[0] == '|' && p[1] == '|')\n\t{\n\t if (getnext)\n\t\t*arg = eval_next_line(*arg, evalarg_used);\n\t else\n\t {\n\t\tif (evaluate && vim9script && !VIM_ISWHITE(p[-1]))\n\t\t{\n\t\t error_white_both(p, 2);\n\t\t clear_tv(rettv);\n\t\t return FAIL;\n\t\t}\n\t\t*arg = p;\n\t }", "\t /*\n\t * Get the second variable.\n\t */\n\t if (evaluate && vim9script && !IS_WHITE_OR_NUL((*arg)[2]))\n\t {\n\t\terror_white_both(*arg, 2);\n\t\tclear_tv(rettv);\n\t\treturn FAIL;\n\t }\n\t *arg = skipwhite_and_linebreak(*arg + 2, evalarg_used);\n\t evalarg_used->eval_flags = !result ? orig_flags\n\t\t\t\t\t\t : orig_flags & ~EVAL_EVALUATE;\n\t if (eval3(arg, &var2, evalarg_used) == FAIL)\n\t\treturn FAIL;", "\t /*\n\t * Compute the result.\n\t */\n\t if (evaluate && !result)\n\t {\n\t\tif (vim9script)\n\t\t result = tv_get_bool_chk(&var2, &error);\n\t\telse if (tv_get_number_chk(&var2, &error) != 0)\n\t\t result = TRUE;\n\t\tclear_tv(&var2);\n\t\tif (error)\n\t\t return FAIL;\n\t }\n\t if (evaluate)\n\t {\n\t\tif (vim9script)\n\t\t{\n\t\t rettv->v_type = VAR_BOOL;\n\t\t rettv->vval.v_number = result ? VVAL_TRUE : VVAL_FALSE;\n\t\t}\n\t\telse\n\t\t{\n\t\t rettv->v_type = VAR_NUMBER;\n\t\t rettv->vval.v_number = result;\n\t\t}\n\t }", "\t p = eval_next_non_blank(*arg, evalarg_used, &getnext);\n\t}", "\tif (evalarg == NULL)\n\t clear_evalarg(&local_evalarg, NULL);\n\telse\n\t evalarg->eval_flags = orig_flags;\n }", " return OK;\n}", "/*\n * Handle second level expression:\n *\texpr3 && expr3 && expr3\t logical AND\n *\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n *\n * Return OK or FAIL.\n */\n static int\neval3(char_u **arg, typval_T *rettv, evalarg_T *evalarg)\n{\n char_u\t*p;\n int\t\tgetnext;", " /*\n * Get the first expression.\n */\n if (eval4(arg, rettv, evalarg) == FAIL)\n\treturn FAIL;", " /*\n * Handle the \"&&\" operator.\n */\n p = eval_next_non_blank(*arg, evalarg, &getnext);\n if (p[0] == '&' && p[1] == '&')\n {\n\tevalarg_T *evalarg_used = evalarg;\n\tevalarg_T local_evalarg;\n\tint\t orig_flags;\n\tint\t evaluate;\n\tlong\t result = TRUE;\n\ttypval_T var2;\n\tint\t error = FALSE;\n\tint\t vim9script = in_vim9script();", "\tif (evalarg == NULL)\n\t{\n\t init_evalarg(&local_evalarg);\n\t evalarg_used = &local_evalarg;\n\t}\n\torig_flags = evalarg_used->eval_flags;\n\tevaluate = orig_flags & EVAL_EVALUATE;\n\tif (evaluate)\n\t{\n\t if (vim9script)\n\t\tresult = tv_get_bool_chk(rettv, &error);\n\t else if (tv_get_number_chk(rettv, &error) == 0)\n\t\tresult = FALSE;\n\t clear_tv(rettv);\n\t if (error)\n\t\treturn FAIL;\n\t}", "\t/*\n\t * Repeat until there is no following \"&&\".\n\t */\n\twhile (p[0] == '&' && p[1] == '&')\n\t{\n\t if (getnext)\n\t\t*arg = eval_next_line(*arg, evalarg_used);\n\t else\n\t {\n\t\tif (evaluate && vim9script && !VIM_ISWHITE(p[-1]))\n\t\t{\n\t\t error_white_both(p, 2);\n\t\t clear_tv(rettv);\n\t\t return FAIL;\n\t\t}\n\t\t*arg = p;\n\t }", "\t /*\n\t * Get the second variable.\n\t */\n\t if (evaluate && vim9script && !IS_WHITE_OR_NUL((*arg)[2]))\n\t {\n\t\terror_white_both(*arg, 2);\n\t\tclear_tv(rettv);\n\t\treturn FAIL;\n\t }\n\t *arg = skipwhite_and_linebreak(*arg + 2, evalarg_used);\n\t evalarg_used->eval_flags = result ? orig_flags\n\t\t\t\t\t\t : orig_flags & ~EVAL_EVALUATE;\n\t CLEAR_FIELD(var2);\n\t if (eval4(arg, &var2, evalarg_used) == FAIL)\n\t\treturn FAIL;", "\t /*\n\t * Compute the result.\n\t */\n\t if (evaluate && result)\n\t {\n\t\tif (vim9script)\n\t\t result = tv_get_bool_chk(&var2, &error);\n\t\telse if (tv_get_number_chk(&var2, &error) == 0)\n\t\t result = FALSE;\n\t\tclear_tv(&var2);\n\t\tif (error)\n\t\t return FAIL;\n\t }\n\t if (evaluate)\n\t {\n\t\tif (vim9script)\n\t\t{\n\t\t rettv->v_type = VAR_BOOL;\n\t\t rettv->vval.v_number = result ? VVAL_TRUE : VVAL_FALSE;\n\t\t}\n\t\telse\n\t\t{\n\t\t rettv->v_type = VAR_NUMBER;\n\t\t rettv->vval.v_number = result;\n\t\t}\n\t }", "\t p = eval_next_non_blank(*arg, evalarg_used, &getnext);\n\t}", "\tif (evalarg == NULL)\n\t clear_evalarg(&local_evalarg, NULL);\n\telse\n\t evalarg->eval_flags = orig_flags;\n }", " return OK;\n}", "/*\n * Handle third level expression:\n *\tvar1 == var2\n *\tvar1 =~ var2\n *\tvar1 != var2\n *\tvar1 !~ var2\n *\tvar1 > var2\n *\tvar1 >= var2\n *\tvar1 < var2\n *\tvar1 <= var2\n *\tvar1 is var2\n *\tvar1 isnot var2\n *\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n *\n * Return OK or FAIL.\n */\n static int\neval4(char_u **arg, typval_T *rettv, evalarg_T *evalarg)\n{\n char_u\t*p;\n int\t\tgetnext;\n exprtype_T\ttype = EXPR_UNKNOWN;\n int\t\tlen = 2;\n int\t\ttype_is = FALSE;", " /*\n * Get the first expression.\n */\n if (eval5(arg, rettv, evalarg) == FAIL)\n\treturn FAIL;", " p = eval_next_non_blank(*arg, evalarg, &getnext);", " type = get_compare_type(p, &len, &type_is);", " /*\n * If there is a comparative operator, use it.\n */\n if (type != EXPR_UNKNOWN)\n {\n\ttypval_T var2;\n\tint\t ic;\n\tint\t vim9script = in_vim9script();\n\tint\t evaluate = evalarg == NULL\n\t\t\t\t ? 0 : (evalarg->eval_flags & EVAL_EVALUATE);\n\tlong\t comp_lnum = SOURCING_LNUM;", "\tif (getnext)\n\t{\n\t *arg = eval_next_line(*arg, evalarg);\n\t p = *arg;\n\t}\n\telse if (evaluate && vim9script && !VIM_ISWHITE(**arg))\n\t{\n\t error_white_both(*arg, len);\n\t clear_tv(rettv);\n\t return FAIL;\n\t}", "\tif (vim9script && type_is && (p[len] == '?' || p[len] == '#'))\n\t{\n\t semsg(_(e_invalid_expression_str), p);\n\t clear_tv(rettv);\n\t return FAIL;\n\t}", "\t// extra question mark appended: ignore case\n\tif (p[len] == '?')\n\t{\n\t ic = TRUE;\n\t ++len;\n\t}\n\t// extra '#' appended: match case\n\telse if (p[len] == '#')\n\t{\n\t ic = FALSE;\n\t ++len;\n\t}\n\t// nothing appended: use 'ignorecase' if not in Vim script\n\telse\n\t ic = vim9script ? FALSE : p_ic;", "\t/*\n\t * Get the second variable.\n\t */\n\tif (evaluate && vim9script && !IS_WHITE_OR_NUL(p[len]))\n\t{\n\t error_white_both(p, len);\n\t clear_tv(rettv);\n\t return FAIL;\n\t}\n\t*arg = skipwhite_and_linebreak(p + len, evalarg);\n\tif (eval5(arg, &var2, evalarg) == FAIL)\n\t{\n\t clear_tv(rettv);\n\t return FAIL;\n\t}\n\tif (evaluate)\n\t{\n\t int ret;", "\t // use the line of the comparison for messages\n\t SOURCING_LNUM = comp_lnum;\n\t if (vim9script && check_compare_types(type, rettv, &var2) == FAIL)\n\t {\n\t\tret = FAIL;\n\t\tclear_tv(rettv);\n\t }\n\t else\n\t\tret = typval_compare(rettv, &var2, type, ic);\n\t clear_tv(&var2);\n\t return ret;\n\t}\n }", " return OK;\n}", "/*\n * Make a copy of blob \"tv1\" and append blob \"tv2\".\n */\n void\neval_addblob(typval_T *tv1, typval_T *tv2)\n{\n blob_T *b1 = tv1->vval.v_blob;\n blob_T *b2 = tv2->vval.v_blob;\n blob_T *b = blob_alloc();\n int\t i;", " if (b == NULL)\n\treturn;", " for (i = 0; i < blob_len(b1); i++)\n\tga_append(&b->bv_ga, blob_get(b1, i));\n for (i = 0; i < blob_len(b2); i++)\n\tga_append(&b->bv_ga, blob_get(b2, i));", " clear_tv(tv1);\n rettv_blob_set(tv1, b);\n}", "/*\n * Make a copy of list \"tv1\" and append list \"tv2\".\n */\n int\neval_addlist(typval_T *tv1, typval_T *tv2)\n{\n typval_T var3;", " // concatenate Lists\n if (list_concat(tv1->vval.v_list, tv2->vval.v_list, &var3) == FAIL)\n {\n\tclear_tv(tv1);\n\tclear_tv(tv2);\n\treturn FAIL;\n }\n clear_tv(tv1);\n *tv1 = var3;\n return OK;\n}", "/*\n * Handle the bitwise left/right shift operator expression:\n *\tvar1 << var2\n *\tvar1 >> var2\n *\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n *\n * Return OK or FAIL.\n */\n static int\neval5(char_u **arg, typval_T *rettv, evalarg_T *evalarg)\n{\n /*\n * Get the first expression.\n */\n if (eval6(arg, rettv, evalarg) == FAIL)\n\treturn FAIL;", " /*\n * Repeat computing, until no '<<' or '>>' is following.\n */\n for (;;)\n {\n\tchar_u\t\t*p;\n\tint\t\tgetnext;\n\texprtype_T\ttype;\n\tint\t\tevaluate;\n\ttypval_T\tvar2;\n\tint\t\tvim9script;", "\tp = eval_next_non_blank(*arg, evalarg, &getnext);\n\tif (p[0] == '<' && p[1] == '<')\n\t type = EXPR_LSHIFT;\n\telse if (p[0] == '>' && p[1] == '>')\n\t type = EXPR_RSHIFT;\n\telse\n\t return OK;", "\t// Handle a bitwise left or right shift operator\n\tif (rettv->v_type != VAR_NUMBER)\n\t{\n\t // left operand should be a number\n\t emsg(_(e_bitshift_ops_must_be_number));\n\t clear_tv(rettv);\n\t return FAIL;\n\t}", "\tevaluate = evalarg == NULL ? 0 : (evalarg->eval_flags & EVAL_EVALUATE);\n\tvim9script = in_vim9script();\n\tif (getnext)\n\t{\n\t *arg = eval_next_line(*arg, evalarg);\n\t p = *arg;\n\t}\n\telse if (evaluate && vim9script && !VIM_ISWHITE(**arg))\n\t{\n\t error_white_both(*arg, 2);\n\t clear_tv(rettv);\n\t return FAIL;\n\t}", "\t/*\n\t * Get the second variable.\n\t */\n\tif (evaluate && vim9script && !IS_WHITE_OR_NUL(p[2]))\n\t{\n\t error_white_both(p, 2);\n\t clear_tv(rettv);\n\t return FAIL;\n\t}\n\t*arg = skipwhite_and_linebreak(p + 2, evalarg);\n\tif (eval6(arg, &var2, evalarg) == FAIL)\n\t{\n\t clear_tv(rettv);\n\t return FAIL;\n\t}", "\tif (var2.v_type != VAR_NUMBER || var2.vval.v_number < 0)\n\t{\n\t // right operand should be a positive number\n\t if (var2.v_type != VAR_NUMBER)\n\t\temsg(_(e_bitshift_ops_must_be_number));\n\t else\n\t\temsg(_(e_bitshift_ops_must_be_positive));\n\t clear_tv(rettv);\n\t clear_tv(&var2);\n\t return FAIL;\n\t}", "\tif (evaluate)\n\t{\n\t if (var2.vval.v_number > MAX_LSHIFT_BITS)\n\t\t// shifting more bits than we have always results in zero\n\t\trettv->vval.v_number = 0;\n\t else if (type == EXPR_LSHIFT)\n\t\trettv->vval.v_number =\n\t\t (uvarnumber_T)rettv->vval.v_number << var2.vval.v_number;\n\t else\n\t\trettv->vval.v_number =\n\t\t (uvarnumber_T)rettv->vval.v_number >> var2.vval.v_number;\n\t}", "\tclear_tv(&var2);\n }", " return OK;\n}", "/*\n * Handle fifth level expression:\n *\t+\tnumber addition, concatenation of list or blob\n *\t-\tnumber subtraction\n *\t.\tstring concatenation (if script version is 1)\n *\t..\tstring concatenation\n *\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n *\n * Return OK or FAIL.\n */\n static int\neval6(char_u **arg, typval_T *rettv, evalarg_T *evalarg)\n{\n /*\n * Get the first expression.\n */\n if (eval7(arg, rettv, evalarg, FALSE) == FAIL)\n\treturn FAIL;", " /*\n * Repeat computing, until no '+', '-' or '.' is following.\n */\n for (;;)\n {\n\tint\t evaluate;\n\tint\t getnext;\n\tchar_u\t *p;\n\tint\t op;\n\tint\t oplen;\n\tint\t concat;\n\ttypval_T var2;\n\tint\t vim9script = in_vim9script();", "\t// \".\" is only string concatenation when scriptversion is 1\n\t// \"+=\", \"-=\" and \"..=\" are assignments\n\t// \"++\" and \"--\" on the next line are a separate command.\n\tp = eval_next_non_blank(*arg, evalarg, &getnext);\n\top = *p;\n\tconcat = op == '.' && (*(p + 1) == '.' || in_old_script(2));\n\tif ((op != '+' && op != '-' && !concat) || p[1] == '='\n\t\t\t\t\t || (p[1] == '.' && p[2] == '='))\n\t break;\n\tif (getnext && (op == '+' || op == '-') && p[0] == p[1])\n\t break;", "\tevaluate = evalarg == NULL ? 0 : (evalarg->eval_flags & EVAL_EVALUATE);\n\toplen = (concat && p[1] == '.') ? 2 : 1;\n\tif (getnext)\n\t *arg = eval_next_line(*arg, evalarg);\n\telse\n\t{\n\t if (evaluate && vim9script && !VIM_ISWHITE(**arg))\n\t {\n\t\terror_white_both(*arg, oplen);\n\t\tclear_tv(rettv);\n\t\treturn FAIL;\n\t }\n\t *arg = p;\n\t}\n\tif ((op != '+' || (rettv->v_type != VAR_LIST\n\t\t\t\t\t\t && rettv->v_type != VAR_BLOB))\n\t\t&& (op == '.' || rettv->v_type != VAR_FLOAT)\n\t\t&& evaluate)\n\t{\n\t int\t\terror = FALSE;", "\t // For \"list + ...\", an illegal use of the first operand as\n\t // a number cannot be determined before evaluating the 2nd\n\t // operand: if this is also a list, all is ok.\n\t // For \"something . ...\", \"something - ...\" or \"non-list + ...\",\n\t // we know that the first operand needs to be a string or number\n\t // without evaluating the 2nd operand. So check before to avoid\n\t // side effects after an error.\n\t if (op != '.')\n\t\ttv_get_number_chk(rettv, &error);\n\t if ((op == '.' && tv_get_string_chk(rettv) == NULL) || error)\n\t {\n\t\tclear_tv(rettv);\n\t\treturn FAIL;\n\t }\n\t}", "\t/*\n\t * Get the second variable.\n\t */\n\tif (evaluate && vim9script && !IS_WHITE_OR_NUL((*arg)[oplen]))\n\t{\n\t error_white_both(*arg, oplen);\n\t clear_tv(rettv);\n\t return FAIL;\n\t}\n\t*arg = skipwhite_and_linebreak(*arg + oplen, evalarg);\n\tif (eval7(arg, &var2, evalarg, !vim9script && op == '.') == FAIL)\n\t{\n\t clear_tv(rettv);\n\t return FAIL;\n\t}", "\tif (evaluate)\n\t{\n\t /*\n\t * Compute the result.\n\t */\n\t if (op == '.')\n\t {\n\t\tchar_u\tbuf1[NUMBUFLEN], buf2[NUMBUFLEN];\n\t\tchar_u\t*s1 = tv_get_string_buf(rettv, buf1);\n\t\tchar_u\t*s2 = NULL;", "\t\tif (vim9script && (var2.v_type == VAR_VOID\n\t\t\t|| var2.v_type == VAR_CHANNEL\n\t\t\t|| var2.v_type == VAR_JOB))\n\t\t semsg(_(e_using_invalid_value_as_string_str),\n\t\t\t\t\t\t vartype_name(var2.v_type));\n\t\telse if (vim9script && var2.v_type == VAR_FLOAT)\n\t\t{\n\t\t vim_snprintf((char *)buf2, NUMBUFLEN, \"%g\",\n\t\t\t\t\t\t\t var2.vval.v_float);\n\t\t s2 = buf2;\n\t\t}\n\t\telse\n\t\t s2 = tv_get_string_buf_chk(&var2, buf2);\n\t\tif (s2 == NULL)\t\t// type error ?\n\t\t{\n\t\t clear_tv(rettv);\n\t\t clear_tv(&var2);\n\t\t return FAIL;\n\t\t}\n\t\tp = concat_str(s1, s2);\n\t\tclear_tv(rettv);\n\t\trettv->v_type = VAR_STRING;\n\t\trettv->vval.v_string = p;\n\t }\n\t else if (op == '+' && rettv->v_type == VAR_BLOB\n\t\t\t\t\t\t && var2.v_type == VAR_BLOB)\n\t\teval_addblob(rettv, &var2);\n\t else if (op == '+' && rettv->v_type == VAR_LIST\n\t\t\t\t\t\t && var2.v_type == VAR_LIST)\n\t {\n\t\tif (eval_addlist(rettv, &var2) == FAIL)\n\t\t return FAIL;\n\t }\n\t else\n\t {\n\t\tint\t\terror = FALSE;\n\t\tvarnumber_T\tn1, n2;\n\t\tfloat_T\t\tf1 = 0, f2 = 0;", "\t\tif (rettv->v_type == VAR_FLOAT)\n\t\t{\n\t\t f1 = rettv->vval.v_float;\n\t\t n1 = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t n1 = tv_get_number_chk(rettv, &error);\n\t\t if (error)\n\t\t {\n\t\t\t// This can only happen for \"list + non-list\" or\n\t\t\t// \"blob + non-blob\". For \"non-list + ...\" or\n\t\t\t// \"something - ...\", we returned before evaluating the\n\t\t\t// 2nd operand.\n\t\t\tclear_tv(rettv);\n\t\t\tclear_tv(&var2);\n\t\t\treturn FAIL;\n\t\t }\n\t\t if (var2.v_type == VAR_FLOAT)\n\t\t\tf1 = n1;\n\t\t}\n\t\tif (var2.v_type == VAR_FLOAT)\n\t\t{\n\t\t f2 = var2.vval.v_float;\n\t\t n2 = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t n2 = tv_get_number_chk(&var2, &error);\n\t\t if (error)\n\t\t {\n\t\t\tclear_tv(rettv);\n\t\t\tclear_tv(&var2);\n\t\t\treturn FAIL;\n\t\t }\n\t\t if (rettv->v_type == VAR_FLOAT)\n\t\t\tf2 = n2;\n\t\t}\n\t\tclear_tv(rettv);", "\t\t// If there is a float on either side the result is a float.\n\t\tif (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)\n\t\t{\n\t\t if (op == '+')\n\t\t\tf1 = f1 + f2;\n\t\t else\n\t\t\tf1 = f1 - f2;\n\t\t rettv->v_type = VAR_FLOAT;\n\t\t rettv->vval.v_float = f1;\n\t\t}\n\t\telse\n\t\t{\n\t\t if (op == '+')\n\t\t\tn1 = n1 + n2;\n\t\t else\n\t\t\tn1 = n1 - n2;\n\t\t rettv->v_type = VAR_NUMBER;\n\t\t rettv->vval.v_number = n1;\n\t\t}\n\t }\n\t clear_tv(&var2);\n\t}\n }\n return OK;\n}", "/*\n * Handle sixth level expression:\n *\t*\tnumber multiplication\n *\t/\tnumber division\n *\t%\tnumber modulo\n *\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n *\n * Return OK or FAIL.\n */\n static int\neval7(\n char_u\t**arg,\n typval_T\t*rettv,\n evalarg_T\t*evalarg,\n int\t\twant_string) // after \".\" operator\n{\n int\t use_float = FALSE;", " /*\n * Get the first expression.\n */\n if (eval8(arg, rettv, evalarg, want_string) == FAIL)\n\treturn FAIL;", " /*\n * Repeat computing, until no '*', '/' or '%' is following.\n */\n for (;;)\n {\n\tint\t evaluate;\n\tint\t getnext;\n\ttypval_T var2;\n\tchar_u\t *p;\n\tint\t op;\n\tvarnumber_T n1, n2;\n\tfloat_T\t f1, f2;\n\tint\t error;", "\t// \"*=\", \"/=\" and \"%=\" are assignments\n\tp = eval_next_non_blank(*arg, evalarg, &getnext);\n\top = *p;\n\tif ((op != '*' && op != '/' && op != '%') || p[1] == '=')\n\t break;", "\tevaluate = evalarg == NULL ? 0 : (evalarg->eval_flags & EVAL_EVALUATE);\n\tif (getnext)\n\t *arg = eval_next_line(*arg, evalarg);\n\telse\n\t{\n\t if (evaluate && in_vim9script() && !VIM_ISWHITE(**arg))\n\t {\n\t\terror_white_both(*arg, 1);\n\t\tclear_tv(rettv);\n\t\treturn FAIL;\n\t }\n\t *arg = p;\n\t}", "\tf1 = 0;\n\tf2 = 0;\n\terror = FALSE;\n\tif (evaluate)\n\t{\n\t if (rettv->v_type == VAR_FLOAT)\n\t {\n\t\tf1 = rettv->vval.v_float;\n\t\tuse_float = TRUE;\n\t\tn1 = 0;\n\t }\n\t else\n\t\tn1 = tv_get_number_chk(rettv, &error);\n\t clear_tv(rettv);\n\t if (error)\n\t\treturn FAIL;\n\t}\n\telse\n\t n1 = 0;", "\t/*\n\t * Get the second variable.\n\t */\n\tif (evaluate && in_vim9script() && !IS_WHITE_OR_NUL((*arg)[1]))\n\t{\n\t error_white_both(*arg, 1);\n\t clear_tv(rettv);\n\t return FAIL;\n\t}\n\t*arg = skipwhite_and_linebreak(*arg + 1, evalarg);\n\tif (eval8(arg, &var2, evalarg, FALSE) == FAIL)\n\t return FAIL;", "\tif (evaluate)\n\t{\n\t if (var2.v_type == VAR_FLOAT)\n\t {\n\t\tif (!use_float)\n\t\t{\n\t\t f1 = n1;\n\t\t use_float = TRUE;\n\t\t}\n\t\tf2 = var2.vval.v_float;\n\t\tn2 = 0;\n\t }\n\t else\n\t {\n\t\tn2 = tv_get_number_chk(&var2, &error);\n\t\tclear_tv(&var2);\n\t\tif (error)\n\t\t return FAIL;\n\t\tif (use_float)\n\t\t f2 = n2;\n\t }", "\t /*\n\t * Compute the result.\n\t * When either side is a float the result is a float.\n\t */\n\t if (use_float)\n\t {\n\t\tif (op == '*')\n\t\t f1 = f1 * f2;\n\t\telse if (op == '/')\n\t\t{\n#ifdef VMS\n\t\t // VMS crashes on divide by zero, work around it\n\t\t if (f2 == 0.0)\n\t\t {\n\t\t\tif (f1 == 0)\n\t\t\t f1 = -1 * __F_FLT_MAX - 1L; // similar to NaN\n\t\t\telse if (f1 < 0)\n\t\t\t f1 = -1 * __F_FLT_MAX;\n\t\t\telse\n\t\t\t f1 = __F_FLT_MAX;\n\t\t }\n\t\t else\n\t\t\tf1 = f1 / f2;\n#else\n\t\t // We rely on the floating point library to handle divide\n\t\t // by zero to result in \"inf\" and not a crash.\n\t\t f1 = f1 / f2;\n#endif\n\t\t}\n\t\telse\n\t\t{\n\t\t emsg(_(e_cannot_use_percent_with_float));\n\t\t return FAIL;\n\t\t}\n\t\trettv->v_type = VAR_FLOAT;\n\t\trettv->vval.v_float = f1;\n\t }\n\t else\n\t {\n\t\tint\t failed = FALSE;", "\t\tif (op == '*')\n\t\t n1 = n1 * n2;\n\t\telse if (op == '/')\n\t\t n1 = num_divide(n1, n2, &failed);\n\t\telse\n\t\t n1 = num_modulus(n1, n2, &failed);\n\t\tif (failed)\n\t\t return FAIL;", "\t\trettv->v_type = VAR_NUMBER;\n\t\trettv->vval.v_number = n1;\n\t }\n\t}\n }", " return OK;\n}", "/*\n * Handle a type cast before a base level expression.\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n * Return OK or FAIL.\n */\n static int\neval8(\n char_u\t**arg,\n typval_T\t*rettv,\n evalarg_T\t*evalarg,\n int\t\twant_string)\t// after \".\" operator\n{\n type_T\t*want_type = NULL;\n garray_T\ttype_list;\t // list of pointers to allocated types\n int\t\tres;\n int\t\tevaluate = evalarg == NULL ? 0\n\t\t\t\t : (evalarg->eval_flags & EVAL_EVALUATE);", " // Recognize <type> in Vim9 script only.\n if (in_vim9script() && **arg == '<' && eval_isnamec1((*arg)[1])\n\t\t\t\t\t && STRNCMP(*arg, \"<SNR>\", 5) != 0)\n {\n\t++*arg;\n\tga_init2(&type_list, sizeof(type_T *), 10);\n\twant_type = parse_type(arg, &type_list, TRUE);\n\tif (want_type == NULL && (evaluate || **arg != '>'))\n\t{\n\t clear_type_list(&type_list);\n\t return FAIL;\n\t}", "\tif (**arg != '>')\n\t{\n\t if (*skipwhite(*arg) == '>')\n\t\tsemsg(_(e_no_white_space_allowed_before_str_str), \">\", *arg);\n\t else\n\t\temsg(_(e_missing_gt));\n\t clear_type_list(&type_list);\n\t return FAIL;\n\t}\n\t++*arg;\n\t*arg = skipwhite_and_linebreak(*arg, evalarg);\n }", " res = eval9(arg, rettv, evalarg, want_string);", " if (want_type != NULL && evaluate)\n {\n\tif (res == OK)\n\t{\n\t type_T *actual = typval2type(rettv, get_copyID(), &type_list,\n\t\t\t\t\t\t\t TVTT_DO_MEMBER);", "\t if (!equal_type(want_type, actual, 0))\n\t {\n\t\tif (want_type == &t_bool && actual != &t_bool\n\t\t\t\t\t&& (actual->tt_flags & TTFLAG_BOOL_OK))\n\t\t{\n\t\t int n = tv2bool(rettv);", "\t\t // can use \"0\" and \"1\" for boolean in some places\n\t\t clear_tv(rettv);\n\t\t rettv->v_type = VAR_BOOL;\n\t\t rettv->vval.v_number = n ? VVAL_TRUE : VVAL_FALSE;\n\t\t}\n\t\telse\n\t\t{\n\t\t where_T where = WHERE_INIT;", "\t\t where.wt_variable = TRUE;\n\t\t res = check_type(want_type, actual, TRUE, where);\n\t\t}\n\t }\n\t}\n\tclear_type_list(&type_list);\n }", " return res;\n}", " int\neval_leader(char_u **arg, int vim9)\n{\n char_u\t*s = *arg;\n char_u\t*p = *arg;", " while (*p == '!' || *p == '-' || *p == '+')\n {\n\tchar_u *n = skipwhite(p + 1);", "\t// ++, --, -+ and +- are not accepted in Vim9 script\n\tif (vim9 && (*p == '-' || *p == '+') && (*n == '-' || *n == '+'))\n\t{\n\t semsg(_(e_invalid_expression_str), s);\n\t return FAIL;\n\t}\n\tp = n;\n }\n *arg = p;\n return OK;\n}", "/*\n * Check for a predefined value \"true\", \"false\" and \"null.*\".\n * Return OK when recognized.\n */\n int\nhandle_predefined(char_u *s, int len, typval_T *rettv)\n{\n switch (len)\n {\n\tcase 4: if (STRNCMP(s, \"true\", 4) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_BOOL;\n\t\t rettv->vval.v_number = VVAL_TRUE;\n\t\t return OK;\n\t\t}\n\t\tif (STRNCMP(s, \"null\", 4) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_SPECIAL;\n\t\t rettv->vval.v_number = VVAL_NULL;\n\t\t return OK;\n\t\t}\n\t\tbreak;\n\tcase 5: if (STRNCMP(s, \"false\", 5) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_BOOL;\n\t\t rettv->vval.v_number = VVAL_FALSE;\n\t\t return OK;\n\t\t}\n\t\tbreak;\n\tcase 8: if (STRNCMP(s, \"null_job\", 8) == 0)\n\t\t{\n#ifdef FEAT_JOB_CHANNEL\n\t\t rettv->v_type = VAR_JOB;\n\t\t rettv->vval.v_job = NULL;\n#else\n\t\t rettv->v_type = VAR_SPECIAL;\n\t\t rettv->vval.v_number = VVAL_NULL;\n#endif\n\t\t return OK;\n\t\t}\n\t\tbreak;\n\tcase 9:\n\t\tif (STRNCMP(s, \"null_\", 5) != 0)\n\t\t break;\n\t\tif (STRNCMP(s + 5, \"list\", 4) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_LIST;\n\t\t rettv->vval.v_list = NULL;\n\t\t return OK;\n\t\t}\n\t\tif (STRNCMP(s + 5, \"dict\", 4) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_DICT;\n\t\t rettv->vval.v_dict = NULL;\n\t\t return OK;\n\t\t}\n\t\tif (STRNCMP(s + 5, \"blob\", 4) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_BLOB;\n\t\t rettv->vval.v_blob = NULL;\n\t\t return OK;\n\t\t}\n\t\tbreak;\n\tcase 10: if (STRNCMP(s, \"null_class\", 10) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_CLASS;\n\t\t rettv->vval.v_class = NULL;\n\t\t return OK;\n\t\t}\n\t\t break;\n\tcase 11: if (STRNCMP(s, \"null_string\", 11) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_STRING;\n\t\t rettv->vval.v_string = NULL;\n\t\t return OK;\n\t\t}\n\t\tif (STRNCMP(s, \"null_object\", 11) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_OBJECT;\n\t\t rettv->vval.v_object = NULL;\n\t\t return OK;\n\t\t}\n\t\tbreak;\n\tcase 12:\n\t\tif (STRNCMP(s, \"null_channel\", 12) == 0)\n\t\t{\n#ifdef FEAT_JOB_CHANNEL\n\t\t rettv->v_type = VAR_CHANNEL;\n\t\t rettv->vval.v_channel = NULL;\n#else\n\t\t rettv->v_type = VAR_SPECIAL;\n\t\t rettv->vval.v_number = VVAL_NULL;\n#endif\n\t\t return OK;\n\t\t}\n\t\tif (STRNCMP(s, \"null_partial\", 12) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_PARTIAL;\n\t\t rettv->vval.v_partial = NULL;\n\t\t return OK;\n\t\t}\n\t\tbreak;\n\tcase 13: if (STRNCMP(s, \"null_function\", 13) == 0)\n\t\t{\n\t\t rettv->v_type = VAR_FUNC;\n\t\t rettv->vval.v_string = NULL;\n\t\t return OK;\n\t\t}\n\t\tbreak;\n }\n return FAIL;\n}", "/*\n * Handle sixth level expression:\n * number\t\tnumber constant\n * 0zFFFFFFFF\t\tBlob constant\n * \"string\"\t\tstring constant\n * 'string'\t\tliteral string constant\n * &option-name\toption value\n * @r\t\t\tregister contents\n * identifier\t\tvariable value\n * function()\t\tfunction call\n * $VAR\t\tenvironment variable\n * (expression)\tnested expression\n * [expr, expr]\tList\n * {arg, arg -> expr}\tLambda\n * {key: val, key: val} Dictionary\n * #{key: val, key: val} Dictionary with literal keys\n *\n * Also handle:\n * ! in front\t\tlogical NOT\n * - in front\t\tunary minus\n * + in front\t\tunary plus (ignored)\n * trailing []\t\tsubscript in String or List\n * trailing .name\tentry in Dictionary\n * trailing ->name()\tmethod call\n *\n * \"arg\" must point to the first non-white of the expression.\n * \"arg\" is advanced to just after the recognized expression.\n *\n * Return OK or FAIL.\n */\n static int\neval9(\n char_u\t**arg,\n typval_T\t*rettv,\n evalarg_T\t*evalarg,\n int\t\twant_string)\t// after \".\" operator\n{\n int\t\tevaluate = evalarg != NULL\n\t\t\t\t && (evalarg->eval_flags & EVAL_EVALUATE);\n int\t\tlen;\n char_u\t*s;\n char_u\t*name_start = NULL;\n char_u\t*start_leader, *end_leader;\n int\t\tret = OK;\n char_u\t*alias;\n static int\trecurse = 0;\n int\t\tvim9script = in_vim9script();", " /*\n * Initialise variable so that clear_tv() can't mistake this for a\n * string and free a string that isn't there.\n */\n rettv->v_type = VAR_UNKNOWN;", " /*\n * Skip '!', '-' and '+' characters. They are handled later.\n */\n start_leader = *arg;\n if (eval_leader(arg, vim9script) == FAIL)\n\treturn FAIL;\n end_leader = *arg;", " if (**arg == '.' && (!isdigit(*(*arg + 1)) || in_old_script(2)))\n {\n\tsemsg(_(e_invalid_expression_str), *arg);\n\t++*arg;\n\treturn FAIL;\n }", " // Limit recursion to 1000 levels. At least at 10000 we run out of stack\n // and crash. With MSVC the stack is smaller.\n if (recurse ==\n#ifdef _MSC_VER\n\t\t 300\n#else\n\t\t 1000\n#endif\n\t\t )\n {\n\tsemsg(_(e_expression_too_recursive_str), *arg);\n\treturn FAIL;\n }\n ++recurse;", " switch (**arg)\n {\n /*\n * Number constant.\n */\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n case '.':\tret = eval_number(arg, rettv, evaluate, want_string);", "\t\t// Apply prefixed \"-\" and \"+\" now. Matters especially when\n\t\t// \"->\" follows.\n\t\tif (ret == OK && evaluate && end_leader > start_leader\n\t\t\t\t\t\t && rettv->v_type != VAR_BLOB)\n\t\t ret = eval9_leader(rettv, TRUE, start_leader, &end_leader);\n\t\tbreak;", " /*\n * String constant: \"string\".\n */\n case '\"':\tret = eval_string(arg, rettv, evaluate, FALSE);\n\t\tbreak;", " /*\n * Literal string constant: 'str''ing'.\n */\n case '\\'':\tret = eval_lit_string(arg, rettv, evaluate, FALSE);\n\t\tbreak;", " /*\n * List: [expr, expr]\n */\n case '[':\tret = eval_list(arg, rettv, evalarg, TRUE);\n\t\tbreak;", " /*\n * Dictionary: #{key: val, key: val}\n */\n case '#':\tif (vim9script)\n\t\t{\n\t\t ret = vim9_bad_comment(*arg) ? FAIL : NOTDONE;\n\t\t}\n\t\telse if ((*arg)[1] == '{')\n\t\t{\n\t\t ++*arg;\n\t\t ret = eval_dict(arg, rettv, evalarg, TRUE);\n\t\t}\n\t\telse\n\t\t ret = NOTDONE;\n\t\tbreak;", " /*\n * Lambda: {arg, arg -> expr}\n * Dictionary: {'key': val, 'key': val}\n */\n case '{':\tif (vim9script)\n\t\t ret = NOTDONE;\n\t\telse\n\t\t ret = get_lambda_tv(arg, rettv, vim9script, evalarg);\n\t\tif (ret == NOTDONE)\n\t\t ret = eval_dict(arg, rettv, evalarg, FALSE);\n\t\tbreak;", " /*\n * Option value: &name\n */\n case '&':\tret = eval_option(arg, rettv, evaluate);\n\t\tbreak;", " /*\n * Environment variable: $VAR.\n * Interpolated string: $\"string\" or $'string'.\n */\n case '$':\tif ((*arg)[1] == '\"' || (*arg)[1] == '\\'')\n\t\t ret = eval_interp_string(arg, rettv, evaluate);\n\t\telse\n\t\t ret = eval_env_var(arg, rettv, evaluate);\n\t\tbreak;", " /*\n * Register contents: @r.\n */\n case '@':\t++*arg;\n\t\tif (evaluate)\n\t\t{\n\t\t if (vim9script && IS_WHITE_OR_NUL(**arg))\n\t\t\tsemsg(_(e_syntax_error_at_str), *arg);\n\t\t else if (vim9script && !valid_yank_reg(**arg, FALSE))\n\t\t\temsg_invreg(**arg);\n\t\t else\n\t\t {\n\t\t\trettv->v_type = VAR_STRING;\n\t\t\trettv->vval.v_string = get_reg_contents(**arg,\n\t\t\t\t\t\t\t\tGREG_EXPR_SRC);\n\t\t }\n\t\t}\n\t\tif (**arg != NUL)\n\t\t ++*arg;\n\t\tbreak;", " /*\n * nested expression: (expression).\n * or lambda: (arg) => expr\n */\n case '(':\tret = NOTDONE;\n\t\tif (vim9script)\n\t\t{\n\t\t ret = get_lambda_tv(arg, rettv, TRUE, evalarg);\n\t\t if (ret == OK && evaluate)\n\t\t {\n\t\t\tufunc_T *ufunc = rettv->vval.v_partial->pt_func;", "\t\t\t// Compile it here to get the return type. The return\n\t\t\t// type is optional, when it's missing use t_unknown.\n\t\t\t// This is recognized in compile_return().\n\t\t\tif (ufunc->uf_ret_type->tt_type == VAR_VOID)\n\t\t\t ufunc->uf_ret_type = &t_unknown;\n\t\t\tif (compile_def_function(ufunc, FALSE,\n\t\t\t\t\tget_compile_type(ufunc), NULL) == FAIL)\n\t\t\t{\n\t\t\t clear_tv(rettv);\n\t\t\t ret = FAIL;\n\t\t\t}\n\t\t }\n\t\t}\n\t\tif (ret == NOTDONE)\n\t\t{\n\t\t *arg = skipwhite_and_linebreak(*arg + 1, evalarg);\n\t\t ret = eval1(arg, rettv, evalarg);\t// recursive!", "\t\t *arg = skipwhite_and_linebreak(*arg, evalarg);\n\t\t if (**arg == ')')\n\t\t\t++*arg;\n\t\t else if (ret == OK)\n\t\t {\n\t\t\temsg(_(e_missing_closing_paren));\n\t\t\tclear_tv(rettv);\n\t\t\tret = FAIL;\n\t\t }\n\t\t}\n\t\tbreak;", " default:\tret = NOTDONE;\n\t\tbreak;\n }", " if (ret == NOTDONE)\n {\n\t/*\n\t * Must be a variable or function name.\n\t * Can also be a curly-braces kind of name: {expr}.\n\t */\n\ts = *arg;\n\tlen = get_name_len(arg, &alias, evaluate, TRUE);\n\tif (alias != NULL)\n\t s = alias;", "\tif (len <= 0)\n\t ret = FAIL;\n\telse\n\t{\n\t int\t flags = evalarg == NULL ? 0 : evalarg->eval_flags;", "\t if (evaluate && vim9script && len == 1 && *s == '_')\n\t {\n\t\temsg(_(e_cannot_use_underscore_here));\n\t\tret = FAIL;\n\t }\n\t else if (evaluate && vim9script && len > 2\n\t\t\t\t\t\t && s[0] == 's' && s[1] == ':')\n\t {\n\t\tsemsg(_(e_cannot_use_s_colon_in_vim9_script_str), s);\n\t\tret = FAIL;\n\t }\n\t else if ((vim9script ? **arg : *skipwhite(*arg)) == '(')\n\t {\n\t\t// \"name(...\" recursive!\n\t\t*arg = skipwhite(*arg);\n\t\tret = eval_func(arg, evalarg, s, len, rettv, flags, NULL);\n\t }\n\t else if (flags & EVAL_CONSTANT)\n\t\tret = FAIL;\n\t else if (evaluate)\n\t {\n\t\t// get the value of \"true\", \"false\", etc. or a variable\n\t\tret = FAIL;\n\t\tif (vim9script)\n\t\t ret = handle_predefined(s, len, rettv);\n\t\tif (ret == FAIL)\n\t\t{\n\t\t name_start = s;\n\t\t ret = eval_variable(s, len, 0, rettv, NULL,\n\t\t\t\t\t EVAL_VAR_VERBOSE + EVAL_VAR_IMPORT);\n\t\t}\n\t }\n\t else\n\t {\n\t\t// skip the name\n\t\tcheck_vars(s, len);\n\t\tret = OK;\n\t }\n\t}\n\tvim_free(alias);\n }", " // Handle following '[', '(' and '.' for expr[expr], expr.name,\n // expr(expr), expr->name(expr)\n if (ret == OK)\n\tret = handle_subscript(arg, name_start, rettv, evalarg, evaluate);", " /*\n * Apply logical NOT and unary '-', from right to left, ignore '+'.\n */\n if (ret == OK && evaluate && end_leader > start_leader)\n\tret = eval9_leader(rettv, FALSE, start_leader, &end_leader);", " --recurse;\n return ret;\n}", "/*\n * Apply the leading \"!\" and \"-\" before an eval9 expression to \"rettv\".\n * When \"numeric_only\" is TRUE only handle \"+\" and \"-\".\n * Adjusts \"end_leaderp\" until it is at \"start_leader\".\n */\n static int\neval9_leader(\n\ttypval_T *rettv,\n\tint\t numeric_only,\n\tchar_u\t *start_leader,\n\tchar_u\t **end_leaderp)\n{\n char_u\t*end_leader = *end_leaderp;\n int\t\tret = OK;\n int\t\terror = FALSE;\n varnumber_T val = 0;\n vartype_T\ttype = rettv->v_type;\n int\t\tvim9script = in_vim9script();\n float_T\t f = 0.0;", " if (rettv->v_type == VAR_FLOAT)\n\tf = rettv->vval.v_float;\n else\n {\n\twhile (VIM_ISWHITE(end_leader[-1]))\n\t --end_leader;\n\tif (vim9script && end_leader[-1] == '!')\n\t val = tv2bool(rettv);\n\telse\n\t val = tv_get_number_chk(rettv, &error);\n }\n if (error)\n {\n\tclear_tv(rettv);\n\tret = FAIL;\n }\n else\n {\n\twhile (end_leader > start_leader)\n\t{\n\t --end_leader;\n\t if (*end_leader == '!')\n\t {\n\t\tif (numeric_only)\n\t\t{\n\t\t ++end_leader;\n\t\t break;\n\t\t}\n\t\tif (rettv->v_type == VAR_FLOAT)\n\t\t{\n\t\t if (vim9script)\n\t\t {\n\t\t\trettv->v_type = VAR_BOOL;\n\t\t\tval = f == 0.0 ? VVAL_TRUE : VVAL_FALSE;\n\t\t }\n\t\t else\n\t\t\tf = !f;\n\t\t}\n\t\telse\n\t\t{\n\t\t val = !val;\n\t\t type = VAR_BOOL;\n\t\t}\n\t }\n\t else if (*end_leader == '-')\n\t {\n\t\tif (rettv->v_type == VAR_FLOAT)\n\t\t f = -f;\n\t\telse\n\t\t{\n\t\t val = -val;\n\t\t type = VAR_NUMBER;\n\t\t}\n\t }\n\t}\n\tif (rettv->v_type == VAR_FLOAT)\n\t{\n\t clear_tv(rettv);\n\t rettv->vval.v_float = f;\n\t}\n\telse\n\t{\n\t clear_tv(rettv);\n\t if (vim9script)\n\t\trettv->v_type = type;\n\t else\n\t\trettv->v_type = VAR_NUMBER;\n\t rettv->vval.v_number = val;\n\t}\n }\n *end_leaderp = end_leader;\n return ret;\n}", "/*\n * Call the function referred to in \"rettv\".\n */\n static int\ncall_func_rettv(\n\tchar_u\t **arg,\n\tevalarg_T *evalarg,\n\ttypval_T *rettv,\n\tint\t evaluate,\n\tdict_T\t *selfdict,\n\ttypval_T *basetv)\n{\n partial_T\t*pt = NULL;\n funcexe_T\tfuncexe;\n typval_T\tfunctv;\n char_u\t*s;\n int\t\tret;", " // need to copy the funcref so that we can clear rettv\n if (evaluate)\n {\n\tfunctv = *rettv;\n\trettv->v_type = VAR_UNKNOWN;", "\t// Invoke the function. Recursive!\n\tif (functv.v_type == VAR_PARTIAL)\n\t{\n\t pt = functv.vval.v_partial;\n\t s = partial_name(pt);\n\t}\n\telse\n\t{\n\t s = functv.vval.v_string;\n\t if (s == NULL || *s == NUL)\n\t {\n\t\temsg(_(e_empty_function_name));\n\t\tret = FAIL;\n\t\tgoto theend;\n\t }\n\t}\n }\n else\n\ts = (char_u *)\"\";", " CLEAR_FIELD(funcexe);\n funcexe.fe_firstline = curwin->w_cursor.lnum;\n funcexe.fe_lastline = curwin->w_cursor.lnum;\n funcexe.fe_evaluate = evaluate;\n funcexe.fe_partial = pt;\n funcexe.fe_selfdict = selfdict;\n funcexe.fe_basetv = basetv;\n ret = get_func_tv(s, -1, rettv, arg, evalarg, &funcexe);", "theend:\n // Clear the funcref afterwards, so that deleting it while\n // evaluating the arguments is possible (see test55).\n if (evaluate)\n\tclear_tv(&functv);", " return ret;\n}", "/*\n * Evaluate \"->method()\".\n * \"*arg\" points to \"method\".\n * Returns FAIL or OK. \"*arg\" is advanced to after the ')'.\n */\n static int\neval_lambda(\n char_u\t**arg,\n typval_T\t*rettv,\n evalarg_T\t*evalarg,\n int\t\tverbose)\t// give error messages\n{\n int\t\tevaluate = evalarg != NULL\n\t\t\t\t && (evalarg->eval_flags & EVAL_EVALUATE);\n typval_T\tbase = *rettv;\n int\t\tret;", " rettv->v_type = VAR_UNKNOWN;", " if (**arg == '{')\n {\n\t// ->{lambda}()\n\tret = get_lambda_tv(arg, rettv, FALSE, evalarg);\n }\n else\n {\n\t// ->(lambda)()\n\t++*arg;\n\tret = eval1(arg, rettv, evalarg);\n\t*arg = skipwhite_and_linebreak(*arg, evalarg);\n\tif (**arg != ')')\n\t{\n\t emsg(_(e_missing_closing_paren));\n\t return FAIL;\n\t}\n\tif (rettv->v_type != VAR_STRING && rettv->v_type != VAR_FUNC\n\t\t\t\t\t && rettv->v_type != VAR_PARTIAL)\n\t{\n\t emsg(_(e_string_or_function_required_for_arrow_parens_expr));\n\t return FAIL;\n\t}\n\t++*arg;\n }\n if (ret != OK)\n\treturn FAIL;", " if (**arg != '(')\n {\n\tif (verbose)\n\t{\n\t if (*skipwhite(*arg) == '(')\n\t\temsg(_(e_no_white_space_allowed_before_parenthesis));\n\t else\n\t\tsemsg(_(e_missing_parenthesis_str), \"lambda\");\n\t}\n\tclear_tv(rettv);\n\tret = FAIL;\n }\n else\n\tret = call_func_rettv(arg, evalarg, rettv, evaluate, NULL, &base);", " // Clear the funcref afterwards, so that deleting it while\n // evaluating the arguments is possible (see test55).\n if (evaluate)\n\tclear_tv(&base);", " return ret;\n}", "/*\n * Evaluate \"->method()\".\n * \"*arg\" points to \"method\".\n * Returns FAIL or OK. \"*arg\" is advanced to after the ')'.\n */\n static int\neval_method(\n char_u\t**arg,\n typval_T\t*rettv,\n evalarg_T\t*evalarg,\n int\t\tverbose)\t// give error messages\n{\n char_u\t*name;\n long\tlen;\n char_u\t*alias;\n char_u\t*tofree = NULL;\n typval_T\tbase = *rettv;\n int\t\tret = OK;\n int\t\tevaluate = evalarg != NULL\n\t\t\t\t && (evalarg->eval_flags & EVAL_EVALUATE);", " rettv->v_type = VAR_UNKNOWN;", " name = *arg;\n len = get_name_len(arg, &alias, evaluate, evaluate);\n if (alias != NULL)\n\tname = alias;", " if (len <= 0)\n {\n\tif (verbose)\n\t emsg(_(e_missing_name_after_method));\n\tret = FAIL;\n }\n else\n {\n\tchar_u *paren;", "\t// If there is no \"(\" immediately following, but there is further on,\n\t// it can be \"import.Func()\", \"dict.Func()\", \"list[nr]\", etc.\n\t// Does not handle anything where \"(\" is part of the expression.\n\t*arg = skipwhite(*arg);", "\tif (**arg != '(' && alias == NULL\n\t\t\t\t && (paren = vim_strchr(*arg, '(')) != NULL)\n\t{\n\t *arg = name;", "\t // Truncate the name a the \"(\". Avoid trying to get another line\n\t // by making \"getline\" NULL.\n\t *paren = NUL;\n\t char_u\t*(*getline)(int, void *, int, getline_opt_T) = NULL;\n\t if (evalarg != NULL)\n\t {\n\t\tgetline = evalarg->eval_getline;\n\t\tevalarg->eval_getline = NULL;\n\t }", "\t char_u *deref = deref_function_name(arg, &tofree, evalarg, verbose);\n\t if (deref == NULL)\n\t {\n\t\t*arg = name + len;\n\t\tret = FAIL;\n\t }\n\t else\n\t {\n\t\tname = deref;\n\t\tlen = (long)STRLEN(name);\n\t }", "\t *paren = '(';\n\t if (getline != NULL)\n\t\tevalarg->eval_getline = getline;\n\t}", "\tif (ret == OK)\n\t{\n\t *arg = skipwhite(*arg);", "\t if (**arg != '(')\n\t {\n\t\tif (verbose)\n\t\t semsg(_(e_missing_parenthesis_str), name);\n\t\tret = FAIL;\n\t }\n\t else if (VIM_ISWHITE((*arg)[-1]))\n\t {\n\t\tif (verbose)\n\t\t emsg(_(e_no_white_space_allowed_before_parenthesis));\n\t\tret = FAIL;\n\t }\n\t else\n\t\tret = eval_func(arg, evalarg, name, len, rettv,\n\t\t\t\t\t evaluate ? EVAL_EVALUATE : 0, &base);\n\t}\n }", " // Clear the funcref afterwards, so that deleting it while\n // evaluating the arguments is possible (see test55).\n if (evaluate)\n\tclear_tv(&base);\n vim_free(tofree);", " return ret;\n}", "/*\n * Evaluate an \"[expr]\" or \"[expr:expr]\" index. Also \"dict.key\".\n * \"*arg\" points to the '[' or '.'.\n * Returns FAIL or OK. \"*arg\" is advanced to after the ']'.\n */\n static int\neval_index(\n char_u\t**arg,\n typval_T\t*rettv,\n evalarg_T\t*evalarg,\n int\t\tverbose)\t// give error messages\n{\n int\t\tevaluate = evalarg != NULL\n\t\t\t\t && (evalarg->eval_flags & EVAL_EVALUATE);\n int\t\tempty1 = FALSE, empty2 = FALSE;\n typval_T\tvar1, var2;\n int\t\trange = FALSE;\n char_u\t*key = NULL;\n int\t\tkeylen = -1;\n int\t\tvim9script = in_vim9script();", " if (check_can_index(rettv, evaluate, verbose) == FAIL)\n\treturn FAIL;", " init_tv(&var1);\n init_tv(&var2);\n if (**arg == '.')\n {\n\t/*\n\t * dict.name\n\t */\n\tkey = *arg + 1;\n\tfor (keylen = 0; eval_isdictc(key[keylen]); ++keylen)\n\t ;\n\tif (keylen == 0)\n\t return FAIL;\n\t*arg = key + keylen;\n }\n else\n {\n\t/*\n\t * something[idx]\n\t *\n\t * Get the (first) variable from inside the [].\n\t */\n\t*arg = skipwhite_and_linebreak(*arg + 1, evalarg);\n\tif (**arg == ':')\n\t empty1 = TRUE;\n\telse if (eval1(arg, &var1, evalarg) == FAIL)\t// recursive!\n\t return FAIL;\n\telse if (vim9script && **arg == ':')\n\t{\n\t semsg(_(e_white_space_required_before_and_after_str_at_str),\n\t\t\t\t\t\t\t\t \":\", *arg);\n\t clear_tv(&var1);\n\t return FAIL;\n\t}\n\telse if (evaluate)\n\t{\n\t int error = FALSE;", "\t // allow for indexing with float\n\t if (vim9script && rettv->v_type == VAR_DICT\n\t\t\t\t\t\t && var1.v_type == VAR_FLOAT)\n\t {\n\t\tvar1.vval.v_string = typval_tostring(&var1, TRUE);\n\t\tvar1.v_type = VAR_STRING;\n\t }", "\t if (vim9script && rettv->v_type == VAR_LIST)\n\t\ttv_get_number_chk(&var1, &error);\n\t else\n\t\terror = tv_get_string_chk(&var1) == NULL;\n\t if (error)\n\t {\n\t\t// not a number or string\n\t\tclear_tv(&var1);\n\t\treturn FAIL;\n\t }\n\t}", "\t/*\n\t * Get the second variable from inside the [:].\n\t */\n\t*arg = skipwhite_and_linebreak(*arg, evalarg);\n\tif (**arg == ':')\n\t{\n\t range = TRUE;\n\t ++*arg;\n\t if (vim9script && !IS_WHITE_OR_NUL(**arg) && **arg != ']')\n\t {\n\t\tsemsg(_(e_white_space_required_before_and_after_str_at_str),\n\t\t\t\t\t\t\t\t\":\", *arg - 1);\n\t\tif (!empty1)\n\t\t clear_tv(&var1);\n\t\treturn FAIL;\n\t }\n\t *arg = skipwhite_and_linebreak(*arg, evalarg);\n\t if (**arg == ']')\n\t\tempty2 = TRUE;\n\t else if (eval1(arg, &var2, evalarg) == FAIL)\t// recursive!\n\t {\n\t\tif (!empty1)\n\t\t clear_tv(&var1);\n\t\treturn FAIL;\n\t }\n\t else if (evaluate && tv_get_string_chk(&var2) == NULL)\n\t {\n\t\t// not a number or string\n\t\tif (!empty1)\n\t\t clear_tv(&var1);\n\t\tclear_tv(&var2);\n\t\treturn FAIL;\n\t }\n\t}", "\t// Check for the ']'.\n\t*arg = skipwhite_and_linebreak(*arg, evalarg);\n\tif (**arg != ']')\n\t{\n\t if (verbose)\n\t\temsg(_(e_missing_closing_square_brace));\n\t clear_tv(&var1);\n\t if (range)\n\t\tclear_tv(&var2);\n\t return FAIL;\n\t}\n\t*arg = *arg + 1;\t// skip over the ']'\n }", " if (evaluate)\n {\n\tint res = eval_index_inner(rettv, range,\n\t\tempty1 ? NULL : &var1, empty2 ? NULL : &var2, FALSE,\n\t\tkey, keylen, verbose);", "\tif (!empty1)\n\t clear_tv(&var1);\n\tif (range)\n\t clear_tv(&var2);\n\treturn res;\n }\n return OK;\n}", "/*\n * Check if \"rettv\" can have an [index] or [sli:ce]\n */\n int\ncheck_can_index(typval_T *rettv, int evaluate, int verbose)\n{\n switch (rettv->v_type)\n {\n\tcase VAR_FUNC:\n\tcase VAR_PARTIAL:\n\t if (verbose)\n\t\temsg(_(e_cannot_index_a_funcref));\n\t return FAIL;\n\tcase VAR_FLOAT:\n\t if (verbose)\n\t\temsg(_(e_using_float_as_string));\n\t return FAIL;\n\tcase VAR_BOOL:\n\tcase VAR_SPECIAL:\n\tcase VAR_JOB:\n\tcase VAR_CHANNEL:\n\tcase VAR_INSTR:\n\tcase VAR_CLASS:\n\tcase VAR_OBJECT:\n\t if (verbose)\n\t\temsg(_(e_cannot_index_special_variable));\n\t return FAIL;\n\tcase VAR_UNKNOWN:\n\tcase VAR_ANY:\n\tcase VAR_VOID:\n\t if (evaluate)\n\t {\n\t\temsg(_(e_cannot_index_special_variable));\n\t\treturn FAIL;\n\t }\n\t // FALLTHROUGH", "\tcase VAR_STRING:\n\tcase VAR_LIST:\n\tcase VAR_DICT:\n\tcase VAR_BLOB:\n\t break;\n\tcase VAR_NUMBER:\n\t if (in_vim9script())\n\t\temsg(_(e_cannot_index_number));\n\t break;\n }\n return OK;\n}", "/*\n * slice() function\n */\n void\nf_slice(typval_T *argvars, typval_T *rettv)\n{\n if (in_vim9script()\n\t && ((argvars[0].v_type != VAR_STRING\n\t\t && argvars[0].v_type != VAR_LIST\n\t\t && argvars[0].v_type != VAR_BLOB\n\t\t && check_for_list_arg(argvars, 0) == FAIL)\n\t\t|| check_for_number_arg(argvars, 1) == FAIL\n\t\t|| check_for_opt_number_arg(argvars, 2) == FAIL))\n\treturn;", " if (check_can_index(argvars, TRUE, FALSE) != OK)\n\treturn;", " copy_tv(argvars, rettv);\n eval_index_inner(rettv, TRUE, argvars + 1,\n\t argvars[2].v_type == VAR_UNKNOWN ? NULL : argvars + 2,\n\t TRUE, NULL, 0, FALSE);\n}", "/*\n * Apply index or range to \"rettv\".\n * \"var1\" is the first index, NULL for [:expr].\n * \"var2\" is the second index, NULL for [expr] and [expr: ]\n * \"exclusive\" is TRUE for slice(): second index is exclusive, use character\n * index for string.\n * Alternatively, \"key\" is not NULL, then key[keylen] is the dict index.\n */\n int\neval_index_inner(\n\ttypval_T *rettv,\n\tint\t is_range,\n\ttypval_T *var1,\n\ttypval_T *var2,\n\tint\t exclusive,\n\tchar_u\t *key,\n\tint\t keylen,\n\tint\t verbose)\n{\n varnumber_T\t n1, n2 = 0;\n long\t len;", " n1 = 0;\n if (var1 != NULL && rettv->v_type != VAR_DICT)\n\tn1 = tv_get_number(var1);", " if (is_range)\n {\n\tif (rettv->v_type == VAR_DICT)\n\t{\n\t if (verbose)\n\t\temsg(_(e_cannot_slice_dictionary));\n\t return FAIL;\n\t}\n\tif (var2 != NULL)\n\t n2 = tv_get_number(var2);\n\telse\n\t n2 = VARNUM_MAX;\n }", " switch (rettv->v_type)\n {\n\tcase VAR_UNKNOWN:\n\tcase VAR_ANY:\n\tcase VAR_VOID:\n\tcase VAR_FUNC:\n\tcase VAR_PARTIAL:\n\tcase VAR_FLOAT:\n\tcase VAR_BOOL:\n\tcase VAR_SPECIAL:\n\tcase VAR_JOB:\n\tcase VAR_CHANNEL:\n\tcase VAR_INSTR:\n\tcase VAR_CLASS:\n\tcase VAR_OBJECT:\n\t break; // not evaluating, skipping over subscript", "\tcase VAR_NUMBER:\n\tcase VAR_STRING:\n\t {\n\t\tchar_u\t*s = tv_get_string(rettv);", "\t\tlen = (long)STRLEN(s);\n\t\tif (in_vim9script() || exclusive)\n\t\t{\n\t\t if (is_range)\n\t\t\ts = string_slice(s, n1, n2, exclusive);\n\t\t else\n\t\t\ts = char_from_string(s, n1);\n\t\t}\n\t\telse if (is_range)\n\t\t{\n\t\t // The resulting variable is a substring. If the indexes\n\t\t // are out of range the result is empty.\n\t\t if (n1 < 0)\n\t\t {\n\t\t\tn1 = len + n1;\n\t\t\tif (n1 < 0)\n\t\t\t n1 = 0;\n\t\t }\n\t\t if (n2 < 0)\n\t\t\tn2 = len + n2;\n\t\t else if (n2 >= len)\n\t\t\tn2 = len;\n\t\t if (n1 >= len || n2 < 0 || n1 > n2)\n\t\t\ts = NULL;\n\t\t else\n\t\t\ts = vim_strnsave(s + n1, n2 - n1 + 1);\n\t\t}\n\t\telse\n\t\t{\n\t\t // The resulting variable is a string of a single\n\t\t // character. If the index is too big or negative the\n\t\t // result is empty.\n\t\t if (n1 >= len || n1 < 0)\n\t\t\ts = NULL;\n\t\t else\n\t\t\ts = vim_strnsave(s + n1, 1);\n\t\t}\n\t\tclear_tv(rettv);\n\t\trettv->v_type = VAR_STRING;\n\t\trettv->vval.v_string = s;\n\t }\n\t break;", "\tcase VAR_BLOB:\n\t blob_slice_or_index(rettv->vval.v_blob, is_range, n1, n2,\n\t\t\t\t\t\t\t exclusive, rettv);\n\t break;", "\tcase VAR_LIST:\n\t if (var1 == NULL)\n\t\tn1 = 0;\n\t if (var2 == NULL)\n\t\tn2 = VARNUM_MAX;\n\t if (list_slice_or_index(rettv->vval.v_list,\n\t\t\t is_range, n1, n2, exclusive, rettv, verbose) == FAIL)\n\t\treturn FAIL;\n\t break;", "\tcase VAR_DICT:\n\t {\n\t\tdictitem_T\t*item;\n\t\ttypval_T\ttmp;", "\t\tif (key == NULL)\n\t\t{\n\t\t key = tv_get_string_chk(var1);\n\t\t if (key == NULL)\n\t\t\treturn FAIL;\n\t\t}", "\t\titem = dict_find(rettv->vval.v_dict, key, keylen);", "\t\tif (item == NULL)\n\t\t{\n\t\t if (verbose)\n\t\t {\n\t\t\tif (keylen > 0)\n\t\t\t key[keylen] = NUL;\n\t\t\tsemsg(_(e_key_not_present_in_dictionary_str), key);\n\t\t }\n\t\t return FAIL;\n\t\t}", "\t\tcopy_tv(&item->di_tv, &tmp);\n\t\tclear_tv(rettv);\n\t\t*rettv = tmp;\n\t }\n\t break;\n }\n return OK;\n}", "/*\n * Return the function name of partial \"pt\".\n */\n char_u *\npartial_name(partial_T *pt)\n{\n if (pt != NULL)\n {\n\tif (pt->pt_name != NULL)\n\t return pt->pt_name;\n\tif (pt->pt_func != NULL)\n\t return pt->pt_func->uf_name;\n }\n return (char_u *)\"\";\n}", " static void\npartial_free(partial_T *pt)\n{\n int i;", " for (i = 0; i < pt->pt_argc; ++i)\n\tclear_tv(&pt->pt_argv[i]);\n vim_free(pt->pt_argv);\n dict_unref(pt->pt_dict);\n if (pt->pt_name != NULL)\n {\n\tfunc_unref(pt->pt_name);\n\tvim_free(pt->pt_name);\n }\n else\n\tfunc_ptr_unref(pt->pt_func);", " // \"out_up\" is no longer used, decrement refcount on partial that owns it.\n partial_unref(pt->pt_outer.out_up_partial);", " // Using pt_outer from another partial.\n partial_unref(pt->pt_outer_partial);", " // Decrease the reference count for the context of a closure. If down\n // to the minimum it may be time to free it.\n if (pt->pt_funcstack != NULL)\n {\n\t--pt->pt_funcstack->fs_refcount;\n\tfuncstack_check_refcount(pt->pt_funcstack);\n }\n // Similarly for loop variables.\n for (i = 0; i < MAX_LOOP_DEPTH; ++i)\n\tif (pt->pt_loopvars[i] != NULL)\n\t{\n\t --pt->pt_loopvars[i]->lvs_refcount;\n\t loopvars_check_refcount(pt->pt_loopvars[i]);\n\t}", " vim_free(pt);\n}", "/*\n * Unreference a closure: decrement the reference count and free it when it\n * becomes zero.\n */\n void\npartial_unref(partial_T *pt)\n{\n if (pt == NULL)\n\treturn;", " int\tdone = FALSE;", " if (--pt->pt_refcount <= 0)\n\tpartial_free(pt);", " // If the reference count goes down to one, the funcstack may be the\n // only reference and can be freed if no other partials reference it.\n else if (pt->pt_refcount == 1)\n {\n\t// careful: if the funcstack is freed it may contain this partial\n\t// and it gets freed as well\n\tif (pt->pt_funcstack != NULL)\n\t done = funcstack_check_refcount(pt->pt_funcstack);", "\tif (!done)\n\t{\n\t int\tdepth;", "\t for (depth = 0; depth < MAX_LOOP_DEPTH; ++depth)\n\t\tif (pt->pt_loopvars[depth] != NULL\n\t\t\t&& loopvars_check_refcount(pt->pt_loopvars[depth]))\n\t\t break;\n\t}\n }\n}", "/*\n * Return the next (unique) copy ID.\n * Used for serializing nested structures.\n */\n int\nget_copyID(void)\n{\n current_copyID += COPYID_INC;\n return current_copyID;\n}", "/*\n * Garbage collection for lists and dictionaries.\n *\n * We use reference counts to be able to free most items right away when they\n * are no longer used. But for composite items it's possible that it becomes\n * unused while the reference count is > 0: When there is a recursive\n * reference. Example:\n *\t:let l = [1, 2, 3]\n *\t:let d = {9: l}\n *\t:let l[1] = d\n *\n * Since this is quite unusual we handle this with garbage collection: every\n * once in a while find out which lists and dicts are not referenced from any\n * variable.\n *\n * Here is a good reference text about garbage collection (refers to Python\n * but it applies to all reference-counting mechanisms):\n *\thttp://python.ca/nas/python/gc/\n */", "/*\n * Do garbage collection for lists and dicts.\n * When \"testing\" is TRUE this is called from test_garbagecollect_now().\n * Return TRUE if some memory was freed.\n */\n int\ngarbage_collect(int testing)\n{\n int\t\tcopyID;\n int\t\tabort = FALSE;\n buf_T\t*buf;\n win_T\t*wp;\n int\t\tdid_free = FALSE;\n tabpage_T\t*tp;", " if (!testing)\n {\n\t// Only do this once.\n\twant_garbage_collect = FALSE;\n\tmay_garbage_collect = FALSE;\n\tgarbage_collect_at_exit = FALSE;\n }", " // The execution stack can grow big, limit the size.\n if (exestack.ga_maxlen - exestack.ga_len > 500)\n {\n\tsize_t\tnew_len;\n\tchar_u\t*pp;\n\tint\tn;", "\t// Keep 150% of the current size, with a minimum of the growth size.\n\tn = exestack.ga_len / 2;\n\tif (n < exestack.ga_growsize)\n\t n = exestack.ga_growsize;", "\t// Don't make it bigger though.\n\tif (exestack.ga_len + n < exestack.ga_maxlen)\n\t{\n\t new_len = (size_t)exestack.ga_itemsize * (exestack.ga_len + n);\n\t pp = vim_realloc(exestack.ga_data, new_len);\n\t if (pp == NULL)\n\t\treturn FAIL;\n\t exestack.ga_maxlen = exestack.ga_len + n;\n\t exestack.ga_data = pp;\n\t}\n }", " // We advance by two because we add one for items referenced through\n // previous_funccal.\n copyID = get_copyID();", " /*\n * 1. Go through all accessible variables and mark all lists and dicts\n * with copyID.\n */", " // Don't free variables in the previous_funccal list unless they are only\n // referenced through previous_funccal. This must be first, because if\n // the item is referenced elsewhere the funccal must not be freed.\n abort = abort || set_ref_in_previous_funccal(copyID);", " // script-local variables\n abort = abort || garbage_collect_scriptvars(copyID);", " // buffer-local variables\n FOR_ALL_BUFFERS(buf)\n\tabort = abort || set_ref_in_item(&buf->b_bufvar.di_tv, copyID,\n\t\t\t\t\t\t\t\t NULL, NULL);", " // window-local variables\n FOR_ALL_TAB_WINDOWS(tp, wp)\n\tabort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,\n\t\t\t\t\t\t\t\t NULL, NULL);\n // window-local variables in autocmd windows\n for (int i = 0; i < AUCMD_WIN_COUNT; ++i)\n\tif (aucmd_win[i].auc_win != NULL)\n\t abort = abort || set_ref_in_item(\n\t\t &aucmd_win[i].auc_win->w_winvar.di_tv, copyID, NULL, NULL);\n#ifdef FEAT_PROP_POPUP\n FOR_ALL_POPUPWINS(wp)\n\tabort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,\n\t\t\t\t\t\t\t\t NULL, NULL);\n FOR_ALL_TABPAGES(tp)\n\tFOR_ALL_POPUPWINS_IN_TAB(tp, wp)\n\t\tabort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,\n\t\t\t\t\t\t\t\t NULL, NULL);\n#endif", " // tabpage-local variables\n FOR_ALL_TABPAGES(tp)\n\tabort = abort || set_ref_in_item(&tp->tp_winvar.di_tv, copyID,\n\t\t\t\t\t\t\t\t NULL, NULL);\n // global variables\n abort = abort || garbage_collect_globvars(copyID);", " // function-local variables\n abort = abort || set_ref_in_call_stack(copyID);", " // named functions (matters for closures)\n abort = abort || set_ref_in_functions(copyID);", " // function call arguments, if v:testing is set.\n abort = abort || set_ref_in_func_args(copyID);", " // funcstacks keep variables for closures\n abort = abort || set_ref_in_funcstacks(copyID);", " // loopvars keep variables for loop blocks\n abort = abort || set_ref_in_loopvars(copyID);", " // v: vars\n abort = abort || garbage_collect_vimvars(copyID);", " // callbacks in buffers\n abort = abort || set_ref_in_buffers(copyID);", " // 'completefunc', 'omnifunc' and 'thesaurusfunc' callbacks\n abort = abort || set_ref_in_insexpand_funcs(copyID);", " // 'operatorfunc' callback\n abort = abort || set_ref_in_opfunc(copyID);", " // 'tagfunc' callback\n abort = abort || set_ref_in_tagfunc(copyID);", " // 'imactivatefunc' and 'imstatusfunc' callbacks\n abort = abort || set_ref_in_im_funcs(copyID);", "#ifdef FEAT_LUA\n abort = abort || set_ref_in_lua(copyID);\n#endif", "#ifdef FEAT_PYTHON\n abort = abort || set_ref_in_python(copyID);\n#endif", "#ifdef FEAT_PYTHON3\n abort = abort || set_ref_in_python3(copyID);\n#endif", "#ifdef FEAT_JOB_CHANNEL\n abort = abort || set_ref_in_channel(copyID);\n abort = abort || set_ref_in_job(copyID);\n#endif\n#ifdef FEAT_NETBEANS_INTG\n abort = abort || set_ref_in_nb_channel(copyID);\n#endif", "#ifdef FEAT_TIMERS\n abort = abort || set_ref_in_timer(copyID);\n#endif", "#ifdef FEAT_QUICKFIX\n abort = abort || set_ref_in_quickfix(copyID);\n#endif", "#ifdef FEAT_TERMINAL\n abort = abort || set_ref_in_term(copyID);\n#endif", "#ifdef FEAT_PROP_POPUP\n abort = abort || set_ref_in_popups(copyID);\n#endif", " if (!abort)\n {\n\t/*\n\t * 2. Free lists and dictionaries that are not referenced.\n\t */\n\tdid_free = free_unref_items(copyID);", "\t/*\n\t * 3. Check if any funccal can be freed now.\n\t * This may call us back recursively.\n\t */\n\tfree_unref_funccal(copyID, testing);\n }\n else if (p_verbose > 0)\n {\n\tverb_msg(_(\"Not enough memory to set references, garbage collection aborted!\"));\n }", " return did_free;\n}", "/*\n * Free lists, dictionaries, channels and jobs that are no longer referenced.\n */\n static int\nfree_unref_items(int copyID)\n{\n int\t\tdid_free = FALSE;", " // Let all \"free\" functions know that we are here. This means no\n // dictionaries, lists, channels or jobs are to be freed, because we will\n // do that here.\n in_free_unref_items = TRUE;", " /*\n * PASS 1: free the contents of the items. We don't free the items\n * themselves yet, so that it is possible to decrement refcount counters\n */", " // Go through the list of dicts and free items without this copyID.\n did_free |= dict_free_nonref(copyID);", " // Go through the list of lists and free items without this copyID.\n did_free |= list_free_nonref(copyID);", " // Go through the list of objects and free items without this copyID.\n did_free |= object_free_nonref(copyID);", "#ifdef FEAT_JOB_CHANNEL\n // Go through the list of jobs and free items without the copyID. This\n // must happen before doing channels, because jobs refer to channels, but\n // the reference from the channel to the job isn't tracked.\n did_free |= free_unused_jobs_contents(copyID, COPYID_MASK);", " // Go through the list of channels and free items without the copyID.\n did_free |= free_unused_channels_contents(copyID, COPYID_MASK);\n#endif", " /*\n * PASS 2: free the items themselves.\n */\n dict_free_items(copyID);\n list_free_items(copyID);", "#ifdef FEAT_JOB_CHANNEL\n // Go through the list of jobs and free items without the copyID. This\n // must happen before doing channels, because jobs refer to channels, but\n // the reference from the channel to the job isn't tracked.\n free_unused_jobs(copyID, COPYID_MASK);", " // Go through the list of channels and free items without the copyID.\n free_unused_channels(copyID, COPYID_MASK);\n#endif", " in_free_unref_items = FALSE;", " return did_free;\n}", "/*\n * Mark all lists and dicts referenced through hashtab \"ht\" with \"copyID\".\n * \"list_stack\" is used to add lists to be marked. Can be NULL.\n *\n * Returns TRUE if setting references failed somehow.\n */\n int\nset_ref_in_ht(hashtab_T *ht, int copyID, list_stack_T **list_stack)\n{\n int\t\ttodo;\n int\t\tabort = FALSE;\n hashitem_T\t*hi;\n hashtab_T\t*cur_ht;\n ht_stack_T\t*ht_stack = NULL;\n ht_stack_T\t*tempitem;", " cur_ht = ht;\n for (;;)\n {\n\tif (!abort)\n\t{\n\t // Mark each item in the hashtab. If the item contains a hashtab\n\t // it is added to ht_stack, if it contains a list it is added to\n\t // list_stack.\n\t todo = (int)cur_ht->ht_used;\n\t for (hi = cur_ht->ht_array; todo > 0; ++hi)\n\t\tif (!HASHITEM_EMPTY(hi))\n\t\t{\n\t\t --todo;\n\t\t abort = abort || set_ref_in_item(&HI2DI(hi)->di_tv, copyID,\n\t\t\t\t\t\t &ht_stack, list_stack);\n\t\t}\n\t}", "\tif (ht_stack == NULL)\n\t break;", "\t// take an item from the stack\n\tcur_ht = ht_stack->ht;\n\ttempitem = ht_stack;\n\tht_stack = ht_stack->prev;\n\tfree(tempitem);\n }", " return abort;\n}", "#if defined(FEAT_LUA) || defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) \\\n\t\t\t\t\t\t\t|| defined(PROTO)\n/*\n * Mark a dict and its items with \"copyID\".\n * Returns TRUE if setting references failed somehow.\n */\n int\nset_ref_in_dict(dict_T *d, int copyID)\n{\n if (d != NULL && d->dv_copyID != copyID)\n {\n\td->dv_copyID = copyID;\n\treturn set_ref_in_ht(&d->dv_hashtab, copyID, NULL);\n }\n return FALSE;\n}\n#endif", "/*\n * Mark a list and its items with \"copyID\".\n * Returns TRUE if setting references failed somehow.\n */\n int\nset_ref_in_list(list_T *ll, int copyID)\n{\n if (ll != NULL && ll->lv_copyID != copyID)\n {\n\tll->lv_copyID = copyID;\n\treturn set_ref_in_list_items(ll, copyID, NULL);\n }\n return FALSE;\n}", "/*\n * Mark all lists and dicts referenced through list \"l\" with \"copyID\".\n * \"ht_stack\" is used to add hashtabs to be marked. Can be NULL.\n *\n * Returns TRUE if setting references failed somehow.\n */\n int\nset_ref_in_list_items(list_T *l, int copyID, ht_stack_T **ht_stack)\n{\n listitem_T\t *li;\n int\t\t abort = FALSE;\n list_T\t *cur_l;\n list_stack_T *list_stack = NULL;\n list_stack_T *tempitem;", " cur_l = l;\n for (;;)\n {\n\tif (!abort && cur_l->lv_first != &range_list_item)\n\t // Mark each item in the list. If the item contains a hashtab\n\t // it is added to ht_stack, if it contains a list it is added to\n\t // list_stack.\n\t for (li = cur_l->lv_first; !abort && li != NULL; li = li->li_next)\n\t\tabort = abort || set_ref_in_item(&li->li_tv, copyID,\n\t\t\t\t\t\t ht_stack, &list_stack);\n\tif (list_stack == NULL)\n\t break;", "\t// take an item from the stack\n\tcur_l = list_stack->list;\n\ttempitem = list_stack;\n\tlist_stack = list_stack->prev;\n\tfree(tempitem);\n }", " return abort;\n}", "/*\n * Mark the partial in callback 'cb' with \"copyID\".\n */\n int\nset_ref_in_callback(callback_T *cb, int copyID)\n{\n typval_T tv;", " if (cb->cb_name == NULL || *cb->cb_name == NUL || cb->cb_partial == NULL)\n\treturn FALSE;", " tv.v_type = VAR_PARTIAL;\n tv.vval.v_partial = cb->cb_partial;\n return set_ref_in_item(&tv, copyID, NULL, NULL);\n}", "/*\n * Mark all lists, dicts and other container types referenced through typval\n * \"tv\" with \"copyID\".\n * \"list_stack\" is used to add lists to be marked. Can be NULL.\n * \"ht_stack\" is used to add hashtabs to be marked. Can be NULL.\n *\n * Returns TRUE if setting references failed somehow.\n */\n int\nset_ref_in_item(\n typval_T\t *tv,\n int\t\t copyID,\n ht_stack_T\t **ht_stack,\n list_stack_T **list_stack)\n{\n int\t\tabort = FALSE;", " switch (tv->v_type)\n {\n\tcase VAR_DICT:\n\t{\n\t dict_T\t*dd = tv->vval.v_dict;", "\t if (dd != NULL && dd->dv_copyID != copyID)\n\t {\n\t\t// Didn't see this dict yet.\n\t\tdd->dv_copyID = copyID;\n\t\tif (ht_stack == NULL)\n\t\t{\n\t\t abort = set_ref_in_ht(&dd->dv_hashtab, copyID, list_stack);\n\t\t}\n\t\telse\n\t\t{\n\t\t ht_stack_T *newitem = ALLOC_ONE(ht_stack_T);", "\t\t if (newitem == NULL)\n\t\t\tabort = TRUE;\n\t\t else\n\t\t {\n\t\t\tnewitem->ht = &dd->dv_hashtab;\n\t\t\tnewitem->prev = *ht_stack;\n\t\t\t*ht_stack = newitem;\n\t\t }\n\t\t}\n\t }\n\t break;\n\t}", "\tcase VAR_LIST:\n\t{\n\t list_T\t*ll = tv->vval.v_list;", "\t if (ll != NULL && ll->lv_copyID != copyID)\n\t {\n\t\t// Didn't see this list yet.\n\t\tll->lv_copyID = copyID;\n\t\tif (list_stack == NULL)\n\t\t{\n\t\t abort = set_ref_in_list_items(ll, copyID, ht_stack);\n\t\t}\n\t\telse\n\t\t{\n\t\t list_stack_T *newitem = ALLOC_ONE(list_stack_T);", "\t\t if (newitem == NULL)\n\t\t\tabort = TRUE;\n\t\t else\n\t\t {\n\t\t\tnewitem->list = ll;\n\t\t\tnewitem->prev = *list_stack;\n\t\t\t*list_stack = newitem;\n\t\t }\n\t\t}\n\t }\n\t break;\n\t}", "\tcase VAR_FUNC:\n\t{\n\t abort = set_ref_in_func(tv->vval.v_string, NULL, copyID);\n\t break;\n\t}", "\tcase VAR_PARTIAL:\n\t{\n\t partial_T\t*pt = tv->vval.v_partial;\n\t int\t\ti;", "\t if (pt != NULL && pt->pt_copyID != copyID)\n\t {\n\t\t// Didn't see this partial yet.\n\t\tpt->pt_copyID = copyID;", "\t\tabort = set_ref_in_func(pt->pt_name, pt->pt_func, copyID);", "\t\tif (pt->pt_dict != NULL)\n\t\t{\n\t\t typval_T dtv;", "\t\t dtv.v_type = VAR_DICT;\n\t\t dtv.vval.v_dict = pt->pt_dict;\n\t\t set_ref_in_item(&dtv, copyID, ht_stack, list_stack);\n\t\t}", "\t\tfor (i = 0; i < pt->pt_argc; ++i)\n\t\t abort = abort || set_ref_in_item(&pt->pt_argv[i], copyID,\n\t\t\t\t\t\t\t ht_stack, list_stack);\n\t\t// pt_funcstack is handled in set_ref_in_funcstacks()\n\t\t// pt_loopvars is handled in set_ref_in_loopvars()\n\t }\n\t break;\n\t}", "\tcase VAR_JOB:\n\t{\n#ifdef FEAT_JOB_CHANNEL\n\t job_T\t *job = tv->vval.v_job;\n\t typval_T dtv;", "\t if (job != NULL && job->jv_copyID != copyID)\n\t {\n\t\tjob->jv_copyID = copyID;\n\t\tif (job->jv_channel != NULL)\n\t\t{\n\t\t dtv.v_type = VAR_CHANNEL;\n\t\t dtv.vval.v_channel = job->jv_channel;\n\t\t set_ref_in_item(&dtv, copyID, ht_stack, list_stack);\n\t\t}\n\t\tif (job->jv_exit_cb.cb_partial != NULL)\n\t\t{\n\t\t dtv.v_type = VAR_PARTIAL;\n\t\t dtv.vval.v_partial = job->jv_exit_cb.cb_partial;\n\t\t set_ref_in_item(&dtv, copyID, ht_stack, list_stack);\n\t\t}\n\t }\n#endif\n\t break;\n\t}", "\tcase VAR_CHANNEL:\n\t{\n#ifdef FEAT_JOB_CHANNEL\n\t channel_T *ch = tv->vval.v_channel;\n\t ch_part_T part;\n\t typval_T dtv;\n\t jsonq_T\t*jq;\n\t cbq_T\t*cq;", "\t if (ch != NULL && ch->ch_copyID != copyID)\n\t {\n\t\tch->ch_copyID = copyID;\n\t\tfor (part = PART_SOCK; part < PART_COUNT; ++part)\n\t\t{\n\t\t for (jq = ch->ch_part[part].ch_json_head.jq_next;\n\t\t\t\t\t\t jq != NULL; jq = jq->jq_next)\n\t\t\tset_ref_in_item(jq->jq_value, copyID,\n\t\t\t\t\t\t\t ht_stack, list_stack);\n\t\t for (cq = ch->ch_part[part].ch_cb_head.cq_next; cq != NULL;\n\t\t\t\t\t\t\t cq = cq->cq_next)\n\t\t\tif (cq->cq_callback.cb_partial != NULL)\n\t\t\t{\n\t\t\t dtv.v_type = VAR_PARTIAL;\n\t\t\t dtv.vval.v_partial = cq->cq_callback.cb_partial;\n\t\t\t set_ref_in_item(&dtv, copyID, ht_stack, list_stack);\n\t\t\t}\n\t\t if (ch->ch_part[part].ch_callback.cb_partial != NULL)\n\t\t {\n\t\t\tdtv.v_type = VAR_PARTIAL;\n\t\t\tdtv.vval.v_partial =\n\t\t\t\t ch->ch_part[part].ch_callback.cb_partial;\n\t\t\tset_ref_in_item(&dtv, copyID, ht_stack, list_stack);\n\t\t }\n\t\t}\n\t\tif (ch->ch_callback.cb_partial != NULL)\n\t\t{\n\t\t dtv.v_type = VAR_PARTIAL;\n\t\t dtv.vval.v_partial = ch->ch_callback.cb_partial;\n\t\t set_ref_in_item(&dtv, copyID, ht_stack, list_stack);\n\t\t}\n\t\tif (ch->ch_close_cb.cb_partial != NULL)\n\t\t{\n\t\t dtv.v_type = VAR_PARTIAL;\n\t\t dtv.vval.v_partial = ch->ch_close_cb.cb_partial;\n\t\t set_ref_in_item(&dtv, copyID, ht_stack, list_stack);\n\t\t}\n\t }\n#endif\n\t break;\n\t}", "\tcase VAR_CLASS:\n\t // TODO: Mark methods in class_obj_methods ?\n\t // Mark initializer expressions?\n\t break;", "\tcase VAR_OBJECT:\n\t {\n\t\tobject_T *obj = tv->vval.v_object;\n\t\tif (obj != NULL && obj->obj_copyID != copyID)\n\t\t{\n\t\t obj->obj_copyID = copyID;", "\t\t // The typval_T array is right after the object_T.\n\t\t typval_T *mtv = (typval_T *)(obj + 1);\n\t\t for (int i = 0; !abort\n\t\t\t && i < obj->obj_class->class_obj_member_count; ++i)\n\t\t\tabort = abort || set_ref_in_item(mtv + i, copyID,\n\t\t\t\t\t\t\t ht_stack, list_stack);\n\t\t}\n\t\tbreak;\n\t }", "\tcase VAR_UNKNOWN:\n\tcase VAR_ANY:\n\tcase VAR_VOID:\n\tcase VAR_BOOL:\n\tcase VAR_SPECIAL:\n\tcase VAR_NUMBER:\n\tcase VAR_FLOAT:\n\tcase VAR_STRING:\n\tcase VAR_BLOB:\n\tcase VAR_INSTR:\n\t // Types that do not contain any other item\n\t break;\n }", " return abort;\n}", "/*\n * Return a string with the string representation of a variable.\n * If the memory is allocated \"tofree\" is set to it, otherwise NULL.\n * \"numbuf\" is used for a number.\n * When \"copyID\" is not NULL replace recursive lists and dicts with \"...\".\n * When both \"echo_style\" and \"composite_val\" are FALSE, put quotes around\n * strings as \"string()\", otherwise does not put quotes around strings, as\n * \":echo\" displays values.\n * When \"restore_copyID\" is FALSE, repeated items in dictionaries and lists\n * are replaced with \"...\".\n * May return NULL.\n */\n char_u *\necho_string_core(\n typval_T\t*tv,\n char_u\t**tofree,\n char_u\t*numbuf,\n int\t\tcopyID,\n int\t\techo_style,\n int\t\trestore_copyID,\n int\t\tcomposite_val)\n{\n static int\trecurse = 0;\n char_u\t*r = NULL;", " if (recurse >= DICT_MAXNEST)\n {\n\tif (!did_echo_string_emsg)\n\t{\n\t // Only give this message once for a recursive call to avoid\n\t // flooding the user with errors. And stop iterating over lists\n\t // and dicts.\n\t did_echo_string_emsg = TRUE;\n\t emsg(_(e_variable_nested_too_deep_for_displaying));\n\t}\n\t*tofree = NULL;\n\treturn (char_u *)\"{E724}\";\n }\n ++recurse;", " switch (tv->v_type)\n {\n\tcase VAR_STRING:\n\t if (echo_style && !composite_val)\n\t {\n\t\t*tofree = NULL;\n\t\tr = tv->vval.v_string;\n\t\tif (r == NULL)\n\t\t r = (char_u *)\"\";\n\t }\n\t else\n\t {\n\t\t*tofree = string_quote(tv->vval.v_string, FALSE);\n\t\tr = *tofree;\n\t }\n\t break;", "\tcase VAR_FUNC:\n\t {\n\t\tchar_u buf[MAX_FUNC_NAME_LEN];", "\t\tif (echo_style)\n\t\t{\n\t\t r = tv->vval.v_string == NULL ? (char_u *)\"function()\"\n\t\t\t\t : make_ufunc_name_readable(tv->vval.v_string,\n\t\t\t\t\t\t buf, MAX_FUNC_NAME_LEN);\n\t\t if (r == buf)\n\t\t {\n\t\t\tr = vim_strsave(buf);\n\t\t\t*tofree = r;\n\t\t }\n\t\t else\n\t\t\t*tofree = NULL;\n\t\t}\n\t\telse\n\t\t{\n\t\t *tofree = string_quote(tv->vval.v_string == NULL ? NULL\n\t\t\t : make_ufunc_name_readable(\n\t\t\t\ttv->vval.v_string, buf, MAX_FUNC_NAME_LEN),\n\t\t\t\t\t\t\t\t\t TRUE);\n\t\t r = *tofree;\n\t\t}\n\t }\n\t break;", "\tcase VAR_PARTIAL:\n\t {\n\t\tpartial_T *pt = tv->vval.v_partial;\n\t\tchar_u\t *fname = string_quote(pt == NULL ? NULL\n\t\t\t\t\t\t : partial_name(pt), FALSE);\n\t\tgarray_T ga;\n\t\tint\t i;\n\t\tchar_u\t *tf;", "\t\tga_init2(&ga, 1, 100);\n\t\tga_concat(&ga, (char_u *)\"function(\");\n\t\tif (fname != NULL)\n\t\t{\n\t\t // When using uf_name prepend \"g:\" for a global function.\n\t\t if (pt != NULL && pt->pt_name == NULL && fname[0] == '\\''\n\t\t\t\t\t\t && vim_isupper(fname[1]))\n\t\t {\n\t\t\tga_concat(&ga, (char_u *)\"'g:\");\n\t\t\tga_concat(&ga, fname + 1);\n\t\t }\n\t\t else\n\t\t\tga_concat(&ga, fname);\n\t\t vim_free(fname);\n\t\t}\n\t\tif (pt != NULL && pt->pt_argc > 0)\n\t\t{\n\t\t ga_concat(&ga, (char_u *)\", [\");\n\t\t for (i = 0; i < pt->pt_argc; ++i)\n\t\t {\n\t\t\tif (i > 0)\n\t\t\t ga_concat(&ga, (char_u *)\", \");\n\t\t\tga_concat(&ga,\n\t\t\t tv2string(&pt->pt_argv[i], &tf, numbuf, copyID));\n\t\t\tvim_free(tf);\n\t\t }\n\t\t ga_concat(&ga, (char_u *)\"]\");\n\t\t}\n\t\tif (pt != NULL && pt->pt_dict != NULL)\n\t\t{\n\t\t typval_T dtv;", "\t\t ga_concat(&ga, (char_u *)\", \");\n\t\t dtv.v_type = VAR_DICT;\n\t\t dtv.vval.v_dict = pt->pt_dict;\n\t\t ga_concat(&ga, tv2string(&dtv, &tf, numbuf, copyID));\n\t\t vim_free(tf);\n\t\t}\n\t\t// terminate with ')' and a NUL\n\t\tga_concat_len(&ga, (char_u *)\")\", 2);", "\t\t*tofree = ga.ga_data;\n\t\tr = *tofree;\n\t\tbreak;\n\t }", "\tcase VAR_BLOB:\n\t r = blob2string(tv->vval.v_blob, tofree, numbuf);\n\t break;", "\tcase VAR_LIST:\n\t if (tv->vval.v_list == NULL)\n\t {\n\t\t// NULL list is equivalent to empty list.\n\t\t*tofree = NULL;\n\t\tr = (char_u *)\"[]\";\n\t }\n\t else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID\n\t\t && tv->vval.v_list->lv_len > 0)\n\t {\n\t\t*tofree = NULL;\n\t\tr = (char_u *)\"[...]\";\n\t }\n\t else\n\t {\n\t\tint old_copyID = tv->vval.v_list->lv_copyID;", "\t\ttv->vval.v_list->lv_copyID = copyID;\n\t\t*tofree = list2string(tv, copyID, restore_copyID);\n\t\tif (restore_copyID)\n\t\t tv->vval.v_list->lv_copyID = old_copyID;\n\t\tr = *tofree;\n\t }\n\t break;", "\tcase VAR_DICT:\n\t if (tv->vval.v_dict == NULL)\n\t {\n\t\t// NULL dict is equivalent to empty dict.\n\t\t*tofree = NULL;\n\t\tr = (char_u *)\"{}\";\n\t }\n\t else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID\n\t\t && tv->vval.v_dict->dv_hashtab.ht_used != 0)\n\t {\n\t\t*tofree = NULL;\n\t\tr = (char_u *)\"{...}\";\n\t }\n\t else\n\t {\n\t\tint old_copyID = tv->vval.v_dict->dv_copyID;", "\t\ttv->vval.v_dict->dv_copyID = copyID;\n\t\t*tofree = dict2string(tv, copyID, restore_copyID);\n\t\tif (restore_copyID)\n\t\t tv->vval.v_dict->dv_copyID = old_copyID;\n\t\tr = *tofree;\n\t }\n\t break;", "\tcase VAR_NUMBER:\n\tcase VAR_UNKNOWN:\n\tcase VAR_ANY:\n\tcase VAR_VOID:\n\t *tofree = NULL;\n\t r = tv_get_string_buf(tv, numbuf);\n\t break;", "\tcase VAR_JOB:\n\tcase VAR_CHANNEL:\n#ifdef FEAT_JOB_CHANNEL\n\t *tofree = NULL;\n\t r = tv->v_type == VAR_JOB ? job_to_string_buf(tv, numbuf)\n\t\t\t\t\t : channel_to_string_buf(tv, numbuf);\n\t if (composite_val)\n\t {\n\t\t*tofree = string_quote(r, FALSE);\n\t\tr = *tofree;\n\t }\n#endif\n\t break;", "\tcase VAR_INSTR:\n\t *tofree = NULL;\n\t r = (char_u *)\"instructions\";\n\t break;", "\tcase VAR_CLASS:\n\t {\n\t\tclass_T *cl = tv->vval.v_class;\n\t\tsize_t len = 6 + (cl == NULL ? 9 : STRLEN(cl->class_name)) + 1;\n\t\tr = *tofree = alloc(len);\n\t\tvim_snprintf((char *)r, len, \"class %s\",\n\t\t\t cl == NULL ? \"[unknown]\" : (char *)cl->class_name);\n\t }\n\t break;", "\tcase VAR_OBJECT:\n\t {\n\t\tgarray_T ga;\n\t\tga_init2(&ga, 1, 50);\n\t\tga_concat(&ga, (char_u *)\"object of \");\n\t\tobject_T *obj = tv->vval.v_object;\n\t\tclass_T *cl = obj == NULL ? NULL : obj->obj_class;\n\t\tga_concat(&ga, cl == NULL ? (char_u *)\"[unknown]\"\n\t\t\t\t\t\t\t : cl->class_name);\n\t\tif (cl != NULL)\n\t\t{\n\t\t ga_concat(&ga, (char_u *)\" {\");\n\t\t for (int i = 0; i < cl->class_obj_member_count; ++i)\n\t\t {\n\t\t\tif (i > 0)\n\t\t\t ga_concat(&ga, (char_u *)\", \");\n\t\t\tocmember_T *m = &cl->class_obj_members[i];\n\t\t\tga_concat(&ga, m->ocm_name);\n\t\t\tga_concat(&ga, (char_u *)\": \");\n\t\t\tchar_u *tf = NULL;\n\t\t\tga_concat(&ga, echo_string_core(\n\t\t\t\t\t (typval_T *)(obj + 1) + i,\n\t\t\t\t\t &tf, numbuf, copyID, echo_style,\n\t\t\t\t\t restore_copyID, composite_val));\n\t\t\tvim_free(tf);\n\t\t }\n\t\t ga_concat(&ga, (char_u *)\"}\");\n\t\t}", "\t\t*tofree = r = ga.ga_data;\n\t }\n\t break;", "\tcase VAR_FLOAT:\n\t *tofree = NULL;\n\t vim_snprintf((char *)numbuf, NUMBUFLEN, \"%g\", tv->vval.v_float);\n\t r = numbuf;\n\t break;", "\tcase VAR_BOOL:\n\tcase VAR_SPECIAL:\n\t *tofree = NULL;\n\t r = (char_u *)get_var_special_name(tv->vval.v_number);\n\t break;\n }", " if (--recurse == 0)\n\tdid_echo_string_emsg = FALSE;\n return r;\n}", "/*\n * Return a string with the string representation of a variable.\n * If the memory is allocated \"tofree\" is set to it, otherwise NULL.\n * \"numbuf\" is used for a number.\n * Does not put quotes around strings, as \":echo\" displays values.\n * When \"copyID\" is not NULL replace recursive lists and dicts with \"...\".\n * May return NULL.\n */\n char_u *\necho_string(\n typval_T\t*tv,\n char_u\t**tofree,\n char_u\t*numbuf,\n int\t\tcopyID)\n{\n return echo_string_core(tv, tofree, numbuf, copyID, TRUE, FALSE, FALSE);\n}", "/*\n * Convert the specified byte index of line 'lnum' in buffer 'buf' to a\n * character index. Works only for loaded buffers. Returns -1 on failure.\n * The index of the first byte and the first character is zero.\n */\n int\nbuf_byteidx_to_charidx(buf_T *buf, int lnum, int byteidx)\n{\n char_u\t*str;\n char_u\t*t;\n int\t\tcount;", " if (buf == NULL || buf->b_ml.ml_mfp == NULL)\n\treturn -1;", " if (lnum > buf->b_ml.ml_line_count)\n\tlnum = buf->b_ml.ml_line_count;", " str = ml_get_buf(buf, lnum, FALSE);\n if (str == NULL)\n\treturn -1;", " if (*str == NUL)\n\treturn 0;", " // count the number of characters\n t = str;\n for (count = 0; *t != NUL && t <= str + byteidx; count++)\n\tt += mb_ptr2len(t);", " // In insert mode, when the cursor is at the end of a non-empty line,\n // byteidx points to the NUL character immediately past the end of the\n // string. In this case, add one to the character count.\n if (*t == NUL && byteidx != 0 && t == str + byteidx)\n\tcount++;", " return count - 1;\n}", "/*\n * Convert the specified character index of line 'lnum' in buffer 'buf' to a\n * byte index. Works only for loaded buffers. Returns -1 on failure.\n * The index of the first byte and the first character is zero.\n */\n int\nbuf_charidx_to_byteidx(buf_T *buf, int lnum, int charidx)\n{\n char_u\t*str;\n char_u\t*t;", " if (buf == NULL || buf->b_ml.ml_mfp == NULL)\n\treturn -1;", " if (lnum > buf->b_ml.ml_line_count)\n\tlnum = buf->b_ml.ml_line_count;", " str = ml_get_buf(buf, lnum, FALSE);\n if (str == NULL)\n\treturn -1;", " // Convert the character offset to a byte offset\n t = str;\n while (*t != NUL && --charidx > 0)\n\tt += mb_ptr2len(t);", " return t - str;\n}", "/*\n * Translate a String variable into a position.\n * Returns NULL when there is an error.\n */\n pos_T *\nvar2fpos(\n typval_T\t*varp,\n int\t\tdollar_lnum,\t// TRUE when $ is last line\n int\t\t*fnum,\t\t// set to fnum for '0, 'A, etc.\n int\t\tcharcol)\t// return character column\n{\n char_u\t\t*name;\n static pos_T\tpos;\n pos_T\t\t*pp;", " // Argument can be [lnum, col, coladd].\n if (varp->v_type == VAR_LIST)\n {\n\tlist_T\t\t*l;\n\tint\t\tlen;\n\tint\t\terror = FALSE;\n\tlistitem_T\t*li;", "\tl = varp->vval.v_list;\n\tif (l == NULL)\n\t return NULL;", "\t// Get the line number\n\tpos.lnum = list_find_nr(l, 0L, &error);\n\tif (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)\n\t return NULL;\t// invalid line number\n\tif (charcol)\n\t len = (long)mb_charlen(ml_get(pos.lnum));\n\telse\n\t len = (long)STRLEN(ml_get(pos.lnum));", "\t// Get the column number\n\t// We accept \"$\" for the column number: last column.\n\tli = list_find(l, 1L);\n\tif (li != NULL && li->li_tv.v_type == VAR_STRING\n\t\t&& li->li_tv.vval.v_string != NULL\n\t\t&& STRCMP(li->li_tv.vval.v_string, \"$\") == 0)\n\t{\n\t pos.col = len + 1;\n\t}\n\telse\n\t{\n\t pos.col = list_find_nr(l, 1L, &error);\n\t if (error)\n\t\treturn NULL;\n\t}", "\t// Accept a position up to the NUL after the line.\n\tif (pos.col == 0 || (int)pos.col > len + 1)\n\t return NULL;\t// invalid column number\n\t--pos.col;", "\t// Get the virtual offset. Defaults to zero.\n\tpos.coladd = list_find_nr(l, 2L, &error);\n\tif (error)\n\t pos.coladd = 0;", "\treturn &pos;\n }", " if (in_vim9script() && check_for_string_arg(varp, 0) == FAIL)\n\treturn NULL;", " name = tv_get_string_chk(varp);\n if (name == NULL)\n\treturn NULL;", " pos.lnum = 0;\n if (name[0] == '.' && (!in_vim9script() || name[1] == NUL))\n {\n\t// cursor\n\tpos = curwin->w_cursor;\n }\n else if (name[0] == 'v' && name[1] == NUL)\n {\n\t// Visual start\n\tif (VIsual_active)\n\t pos = VIsual;\n\telse\n\t pos = curwin->w_cursor;\n }\n else if (name[0] == '\\'' && (!in_vim9script()\n\t\t\t\t\t|| (name[1] != NUL && name[2] == NUL)))\n {\n\t// mark\n\tpp = getmark_buf_fnum(curbuf, name[1], FALSE, fnum);\n\tif (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)\n\t return NULL;\n\tpos = *pp;\n }\n if (pos.lnum != 0)\n {\n\tif (charcol)\n\t pos.col = buf_byteidx_to_charidx(curbuf, pos.lnum, pos.col);\n\treturn &pos;\n }", " pos.coladd = 0;", " if (name[0] == 'w' && dollar_lnum)\n {\n\tpos.col = 0;\n\tif (name[1] == '0')\t\t// \"w0\": first visible line\n\t{\n\t update_topline();\n\t // In silent Ex mode topline is zero, but that's not a valid line\n\t // number; use one instead.\n\t pos.lnum = curwin->w_topline > 0 ? curwin->w_topline : 1;\n\t return &pos;\n\t}\n\telse if (name[1] == '$')\t// \"w$\": last visible line\n\t{\n\t validate_botline();\n\t // In silent Ex mode botline is zero, return zero then.\n\t pos.lnum = curwin->w_botline > 0 ? curwin->w_botline - 1 : 0;\n\t return &pos;\n\t}\n }\n else if (name[0] == '$')\t\t// last column or line\n {\n\tif (dollar_lnum)\n\t{\n\t pos.lnum = curbuf->b_ml.ml_line_count;\n\t pos.col = 0;\n\t}\n\telse\n\t{\n\t pos.lnum = curwin->w_cursor.lnum;\n\t if (charcol)\n\t\tpos.col = (colnr_T)mb_charlen(ml_get_curline());\n\t else\n\t\tpos.col = (colnr_T)STRLEN(ml_get_curline());\n\t}\n\treturn &pos;\n }\n if (in_vim9script())\n\tsemsg(_(e_invalid_value_for_line_number_str), name);\n return NULL;\n}", "/*\n * Convert list in \"arg\" into position \"posp\" and optional file number \"fnump\".\n * When \"fnump\" is NULL there is no file number, only 3 items: [lnum, col, off]\n * Note that the column is passed on as-is, the caller may want to decrement\n * it to use 1 for the first column.\n * If \"charcol\" is TRUE use the column as the character index instead of the\n * byte index.\n * Return FAIL when conversion is not possible, doesn't check the position for\n * validity.\n */\n int\nlist2fpos(\n typval_T\t*arg,\n pos_T\t*posp,\n int\t\t*fnump,\n colnr_T\t*curswantp,\n int\t\tcharcol)\n{\n list_T\t*l = arg->vval.v_list;\n long\ti = 0;\n long\tn;", " // List must be: [fnum, lnum, col, coladd, curswant], where \"fnum\" is only\n // there when \"fnump\" isn't NULL; \"coladd\" and \"curswant\" are optional.\n if (arg->v_type != VAR_LIST\n\t || l == NULL\n\t || l->lv_len < (fnump == NULL ? 2 : 3)\n\t || l->lv_len > (fnump == NULL ? 4 : 5))\n\treturn FAIL;", " if (fnump != NULL)\n {\n\tn = list_find_nr(l, i++, NULL);\t// fnum\n\tif (n < 0)\n\t return FAIL;\n\tif (n == 0)\n\t n = curbuf->b_fnum;\t\t// current buffer\n\t*fnump = n;\n }", " n = list_find_nr(l, i++, NULL);\t// lnum\n if (n < 0)\n\treturn FAIL;\n posp->lnum = n;", " n = list_find_nr(l, i++, NULL);\t// col\n if (n < 0)\n\treturn FAIL;\n // If character position is specified, then convert to byte position\n // If the line number is zero use the cursor line.\n if (charcol)\n {\n\tbuf_T\t*buf;", "\t// Get the text for the specified line in a loaded buffer\n\tbuf = buflist_findnr(fnump == NULL ? curbuf->b_fnum : *fnump);\n\tif (buf == NULL || buf->b_ml.ml_mfp == NULL)\n\t return FAIL;", "\tn = buf_charidx_to_byteidx(buf,\n\t\t posp->lnum == 0 ? curwin->w_cursor.lnum : posp->lnum, n) + 1;\n }\n posp->col = n;", " n = list_find_nr(l, i, NULL);\t// off\n if (n < 0)\n\tposp->coladd = 0;\n else\n\tposp->coladd = n;", " if (curswantp != NULL)\n\t*curswantp = list_find_nr(l, i + 1, NULL); // curswant", " return OK;\n}", "/*\n * Get the length of an environment variable name.\n * Advance \"arg\" to the first character after the name.\n * Return 0 for error.\n */\n int\nget_env_len(char_u **arg)\n{\n char_u\t*p;\n int\t\tlen;", " for (p = *arg; vim_isIDc(*p); ++p)\n\t;\n if (p == *arg)\t // no name found\n\treturn 0;", " len = (int)(p - *arg);\n *arg = p;\n return len;\n}", "/*\n * Get the length of the name of a function or internal variable.\n * \"arg\" is advanced to after the name.\n * Return 0 if something is wrong.\n */\n int\nget_id_len(char_u **arg)\n{\n char_u\t*p;\n int\t\tlen;", " // Find the end of the name.\n for (p = *arg; eval_isnamec(*p); ++p)\n {\n\tif (*p == ':')\n\t{\n\t // \"s:\" is start of \"s:var\", but \"n:\" is not and can be used in\n\t // slice \"[n:]\". Also \"xx:\" is not a namespace.\n\t len = (int)(p - *arg);\n\t if ((len == 1 && vim_strchr(NAMESPACE_CHAR, **arg) == NULL)\n\t\t || len > 1)\n\t\tbreak;\n\t}\n }\n if (p == *arg)\t // no name found\n\treturn 0;", " len = (int)(p - *arg);\n *arg = p;", " return len;\n}", "/*\n * Get the length of the name of a variable or function.\n * Only the name is recognized, does not handle \".key\" or \"[idx]\".\n * \"arg\" is advanced to the first non-white character after the name.\n * Return -1 if curly braces expansion failed.\n * Return 0 if something else is wrong.\n * If the name contains 'magic' {}'s, expand them and return the\n * expanded name in an allocated string via 'alias' - caller must free.\n */\n int\nget_name_len(\n char_u\t**arg,\n char_u\t**alias,\n int\t\tevaluate,\n int\t\tverbose)\n{\n int\t\tlen;\n char_u\t*p;\n char_u\t*expr_start;\n char_u\t*expr_end;", " *alias = NULL; // default to no alias", " if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA\n\t\t\t\t\t\t && (*arg)[2] == (int)KE_SNR)\n {\n\t// hard coded <SNR>, already translated\n\t*arg += 3;\n\treturn get_id_len(arg) + 3;\n }\n len = eval_fname_script(*arg);\n if (len > 0)\n {\n\t// literal \"<SID>\", \"s:\" or \"<SNR>\"\n\t*arg += len;\n }", " /*\n * Find the end of the name; check for {} construction.\n */\n p = find_name_end(*arg, &expr_start, &expr_end,\n\t\t\t\t\t len > 0 ? 0 : FNE_CHECK_START);\n if (expr_start != NULL)\n {\n\tchar_u\t*temp_string;", "\tif (!evaluate)\n\t{\n\t len += (int)(p - *arg);\n\t *arg = skipwhite(p);\n\t return len;\n\t}", "\t/*\n\t * Include any <SID> etc in the expanded string:\n\t * Thus the -len here.\n\t */\n\ttemp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);\n\tif (temp_string == NULL)\n\t return -1;\n\t*alias = temp_string;\n\t*arg = skipwhite(p);\n\treturn (int)STRLEN(temp_string);\n }", " len += get_id_len(arg);\n // Only give an error when there is something, otherwise it will be\n // reported at a higher level.\n if (len == 0 && verbose && **arg != NUL)\n\tsemsg(_(e_invalid_expression_str), *arg);", " return len;\n}", "/*\n * Find the end of a variable or function name, taking care of magic braces.\n * If \"expr_start\" is not NULL then \"expr_start\" and \"expr_end\" are set to the\n * start and end of the first magic braces item.\n * \"flags\" can have FNE_INCL_BR and FNE_CHECK_START.\n * Return a pointer to just after the name. Equal to \"arg\" if there is no\n * valid name.\n */\n char_u *\nfind_name_end(\n char_u\t*arg,\n char_u\t**expr_start,\n char_u\t**expr_end,\n int\t\tflags)\n{\n int\t\tmb_nest = 0;\n int\t\tbr_nest = 0;\n char_u\t*p;\n int\t\tlen;\n int\t\tvim9script = in_vim9script();", " if (expr_start != NULL)\n {\n\t*expr_start = NULL;\n\t*expr_end = NULL;\n }", " // Quick check for valid starting character.\n if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg)\n\t\t\t\t\t\t&& (*arg != '{' || vim9script))\n\treturn arg;", " for (p = arg; *p != NUL\n\t\t && (eval_isnamec(*p)\n\t\t\t|| (*p == '{' && !vim9script)\n\t\t\t|| ((flags & FNE_INCL_BR) && (*p == '['\n\t\t\t\t\t || (*p == '.' && eval_isdictc(p[1]))))\n\t\t\t|| mb_nest != 0\n\t\t\t|| br_nest != 0); MB_PTR_ADV(p))\n {\n\tif (*p == '\\'')\n\t{\n\t // skip over 'string' to avoid counting [ and ] inside it.\n\t for (p = p + 1; *p != NUL && *p != '\\''; MB_PTR_ADV(p))\n\t\t;\n\t if (*p == NUL)\n\t\tbreak;\n\t}\n\telse if (*p == '\"')\n\t{\n\t // skip over \"str\\\"ing\" to avoid counting [ and ] inside it.\n\t for (p = p + 1; *p != NUL && *p != '\"'; MB_PTR_ADV(p))\n\t\tif (*p == '\\\\' && p[1] != NUL)\n\t\t ++p;\n\t if (*p == NUL)\n\t\tbreak;\n\t}\n\telse if (br_nest == 0 && mb_nest == 0 && *p == ':')\n\t{\n\t // \"s:\" is start of \"s:var\", but \"n:\" is not and can be used in\n\t // slice \"[n:]\". Also \"xx:\" is not a namespace. But {ns}: is.\n\t len = (int)(p - arg);\n\t if ((len == 1 && vim_strchr(NAMESPACE_CHAR, *arg) == NULL)\n\t\t || (len > 1 && p[-1] != '}'))\n\t\tbreak;\n\t}", "\tif (mb_nest == 0)\n\t{\n\t if (*p == '[')\n\t\t++br_nest;\n\t else if (*p == ']')\n\t\t--br_nest;\n\t}", "\tif (br_nest == 0 && !vim9script)\n\t{\n\t if (*p == '{')\n\t {\n\t\tmb_nest++;\n\t\tif (expr_start != NULL && *expr_start == NULL)\n\t\t *expr_start = p;\n\t }\n\t else if (*p == '}')\n\t {\n\t\tmb_nest--;\n\t\tif (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)\n\t\t *expr_end = p;\n\t }\n\t}\n }", " return p;\n}", "/*\n * Expands out the 'magic' {}'s in a variable/function name.\n * Note that this can call itself recursively, to deal with\n * constructs like foo{bar}{baz}{bam}\n * The four pointer arguments point to \"foo{expre}ss{ion}bar\"\n *\t\t\t\"in_start\" ^\n *\t\t\t\"expr_start\"\t ^\n *\t\t\t\"expr_end\"\t\t ^\n *\t\t\t\"in_end\"\t\t\t ^\n *\n * Returns a new allocated string, which the caller must free.\n * Returns NULL for failure.\n */\n static char_u *\nmake_expanded_name(\n char_u\t*in_start,\n char_u\t*expr_start,\n char_u\t*expr_end,\n char_u\t*in_end)\n{\n char_u\tc1;\n char_u\t*retval = NULL;\n char_u\t*temp_result;", " if (expr_end == NULL || in_end == NULL)\n\treturn NULL;\n *expr_start\t= NUL;\n *expr_end = NUL;\n c1 = *in_end;\n *in_end = NUL;", " temp_result = eval_to_string(expr_start + 1, FALSE, FALSE);\n if (temp_result != NULL)\n {\n\tretval = alloc(STRLEN(temp_result) + (expr_start - in_start)\n\t\t\t\t\t\t + (in_end - expr_end) + 1);\n\tif (retval != NULL)\n\t{\n\t STRCPY(retval, in_start);\n\t STRCAT(retval, temp_result);\n\t STRCAT(retval, expr_end + 1);\n\t}\n }\n vim_free(temp_result);", " *in_end = c1;\t\t// put char back for error messages\n *expr_start = '{';\n *expr_end = '}';", " if (retval != NULL)\n {\n\ttemp_result = find_name_end(retval, &expr_start, &expr_end, 0);\n\tif (expr_start != NULL)\n\t{\n\t // Further expansion!\n\t temp_result = make_expanded_name(retval, expr_start,\n\t\t\t\t\t\t expr_end, temp_result);\n\t vim_free(retval);\n\t retval = temp_result;\n\t}\n }", " return retval;\n}", "/*\n * Return TRUE if character \"c\" can be used in a variable or function name.\n * Does not include '{' or '}' for magic braces.\n */\n int\neval_isnamec(int c)\n{\n return ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR;\n}", "/*\n * Return TRUE if character \"c\" can be used as the first character in a\n * variable or function name (excluding '{' and '}').\n */\n int\neval_isnamec1(int c)\n{\n return ASCII_ISALPHA(c) || c == '_';\n}", "/*\n * Return TRUE if character \"c\" can be used as the first character of a\n * dictionary key.\n */\n int\neval_isdictc(int c)\n{\n return ASCII_ISALNUM(c) || c == '_';\n}", "/*\n * Handle:\n * - expr[expr], expr[expr:expr] subscript\n * - \".name\" lookup\n * - function call with Funcref variable: func(expr)\n * - method call: var->method()\n *\n * Can all be combined in any order: dict.func(expr)[idx]['func'](expr)->len()\n * \"name_start\" points to a variable before the subscript or is NULL.\n */\n int\nhandle_subscript(\n char_u\t**arg,\n char_u\t*name_start,\n typval_T\t*rettv,\n evalarg_T\t*evalarg,\n int\t\tverbose)\t// give error messages\n{\n int\t\tevaluate = evalarg != NULL\n\t\t\t\t && (evalarg->eval_flags & EVAL_EVALUATE);\n int\t\tret = OK;\n dict_T\t*selfdict = NULL;\n int\t\tcheck_white = TRUE;\n int\t\tgetnext;\n char_u\t*p;", " while (ret == OK)\n {\n\t// When at the end of the line and \".name\" or \"->{\" or \"->X\" follows in\n\t// the next line then consume the line break.\n\tp = eval_next_non_blank(*arg, evalarg, &getnext);\n\tif (getnext\n\t && ((rettv->v_type == VAR_DICT && *p == '.' && eval_isdictc(p[1]))\n\t\t|| (p[0] == '-' && p[1] == '>' && (p[2] == '{'\n\t\t\t|| ASCII_ISALPHA(in_vim9script() ? *skipwhite(p + 2)\n\t\t\t\t\t\t\t\t : p[2])))))\n\t{\n\t *arg = eval_next_line(*arg, evalarg);\n\t p = *arg;\n\t check_white = FALSE;\n\t}", "\tif (rettv->v_type == VAR_ANY)\n\t{\n\t char_u\t*exp_name;\n\t int\t\tcc;\n\t int\t\tidx;\n\t ufunc_T\t*ufunc;\n\t type_T\t*type;", "\t // Found script from \"import {name} as name\", script item name must\n\t // follow. \"rettv->vval.v_number\" has the script ID.\n\t if (**arg != '.')\n\t {\n\t\tif (verbose)\n\t\t semsg(_(e_expected_dot_after_name_str),\n\t\t\t\t\tname_start != NULL ? name_start: *arg);\n\t\tret = FAIL;\n\t\tbreak;\n\t }\n\t ++*arg;\n\t if (IS_WHITE_OR_NUL(**arg))\n\t {\n\t\tif (verbose)\n\t\t emsg(_(e_no_white_space_allowed_after_dot));\n\t\tret = FAIL;\n\t\tbreak;\n\t }", "\t // isolate the name\n\t exp_name = *arg;\n\t while (eval_isnamec(**arg))\n\t\t++*arg;\n\t cc = **arg;\n\t **arg = NUL;", "\t idx = find_exported(rettv->vval.v_number, exp_name, &ufunc, &type,\n\t\t evalarg == NULL ? NULL : evalarg->eval_cctx,\n\t\t evalarg == NULL ? NULL : evalarg->eval_cstack, verbose);\n\t **arg = cc;", "\t if (idx < 0 && ufunc == NULL)\n\t {\n\t\tret = FAIL;\n\t\tbreak;\n\t }\n\t if (idx >= 0)\n\t {\n\t\tscriptitem_T *si = SCRIPT_ITEM(rettv->vval.v_number);\n\t\tsvar_T\t\t*sv = ((svar_T *)si->sn_var_vals.ga_data) + idx;", "\t\tcopy_tv(sv->sv_tv, rettv);\n\t }\n\t else\n\t {\n\t\trettv->v_type = VAR_FUNC;\n\t\trettv->vval.v_string = vim_strsave(ufunc->uf_name);\n\t }\n\t continue;\n\t}", "\tif ((**arg == '(' && (!evaluate || rettv->v_type == VAR_FUNC\n\t\t\t || rettv->v_type == VAR_PARTIAL))\n\t\t && (!check_white || !VIM_ISWHITE(*(*arg - 1))))\n\t{\n\t ret = call_func_rettv(arg, evalarg, rettv, evaluate,\n\t\t\t\t\t\t\t selfdict, NULL);", "\t // Stop the expression evaluation when immediately aborting on\n\t // error, or when an interrupt occurred or an exception was thrown\n\t // but not caught.\n\t if (aborting())\n\t {\n\t\tif (ret == OK)\n\t\t clear_tv(rettv);\n\t\tret = FAIL;\n\t }\n\t dict_unref(selfdict);\n\t selfdict = NULL;\n\t}\n\telse if (p[0] == '-' && p[1] == '>')\n\t{\n\t if (in_vim9script())\n\t\t*arg = skipwhite(p + 2);\n\t else\n\t\t*arg = p + 2;\n\t if (ret == OK)\n\t {\n\t\tif (VIM_ISWHITE(**arg))\n\t\t{\n\t\t emsg(_(e_no_white_space_allowed_before_parenthesis));\n\t\t ret = FAIL;\n\t\t}\n\t\telse if ((**arg == '{' && !in_vim9script()) || **arg == '(')\n\t\t // expr->{lambda}() or expr->(lambda)()\n\t\t ret = eval_lambda(arg, rettv, evalarg, verbose);\n\t\telse\n\t\t // expr->name()\n\t\t ret = eval_method(arg, rettv, evalarg, verbose);\n\t }\n\t}\n\t// \".\" is \".name\" lookup when we found a dict or when evaluating and\n\t// scriptversion is at least 2, where string concatenation is \"..\".\n\telse if (**arg == '['\n\t\t|| (**arg == '.' && (rettv->v_type == VAR_DICT\n\t\t\t|| (!evaluate\n\t\t\t && (*arg)[1] != '.'\n\t\t\t && !in_old_script(2)))))\n\t{\n\t dict_unref(selfdict);\n\t if (rettv->v_type == VAR_DICT)\n\t {\n\t\tselfdict = rettv->vval.v_dict;\n\t\tif (selfdict != NULL)\n\t\t ++selfdict->dv_refcount;\n\t }\n\t else\n\t\tselfdict = NULL;\n\t if (eval_index(arg, rettv, evalarg, verbose) == FAIL)\n\t {\n\t\tclear_tv(rettv);\n\t\tret = FAIL;\n\t }\n\t}\n\telse if (**arg == '.' && (rettv->v_type == VAR_CLASS\n\t\t\t\t\t || rettv->v_type == VAR_OBJECT))\n\t{\n\t // class member: SomeClass.varname\n\t // class method: SomeClass.SomeMethod()\n\t // class constructor: SomeClass.new()\n\t // object member: someObject.varname\n\t // object method: someObject.SomeMethod()\n\t if (class_object_index(arg, rettv, evalarg, verbose) == FAIL)\n\t {\n\t\tclear_tv(rettv);\n\t\tret = FAIL;\n\t }\n\t}\n\telse\n\t break;\n }", " // Turn \"dict.Func\" into a partial for \"Func\" bound to \"dict\".\n // Don't do this when \"Func\" is already a partial that was bound\n // explicitly (pt_auto is FALSE).\n if (selfdict != NULL\n\t && (rettv->v_type == VAR_FUNC\n\t\t|| (rettv->v_type == VAR_PARTIAL\n\t\t && (rettv->vval.v_partial->pt_auto\n\t\t\t|| rettv->vval.v_partial->pt_dict == NULL))))\n\tselfdict = make_partial(selfdict, rettv);", " dict_unref(selfdict);\n return ret;\n}", "/*\n * Make a copy of an item.\n * Lists and Dictionaries are also copied. A deep copy if \"deep\" is set.\n * \"top\" is TRUE for the toplevel of copy().\n * For deepcopy() \"copyID\" is zero for a full copy or the ID for when a\n * reference to an already copied list/dict can be used.\n * Returns FAIL or OK.\n */\n int\nitem_copy(\n typval_T\t*from,\n typval_T\t*to,\n int\t\tdeep,\n int\t\ttop,\n int\t\tcopyID)\n{\n static int\trecurse = 0;\n int\t\tret = OK;", " if (recurse >= DICT_MAXNEST)\n {\n\temsg(_(e_variable_nested_too_deep_for_making_copy));\n\treturn FAIL;\n }\n ++recurse;", " switch (from->v_type)\n {\n\tcase VAR_NUMBER:\n\tcase VAR_FLOAT:\n\tcase VAR_STRING:\n\tcase VAR_FUNC:\n\tcase VAR_PARTIAL:\n\tcase VAR_BOOL:\n\tcase VAR_SPECIAL:\n\tcase VAR_JOB:\n\tcase VAR_CHANNEL:\n\tcase VAR_INSTR:\n\tcase VAR_CLASS:\n\tcase VAR_OBJECT:\n\t copy_tv(from, to);\n\t break;\n\tcase VAR_LIST:\n\t to->v_type = VAR_LIST;\n\t to->v_lock = 0;\n\t if (from->vval.v_list == NULL)\n\t\tto->vval.v_list = NULL;\n\t else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)\n\t {\n\t\t// use the copy made earlier\n\t\tto->vval.v_list = from->vval.v_list->lv_copylist;\n\t\t++to->vval.v_list->lv_refcount;\n\t }\n\t else\n\t\tto->vval.v_list = list_copy(from->vval.v_list,\n\t\t\t\t\t\t\t deep, top, copyID);\n\t if (to->vval.v_list == NULL)\n\t\tret = FAIL;\n\t break;\n\tcase VAR_BLOB:\n\t ret = blob_copy(from->vval.v_blob, to);\n\t break;\n\tcase VAR_DICT:\n\t to->v_type = VAR_DICT;\n\t to->v_lock = 0;\n\t if (from->vval.v_dict == NULL)\n\t\tto->vval.v_dict = NULL;\n\t else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)\n\t {\n\t\t// use the copy made earlier\n\t\tto->vval.v_dict = from->vval.v_dict->dv_copydict;\n\t\t++to->vval.v_dict->dv_refcount;\n\t }\n\t else\n\t\tto->vval.v_dict = dict_copy(from->vval.v_dict,\n\t\t\t\t\t\t\t deep, top, copyID);\n\t if (to->vval.v_dict == NULL)\n\t\tret = FAIL;\n\t break;\n\tcase VAR_UNKNOWN:\n\tcase VAR_ANY:\n\tcase VAR_VOID:\n\t internal_error_no_abort(\"item_copy(UNKNOWN)\");\n\t ret = FAIL;\n }\n --recurse;\n return ret;\n}", " void\necho_one(typval_T *rettv, int with_space, int *atstart, int *needclr)\n{\n char_u\t*tofree;\n char_u\tnumbuf[NUMBUFLEN];\n char_u\t*p = echo_string(rettv, &tofree, numbuf, get_copyID());", " if (*atstart)\n {\n\t*atstart = FALSE;\n\t// Call msg_start() after eval1(), evaluating the expression\n\t// may cause a message to appear.\n\tif (with_space)\n\t{\n\t // Mark the saved text as finishing the line, so that what\n\t // follows is displayed on a new line when scrolling back\n\t // at the more prompt.\n\t msg_sb_eol();\n\t msg_start();\n\t}\n }\n else if (with_space)\n\tmsg_puts_attr(\" \", echo_attr);", " if (p != NULL)\n\tfor ( ; *p != NUL && !got_int; ++p)\n\t{\n\t if (*p == '\\n' || *p == '\\r' || *p == TAB)\n\t {\n\t\tif (*p != TAB && *needclr)\n\t\t{\n\t\t // remove any text still there from the command\n\t\t msg_clr_eos();\n\t\t *needclr = FALSE;\n\t\t}\n\t\tmsg_putchar_attr(*p, echo_attr);\n\t }\n\t else\n\t {\n\t\tif (has_mbyte)\n\t\t{\n\t\t int i = (*mb_ptr2len)(p);", "\t\t (void)msg_outtrans_len_attr(p, i, echo_attr);\n\t\t p += i - 1;\n\t\t}\n\t\telse\n\t\t (void)msg_outtrans_len_attr(p, 1, echo_attr);\n\t }\n\t}\n vim_free(tofree);\n}", "/*\n * \":echo expr1 ...\"\tprint each argument separated with a space, add a\n *\t\t\tnewline at the end.\n * \":echon expr1 ...\"\tprint each argument plain.\n */\n void\nex_echo(exarg_T *eap)\n{\n char_u\t*arg = eap->arg;\n typval_T\trettv;\n char_u\t*arg_start;\n int\t\tneedclr = TRUE;\n int\t\tatstart = TRUE;\n int\t\tdid_emsg_before = did_emsg;\n int\t\tcalled_emsg_before = called_emsg;\n evalarg_T\tevalarg;", " fill_evalarg_from_eap(&evalarg, eap, eap->skip);", " if (eap->skip)\n\t++emsg_skip;\n while ((!ends_excmd2(eap->cmd, arg) || *arg == '\"') && !got_int)\n {\n\t// If eval1() causes an error message the text from the command may\n\t// still need to be cleared. E.g., \"echo 22,44\".\n\tneed_clr_eos = needclr;", "\targ_start = arg;\n\tif (eval1(&arg, &rettv, &evalarg) == FAIL)\n\t{\n\t /*\n\t * Report the invalid expression unless the expression evaluation\n\t * has been cancelled due to an aborting error, an interrupt, or an\n\t * exception.\n\t */\n\t if (!aborting() && did_emsg == did_emsg_before\n\t\t\t\t\t && called_emsg == called_emsg_before)\n\t\tsemsg(_(e_invalid_expression_str), arg_start);\n\t need_clr_eos = FALSE;\n\t break;\n\t}\n\tneed_clr_eos = FALSE;", "\tif (!eap->skip)\n\t{\n\t if (rettv.v_type == VAR_VOID)\n\t {\n\t\tsemsg(_(e_expression_does_not_result_in_value_str), arg_start);\n\t\tbreak;\n\t }\n\t echo_one(&rettv, eap->cmdidx == CMD_echo, &atstart, &needclr);\n\t}", "\tclear_tv(&rettv);\n\targ = skipwhite(arg);\n }\n set_nextcmd(eap, arg);\n clear_evalarg(&evalarg, eap);", " if (eap->skip)\n\t--emsg_skip;\n else\n {\n\t// remove text that may still be there from the command\n\tif (needclr)\n\t msg_clr_eos();\n\tif (eap->cmdidx == CMD_echo)\n\t msg_end();\n }\n}", "/*\n * \":echohl {name}\".\n */\n void\nex_echohl(exarg_T *eap)\n{\n echo_attr = syn_name2attr(eap->arg);\n}", "/*\n * Returns the :echo attribute\n */\n int\nget_echo_attr(void)\n{\n return echo_attr;\n}", "/*\n * \":execute expr1 ...\"\texecute the result of an expression.\n * \":echomsg expr1 ...\"\tPrint a message\n * \":echowindow expr1 ...\" Print a message in the messages window\n * \":echoerr expr1 ...\"\tPrint an error\n * \":echoconsole expr1 ...\" Print a message on stdout\n * Each gets spaces around each argument and a newline at the end for\n * echo commands\n */\n void\nex_execute(exarg_T *eap)\n{\n char_u\t*arg = eap->arg;\n typval_T\trettv;\n int\t\tret = OK;\n char_u\t*p;\n garray_T\tga;\n int\t\tlen;\n long\tstart_lnum = SOURCING_LNUM;", " ga_init2(&ga, 1, 80);", " if (eap->skip)\n\t++emsg_skip;\n while (!ends_excmd2(eap->cmd, arg) || *arg == '\"')\n {\n\tret = eval1_emsg(&arg, &rettv, eap);\n\tif (ret == FAIL)\n\t break;", "\tif (!eap->skip)\n\t{\n\t char_u buf[NUMBUFLEN];", "\t if (eap->cmdidx == CMD_execute)\n\t {\n\t\tif (rettv.v_type == VAR_CHANNEL || rettv.v_type == VAR_JOB)\n\t\t{\n\t\t semsg(_(e_using_invalid_value_as_string_str),\n\t\t\t\t\t\t vartype_name(rettv.v_type));\n\t\t p = NULL;\n\t\t}\n\t\telse\n\t\t p = tv_get_string_buf(&rettv, buf);\n\t }\n\t else\n\t\tp = tv_stringify(&rettv, buf);\n\t if (p == NULL)\n\t {\n\t\tclear_tv(&rettv);\n\t\tret = FAIL;\n\t\tbreak;\n\t }\n\t len = (int)STRLEN(p);\n\t if (ga_grow(&ga, len + 2) == FAIL)\n\t {\n\t\tclear_tv(&rettv);\n\t\tret = FAIL;\n\t\tbreak;\n\t }\n\t if (ga.ga_len)\n\t\t((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';\n\t STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);\n\t ga.ga_len += len;\n\t}", "\tclear_tv(&rettv);\n\targ = skipwhite(arg);\n }", " if (ret != FAIL && ga.ga_data != NULL)\n {\n\t// use the first line of continuation lines for messages\n\tSOURCING_LNUM = start_lnum;", "\tif (eap->cmdidx == CMD_echomsg\n\t\t|| eap->cmdidx == CMD_echowindow\n\t\t|| eap->cmdidx == CMD_echoerr)\n\t{\n\t // Mark the already saved text as finishing the line, so that what\n\t // follows is displayed on a new line when scrolling back at the\n\t // more prompt.\n\t msg_sb_eol();\n\t}", "\tif (eap->cmdidx == CMD_echomsg)\n\t{\n\t msg_attr(ga.ga_data, echo_attr);\n\t out_flush();\n\t}\n\telse if (eap->cmdidx == CMD_echowindow)\n\t{\n#ifdef HAS_MESSAGE_WINDOW\n\t start_echowindow(eap->addr_count > 0 ? eap->line2 : 0);\n#endif\n\t msg_attr(ga.ga_data, echo_attr);\n#ifdef HAS_MESSAGE_WINDOW\n\t end_echowindow();\n#endif\n\t}\n\telse if (eap->cmdidx == CMD_echoconsole)\n\t{\n\t ui_write(ga.ga_data, (int)STRLEN(ga.ga_data), TRUE);\n\t ui_write((char_u *)\"\\r\\n\", 2, TRUE);\n\t}\n\telse if (eap->cmdidx == CMD_echoerr)\n\t{\n\t int\t\tsave_did_emsg = did_emsg;", "\t // We don't want to abort following commands, restore did_emsg.\n\t emsg(ga.ga_data);\n\t if (!force_abort)\n\t\tdid_emsg = save_did_emsg;\n\t}\n\telse if (eap->cmdidx == CMD_execute)\n\t{\n\t int save_sticky_cmdmod_flags = sticky_cmdmod_flags;", "\t // \"legacy exe cmd\" and \"vim9cmd exe cmd\" applies to \"cmd\".\n\t sticky_cmdmod_flags = cmdmod.cmod_flags\n\t\t\t\t\t\t& (CMOD_LEGACY | CMOD_VIM9CMD);\n\t do_cmdline((char_u *)ga.ga_data,\n\t\t eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);\n\t sticky_cmdmod_flags = save_sticky_cmdmod_flags;\n\t}\n }", " ga_clear(&ga);", " if (eap->skip)\n\t--emsg_skip;\n set_nextcmd(eap, arg);\n}", "/*\n * Skip over the name of an option: \"&option\", \"&g:option\" or \"&l:option\".\n * \"arg\" points to the \"&\" or '+' when called, to \"option\" when returning.\n * Returns NULL when no option name found. Otherwise pointer to the char\n * after the option name.\n */\n char_u *\nfind_option_end(char_u **arg, int *scope)\n{\n char_u\t*p = *arg;", " ++p;\n if (*p == 'g' && p[1] == ':')\n {\n\t*scope = OPT_GLOBAL;\n\tp += 2;\n }\n else if (*p == 'l' && p[1] == ':')\n {\n\t*scope = OPT_LOCAL;\n\tp += 2;\n }\n else\n\t*scope = 0;", " if (!ASCII_ISALPHA(*p))\n\treturn NULL;\n *arg = p;", " if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)\n\tp += 4;\t // termcap option\n else\n\twhile (ASCII_ISALPHA(*p))\n\t ++p;\n return p;\n}", "/*\n * Display script name where an item was last set.\n * Should only be invoked when 'verbose' is non-zero.\n */\n void\nlast_set_msg(sctx_T script_ctx)\n{\n char_u *p;", " if (script_ctx.sc_sid == 0)\n\treturn;", " p = home_replace_save(NULL, get_scriptname(script_ctx.sc_sid));\n if (p == NULL)\n\treturn;", " verbose_enter();\n msg_puts(_(\"\\n\\tLast set from \"));\n msg_puts((char *)p);\n if (script_ctx.sc_lnum > 0)\n {\n\tmsg_puts(_(line_msg));\n\tmsg_outnum((long)script_ctx.sc_lnum);\n }\n verbose_leave();\n vim_free(p);\n}", "#endif // FEAT_EVAL", "/*\n * Perform a substitution on \"str\" with pattern \"pat\" and substitute \"sub\".\n * When \"sub\" is NULL \"expr\" is used, must be a VAR_FUNC or VAR_PARTIAL.\n * \"flags\" can be \"g\" to do a global substitute.\n * Returns an allocated string, NULL for error.\n */\n char_u *\ndo_string_sub(\n char_u\t*str,\n char_u\t*pat,\n char_u\t*sub,\n typval_T\t*expr,\n char_u\t*flags)\n{\n int\t\tsublen;\n regmatch_T\tregmatch;\n int\t\ti;\n int\t\tdo_all;\n char_u\t*tail;\n char_u\t*end;\n garray_T\tga;\n char_u\t*ret;\n char_u\t*save_cpo;\n char_u\t*zero_width = NULL;", " // Make 'cpoptions' empty, so that the 'l' flag doesn't work here\n save_cpo = p_cpo;\n p_cpo = empty_option;", " ga_init2(&ga, 1, 200);", " do_all = (flags[0] == 'g');", " regmatch.rm_ic = p_ic;\n regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);\n if (regmatch.regprog != NULL)\n {\n\ttail = str;\n\tend = str + STRLEN(str);\n\twhile (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))\n\t{\n\t // Skip empty match except for first match.\n\t if (regmatch.startp[0] == regmatch.endp[0])\n\t {\n\t\tif (zero_width == regmatch.startp[0])\n\t\t{\n\t\t // avoid getting stuck on a match with an empty string\n\t\t i = mb_ptr2len(tail);\n\t\t mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail,\n\t\t\t\t\t\t\t\t (size_t)i);\n\t\t ga.ga_len += i;\n\t\t tail += i;\n\t\t continue;\n\t\t}\n\t\tzero_width = regmatch.startp[0];\n\t }", "\t /*\n\t * Get some space for a temporary buffer to do the substitution\n\t * into. It will contain:\n\t * - The text up to where the match is.\n\t * - The substituted text.\n\t * - The text after the match.\n\t */\n\t sublen = vim_regsub(&regmatch, sub, expr, tail, 0, REGSUB_MAGIC);", "\t if (sublen <= 0)\n\t {\n\t\tga_clear(&ga);\n\t\tbreak;\n\t }", "\t if (ga_grow(&ga, (int)((end - tail) + sublen -\n\t\t\t (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)\n\t {\n\t\tga_clear(&ga);\n\t\tbreak;\n\t }", "\t // copy the text up to where the match is\n\t i = (int)(regmatch.startp[0] - tail);\n\t mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);\n\t // add the substituted text\n\t (void)vim_regsub(&regmatch, sub, expr,\n\t\t\t\t (char_u *)ga.ga_data + ga.ga_len + i, sublen,\n\t\t\t\t REGSUB_COPY | REGSUB_MAGIC);\n\t ga.ga_len += i + sublen - 1;\n\t tail = regmatch.endp[0];\n\t if (*tail == NUL)\n\t\tbreak;\n\t if (!do_all)\n\t\tbreak;\n\t}", "\tif (ga.ga_data != NULL)\n\t STRCPY((char *)ga.ga_data + ga.ga_len, tail);", "\tvim_regfree(regmatch.regprog);\n }", " ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);\n ga_clear(&ga);\n if (p_cpo == empty_option)\n\tp_cpo = save_cpo;\n else\n {\n\t// Darn, evaluating {sub} expression or {expr} changed the value.\n\t// If it's still empty it was changed and restored, need to restore in\n\t// the complicated way.\n\tif (*p_cpo == NUL)\n\t set_option_value_give_err((char_u *)\"cpo\", 0L, save_cpo, 0);\n\tfree_string_option(save_cpo);\n }", " return ret;\n}" ]
[ 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [7314, 1117, 697], "buggy_code_start_loc": [7314, 883, 697], "filenames": ["src/eval.c", "src/testdir/test_substitute.vim", "src/version.c"], "fixing_code_end_loc": [7320, 1134, 700], "fixing_code_start_loc": [7315, 883, 698], "message": "Out-of-bounds Write in GitHub repository vim/vim prior to 9.0.1145.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "7A64F3DA-66B5-4F73-A776-7457E9CBCE52", "versionEndExcluding": "9.0.1145", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Out-of-bounds Write in GitHub repository vim/vim prior to 9.0.1145."}], "evaluatorComment": null, "id": "CVE-2023-0054", "lastModified": "2023-05-03T12:16:43.723", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.3, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-04T19:15:09.573", "references": [{"source": "security@huntr.dev", "tags": null, "url": "http://seclists.org/fulldisclosure/2023/Mar/17"}, {"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/3ac1d97a1d9353490493d30088256360435f7731"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Third Party Advisory"], "url": "https://huntr.dev/bounties/b289ee0f-fd16-4147-bd01-c6289c45e49d"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}, {"source": "security@huntr.dev", "tags": null, "url": "https://support.apple.com/kb/HT213670"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-787"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/3ac1d97a1d9353490493d30088256360435f7731"}, "type": "CWE-787"}
190
Determine whether the {function_name} code is vulnerable or not.
[ "\" Tests for the substitute (:s) command", "source shared.vim\nsource check.vim\nsource screendump.vim", "func Test_multiline_subst()\n enew!\n call append(0, [\"1 aa\",\n\t \\ \"bb\",\n\t \\ \"cc\",\n\t \\ \"2 dd\",\n\t \\ \"ee\",\n\t \\ \"3 ef\",\n\t \\ \"gh\",\n\t \\ \"4 ij\",\n\t \\ \"5 a8\",\n\t \\ \"8b c9\",\n\t \\ \"9d\",\n\t \\ \"6 e7\",\n\t \\ \"77f\",\n\t \\ \"xxxxx\"])", " 1\n \" test if replacing a line break works with a back reference\n /^1/,/^2/s/\\n\\(.\\)/ \\1/\n \" test if inserting a line break works with a back reference\n /^3/,/^4/s/\\(.\\)$/\\r\\1/\n \" test if replacing a line break with another line break works\n /^5/,/^6/s/\\(\\_d\\{3}\\)/x\\1x/\n call assert_equal('1 aa bb cc 2 dd ee', getline(1))\n call assert_equal('3 e', getline(2))\n call assert_equal('f', getline(3))\n call assert_equal('g', getline(4))\n call assert_equal('h', getline(5))\n call assert_equal('4 i', getline(6))\n call assert_equal('j', getline(7))\n call assert_equal('5 ax8', getline(8))\n call assert_equal('8xb cx9', getline(9))\n call assert_equal('9xd', getline(10))\n call assert_equal('6 ex7', getline(11))\n call assert_equal('7x7f', getline(12))\n call assert_equal('xxxxx', getline(13))\n enew!\nendfunc", "func Test_substitute_variants()\n \" Validate that all the 2-/3-letter variants which embed the flags into the\n \" command name actually work.\n enew!\n let ln = 'Testing string'\n let variants = [\n\t\\ { 'cmd': ':s/Test/test/c', 'exp': 'testing string', 'prompt': 'y' },\n\t\\ { 'cmd': ':s/foo/bar/ce', 'exp': ln },\n\t\\ { 'cmd': ':s/t/r/cg', 'exp': 'Tesring srring', 'prompt': 'a' },\n\t\\ { 'cmd': ':s/t/r/ci', 'exp': 'resting string', 'prompt': 'y' },\n\t\\ { 'cmd': ':s/t/r/cI', 'exp': 'Tesring string', 'prompt': 'y' },\n\t\\ { 'cmd': ':s/t/r/c', 'exp': 'Testing string', 'prompt': 'n' },\n\t\\ { 'cmd': ':s/t/r/cn', 'exp': ln },\n\t\\ { 'cmd': ':s/t/r/cp', 'exp': 'Tesring string', 'prompt': 'y' },\n\t\\ { 'cmd': ':s/t/r/cl', 'exp': 'Tesring string', 'prompt': 'y' },\n\t\\ { 'cmd': ':s/t/r/gc', 'exp': 'Tesring srring', 'prompt': 'a' },\n\t\\ { 'cmd': ':s/i/I/gc', 'exp': 'TestIng string', 'prompt': 'l' },\n\t\\ { 'cmd': ':s/foo/bar/ge', 'exp': ln },\n\t\\ { 'cmd': ':s/t/r/g', 'exp': 'Tesring srring' },\n\t\\ { 'cmd': ':s/t/r/gi', 'exp': 'resring srring' },\n\t\\ { 'cmd': ':s/t/r/gI', 'exp': 'Tesring srring' },\n\t\\ { 'cmd': ':s/t/r/gn', 'exp': ln },\n\t\\ { 'cmd': ':s/t/r/gp', 'exp': 'Tesring srring' },\n\t\\ { 'cmd': ':s/t/r/gl', 'exp': 'Tesring srring' },\n\t\\ { 'cmd': ':s//r/gr', 'exp': 'Testr strr' },\n\t\\ { 'cmd': ':s/t/r/ic', 'exp': 'resting string', 'prompt': 'y' },\n\t\\ { 'cmd': ':s/foo/bar/ie', 'exp': ln },\n\t\\ { 'cmd': ':s/t/r/i', 'exp': 'resting string' },\n\t\\ { 'cmd': ':s/t/r/iI', 'exp': 'Tesring string' },\n\t\\ { 'cmd': ':s/t/r/in', 'exp': ln },\n\t\\ { 'cmd': ':s/t/r/ip', 'exp': 'resting string' },\n\t\\ { 'cmd': ':s//r/ir', 'exp': 'Testr string' },\n\t\\ { 'cmd': ':s/t/r/Ic', 'exp': 'Tesring string', 'prompt': 'y' },\n\t\\ { 'cmd': ':s/foo/bar/Ie', 'exp': ln },\n\t\\ { 'cmd': ':s/t/r/Ig', 'exp': 'Tesring srring' },\n\t\\ { 'cmd': ':s/t/r/Ii', 'exp': 'resting string' },\n\t\\ { 'cmd': ':s/t/r/I', 'exp': 'Tesring string' },\n\t\\ { 'cmd': ':s/t/r/Ip', 'exp': 'Tesring string' },\n\t\\ { 'cmd': ':s/t/r/Il', 'exp': 'Tesring string' },\n\t\\ { 'cmd': ':s//r/Ir', 'exp': 'Testr string' },\n\t\\ { 'cmd': ':s//r/rc', 'exp': 'Testr string', 'prompt': 'y' },\n\t\\ { 'cmd': ':s//r/rg', 'exp': 'Testr strr' },\n\t\\ { 'cmd': ':s//r/ri', 'exp': 'Testr string' },\n\t\\ { 'cmd': ':s//r/rI', 'exp': 'Testr string' },\n\t\\ { 'cmd': ':s//r/rn', 'exp': 'Testing string' },\n\t\\ { 'cmd': ':s//r/rp', 'exp': 'Testr string' },\n\t\\ { 'cmd': ':s//r/rl', 'exp': 'Testr string' },\n\t\\ { 'cmd': ':s//r/r', 'exp': 'Testr string' },\n\t\\ { 'cmd': ':s/i/I/gc', 'exp': 'Testing string', 'prompt': 'q' },\n\t\\]", " for var in variants\n for run in [1, 2]\n let cmd = var.cmd\n if run == 2 && cmd =~ \"/.*/.*/.\"\n\t\" Change :s/from/to/{flags} to :s{flags}\n\tlet cmd = substitute(cmd, '/.*/', '', '')\n endif\n call setline(1, [ln])\n let msg = printf('using \"%s\"', cmd)\n let @/='ing'\n let v:errmsg = ''\n call feedkeys(cmd . \"\\<CR>\" . get(var, 'prompt', ''), 'ntx')\n \" No error should exist (matters for testing e flag)\n call assert_equal('', v:errmsg, msg)\n call assert_equal(var.exp, getline('.'), msg)\n endfor\n endfor\nendfunc", "\" Test the l, p, # flags.\nfunc Test_substitute_flags_lp()\n new\n call setline(1, \"abc\\tdef\\<C-h>ghi\")", " let a = execute('s/a/a/p')\n call assert_equal(\"\\nabc def^Hghi\", a)", " let a = execute('s/a/a/l')\n call assert_equal(\"\\nabc^Idef^Hghi$\", a)", " let a = execute('s/a/a/#')\n call assert_equal(\"\\n 1 abc def^Hghi\", a)", " let a = execute('s/a/a/p#')\n call assert_equal(\"\\n 1 abc def^Hghi\", a)", " let a = execute('s/a/a/l#')\n call assert_equal(\"\\n 1 abc^Idef^Hghi$\", a)", " let a = execute('s/a/a/')\n call assert_equal(\"\", a)", " bwipe!\nendfunc", "func Test_substitute_repeat()\n \" This caused an invalid memory access.\n split Xsubfile\n s/^/x\n call feedkeys(\"Qsc\\<CR>y\", 'tx')\n bwipe!\nendfunc", "\" Test %s/\\n// which is implemented as a special case to use a\n\" more efficient join rather than doing a regular substitution.\nfunc Test_substitute_join()\n new", " call setline(1, [\"foo\\tbar\", \"bar\\<C-H>foo\"])\n let a = execute('%s/\\n//')\n call assert_equal(\"\", a)\n call assert_equal([\"foo\\tbarbar\\<C-H>foo\"], getline(1, '$'))\n call assert_equal('\\n', histget(\"search\", -1))", " call setline(1, [\"foo\\tbar\", \"bar\\<C-H>foo\"])\n let a = execute('%s/\\n//g')\n call assert_equal(\"\", a)\n call assert_equal([\"foo\\tbarbar\\<C-H>foo\"], getline(1, '$'))\n call assert_equal('\\n', histget(\"search\", -1))", " call setline(1, [\"foo\\tbar\", \"bar\\<C-H>foo\"])\n let a = execute('%s/\\n//p')\n call assert_equal(\"\\nfoo barbar^Hfoo\", a)\n call assert_equal([\"foo\\tbarbar\\<C-H>foo\"], getline(1, '$'))\n call assert_equal('\\n', histget(\"search\", -1))", " call setline(1, [\"foo\\tbar\", \"bar\\<C-H>foo\"])\n let a = execute('%s/\\n//l')\n call assert_equal(\"\\nfoo^Ibarbar^Hfoo$\", a)\n call assert_equal([\"foo\\tbarbar\\<C-H>foo\"], getline(1, '$'))\n call assert_equal('\\n', histget(\"search\", -1))", " call setline(1, [\"foo\\tbar\", \"bar\\<C-H>foo\"])\n let a = execute('%s/\\n//#')\n call assert_equal(\"\\n 1 foo barbar^Hfoo\", a)\n call assert_equal([\"foo\\tbarbar\\<C-H>foo\"], getline(1, '$'))\n call assert_equal('\\n', histget(\"search\", -1))", " call setline(1, ['foo', 'bar', 'baz', 'qux'])\n call execute('1,2s/\\n//')\n call assert_equal(['foobarbaz', 'qux'], getline(1, '$'))", " bwipe!\nendfunc", "func Test_substitute_count()\n new\n call setline(1, ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo'])\n 2", " s/foo/bar/3\n call assert_equal(['foo foo', 'bar foo', 'bar foo', 'bar foo', 'foo foo'],\n \\ getline(1, '$'))", " call assert_fails('s/foo/bar/0', 'E939:')", " call setline(1, ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo'])\n 2,4s/foo/bar/ 10\n call assert_equal(['foo foo', 'foo foo', 'foo foo', 'bar foo', 'bar foo'],\n \\ getline(1, '$'))", " bwipe!\nendfunc", "\" Test substitute 'n' flag (report number of matches, do not substitute).\nfunc Test_substitute_flag_n()\n new\n let lines = ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo']\n call setline(1, lines)", " call assert_equal(\"\\n3 matches on 3 lines\", execute('2,4s/foo/bar/n'))\n call assert_equal(\"\\n6 matches on 3 lines\", execute('2,4s/foo/bar/gn'))", " \" c flag (confirm) should be ignored when using n flag.\n call assert_equal(\"\\n3 matches on 3 lines\", execute('2,4s/foo/bar/nc'))", " \" No substitution should have been done.\n call assert_equal(lines, getline(1, '$'))", " %delete _\n call setline(1, ['A', 'Bar', 'Baz'])\n call assert_equal(\"\\n1 match on 1 line\", execute('s/\\nB\\@=//gn'))", " bwipe!\nendfunc", "func Test_substitute_errors()\n new\n call setline(1, 'foobar')", " call assert_fails('s/FOO/bar/', 'E486:')\n call assert_fails('s/foo/bar/@', 'E488:')\n call assert_fails('s/\\(/bar/', 'E54:')\n call assert_fails('s afooabara', 'E146:')\n call assert_fails('s\\\\a', 'E10:')", " setl nomodifiable\n call assert_fails('s/foo/bar/', 'E21:')", " call assert_fails(\"let s=substitute([], 'a', 'A', 'g')\", 'E730:')\n call assert_fails(\"let s=substitute('abcda', [], 'A', 'g')\", 'E730:')\n call assert_fails(\"let s=substitute('abcda', 'a', [], 'g')\", 'E730:')\n call assert_fails(\"let s=substitute('abcda', 'a', 'A', [])\", 'E730:')\n call assert_fails(\"let s=substitute('abc', '\\\\%(', 'A', 'g')\", 'E53:')", " bwipe!\nendfunc", "\" Test for *sub-replace-special* and *sub-replace-expression* on substitute().\nfunc Test_sub_replace_1()\n \" Run the tests with 'magic' on\n set magic\n set cpo&\n call assert_equal('AA', substitute('A', 'A', '&&', ''))\n call assert_equal('&', substitute('B', 'B', '\\&', ''))\n call assert_equal('C123456789987654321', substitute('C123456789', 'C\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)', '\\0\\9\\8\\7\\6\\5\\4\\3\\2\\1', ''))\n call assert_equal('d', substitute('D', 'D', 'd', ''))\n call assert_equal('~', substitute('E', 'E', '~', ''))\n call assert_equal('~', substitute('F', 'F', '\\~', ''))\n call assert_equal('Gg', substitute('G', 'G', '\\ugg', ''))\n call assert_equal('Hh', substitute('H', 'H', '\\Uh\\Eh', ''))\n call assert_equal('iI', substitute('I', 'I', '\\lII', ''))\n call assert_equal('jJ', substitute('J', 'J', '\\LJ\\EJ', ''))\n call assert_equal('Kk', substitute('K', 'K', '\\Uk\\ek', ''))\n call assert_equal(\"l\\<C-V>\\<C-M>l\",\n\t\t\t\\ substitute('lLl', 'L', \"\\<C-V>\\<C-M>\", ''))\n call assert_equal(\"m\\<C-M>m\", substitute('mMm', 'M', '\\r', ''))\n call assert_equal(\"n\\<C-V>\\<C-M>n\",\n\t\t\t\\ substitute('nNn', 'N', \"\\\\\\<C-V>\\<C-M>\", ''))\n call assert_equal(\"o\\no\", substitute('oOo', 'O', '\\n', ''))\n call assert_equal(\"p\\<C-H>p\", substitute('pPp', 'P', '\\b', ''))\n call assert_equal(\"q\\tq\", substitute('qQq', 'Q', '\\t', ''))\n call assert_equal('r\\r', substitute('rRr', 'R', '\\\\', ''))\n call assert_equal('scs', substitute('sSs', 'S', '\\c', ''))\n call assert_equal(\"u\\nu\", substitute('uUu', 'U', \"\\n\", ''))\n call assert_equal(\"v\\<C-H>v\", substitute('vVv', 'V', \"\\b\", ''))\n call assert_equal(\"w\\\\w\", substitute('wWw', 'W', \"\\\\\", ''))\n call assert_equal(\"x\\<C-M>x\", substitute('xXx', 'X', \"\\r\", ''))\n call assert_equal(\"YyyY\", substitute('Y', 'Y', '\\L\\uyYy\\l\\EY', ''))\n call assert_equal(\"zZZz\", substitute('Z', 'Z', '\\U\\lZzZ\\u\\Ez', ''))\n \" \\v or \\V after $\n call assert_equal('abxx', substitute('abcd', 'xy$\\v|cd$', 'xx', ''))\n call assert_equal('abxx', substitute('abcd', 'xy$\\V\\|cd\\$', 'xx', ''))\nendfunc", "func Test_sub_replace_2()\n \" Run the tests with 'magic' off\n set nomagic\n set cpo&\n call assert_equal('AA', substitute('A', 'A', '&&', ''))\n call assert_equal('&', substitute('B', 'B', '\\&', ''))\n call assert_equal('C123456789987654321', substitute('C123456789', 'C\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)', '\\0\\9\\8\\7\\6\\5\\4\\3\\2\\1', ''))\n call assert_equal('d', substitute('D', 'D', 'd', ''))\n call assert_equal('~', substitute('E', 'E', '~', ''))\n call assert_equal('~', substitute('F', 'F', '\\~', ''))\n call assert_equal('Gg', substitute('G', 'G', '\\ugg', ''))\n call assert_equal('Hh', substitute('H', 'H', '\\Uh\\Eh', ''))\n call assert_equal('iI', substitute('I', 'I', '\\lII', ''))\n call assert_equal('jJ', substitute('J', 'J', '\\LJ\\EJ', ''))\n call assert_equal('Kk', substitute('K', 'K', '\\Uk\\ek', ''))\n call assert_equal(\"l\\<C-V>\\<C-M>l\",\n\t\t\t\\ substitute('lLl', 'L', \"\\<C-V>\\<C-M>\", ''))\n call assert_equal(\"m\\<C-M>m\", substitute('mMm', 'M', '\\r', ''))\n call assert_equal(\"n\\<C-V>\\<C-M>n\",\n\t\t\t\\ substitute('nNn', 'N', \"\\\\\\<C-V>\\<C-M>\", ''))\n call assert_equal(\"o\\no\", substitute('oOo', 'O', '\\n', ''))\n call assert_equal(\"p\\<C-H>p\", substitute('pPp', 'P', '\\b', ''))\n call assert_equal(\"q\\tq\", substitute('qQq', 'Q', '\\t', ''))\n call assert_equal('r\\r', substitute('rRr', 'R', '\\\\', ''))\n call assert_equal('scs', substitute('sSs', 'S', '\\c', ''))\n call assert_equal(\"t\\<C-M>t\", substitute('tTt', 'T', \"\\r\", ''))\n call assert_equal(\"u\\nu\", substitute('uUu', 'U', \"\\n\", ''))\n call assert_equal(\"v\\<C-H>v\", substitute('vVv', 'V', \"\\b\", ''))\n call assert_equal('w\\w', substitute('wWw', 'W', \"\\\\\", ''))\n call assert_equal('XxxX', substitute('X', 'X', '\\L\\uxXx\\l\\EX', ''))\n call assert_equal('yYYy', substitute('Y', 'Y', '\\U\\lYyY\\u\\Ey', ''))\nendfunc", "func Test_sub_replace_3()\n set magic&\n set cpo&\n call assert_equal('a\\a', substitute('aAa', 'A', '\\=\"\\\\\"', ''))\n call assert_equal('b\\\\b', substitute('bBb', 'B', '\\=\"\\\\\\\\\"', ''))\n call assert_equal(\"c\\rc\", substitute('cCc', 'C', \"\\\\=\\\"\\r\\\"\", ''))\n call assert_equal(\"d\\\\\\rd\", substitute('dDd', 'D', \"\\\\=\\\"\\\\\\\\\\r\\\"\", ''))\n call assert_equal(\"e\\\\\\\\\\re\", substitute('eEe', 'E', \"\\\\=\\\"\\\\\\\\\\\\\\\\\\r\\\"\", ''))\n call assert_equal('f\\rf', substitute('fFf', 'F', '\\=\"\\\\r\"', ''))\n call assert_equal('j\\nj', substitute('jJj', 'J', '\\=\"\\\\n\"', ''))\n call assert_equal(\"k\\<C-M>k\", substitute('kKk', 'K', '\\=\"\\r\"', ''))\n call assert_equal(\"l\\nl\", substitute('lLl', 'L', '\\=\"\\n\"', ''))\nendfunc", "\" Test for submatch() on substitute().\nfunc Test_sub_replace_4()\n set magic&\n set cpo&\n call assert_equal('a\\a', substitute('aAa', 'A',\n\t\t\\ '\\=substitute(submatch(0), \".\", \"\\\\\", \"\")', ''))\n call assert_equal('b\\b', substitute('bBb', 'B',\n\t\t\\ '\\=substitute(submatch(0), \".\", \"\\\\\\\\\", \"\")', ''))\n call assert_equal(\"c\\<C-V>\\<C-M>c\", substitute('cCc', 'C', '\\=substitute(submatch(0), \".\", \"\\<C-V>\\<C-M>\", \"\")', ''))\n call assert_equal(\"d\\<C-V>\\<C-M>d\", substitute('dDd', 'D', '\\=substitute(submatch(0), \".\", \"\\\\\\<C-V>\\<C-M>\", \"\")', ''))\n call assert_equal(\"e\\\\\\<C-V>\\<C-M>e\", substitute('eEe', 'E', '\\=substitute(submatch(0), \".\", \"\\\\\\\\\\<C-V>\\<C-M>\", \"\")', ''))\n call assert_equal(\"f\\<C-M>f\", substitute('fFf', 'F', '\\=substitute(submatch(0), \".\", \"\\\\r\", \"\")', ''))\n call assert_equal(\"j\\nj\", substitute('jJj', 'J', '\\=substitute(submatch(0), \".\", \"\\\\n\", \"\")', ''))\n call assert_equal(\"k\\rk\", substitute('kKk', 'K', '\\=substitute(submatch(0), \".\", \"\\r\", \"\")', ''))\n call assert_equal(\"l\\nl\", substitute('lLl', 'L', '\\=substitute(submatch(0), \".\", \"\\n\", \"\")', ''))\nendfunc", "func Test_sub_replace_5()\n set magic&\n set cpo&\n call assert_equal('A123456789987654321', substitute('A123456789',\n\t\t\\ 'A\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)',\n\t\t\\ '\\=submatch(0) . submatch(9) . submatch(8) . ' .\n\t\t\\ 'submatch(7) . submatch(6) . submatch(5) . ' .\n\t\t\\ 'submatch(4) . submatch(3) . submatch(2) . submatch(1)',\n\t\t\\ ''))\n call assert_equal(\"[['A123456789'], ['9'], ['8'], ['7'], ['6'], \" .\n\t\t\\ \"['5'], ['4'], ['3'], ['2'], ['1']]\",\n\t\t\\ substitute('A123456789',\n\t\t\\ 'A\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)',\n\t\t\\ '\\=string([submatch(0, 1), submatch(9, 1), ' .\n\t\t\\ 'submatch(8, 1), 7->submatch(1), submatch(6, 1), ' .\n\t\t\\ 'submatch(5, 1), submatch(4, 1), submatch(3, 1), ' .\n\t\t\\ 'submatch(2, 1), submatch(1, 1)])',\n\t\t\\ ''))\nendfunc", "func Test_sub_replace_6()\n set magic&\n set cpo+=/\n call assert_equal('a', substitute('A', 'A', 'a', ''))\n call assert_equal('%', substitute('B', 'B', '%', ''))\n set cpo-=/\n call assert_equal('c', substitute('C', 'C', 'c', ''))\n call assert_equal('%', substitute('D', 'D', '%', ''))\nendfunc", "func Test_sub_replace_7()\n set magic&\n set cpo&\n call assert_equal('A\u0016A', substitute('A\u0016A', 'A.', '\\=submatch(0)', ''))\n call assert_equal(\"B\\nB\", substitute(\"B\\nB\", 'B.', '\\=submatch(0)', ''))\n call assert_equal(\"['B\\n']B\", substitute(\"B\\nB\", 'B.', '\\=string(submatch(0, 1))', ''))\n call assert_equal('-abab', substitute('-bb', '\\zeb', 'a', 'g'))\n call assert_equal('c-cbcbc', substitute('-bb', '\\ze', 'c', 'g'))\nendfunc", "\" Test for *:s%* on :substitute.\nfunc Test_sub_replace_8()\n new\n set magic&\n set cpo&\n $put =',,X'\n s/\\(^\\|,\\)\\ze\\(,\\|X\\)/\\1N/g\n call assert_equal('N,,NX', getline(\"$\"))\n $put =',,Y'\n let cmd = ':s/\\(^\\|,\\)\\ze\\(,\\|Y\\)/\\1N/gc'\n call feedkeys(cmd . \"\\<CR>a\", \"xt\")\n call assert_equal('N,,NY', getline(\"$\"))\n :$put =',,Z'\n let cmd = ':s/\\(^\\|,\\)\\ze\\(,\\|Z\\)/\\1N/gc'\n call feedkeys(cmd . \"\\<CR>yy\", \"xt\")\n call assert_equal('N,,NZ', getline(\"$\"))\n enew! | close\nendfunc", "func Test_sub_replace_9()\n new\n set magic&\n set cpo&\n $put ='xxx'\n call feedkeys(\":s/x/X/gc\\<CR>yyq\", \"xt\")\n call assert_equal('XXx', getline(\"$\"))\n enew! | close\nendfunc", "func Test_sub_replace_10()\n set magic&\n set cpo&\n call assert_equal('a1a2a3a', substitute('123', '\\zs', 'a', 'g'))\n call assert_equal('aaa', substitute('123', '\\zs.', 'a', 'g'))\n call assert_equal('1a2a3a', substitute('123', '.\\zs', 'a', 'g'))\n call assert_equal('a1a2a3a', substitute('123', '\\ze', 'a', 'g'))\n call assert_equal('a1a2a3', substitute('123', '\\ze.', 'a', 'g'))\n call assert_equal('aaa', substitute('123', '.\\ze', 'a', 'g'))\n call assert_equal('aa2a3a', substitute('123', '1\\|\\ze', 'a', 'g'))\n call assert_equal('1aaa', substitute('123', '1\\zs\\|[23]', 'a', 'g'))\nendfunc", "func SubReplacer(text, submatches)\n return a:text .. a:submatches[0] .. a:text\nendfunc\nfunc SubReplacerVar(text, ...)\n return a:text .. a:1[0] .. a:text\nendfunc\ndef SubReplacerVar9(text: string, ...args: list<list<string>>): string\n return text .. args[0][0] .. text\nenddef\nfunc SubReplacer20(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, submatches)\n return a:t3 .. a:submatches[0] .. a:t11\nendfunc", "func Test_substitute_partial()\n call assert_equal('1foo2foo3', substitute('123', '2', function('SubReplacer', ['foo']), 'g'))\n call assert_equal('1foo2foo3', substitute('123', '2', function('SubReplacerVar', ['foo']), 'g'))\n call assert_equal('1foo2foo3', substitute('123', '2', function('SubReplacerVar9', ['foo']), 'g'))", " \" 19 arguments plus one is just OK\n let Replacer = function('SubReplacer20', repeat(['foo'], 19))\n call assert_equal('1foo2foo3', substitute('123', '2', Replacer, 'g'))", " \" 20 arguments plus one is too many\n let Replacer = function('SubReplacer20', repeat(['foo'], 20))\n call assert_fails(\"call substitute('123', '2', Replacer, 'g')\", 'E118:')\nendfunc", "func Test_substitute_float()\n call assert_equal('number 1.23', substitute('number ', '$', { -> 1.23 }, ''))\n vim9 assert_equal('number 1.23', substitute('number ', '$', () => 1.23, ''))\nendfunc", "\" Tests for *sub-replace-special* and *sub-replace-expression* on :substitute.", "\" Execute a list of :substitute command tests\nfunc Run_SubCmd_Tests(tests)\n enew!\n for t in a:tests\n let start = line('.') + 1\n let end = start + len(t[2]) - 1\n exe \"normal o\" . t[0]\n call cursor(start, 1)\n exe t[1]\n call assert_equal(t[2], getline(start, end), t[1])\n endfor\n enew!\nendfunc", "func Test_sub_cmd_1()\n set magic\n set cpo&", " \" List entry format: [input, cmd, output]\n let tests = [['A', 's/A/&&/', ['AA']],\n\t \\ ['B', 's/B/\\&/', ['&']],\n\t \\ ['C123456789', 's/C\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)/\\0\\9\\8\\7\\6\\5\\4\\3\\2\\1/', ['C123456789987654321']],\n\t \\ ['D', 's/D/d/', ['d']],\n\t \\ ['E', 's/E/~/', ['d']],\n\t \\ ['F', 's/F/\\~/', ['~']],\n\t \\ ['G', 's/G/\\ugg/', ['Gg']],\n\t \\ ['H', 's/H/\\Uh\\Eh/', ['Hh']],\n\t \\ ['I', 's/I/\\lII/', ['iI']],\n\t \\ ['J', 's/J/\\LJ\\EJ/', ['jJ']],\n\t \\ ['K', 's/K/\\Uk\\ek/', ['Kk']],\n\t \\ ['lLl', \"s/L/\\<C-V>\\<C-M>/\", [\"l\\<C-V>\", 'l']],\n\t \\ ['mMm', 's/M/\\r/', ['m', 'm']],\n\t \\ ['nNn', \"s/N/\\\\\\<C-V>\\<C-M>/\", [\"n\\<C-V>\", 'n']],\n\t \\ ['oOo', 's/O/\\n/', [\"o\\no\"]],\n\t \\ ['pPp', 's/P/\\b/', [\"p\\<C-H>p\"]],\n\t \\ ['qQq', 's/Q/\\t/', [\"q\\tq\"]],\n\t \\ ['rRr', 's/R/\\\\/', ['r\\r']],\n\t \\ ['sSs', 's/S/\\c/', ['scs']],\n\t \\ ['tTt', \"s/T/\\<C-V>\\<C-J>/\", [\"t\\<C-V>\\<C-J>t\"]],\n\t \\ ['U', 's/U/\\L\\uuUu\\l\\EU/', ['UuuU']],\n\t \\ ['V', 's/V/\\U\\lVvV\\u\\Ev/', ['vVVv']],\n\t \\ ['\\', 's/\\\\/\\\\\\\\/', ['\\\\']]\n\t \\ ]\n call Run_SubCmd_Tests(tests)\nendfunc", "func Test_sub_cmd_2()\n set nomagic\n set cpo&", " \" List entry format: [input, cmd, output]\n let tests = [['A', 's/A/&&/', ['&&']],\n\t \\ ['B', 's/B/\\&/', ['B']],\n\t \\ ['C123456789', 's/\\mC\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)/\\0\\9\\8\\7\\6\\5\\4\\3\\2\\1/', ['C123456789987654321']],\n\t \\ ['D', 's/D/d/', ['d']],\n\t \\ ['E', 's/E/~/', ['~']],\n\t \\ ['F', 's/F/\\~/', ['~']],\n\t \\ ['G', 's/G/\\ugg/', ['Gg']],\n\t \\ ['H', 's/H/\\Uh\\Eh/', ['Hh']],\n\t \\ ['I', 's/I/\\lII/', ['iI']],\n\t \\ ['J', 's/J/\\LJ\\EJ/', ['jJ']],\n\t \\ ['K', 's/K/\\Uk\\ek/', ['Kk']],\n\t \\ ['lLl', \"s/L/\\<C-V>\\<C-M>/\", [\"l\\<C-V>\", 'l']],\n\t \\ ['mMm', 's/M/\\r/', ['m', 'm']],\n\t \\ ['nNn', \"s/N/\\\\\\<C-V>\\<C-M>/\", [\"n\\<C-V>\", 'n']],\n\t \\ ['oOo', 's/O/\\n/', [\"o\\no\"]],\n\t \\ ['pPp', 's/P/\\b/', [\"p\\<C-H>p\"]],\n\t \\ ['qQq', 's/Q/\\t/', [\"q\\tq\"]],\n\t \\ ['rRr', 's/R/\\\\/', ['r\\r']],\n\t \\ ['sSs', 's/S/\\c/', ['scs']],\n\t \\ ['tTt', \"s/T/\\<C-V>\\<C-J>/\", [\"t\\<C-V>\\<C-J>t\"]],\n\t \\ ['U', 's/U/\\L\\uuUu\\l\\EU/', ['UuuU']],\n\t \\ ['V', 's/V/\\U\\lVvV\\u\\Ev/', ['vVVv']],\n\t \\ ['\\', 's/\\\\/\\\\\\\\/', ['\\\\']]\n\t \\ ]\n call Run_SubCmd_Tests(tests)\nendfunc", "func Test_sub_cmd_3()\n set nomagic\n set cpo&", " \" List entry format: [input, cmd, output]\n let tests = [['aAa', \"s/A/\\\\='\\\\'/\", ['a\\a']],\n\t \\ ['bBb', \"s/B/\\\\='\\\\\\\\'/\", ['b\\\\b']],\n\t \\ ['cCc', \"s/C/\\\\='\\<C-V>\\<C-M>'/\", [\"c\\<C-V>\", 'c']],\n\t \\ ['dDd', \"s/D/\\\\='\\\\\\<C-V>\\<C-M>'/\", [\"d\\\\\\<C-V>\", 'd']],\n\t \\ ['eEe', \"s/E/\\\\='\\\\\\\\\\<C-V>\\<C-M>'/\", [\"e\\\\\\\\\\<C-V>\", 'e']],\n\t \\ ['fFf', \"s/F/\\\\='\\r'/\", ['f', 'f']],\n\t \\ ['gGg', \"s/G/\\\\='\\<C-V>\\<C-J>'/\", [\"g\\<C-V>\", 'g']],\n\t \\ ['hHh', \"s/H/\\\\='\\\\\\<C-V>\\<C-J>'/\", [\"h\\\\\\<C-V>\", 'h']],\n\t \\ ['iIi', \"s/I/\\\\='\\\\\\\\\\<C-V>\\<C-J>'/\", [\"i\\\\\\\\\\<C-V>\", 'i']],\n\t \\ ['jJj', \"s/J/\\\\='\\n'/\", ['j', 'j']],\n\t \\ ['kKk', 's/K/\\=\"\\r\"/', ['k', 'k']],\n\t \\ ['lLl', 's/L/\\=\"\\n\"/', ['l', 'l']]\n\t \\ ]\n call Run_SubCmd_Tests(tests)\nendfunc", "\" Test for submatch() on :substitute.\nfunc Test_sub_cmd_4()\n set magic&\n set cpo&", " \" List entry format: [input, cmd, output]\n let tests = [ ['aAa', \"s/A/\\\\=substitute(submatch(0), '.', '\\\\', '')/\",\n\t \\\t\t\t\t['a\\a']],\n\t \\ ['bBb', \"s/B/\\\\=substitute(submatch(0), '.', '\\\\', '')/\",\n\t \\\t\t\t\t['b\\b']],\n\t \\ ['cCc', \"s/C/\\\\=substitute(submatch(0), '.', '\\<C-V>\\<C-M>', '')/\",\n\t \\\t\t\t\t[\"c\\<C-V>\", 'c']],\n\t \\ ['dDd', \"s/D/\\\\=substitute(submatch(0), '.', '\\\\\\<C-V>\\<C-M>', '')/\",\n\t \\\t\t\t\t[\"d\\<C-V>\", 'd']],\n\t \\ ['eEe', \"s/E/\\\\=substitute(submatch(0), '.', '\\\\\\\\\\<C-V>\\<C-M>', '')/\",\n\t \\\t\t\t\t[\"e\\\\\\<C-V>\", 'e']],\n\t \\ ['fFf', \"s/F/\\\\=substitute(submatch(0), '.', '\\\\r', '')/\",\n\t \\\t\t\t\t['f', 'f']],\n\t \\ ['gGg', 's/G/\\=substitute(submatch(0), \".\", \"\\<C-V>\\<C-J>\", \"\")/',\n\t \\\t\t\t\t[\"g\\<C-V>\", 'g']],\n\t \\ ['hHh', 's/H/\\=substitute(submatch(0), \".\", \"\\\\\\<C-V>\\<C-J>\", \"\")/',\n\t \\\t\t\t\t[\"h\\<C-V>\", 'h']],\n\t \\ ['iIi', 's/I/\\=substitute(submatch(0), \".\", \"\\\\\\\\\\<C-V>\\<C-J>\", \"\")/',\n\t \\\t\t\t\t[\"i\\\\\\<C-V>\", 'i']],\n\t \\ ['jJj', \"s/J/\\\\=substitute(submatch(0), '.', '\\\\n', '')/\",\n\t \\\t\t\t\t['j', 'j']],\n\t \\ ['kKk', \"s/K/\\\\=substitute(submatch(0), '.', '\\\\r', '')/\",\n\t \\\t\t\t\t['k', 'k']],\n\t \\ ['lLl', \"s/L/\\\\=substitute(submatch(0), '.', '\\\\n', '')/\",\n\t \\\t\t\t\t['l', 'l']],\n\t \\ ]\n call Run_SubCmd_Tests(tests)\nendfunc", "func Test_sub_cmd_5()\n set magic&\n set cpo&", " \" List entry format: [input, cmd, output]\n let tests = [ ['A123456789', 's/A\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)/\\=submatch(0) . submatch(9) . submatch(8) . submatch(7) . submatch(6) . submatch(5) . submatch(4) . submatch(3) . submatch(2) . submatch(1)/', ['A123456789987654321']],\n\t \\ ['B123456789', 's/B\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)/\\=string([submatch(0, 1), submatch(9, 1), submatch(8, 1), submatch(7, 1), submatch(6, 1), submatch(5, 1), submatch(4, 1), submatch(3, 1), submatch(2, 1), submatch(1, 1)])/', [\"[['B123456789'], ['9'], ['8'], ['7'], ['6'], ['5'], ['4'], ['3'], ['2'], ['1']]\"]],\n\t \\ ]\n call Run_SubCmd_Tests(tests)\nendfunc", "\" Test for *:s%* on :substitute.\nfunc Test_sub_cmd_6()\n set magic&\n set cpo+=/", " \" List entry format: [input, cmd, output]\n let tests = [ ['A', 's/A/a/', ['a']],\n\t \\ ['B', 's/B/%/', ['a']],\n\t \\ ]\n call Run_SubCmd_Tests(tests)", " set cpo-=/\n let tests = [ ['C', 's/C/c/', ['c']],\n\t \\ ['D', 's/D/%/', ['%']],\n\t \\ ]\n call Run_SubCmd_Tests(tests)", " set cpo&\nendfunc", "\" Test for :s replacing \\n with line break.\nfunc Test_sub_cmd_7()\n set magic&\n set cpo&", " \" List entry format: [input, cmd, output]\n let tests = [ [\"A\\<C-V>\\<C-M>A\", 's/A./\\=submatch(0)/', ['A', 'A']],\n\t \\ [\"B\\<C-V>\\<C-J>B\", 's/B./\\=submatch(0)/', ['B', 'B']],\n\t \\ [\"C\\<C-V>\\<C-J>C\", 's/C./\\=strtrans(string(submatch(0, 1)))/', [strtrans(\"['C\\<C-J>']C\")]],\n\t \\ [\"D\\<C-V>\\<C-J>\\nD\", 's/D.\\nD/\\=strtrans(string(submatch(0, 1)))/', [strtrans(\"['D\\<C-J>', 'D']\")]],\n\t \\ [\"E\\<C-V>\\<C-J>\\n\\<C-V>\\<C-J>\\n\\<C-V>\\<C-J>\\n\\<C-V>\\<C-J>\\n\\<C-V>\\<C-J>E\", 's/E\\_.\\{-}E/\\=strtrans(string(submatch(0, 1)))/', [strtrans(\"['E\\<C-J>', '\\<C-J>', '\\<C-J>', '\\<C-J>', '\\<C-J>E']\")]],\n\t \\ ]\n call Run_SubCmd_Tests(tests)", " exe \"normal oQ\\nQ\\<Esc>k\"\n call assert_fails('s/Q[^\\n]Q/\\=submatch(0).\"foobar\"/', 'E486:')\n enew!\nendfunc", "func TitleString()\n let check = 'foo' =~ 'bar'\n return \"\"\nendfunc", "func Test_sub_cmd_8()\n set titlestring=%{TitleString()}", " enew!\n call append(0, ['', 'test_one', 'test_two'])\n call cursor(1,1)\n /^test_one/s/.*/\\=\"foo\\nbar\"/\n call assert_equal('foo', getline(2))\n call assert_equal('bar', getline(3))\n call feedkeys(':/^test_two/s/.*/\\=\"foo\\nbar\"/c', \"t\")\n call feedkeys(\"\\<CR>y\", \"xt\")\n call assert_equal('foo', getline(4))\n call assert_equal('bar', getline(5))", " enew!\n set titlestring&\nendfunc", "func Test_sub_cmd_9()\n new\n let input = ['1 aaa', '2 aaa', '3 aaa']\n call setline(1, input)\n func Foo()\n return submatch(0)\n endfunc\n %s/aaa/\\=Foo()/gn\n call assert_equal(input, getline(1, '$'))\n call assert_equal(1, &modifiable)", " delfunc Foo\n bw!\nendfunc", "func Test_sub_highlight_zero_match()\n CheckRunVimInTerminal", " let lines =<< trim END\n call setline(1, ['one', 'two', 'three'])\n END\n call writefile(lines, 'XscriptSubHighlight', 'D')\n let buf = RunVimInTerminal('-S XscriptSubHighlight', #{rows: 8, cols: 60})\n call term_sendkeys(buf, \":%s/^/ /c\\<CR>\")\n call VerifyScreenDump(buf, 'Test_sub_highlight_zer_match_1', {})", " call term_sendkeys(buf, \"\\<Esc>\")\n call StopVimInTerminal(buf)\nendfunc", "func Test_nocatch_sub_failure_handling()\n \" normal error results in all replacements \n func Foo()\n foobar\n endfunc\n new\n call setline(1, ['1 aaa', '2 aaa', '3 aaa'])\n \" need silent! to avoid a delay when entering Insert mode\n silent! %s/aaa/\\=Foo()/g\n call assert_equal(['1 0', '2 0', '3 0'], getline(1, 3))", " \" Throw without try-catch causes abort after the first line.\n \" We cannot test this, since it would stop executing the test script.", " \" try/catch does not result in any changes\n func! Foo()\n throw 'error'\n endfunc\n call setline(1, ['1 aaa', '2 aaa', '3 aaa'])\n let error_caught = 0\n try\n %s/aaa/\\=Foo()/g\n catch\n let error_caught = 1\n endtry\n call assert_equal(1, error_caught)\n call assert_equal(['1 aaa', '2 aaa', '3 aaa'], getline(1, 3))", " \" Same, but using \"n\" flag so that \"sandbox\" gets set\n call setline(1, ['1 aaa', '2 aaa', '3 aaa'])\n let error_caught = 0\n try\n %s/aaa/\\=Foo()/gn\n catch\n let error_caught = 1\n endtry\n call assert_equal(1, error_caught)\n call assert_equal(['1 aaa', '2 aaa', '3 aaa'], getline(1, 3))", " delfunc Foo\n bwipe!\nendfunc", "\" Test \":s/pat/sub/\" with different ~s in sub.\nfunc Test_replace_with_tilde()\n new\n \" Set the last replace string to empty\n s/^$//\n call append(0, ['- Bug in \"vPPPP\" on this text:'])\n normal gg\n s/u/~u~/\n call assert_equal('- Bug in \"vPPPP\" on this text:', getline(1))\n s/i/~u~/\n call assert_equal('- Bug uuun \"vPPPP\" on this text:', getline(1))\n s/o/~~~/\n call assert_equal('- Bug uuun \"vPPPP\" uuuuuuuuun this text:', getline(1))\n close!\nendfunc", "func Test_replace_keeppatterns()\n new\n a\nfoobar", "substitute foo asdf", "one two\n.", " normal gg\n /^substitute\n s/foo/bar/\n call assert_equal('foo', @/)\n call assert_equal('substitute bar asdf', getline('.'))", " /^substitute\n keeppatterns s/asdf/xyz/\n call assert_equal('^substitute', @/)\n call assert_equal('substitute bar xyz', getline('.'))", " exe \"normal /bar /e\\<CR>\"\n call assert_equal(15, col('.'))\n normal -\n keeppatterns /xyz\n call assert_equal('bar ', @/)\n call assert_equal('substitute bar xyz', getline('.'))\n exe \"normal 0dn\"\n call assert_equal('xyz', getline('.'))", " close!\nendfunc", "func Test_sub_beyond_end()\n new\n call setline(1, '#')\n let @/ = '^#\\n\\zs'\n s///e\n call assert_equal('#', getline(1))\n bwipe!\nendfunc", "\" Test for repeating last substitution using :~ and :&r\nfunc Test_repeat_last_sub()\n new\n call setline(1, ['blue green yellow orange white'])\n s/blue/red/\n let @/ = 'yellow'\n ~\n let @/ = 'white'\n :&r\n let @/ = 'green'\n s//gray\n call assert_equal('red gray red orange red', getline(1))\n close!\nendfunc", "\" Test for Vi compatible substitution:\n\" \\/{string}/, \\?{string}? and \\&{string}&\nfunc Test_sub_vi_compatibility()\n new\n call setline(1, ['blue green yellow orange blue'])\n let @/ = 'orange'\n s\\/white/\n let @/ = 'blue'\n s\\?amber?\n let @/ = 'white'\n s\\&green&\n call assert_equal('amber green yellow white green', getline(1))\n close!", " call assert_fails('vim9cmd s\\/white/', 'E1270:')\n call assert_fails('vim9cmd s\\?white?', 'E1270:')\n call assert_fails('vim9cmd s\\&white&', 'E1270:')\nendfunc", "\" Test for substitute with the new text longer than the original text\nfunc Test_sub_expand_text()\n new\n call setline(1, 'abcabcabcabcabcabcabcabc')\n s/b/\\=repeat('B', 10)/g\n call assert_equal(repeat('aBBBBBBBBBBc', 8), getline(1))\n close!\nendfunc", "\" Test for command failures when the last substitute pattern is not set.\nfunc Test_sub_with_no_last_pat()\n let lines =<< trim [SCRIPT]\n call assert_fails('~', 'E33:')\n call assert_fails('s//abc/g', 'E35:')\n call assert_fails('s\\/bar', 'E35:')\n call assert_fails('s\\&bar&', 'E33:')\n call writefile(v:errors, 'Xresult')\n qall!\n [SCRIPT]\n call writefile(lines, 'Xscript', 'D')\n if RunVim([], [], '--clean -S Xscript')\n call assert_equal([], readfile('Xresult'))\n endif", " let lines =<< trim [SCRIPT]\n set cpo+=/\n call assert_fails('s/abc/%/', 'E33:')\n call writefile(v:errors, 'Xresult')\n qall!\n [SCRIPT]\n call writefile(lines, 'Xscript')\n if RunVim([], [], '--clean -S Xscript')\n call assert_equal([], readfile('Xresult'))\n endif", " call delete('Xresult')\nendfunc", "func Test_substitute()", " call assert_equal('a1a2a3a', substitute('123', '\\zs', 'a', 'g'))", " \" Substitute with special keys\n call assert_equal(\"a\\<End>c\", substitute('abc', \"a.c\", \"a\\<End>c\", ''))\nendfunc", "func Test_substitute_expr()\n let g:val = 'XXX'\n call assert_equal('XXX', substitute('yyy', 'y*', '\\=g:val', ''))\n call assert_equal('XXX', substitute('yyy', 'y*', {-> g:val}, ''))\n call assert_equal(\"-\\u1b \\uf2-\", substitute(\"-%1b %f2-\", '%\\(\\x\\x\\)',\n\t\t\t \\ '\\=nr2char(\"0x\" . submatch(1))', 'g'))\n call assert_equal(\"-\\u1b \\uf2-\", substitute(\"-%1b %f2-\", '%\\(\\x\\x\\)',\n\t\t\t \\ {-> nr2char(\"0x\" . submatch(1))}, 'g'))", " call assert_equal('231', substitute('123', '\\(.\\)\\(.\\)\\(.\\)',\n\t\\ {-> submatch(2) . submatch(3) . submatch(1)}, ''))", " func Recurse()\n return substitute('yyy', 'y\\(.\\)y', {-> submatch(1)}, '')\n endfunc\n \" recursive call works\n call assert_equal('-y-x-', substitute('xxx', 'x\\(.\\)x', {-> '-' . Recurse() . '-' . submatch(1) . '-'}, ''))", " call assert_fails(\"let s=submatch([])\", 'E745:')\n call assert_fails(\"let s=submatch(2, [])\", 'E745:')\nendfunc", "func Test_invalid_submatch()\n \" This was causing invalid memory access in Vim-7.4.2232 and older\n call assert_fails(\"call substitute('x', '.', {-> submatch(10)}, '')\", 'E935:')\n call assert_fails('eval submatch(-1)', 'E935:')\n call assert_equal('', submatch(0))\n call assert_equal('', submatch(1))\n call assert_equal([], submatch(0, 1))\n call assert_equal([], submatch(1, 1))\nendfunc", "func Test_submatch_list_concatenate()\n let pat = 'A\\(.\\)'\n let Rep = {-> string([submatch(0, 1)] + [[submatch(1)]])}\n call substitute('A1', pat, Rep, '')->assert_equal(\"[['A1'], ['1']]\")\nendfunc", "func Test_substitute_expr_arg()\n call assert_equal('123456789-123456789=', substitute('123456789',\n\t\\ '\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)',\n\t\\ {m -> m[0] . '-' . m[1] . m[2] . m[3] . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))", " call assert_equal('123456-123456=789', substitute('123456789',\n\t\\ '\\(.\\)\\(.\\)\\(.\\)\\(a*\\)\\(n*\\)\\(.\\)\\(.\\)\\(.\\)\\(x*\\)',\n\t\\ {m -> m[0] . '-' . m[1] . m[2] . m[3] . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))", " call assert_equal('123456789-123456789x=', substitute('123456789',\n\t\\ '\\(.\\)\\(.\\)\\(.*\\)',\n\t\\ {m -> m[0] . '-' . m[1] . m[2] . m[3] . 'x' . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))", " call assert_fails(\"call substitute('xxx', '.', {m -> string(add(m, 'x'))}, '')\", 'E742:')\n call assert_fails(\"call substitute('xxx', '.', {m -> string(insert(m, 'x'))}, '')\", 'E742:')\n call assert_fails(\"call substitute('xxx', '.', {m -> string(extend(m, ['x']))}, '')\", 'E742:')\n call assert_fails(\"call substitute('xxx', '.', {m -> string(remove(m, 1))}, '')\", 'E742:')\nendfunc", "\" Test for using a function to supply the substitute string\nfunc Test_substitute_using_func()\n func Xfunc()\n return '1234'\n endfunc\n call assert_equal('a1234f', substitute('abcdef', 'b..e',\n \\ function(\"Xfunc\"), ''))\n delfunc Xfunc\nendfunc", "\" Test for using submatch() with a multiline match\nfunc Test_substitute_multiline_submatch()\n new\n call setline(1, ['line1', 'line2', 'line3', 'line4'])\n %s/^line1\\(\\_.\\+\\)line4$/\\=submatch(1)/\n call assert_equal(['', 'line2', 'line3', ''], getline(1, '$'))\n close!\nendfunc", "func Test_substitute_skipped_range()\n new\n if 0\n /1/5/2/2/\\n\n endif\n call assert_equal([0, 1, 1, 0, 1], getcurpos())\n bwipe!\nendfunc", "\" Test using the 'gdefault' option (when on, flag 'g' is default on).\nfunc Test_substitute_gdefault()\n new", " \" First check without 'gdefault'\n call setline(1, 'foo bar foo')\n s/foo/FOO/\n call assert_equal('FOO bar foo', getline(1))\n call setline(1, 'foo bar foo')\n s/foo/FOO/g\n call assert_equal('FOO bar FOO', getline(1))\n call setline(1, 'foo bar foo')\n s/foo/FOO/gg\n call assert_equal('FOO bar foo', getline(1))", " \" Then check with 'gdefault'\n set gdefault\n call setline(1, 'foo bar foo')\n s/foo/FOO/\n call assert_equal('FOO bar FOO', getline(1))\n call setline(1, 'foo bar foo')\n s/foo/FOO/g\n call assert_equal('FOO bar foo', getline(1))\n call setline(1, 'foo bar foo')\n s/foo/FOO/gg\n call assert_equal('FOO bar FOO', getline(1))", " \" Setting 'compatible' should reset 'gdefault'\n call assert_equal(1, &gdefault)\n set compatible\n call assert_equal(0, &gdefault)\n set nocompatible\n call assert_equal(0, &gdefault)", " bw!\nendfunc", "\" This was using \"old_sub\" after it was freed.\nfunc Test_using_old_sub()\n set compatible maxfuncdepth=10\n new\n call setline(1, 'some text.')\n func Repl()\n ~\n s/\n endfunc\n silent! s/\\%')/\\=Repl()", " delfunc Repl\n bwipe!\n set nocompatible\nendfunc", "\" This was switching windows in between computing the length and using it.\nfunc Test_sub_change_window()\n silent! lfile\n sil! norm o0000000000000000000000000000000000000000000000000000\n func Repl()\n lopen\n endfunc\n silent! s/\\%')/\\=Repl()\n bwipe!\n bwipe!\n delfunc Repl\nendfunc", "\" This was undoign a change in between computing the length and using it.\nfunc Do_Test_sub_undo_change()\n new\n norm o0000000000000000000000000000000000000000000000000000\n silent! s/\\%')/\\=Repl()\n bwipe!\nendfunc", "func Test_sub_undo_change()\n func Repl()\n silent! norm g-\n endfunc\n call Do_Test_sub_undo_change()", " func! Repl()\n silent earlier\n endfunc\n call Do_Test_sub_undo_change()", " delfunc Repl\nendfunc", "\" This was opening a command line window from the expression\nfunc Test_sub_open_cmdline_win()\n \" the error only happens in a very specific setup, run a new Vim instance to\n \" get a clean starting point.\n let lines =<< trim [SCRIPT]\n set vb t_vb=\n norm o0000000000000000000000000000000000000000000000000000\n func Replace()\n norm q/\n endfunc\n s/\\%')/\\=Replace()\n redir >Xresult\n messages\n redir END\n qall!\n [SCRIPT]\n call writefile(lines, 'Xscript', 'D')\n if RunVim([], [], '-u NONE -S Xscript')\n call assert_match('E565: Not allowed to change text or change window',\n \\ readfile('Xresult')->join('XX'))\n endif", " call delete('Xresult')\nendfunc", "\" This was editing a script file from the expression\nfunc Test_sub_edit_scriptfile()\n new\n norm o0000000000000000000000000000000000000000000000000000\n func EditScript()\n silent! scr! Xsedfile\n endfunc\n s/\\%')/\\=EditScript()", " delfunc EditScript\n bwipe!\nendfunc", "\" This was editing another file from the expression.\nfunc Test_sub_expr_goto_other_file()\n call writefile([''], 'Xfileone', 'D')\n enew!\n call setline(1, ['a', 'b', 'c', 'd',\n\t\\ 'Xfileone zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'])", " func g:SplitGotoFile()\n exe \"sil! norm 0\\<C-W>gf\"\n return ''\n endfunc", " $\n s/\\%')/\\=g:SplitGotoFile()", " delfunc g:SplitGotoFile\n bwipe!\nendfunc\n", "", "\" Test for the 2-letter and 3-letter :substitute commands\nfunc Test_substitute_short_cmd()\n new\n call setline(1, ['one', 'one one one'])\n s/one/two\n call cursor(2, 1)", " \" :sc\n call feedkeys(\":sc\\<CR>y\", 'xt')\n call assert_equal('two one one', getline(2))", " \" :scg\n call setline(2, 'one one one')\n call feedkeys(\":scg\\<CR>nyq\", 'xt')\n call assert_equal('one two one', getline(2))", " \" :sci\n call setline(2, 'ONE One onE')\n call feedkeys(\":sci\\<CR>y\", 'xt')\n call assert_equal('two One onE', getline(2))", " \" :scI\n set ignorecase\n call setline(2, 'ONE One one')\n call feedkeys(\":scI\\<CR>y\", 'xt')\n call assert_equal('ONE One two', getline(2))\n set ignorecase&", " \" :scn\n call setline(2, 'one one one')\n let t = execute('scn')->split(\"\\n\")\n call assert_equal(['1 match on 1 line'], t)\n call assert_equal('one one one', getline(2))", " \" :scp\n call setline(2, \"\\tone one one\")\n redir => output\n call feedkeys(\":scp\\<CR>y\", 'xt')\n redir END\n call assert_equal(' two one one', output->split(\"\\n\")[-1])\n call assert_equal(\"\\ttwo one one\", getline(2))", " \" :scl\n call setline(2, \"\\tone one one\")\n redir => output\n call feedkeys(\":scl\\<CR>y\", 'xt')\n redir END\n call assert_equal(\"^Itwo one one$\", output->split(\"\\n\")[-1])\n call assert_equal(\"\\ttwo one one\", getline(2))", " \" :sgc\n call setline(2, 'one one one one one')\n call feedkeys(\":sgc\\<CR>nyyq\", 'xt')\n call assert_equal('one two two one one', getline(2))", " \" :sg\n call setline(2, 'one one one')\n sg\n call assert_equal('two two two', getline(2))", " \" :sgi\n call setline(2, 'ONE One onE')\n sgi\n call assert_equal('two two two', getline(2))", " \" :sgI\n set ignorecase\n call setline(2, 'ONE One one')\n sgI\n call assert_equal('ONE One two', getline(2))\n set ignorecase&", " \" :sgn\n call setline(2, 'one one one')\n let t = execute('sgn')->split(\"\\n\")\n call assert_equal(['3 matches on 1 line'], t)\n call assert_equal('one one one', getline(2))", " \" :sgp\n call setline(2, \"\\tone one one\")\n redir => output\n sgp\n redir END\n call assert_equal(' two two two', output->split(\"\\n\")[-1])\n call assert_equal(\"\\ttwo two two\", getline(2))", " \" :sgl\n call setline(2, \"\\tone one one\")\n redir => output\n sgl\n redir END\n call assert_equal(\"^Itwo two two$\", output->split(\"\\n\")[-1])\n call assert_equal(\"\\ttwo two two\", getline(2))", " \" :sgr\n call setline(2, \"one one one\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n sgr\n call assert_equal('xyz xyz xyz', getline(2))", " \" :sic\n call cursor(1, 1)\n s/one/two/e\n call setline(2, \"ONE One one\")\n call cursor(2, 1)\n call feedkeys(\":sic\\<CR>y\", 'xt')\n call assert_equal('two One one', getline(2))", " \" :si\n call setline(2, \"ONE One one\")\n si\n call assert_equal('two One one', getline(2))", " \" :siI\n call setline(2, \"ONE One one\")\n siI\n call assert_equal('ONE One two', getline(2))", " \" :sin\n call setline(2, 'ONE One onE')\n let t = execute('sin')->split(\"\\n\")\n call assert_equal(['1 match on 1 line'], t)\n call assert_equal('ONE One onE', getline(2))", " \" :sip\n call setline(2, \"\\tONE One onE\")\n redir => output\n sip\n redir END\n call assert_equal(' two One onE', output->split(\"\\n\")[-1])\n call assert_equal(\"\\ttwo One onE\", getline(2))", " \" :sir\n call setline(2, \"ONE One onE\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n sir\n call assert_equal('xyz One onE', getline(2))", " \" :sIc\n call cursor(1, 1)\n s/one/two/e\n call setline(2, \"ONE One one\")\n call cursor(2, 1)\n call feedkeys(\":sIc\\<CR>y\", 'xt')\n call assert_equal('ONE One two', getline(2))", " \" :sIg\n call setline(2, \"ONE one onE one\")\n sIg\n call assert_equal('ONE two onE two', getline(2))", " \" :sIi\n call setline(2, \"ONE One one\")\n sIi\n call assert_equal('two One one', getline(2))", " \" :sI\n call setline(2, \"ONE One one\")\n sI\n call assert_equal('ONE One two', getline(2))", " \" :sIn\n call setline(2, 'ONE One one')\n let t = execute('sIn')->split(\"\\n\")\n call assert_equal(['1 match on 1 line'], t)\n call assert_equal('ONE One one', getline(2))", " \" :sIp\n call setline(2, \"\\tONE One one\")\n redir => output\n sIp\n redir END\n call assert_equal(' ONE One two', output->split(\"\\n\")[-1])\n call assert_equal(\"\\tONE One two\", getline(2))", " \" :sIl\n call setline(2, \"\\tONE onE one\")\n redir => output\n sIl\n redir END\n call assert_equal(\"^IONE onE two$\", output->split(\"\\n\")[-1])\n call assert_equal(\"\\tONE onE two\", getline(2))", " \" :sIr\n call setline(2, \"ONE one onE\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n sIr\n call assert_equal('ONE xyz onE', getline(2))", " \" :src\n call setline(2, \"ONE one one\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n call feedkeys(\":src\\<CR>y\", 'xt')\n call assert_equal('ONE xyz one', getline(2))", " \" :srg\n call setline(2, \"one one one\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n srg\n call assert_equal('xyz xyz xyz', getline(2))", " \" :sri\n call setline(2, \"ONE one onE\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n sri\n call assert_equal('xyz one onE', getline(2))", " \" :srI\n call setline(2, \"ONE one onE\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n srI\n call assert_equal('ONE xyz onE', getline(2))", " \" :srn\n call setline(2, \"ONE one onE\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n let t = execute('srn')->split(\"\\n\")\n call assert_equal(['1 match on 1 line'], t)\n call assert_equal('ONE one onE', getline(2))", " \" :srp\n call setline(2, \"\\tONE one onE\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n redir => output\n srp\n redir END\n call assert_equal(' ONE xyz onE', output->split(\"\\n\")[-1])\n call assert_equal(\"\\tONE xyz onE\", getline(2))", " \" :srl\n call setline(2, \"\\tONE one onE\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n redir => output\n srl\n redir END\n call assert_equal(\"^IONE xyz onE$\", output->split(\"\\n\")[-1])\n call assert_equal(\"\\tONE xyz onE\", getline(2))", " \" :sr\n call setline(2, \"ONE one onE\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n sr\n call assert_equal('ONE xyz onE', getline(2))", " \" :sce\n s/abc/xyz/e\n call assert_fails(\"sc\", 'E486:')\n sce\n \" :sge\n call assert_fails(\"sg\", 'E486:')\n sge\n \" :sie\n call assert_fails(\"si\", 'E486:')\n sie\n \" :sIe\n call assert_fails(\"sI\", 'E486:')\n sIe", " bw!\nendfunc", "\" This should be done last to reveal a memory leak when vim_regsub_both() is\n\" called to evaluate an expression but it is not used in a second call.\nfunc Test_z_substitute_expr_leak()\n func SubExpr()\n ~n\n endfunc\n silent! s/\\%')/\\=SubExpr()\n delfunc SubExpr\nendfunc", "\" vim: shiftwidth=2 sts=2 expandtab" ]
[ 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 0, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [7314, 1117, 697], "buggy_code_start_loc": [7314, 883, 697], "filenames": ["src/eval.c", "src/testdir/test_substitute.vim", "src/version.c"], "fixing_code_end_loc": [7320, 1134, 700], "fixing_code_start_loc": [7315, 883, 698], "message": "Out-of-bounds Write in GitHub repository vim/vim prior to 9.0.1145.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "7A64F3DA-66B5-4F73-A776-7457E9CBCE52", "versionEndExcluding": "9.0.1145", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Out-of-bounds Write in GitHub repository vim/vim prior to 9.0.1145."}], "evaluatorComment": null, "id": "CVE-2023-0054", "lastModified": "2023-05-03T12:16:43.723", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.3, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-04T19:15:09.573", "references": [{"source": "security@huntr.dev", "tags": null, "url": "http://seclists.org/fulldisclosure/2023/Mar/17"}, {"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/3ac1d97a1d9353490493d30088256360435f7731"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Third Party Advisory"], "url": "https://huntr.dev/bounties/b289ee0f-fd16-4147-bd01-c6289c45e49d"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}, {"source": "security@huntr.dev", "tags": null, "url": "https://support.apple.com/kb/HT213670"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-787"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/3ac1d97a1d9353490493d30088256360435f7731"}, "type": "CWE-787"}
190
Determine whether the {function_name} code is vulnerable or not.
[ "\" Tests for the substitute (:s) command", "source shared.vim\nsource check.vim\nsource screendump.vim", "func Test_multiline_subst()\n enew!\n call append(0, [\"1 aa\",\n\t \\ \"bb\",\n\t \\ \"cc\",\n\t \\ \"2 dd\",\n\t \\ \"ee\",\n\t \\ \"3 ef\",\n\t \\ \"gh\",\n\t \\ \"4 ij\",\n\t \\ \"5 a8\",\n\t \\ \"8b c9\",\n\t \\ \"9d\",\n\t \\ \"6 e7\",\n\t \\ \"77f\",\n\t \\ \"xxxxx\"])", " 1\n \" test if replacing a line break works with a back reference\n /^1/,/^2/s/\\n\\(.\\)/ \\1/\n \" test if inserting a line break works with a back reference\n /^3/,/^4/s/\\(.\\)$/\\r\\1/\n \" test if replacing a line break with another line break works\n /^5/,/^6/s/\\(\\_d\\{3}\\)/x\\1x/\n call assert_equal('1 aa bb cc 2 dd ee', getline(1))\n call assert_equal('3 e', getline(2))\n call assert_equal('f', getline(3))\n call assert_equal('g', getline(4))\n call assert_equal('h', getline(5))\n call assert_equal('4 i', getline(6))\n call assert_equal('j', getline(7))\n call assert_equal('5 ax8', getline(8))\n call assert_equal('8xb cx9', getline(9))\n call assert_equal('9xd', getline(10))\n call assert_equal('6 ex7', getline(11))\n call assert_equal('7x7f', getline(12))\n call assert_equal('xxxxx', getline(13))\n enew!\nendfunc", "func Test_substitute_variants()\n \" Validate that all the 2-/3-letter variants which embed the flags into the\n \" command name actually work.\n enew!\n let ln = 'Testing string'\n let variants = [\n\t\\ { 'cmd': ':s/Test/test/c', 'exp': 'testing string', 'prompt': 'y' },\n\t\\ { 'cmd': ':s/foo/bar/ce', 'exp': ln },\n\t\\ { 'cmd': ':s/t/r/cg', 'exp': 'Tesring srring', 'prompt': 'a' },\n\t\\ { 'cmd': ':s/t/r/ci', 'exp': 'resting string', 'prompt': 'y' },\n\t\\ { 'cmd': ':s/t/r/cI', 'exp': 'Tesring string', 'prompt': 'y' },\n\t\\ { 'cmd': ':s/t/r/c', 'exp': 'Testing string', 'prompt': 'n' },\n\t\\ { 'cmd': ':s/t/r/cn', 'exp': ln },\n\t\\ { 'cmd': ':s/t/r/cp', 'exp': 'Tesring string', 'prompt': 'y' },\n\t\\ { 'cmd': ':s/t/r/cl', 'exp': 'Tesring string', 'prompt': 'y' },\n\t\\ { 'cmd': ':s/t/r/gc', 'exp': 'Tesring srring', 'prompt': 'a' },\n\t\\ { 'cmd': ':s/i/I/gc', 'exp': 'TestIng string', 'prompt': 'l' },\n\t\\ { 'cmd': ':s/foo/bar/ge', 'exp': ln },\n\t\\ { 'cmd': ':s/t/r/g', 'exp': 'Tesring srring' },\n\t\\ { 'cmd': ':s/t/r/gi', 'exp': 'resring srring' },\n\t\\ { 'cmd': ':s/t/r/gI', 'exp': 'Tesring srring' },\n\t\\ { 'cmd': ':s/t/r/gn', 'exp': ln },\n\t\\ { 'cmd': ':s/t/r/gp', 'exp': 'Tesring srring' },\n\t\\ { 'cmd': ':s/t/r/gl', 'exp': 'Tesring srring' },\n\t\\ { 'cmd': ':s//r/gr', 'exp': 'Testr strr' },\n\t\\ { 'cmd': ':s/t/r/ic', 'exp': 'resting string', 'prompt': 'y' },\n\t\\ { 'cmd': ':s/foo/bar/ie', 'exp': ln },\n\t\\ { 'cmd': ':s/t/r/i', 'exp': 'resting string' },\n\t\\ { 'cmd': ':s/t/r/iI', 'exp': 'Tesring string' },\n\t\\ { 'cmd': ':s/t/r/in', 'exp': ln },\n\t\\ { 'cmd': ':s/t/r/ip', 'exp': 'resting string' },\n\t\\ { 'cmd': ':s//r/ir', 'exp': 'Testr string' },\n\t\\ { 'cmd': ':s/t/r/Ic', 'exp': 'Tesring string', 'prompt': 'y' },\n\t\\ { 'cmd': ':s/foo/bar/Ie', 'exp': ln },\n\t\\ { 'cmd': ':s/t/r/Ig', 'exp': 'Tesring srring' },\n\t\\ { 'cmd': ':s/t/r/Ii', 'exp': 'resting string' },\n\t\\ { 'cmd': ':s/t/r/I', 'exp': 'Tesring string' },\n\t\\ { 'cmd': ':s/t/r/Ip', 'exp': 'Tesring string' },\n\t\\ { 'cmd': ':s/t/r/Il', 'exp': 'Tesring string' },\n\t\\ { 'cmd': ':s//r/Ir', 'exp': 'Testr string' },\n\t\\ { 'cmd': ':s//r/rc', 'exp': 'Testr string', 'prompt': 'y' },\n\t\\ { 'cmd': ':s//r/rg', 'exp': 'Testr strr' },\n\t\\ { 'cmd': ':s//r/ri', 'exp': 'Testr string' },\n\t\\ { 'cmd': ':s//r/rI', 'exp': 'Testr string' },\n\t\\ { 'cmd': ':s//r/rn', 'exp': 'Testing string' },\n\t\\ { 'cmd': ':s//r/rp', 'exp': 'Testr string' },\n\t\\ { 'cmd': ':s//r/rl', 'exp': 'Testr string' },\n\t\\ { 'cmd': ':s//r/r', 'exp': 'Testr string' },\n\t\\ { 'cmd': ':s/i/I/gc', 'exp': 'Testing string', 'prompt': 'q' },\n\t\\]", " for var in variants\n for run in [1, 2]\n let cmd = var.cmd\n if run == 2 && cmd =~ \"/.*/.*/.\"\n\t\" Change :s/from/to/{flags} to :s{flags}\n\tlet cmd = substitute(cmd, '/.*/', '', '')\n endif\n call setline(1, [ln])\n let msg = printf('using \"%s\"', cmd)\n let @/='ing'\n let v:errmsg = ''\n call feedkeys(cmd . \"\\<CR>\" . get(var, 'prompt', ''), 'ntx')\n \" No error should exist (matters for testing e flag)\n call assert_equal('', v:errmsg, msg)\n call assert_equal(var.exp, getline('.'), msg)\n endfor\n endfor\nendfunc", "\" Test the l, p, # flags.\nfunc Test_substitute_flags_lp()\n new\n call setline(1, \"abc\\tdef\\<C-h>ghi\")", " let a = execute('s/a/a/p')\n call assert_equal(\"\\nabc def^Hghi\", a)", " let a = execute('s/a/a/l')\n call assert_equal(\"\\nabc^Idef^Hghi$\", a)", " let a = execute('s/a/a/#')\n call assert_equal(\"\\n 1 abc def^Hghi\", a)", " let a = execute('s/a/a/p#')\n call assert_equal(\"\\n 1 abc def^Hghi\", a)", " let a = execute('s/a/a/l#')\n call assert_equal(\"\\n 1 abc^Idef^Hghi$\", a)", " let a = execute('s/a/a/')\n call assert_equal(\"\", a)", " bwipe!\nendfunc", "func Test_substitute_repeat()\n \" This caused an invalid memory access.\n split Xsubfile\n s/^/x\n call feedkeys(\"Qsc\\<CR>y\", 'tx')\n bwipe!\nendfunc", "\" Test %s/\\n// which is implemented as a special case to use a\n\" more efficient join rather than doing a regular substitution.\nfunc Test_substitute_join()\n new", " call setline(1, [\"foo\\tbar\", \"bar\\<C-H>foo\"])\n let a = execute('%s/\\n//')\n call assert_equal(\"\", a)\n call assert_equal([\"foo\\tbarbar\\<C-H>foo\"], getline(1, '$'))\n call assert_equal('\\n', histget(\"search\", -1))", " call setline(1, [\"foo\\tbar\", \"bar\\<C-H>foo\"])\n let a = execute('%s/\\n//g')\n call assert_equal(\"\", a)\n call assert_equal([\"foo\\tbarbar\\<C-H>foo\"], getline(1, '$'))\n call assert_equal('\\n', histget(\"search\", -1))", " call setline(1, [\"foo\\tbar\", \"bar\\<C-H>foo\"])\n let a = execute('%s/\\n//p')\n call assert_equal(\"\\nfoo barbar^Hfoo\", a)\n call assert_equal([\"foo\\tbarbar\\<C-H>foo\"], getline(1, '$'))\n call assert_equal('\\n', histget(\"search\", -1))", " call setline(1, [\"foo\\tbar\", \"bar\\<C-H>foo\"])\n let a = execute('%s/\\n//l')\n call assert_equal(\"\\nfoo^Ibarbar^Hfoo$\", a)\n call assert_equal([\"foo\\tbarbar\\<C-H>foo\"], getline(1, '$'))\n call assert_equal('\\n', histget(\"search\", -1))", " call setline(1, [\"foo\\tbar\", \"bar\\<C-H>foo\"])\n let a = execute('%s/\\n//#')\n call assert_equal(\"\\n 1 foo barbar^Hfoo\", a)\n call assert_equal([\"foo\\tbarbar\\<C-H>foo\"], getline(1, '$'))\n call assert_equal('\\n', histget(\"search\", -1))", " call setline(1, ['foo', 'bar', 'baz', 'qux'])\n call execute('1,2s/\\n//')\n call assert_equal(['foobarbaz', 'qux'], getline(1, '$'))", " bwipe!\nendfunc", "func Test_substitute_count()\n new\n call setline(1, ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo'])\n 2", " s/foo/bar/3\n call assert_equal(['foo foo', 'bar foo', 'bar foo', 'bar foo', 'foo foo'],\n \\ getline(1, '$'))", " call assert_fails('s/foo/bar/0', 'E939:')", " call setline(1, ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo'])\n 2,4s/foo/bar/ 10\n call assert_equal(['foo foo', 'foo foo', 'foo foo', 'bar foo', 'bar foo'],\n \\ getline(1, '$'))", " bwipe!\nendfunc", "\" Test substitute 'n' flag (report number of matches, do not substitute).\nfunc Test_substitute_flag_n()\n new\n let lines = ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo']\n call setline(1, lines)", " call assert_equal(\"\\n3 matches on 3 lines\", execute('2,4s/foo/bar/n'))\n call assert_equal(\"\\n6 matches on 3 lines\", execute('2,4s/foo/bar/gn'))", " \" c flag (confirm) should be ignored when using n flag.\n call assert_equal(\"\\n3 matches on 3 lines\", execute('2,4s/foo/bar/nc'))", " \" No substitution should have been done.\n call assert_equal(lines, getline(1, '$'))", " %delete _\n call setline(1, ['A', 'Bar', 'Baz'])\n call assert_equal(\"\\n1 match on 1 line\", execute('s/\\nB\\@=//gn'))", " bwipe!\nendfunc", "func Test_substitute_errors()\n new\n call setline(1, 'foobar')", " call assert_fails('s/FOO/bar/', 'E486:')\n call assert_fails('s/foo/bar/@', 'E488:')\n call assert_fails('s/\\(/bar/', 'E54:')\n call assert_fails('s afooabara', 'E146:')\n call assert_fails('s\\\\a', 'E10:')", " setl nomodifiable\n call assert_fails('s/foo/bar/', 'E21:')", " call assert_fails(\"let s=substitute([], 'a', 'A', 'g')\", 'E730:')\n call assert_fails(\"let s=substitute('abcda', [], 'A', 'g')\", 'E730:')\n call assert_fails(\"let s=substitute('abcda', 'a', [], 'g')\", 'E730:')\n call assert_fails(\"let s=substitute('abcda', 'a', 'A', [])\", 'E730:')\n call assert_fails(\"let s=substitute('abc', '\\\\%(', 'A', 'g')\", 'E53:')", " bwipe!\nendfunc", "\" Test for *sub-replace-special* and *sub-replace-expression* on substitute().\nfunc Test_sub_replace_1()\n \" Run the tests with 'magic' on\n set magic\n set cpo&\n call assert_equal('AA', substitute('A', 'A', '&&', ''))\n call assert_equal('&', substitute('B', 'B', '\\&', ''))\n call assert_equal('C123456789987654321', substitute('C123456789', 'C\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)', '\\0\\9\\8\\7\\6\\5\\4\\3\\2\\1', ''))\n call assert_equal('d', substitute('D', 'D', 'd', ''))\n call assert_equal('~', substitute('E', 'E', '~', ''))\n call assert_equal('~', substitute('F', 'F', '\\~', ''))\n call assert_equal('Gg', substitute('G', 'G', '\\ugg', ''))\n call assert_equal('Hh', substitute('H', 'H', '\\Uh\\Eh', ''))\n call assert_equal('iI', substitute('I', 'I', '\\lII', ''))\n call assert_equal('jJ', substitute('J', 'J', '\\LJ\\EJ', ''))\n call assert_equal('Kk', substitute('K', 'K', '\\Uk\\ek', ''))\n call assert_equal(\"l\\<C-V>\\<C-M>l\",\n\t\t\t\\ substitute('lLl', 'L', \"\\<C-V>\\<C-M>\", ''))\n call assert_equal(\"m\\<C-M>m\", substitute('mMm', 'M', '\\r', ''))\n call assert_equal(\"n\\<C-V>\\<C-M>n\",\n\t\t\t\\ substitute('nNn', 'N', \"\\\\\\<C-V>\\<C-M>\", ''))\n call assert_equal(\"o\\no\", substitute('oOo', 'O', '\\n', ''))\n call assert_equal(\"p\\<C-H>p\", substitute('pPp', 'P', '\\b', ''))\n call assert_equal(\"q\\tq\", substitute('qQq', 'Q', '\\t', ''))\n call assert_equal('r\\r', substitute('rRr', 'R', '\\\\', ''))\n call assert_equal('scs', substitute('sSs', 'S', '\\c', ''))\n call assert_equal(\"u\\nu\", substitute('uUu', 'U', \"\\n\", ''))\n call assert_equal(\"v\\<C-H>v\", substitute('vVv', 'V', \"\\b\", ''))\n call assert_equal(\"w\\\\w\", substitute('wWw', 'W', \"\\\\\", ''))\n call assert_equal(\"x\\<C-M>x\", substitute('xXx', 'X', \"\\r\", ''))\n call assert_equal(\"YyyY\", substitute('Y', 'Y', '\\L\\uyYy\\l\\EY', ''))\n call assert_equal(\"zZZz\", substitute('Z', 'Z', '\\U\\lZzZ\\u\\Ez', ''))\n \" \\v or \\V after $\n call assert_equal('abxx', substitute('abcd', 'xy$\\v|cd$', 'xx', ''))\n call assert_equal('abxx', substitute('abcd', 'xy$\\V\\|cd\\$', 'xx', ''))\nendfunc", "func Test_sub_replace_2()\n \" Run the tests with 'magic' off\n set nomagic\n set cpo&\n call assert_equal('AA', substitute('A', 'A', '&&', ''))\n call assert_equal('&', substitute('B', 'B', '\\&', ''))\n call assert_equal('C123456789987654321', substitute('C123456789', 'C\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)', '\\0\\9\\8\\7\\6\\5\\4\\3\\2\\1', ''))\n call assert_equal('d', substitute('D', 'D', 'd', ''))\n call assert_equal('~', substitute('E', 'E', '~', ''))\n call assert_equal('~', substitute('F', 'F', '\\~', ''))\n call assert_equal('Gg', substitute('G', 'G', '\\ugg', ''))\n call assert_equal('Hh', substitute('H', 'H', '\\Uh\\Eh', ''))\n call assert_equal('iI', substitute('I', 'I', '\\lII', ''))\n call assert_equal('jJ', substitute('J', 'J', '\\LJ\\EJ', ''))\n call assert_equal('Kk', substitute('K', 'K', '\\Uk\\ek', ''))\n call assert_equal(\"l\\<C-V>\\<C-M>l\",\n\t\t\t\\ substitute('lLl', 'L', \"\\<C-V>\\<C-M>\", ''))\n call assert_equal(\"m\\<C-M>m\", substitute('mMm', 'M', '\\r', ''))\n call assert_equal(\"n\\<C-V>\\<C-M>n\",\n\t\t\t\\ substitute('nNn', 'N', \"\\\\\\<C-V>\\<C-M>\", ''))\n call assert_equal(\"o\\no\", substitute('oOo', 'O', '\\n', ''))\n call assert_equal(\"p\\<C-H>p\", substitute('pPp', 'P', '\\b', ''))\n call assert_equal(\"q\\tq\", substitute('qQq', 'Q', '\\t', ''))\n call assert_equal('r\\r', substitute('rRr', 'R', '\\\\', ''))\n call assert_equal('scs', substitute('sSs', 'S', '\\c', ''))\n call assert_equal(\"t\\<C-M>t\", substitute('tTt', 'T', \"\\r\", ''))\n call assert_equal(\"u\\nu\", substitute('uUu', 'U', \"\\n\", ''))\n call assert_equal(\"v\\<C-H>v\", substitute('vVv', 'V', \"\\b\", ''))\n call assert_equal('w\\w', substitute('wWw', 'W', \"\\\\\", ''))\n call assert_equal('XxxX', substitute('X', 'X', '\\L\\uxXx\\l\\EX', ''))\n call assert_equal('yYYy', substitute('Y', 'Y', '\\U\\lYyY\\u\\Ey', ''))\nendfunc", "func Test_sub_replace_3()\n set magic&\n set cpo&\n call assert_equal('a\\a', substitute('aAa', 'A', '\\=\"\\\\\"', ''))\n call assert_equal('b\\\\b', substitute('bBb', 'B', '\\=\"\\\\\\\\\"', ''))\n call assert_equal(\"c\\rc\", substitute('cCc', 'C', \"\\\\=\\\"\\r\\\"\", ''))\n call assert_equal(\"d\\\\\\rd\", substitute('dDd', 'D', \"\\\\=\\\"\\\\\\\\\\r\\\"\", ''))\n call assert_equal(\"e\\\\\\\\\\re\", substitute('eEe', 'E', \"\\\\=\\\"\\\\\\\\\\\\\\\\\\r\\\"\", ''))\n call assert_equal('f\\rf', substitute('fFf', 'F', '\\=\"\\\\r\"', ''))\n call assert_equal('j\\nj', substitute('jJj', 'J', '\\=\"\\\\n\"', ''))\n call assert_equal(\"k\\<C-M>k\", substitute('kKk', 'K', '\\=\"\\r\"', ''))\n call assert_equal(\"l\\nl\", substitute('lLl', 'L', '\\=\"\\n\"', ''))\nendfunc", "\" Test for submatch() on substitute().\nfunc Test_sub_replace_4()\n set magic&\n set cpo&\n call assert_equal('a\\a', substitute('aAa', 'A',\n\t\t\\ '\\=substitute(submatch(0), \".\", \"\\\\\", \"\")', ''))\n call assert_equal('b\\b', substitute('bBb', 'B',\n\t\t\\ '\\=substitute(submatch(0), \".\", \"\\\\\\\\\", \"\")', ''))\n call assert_equal(\"c\\<C-V>\\<C-M>c\", substitute('cCc', 'C', '\\=substitute(submatch(0), \".\", \"\\<C-V>\\<C-M>\", \"\")', ''))\n call assert_equal(\"d\\<C-V>\\<C-M>d\", substitute('dDd', 'D', '\\=substitute(submatch(0), \".\", \"\\\\\\<C-V>\\<C-M>\", \"\")', ''))\n call assert_equal(\"e\\\\\\<C-V>\\<C-M>e\", substitute('eEe', 'E', '\\=substitute(submatch(0), \".\", \"\\\\\\\\\\<C-V>\\<C-M>\", \"\")', ''))\n call assert_equal(\"f\\<C-M>f\", substitute('fFf', 'F', '\\=substitute(submatch(0), \".\", \"\\\\r\", \"\")', ''))\n call assert_equal(\"j\\nj\", substitute('jJj', 'J', '\\=substitute(submatch(0), \".\", \"\\\\n\", \"\")', ''))\n call assert_equal(\"k\\rk\", substitute('kKk', 'K', '\\=substitute(submatch(0), \".\", \"\\r\", \"\")', ''))\n call assert_equal(\"l\\nl\", substitute('lLl', 'L', '\\=substitute(submatch(0), \".\", \"\\n\", \"\")', ''))\nendfunc", "func Test_sub_replace_5()\n set magic&\n set cpo&\n call assert_equal('A123456789987654321', substitute('A123456789',\n\t\t\\ 'A\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)',\n\t\t\\ '\\=submatch(0) . submatch(9) . submatch(8) . ' .\n\t\t\\ 'submatch(7) . submatch(6) . submatch(5) . ' .\n\t\t\\ 'submatch(4) . submatch(3) . submatch(2) . submatch(1)',\n\t\t\\ ''))\n call assert_equal(\"[['A123456789'], ['9'], ['8'], ['7'], ['6'], \" .\n\t\t\\ \"['5'], ['4'], ['3'], ['2'], ['1']]\",\n\t\t\\ substitute('A123456789',\n\t\t\\ 'A\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)',\n\t\t\\ '\\=string([submatch(0, 1), submatch(9, 1), ' .\n\t\t\\ 'submatch(8, 1), 7->submatch(1), submatch(6, 1), ' .\n\t\t\\ 'submatch(5, 1), submatch(4, 1), submatch(3, 1), ' .\n\t\t\\ 'submatch(2, 1), submatch(1, 1)])',\n\t\t\\ ''))\nendfunc", "func Test_sub_replace_6()\n set magic&\n set cpo+=/\n call assert_equal('a', substitute('A', 'A', 'a', ''))\n call assert_equal('%', substitute('B', 'B', '%', ''))\n set cpo-=/\n call assert_equal('c', substitute('C', 'C', 'c', ''))\n call assert_equal('%', substitute('D', 'D', '%', ''))\nendfunc", "func Test_sub_replace_7()\n set magic&\n set cpo&\n call assert_equal('A\u0016A', substitute('A\u0016A', 'A.', '\\=submatch(0)', ''))\n call assert_equal(\"B\\nB\", substitute(\"B\\nB\", 'B.', '\\=submatch(0)', ''))\n call assert_equal(\"['B\\n']B\", substitute(\"B\\nB\", 'B.', '\\=string(submatch(0, 1))', ''))\n call assert_equal('-abab', substitute('-bb', '\\zeb', 'a', 'g'))\n call assert_equal('c-cbcbc', substitute('-bb', '\\ze', 'c', 'g'))\nendfunc", "\" Test for *:s%* on :substitute.\nfunc Test_sub_replace_8()\n new\n set magic&\n set cpo&\n $put =',,X'\n s/\\(^\\|,\\)\\ze\\(,\\|X\\)/\\1N/g\n call assert_equal('N,,NX', getline(\"$\"))\n $put =',,Y'\n let cmd = ':s/\\(^\\|,\\)\\ze\\(,\\|Y\\)/\\1N/gc'\n call feedkeys(cmd . \"\\<CR>a\", \"xt\")\n call assert_equal('N,,NY', getline(\"$\"))\n :$put =',,Z'\n let cmd = ':s/\\(^\\|,\\)\\ze\\(,\\|Z\\)/\\1N/gc'\n call feedkeys(cmd . \"\\<CR>yy\", \"xt\")\n call assert_equal('N,,NZ', getline(\"$\"))\n enew! | close\nendfunc", "func Test_sub_replace_9()\n new\n set magic&\n set cpo&\n $put ='xxx'\n call feedkeys(\":s/x/X/gc\\<CR>yyq\", \"xt\")\n call assert_equal('XXx', getline(\"$\"))\n enew! | close\nendfunc", "func Test_sub_replace_10()\n set magic&\n set cpo&\n call assert_equal('a1a2a3a', substitute('123', '\\zs', 'a', 'g'))\n call assert_equal('aaa', substitute('123', '\\zs.', 'a', 'g'))\n call assert_equal('1a2a3a', substitute('123', '.\\zs', 'a', 'g'))\n call assert_equal('a1a2a3a', substitute('123', '\\ze', 'a', 'g'))\n call assert_equal('a1a2a3', substitute('123', '\\ze.', 'a', 'g'))\n call assert_equal('aaa', substitute('123', '.\\ze', 'a', 'g'))\n call assert_equal('aa2a3a', substitute('123', '1\\|\\ze', 'a', 'g'))\n call assert_equal('1aaa', substitute('123', '1\\zs\\|[23]', 'a', 'g'))\nendfunc", "func SubReplacer(text, submatches)\n return a:text .. a:submatches[0] .. a:text\nendfunc\nfunc SubReplacerVar(text, ...)\n return a:text .. a:1[0] .. a:text\nendfunc\ndef SubReplacerVar9(text: string, ...args: list<list<string>>): string\n return text .. args[0][0] .. text\nenddef\nfunc SubReplacer20(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, submatches)\n return a:t3 .. a:submatches[0] .. a:t11\nendfunc", "func Test_substitute_partial()\n call assert_equal('1foo2foo3', substitute('123', '2', function('SubReplacer', ['foo']), 'g'))\n call assert_equal('1foo2foo3', substitute('123', '2', function('SubReplacerVar', ['foo']), 'g'))\n call assert_equal('1foo2foo3', substitute('123', '2', function('SubReplacerVar9', ['foo']), 'g'))", " \" 19 arguments plus one is just OK\n let Replacer = function('SubReplacer20', repeat(['foo'], 19))\n call assert_equal('1foo2foo3', substitute('123', '2', Replacer, 'g'))", " \" 20 arguments plus one is too many\n let Replacer = function('SubReplacer20', repeat(['foo'], 20))\n call assert_fails(\"call substitute('123', '2', Replacer, 'g')\", 'E118:')\nendfunc", "func Test_substitute_float()\n call assert_equal('number 1.23', substitute('number ', '$', { -> 1.23 }, ''))\n vim9 assert_equal('number 1.23', substitute('number ', '$', () => 1.23, ''))\nendfunc", "\" Tests for *sub-replace-special* and *sub-replace-expression* on :substitute.", "\" Execute a list of :substitute command tests\nfunc Run_SubCmd_Tests(tests)\n enew!\n for t in a:tests\n let start = line('.') + 1\n let end = start + len(t[2]) - 1\n exe \"normal o\" . t[0]\n call cursor(start, 1)\n exe t[1]\n call assert_equal(t[2], getline(start, end), t[1])\n endfor\n enew!\nendfunc", "func Test_sub_cmd_1()\n set magic\n set cpo&", " \" List entry format: [input, cmd, output]\n let tests = [['A', 's/A/&&/', ['AA']],\n\t \\ ['B', 's/B/\\&/', ['&']],\n\t \\ ['C123456789', 's/C\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)/\\0\\9\\8\\7\\6\\5\\4\\3\\2\\1/', ['C123456789987654321']],\n\t \\ ['D', 's/D/d/', ['d']],\n\t \\ ['E', 's/E/~/', ['d']],\n\t \\ ['F', 's/F/\\~/', ['~']],\n\t \\ ['G', 's/G/\\ugg/', ['Gg']],\n\t \\ ['H', 's/H/\\Uh\\Eh/', ['Hh']],\n\t \\ ['I', 's/I/\\lII/', ['iI']],\n\t \\ ['J', 's/J/\\LJ\\EJ/', ['jJ']],\n\t \\ ['K', 's/K/\\Uk\\ek/', ['Kk']],\n\t \\ ['lLl', \"s/L/\\<C-V>\\<C-M>/\", [\"l\\<C-V>\", 'l']],\n\t \\ ['mMm', 's/M/\\r/', ['m', 'm']],\n\t \\ ['nNn', \"s/N/\\\\\\<C-V>\\<C-M>/\", [\"n\\<C-V>\", 'n']],\n\t \\ ['oOo', 's/O/\\n/', [\"o\\no\"]],\n\t \\ ['pPp', 's/P/\\b/', [\"p\\<C-H>p\"]],\n\t \\ ['qQq', 's/Q/\\t/', [\"q\\tq\"]],\n\t \\ ['rRr', 's/R/\\\\/', ['r\\r']],\n\t \\ ['sSs', 's/S/\\c/', ['scs']],\n\t \\ ['tTt', \"s/T/\\<C-V>\\<C-J>/\", [\"t\\<C-V>\\<C-J>t\"]],\n\t \\ ['U', 's/U/\\L\\uuUu\\l\\EU/', ['UuuU']],\n\t \\ ['V', 's/V/\\U\\lVvV\\u\\Ev/', ['vVVv']],\n\t \\ ['\\', 's/\\\\/\\\\\\\\/', ['\\\\']]\n\t \\ ]\n call Run_SubCmd_Tests(tests)\nendfunc", "func Test_sub_cmd_2()\n set nomagic\n set cpo&", " \" List entry format: [input, cmd, output]\n let tests = [['A', 's/A/&&/', ['&&']],\n\t \\ ['B', 's/B/\\&/', ['B']],\n\t \\ ['C123456789', 's/\\mC\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)/\\0\\9\\8\\7\\6\\5\\4\\3\\2\\1/', ['C123456789987654321']],\n\t \\ ['D', 's/D/d/', ['d']],\n\t \\ ['E', 's/E/~/', ['~']],\n\t \\ ['F', 's/F/\\~/', ['~']],\n\t \\ ['G', 's/G/\\ugg/', ['Gg']],\n\t \\ ['H', 's/H/\\Uh\\Eh/', ['Hh']],\n\t \\ ['I', 's/I/\\lII/', ['iI']],\n\t \\ ['J', 's/J/\\LJ\\EJ/', ['jJ']],\n\t \\ ['K', 's/K/\\Uk\\ek/', ['Kk']],\n\t \\ ['lLl', \"s/L/\\<C-V>\\<C-M>/\", [\"l\\<C-V>\", 'l']],\n\t \\ ['mMm', 's/M/\\r/', ['m', 'm']],\n\t \\ ['nNn', \"s/N/\\\\\\<C-V>\\<C-M>/\", [\"n\\<C-V>\", 'n']],\n\t \\ ['oOo', 's/O/\\n/', [\"o\\no\"]],\n\t \\ ['pPp', 's/P/\\b/', [\"p\\<C-H>p\"]],\n\t \\ ['qQq', 's/Q/\\t/', [\"q\\tq\"]],\n\t \\ ['rRr', 's/R/\\\\/', ['r\\r']],\n\t \\ ['sSs', 's/S/\\c/', ['scs']],\n\t \\ ['tTt', \"s/T/\\<C-V>\\<C-J>/\", [\"t\\<C-V>\\<C-J>t\"]],\n\t \\ ['U', 's/U/\\L\\uuUu\\l\\EU/', ['UuuU']],\n\t \\ ['V', 's/V/\\U\\lVvV\\u\\Ev/', ['vVVv']],\n\t \\ ['\\', 's/\\\\/\\\\\\\\/', ['\\\\']]\n\t \\ ]\n call Run_SubCmd_Tests(tests)\nendfunc", "func Test_sub_cmd_3()\n set nomagic\n set cpo&", " \" List entry format: [input, cmd, output]\n let tests = [['aAa', \"s/A/\\\\='\\\\'/\", ['a\\a']],\n\t \\ ['bBb', \"s/B/\\\\='\\\\\\\\'/\", ['b\\\\b']],\n\t \\ ['cCc', \"s/C/\\\\='\\<C-V>\\<C-M>'/\", [\"c\\<C-V>\", 'c']],\n\t \\ ['dDd', \"s/D/\\\\='\\\\\\<C-V>\\<C-M>'/\", [\"d\\\\\\<C-V>\", 'd']],\n\t \\ ['eEe', \"s/E/\\\\='\\\\\\\\\\<C-V>\\<C-M>'/\", [\"e\\\\\\\\\\<C-V>\", 'e']],\n\t \\ ['fFf', \"s/F/\\\\='\\r'/\", ['f', 'f']],\n\t \\ ['gGg', \"s/G/\\\\='\\<C-V>\\<C-J>'/\", [\"g\\<C-V>\", 'g']],\n\t \\ ['hHh', \"s/H/\\\\='\\\\\\<C-V>\\<C-J>'/\", [\"h\\\\\\<C-V>\", 'h']],\n\t \\ ['iIi', \"s/I/\\\\='\\\\\\\\\\<C-V>\\<C-J>'/\", [\"i\\\\\\\\\\<C-V>\", 'i']],\n\t \\ ['jJj', \"s/J/\\\\='\\n'/\", ['j', 'j']],\n\t \\ ['kKk', 's/K/\\=\"\\r\"/', ['k', 'k']],\n\t \\ ['lLl', 's/L/\\=\"\\n\"/', ['l', 'l']]\n\t \\ ]\n call Run_SubCmd_Tests(tests)\nendfunc", "\" Test for submatch() on :substitute.\nfunc Test_sub_cmd_4()\n set magic&\n set cpo&", " \" List entry format: [input, cmd, output]\n let tests = [ ['aAa', \"s/A/\\\\=substitute(submatch(0), '.', '\\\\', '')/\",\n\t \\\t\t\t\t['a\\a']],\n\t \\ ['bBb', \"s/B/\\\\=substitute(submatch(0), '.', '\\\\', '')/\",\n\t \\\t\t\t\t['b\\b']],\n\t \\ ['cCc', \"s/C/\\\\=substitute(submatch(0), '.', '\\<C-V>\\<C-M>', '')/\",\n\t \\\t\t\t\t[\"c\\<C-V>\", 'c']],\n\t \\ ['dDd', \"s/D/\\\\=substitute(submatch(0), '.', '\\\\\\<C-V>\\<C-M>', '')/\",\n\t \\\t\t\t\t[\"d\\<C-V>\", 'd']],\n\t \\ ['eEe', \"s/E/\\\\=substitute(submatch(0), '.', '\\\\\\\\\\<C-V>\\<C-M>', '')/\",\n\t \\\t\t\t\t[\"e\\\\\\<C-V>\", 'e']],\n\t \\ ['fFf', \"s/F/\\\\=substitute(submatch(0), '.', '\\\\r', '')/\",\n\t \\\t\t\t\t['f', 'f']],\n\t \\ ['gGg', 's/G/\\=substitute(submatch(0), \".\", \"\\<C-V>\\<C-J>\", \"\")/',\n\t \\\t\t\t\t[\"g\\<C-V>\", 'g']],\n\t \\ ['hHh', 's/H/\\=substitute(submatch(0), \".\", \"\\\\\\<C-V>\\<C-J>\", \"\")/',\n\t \\\t\t\t\t[\"h\\<C-V>\", 'h']],\n\t \\ ['iIi', 's/I/\\=substitute(submatch(0), \".\", \"\\\\\\\\\\<C-V>\\<C-J>\", \"\")/',\n\t \\\t\t\t\t[\"i\\\\\\<C-V>\", 'i']],\n\t \\ ['jJj', \"s/J/\\\\=substitute(submatch(0), '.', '\\\\n', '')/\",\n\t \\\t\t\t\t['j', 'j']],\n\t \\ ['kKk', \"s/K/\\\\=substitute(submatch(0), '.', '\\\\r', '')/\",\n\t \\\t\t\t\t['k', 'k']],\n\t \\ ['lLl', \"s/L/\\\\=substitute(submatch(0), '.', '\\\\n', '')/\",\n\t \\\t\t\t\t['l', 'l']],\n\t \\ ]\n call Run_SubCmd_Tests(tests)\nendfunc", "func Test_sub_cmd_5()\n set magic&\n set cpo&", " \" List entry format: [input, cmd, output]\n let tests = [ ['A123456789', 's/A\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)/\\=submatch(0) . submatch(9) . submatch(8) . submatch(7) . submatch(6) . submatch(5) . submatch(4) . submatch(3) . submatch(2) . submatch(1)/', ['A123456789987654321']],\n\t \\ ['B123456789', 's/B\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)/\\=string([submatch(0, 1), submatch(9, 1), submatch(8, 1), submatch(7, 1), submatch(6, 1), submatch(5, 1), submatch(4, 1), submatch(3, 1), submatch(2, 1), submatch(1, 1)])/', [\"[['B123456789'], ['9'], ['8'], ['7'], ['6'], ['5'], ['4'], ['3'], ['2'], ['1']]\"]],\n\t \\ ]\n call Run_SubCmd_Tests(tests)\nendfunc", "\" Test for *:s%* on :substitute.\nfunc Test_sub_cmd_6()\n set magic&\n set cpo+=/", " \" List entry format: [input, cmd, output]\n let tests = [ ['A', 's/A/a/', ['a']],\n\t \\ ['B', 's/B/%/', ['a']],\n\t \\ ]\n call Run_SubCmd_Tests(tests)", " set cpo-=/\n let tests = [ ['C', 's/C/c/', ['c']],\n\t \\ ['D', 's/D/%/', ['%']],\n\t \\ ]\n call Run_SubCmd_Tests(tests)", " set cpo&\nendfunc", "\" Test for :s replacing \\n with line break.\nfunc Test_sub_cmd_7()\n set magic&\n set cpo&", " \" List entry format: [input, cmd, output]\n let tests = [ [\"A\\<C-V>\\<C-M>A\", 's/A./\\=submatch(0)/', ['A', 'A']],\n\t \\ [\"B\\<C-V>\\<C-J>B\", 's/B./\\=submatch(0)/', ['B', 'B']],\n\t \\ [\"C\\<C-V>\\<C-J>C\", 's/C./\\=strtrans(string(submatch(0, 1)))/', [strtrans(\"['C\\<C-J>']C\")]],\n\t \\ [\"D\\<C-V>\\<C-J>\\nD\", 's/D.\\nD/\\=strtrans(string(submatch(0, 1)))/', [strtrans(\"['D\\<C-J>', 'D']\")]],\n\t \\ [\"E\\<C-V>\\<C-J>\\n\\<C-V>\\<C-J>\\n\\<C-V>\\<C-J>\\n\\<C-V>\\<C-J>\\n\\<C-V>\\<C-J>E\", 's/E\\_.\\{-}E/\\=strtrans(string(submatch(0, 1)))/', [strtrans(\"['E\\<C-J>', '\\<C-J>', '\\<C-J>', '\\<C-J>', '\\<C-J>E']\")]],\n\t \\ ]\n call Run_SubCmd_Tests(tests)", " exe \"normal oQ\\nQ\\<Esc>k\"\n call assert_fails('s/Q[^\\n]Q/\\=submatch(0).\"foobar\"/', 'E486:')\n enew!\nendfunc", "func TitleString()\n let check = 'foo' =~ 'bar'\n return \"\"\nendfunc", "func Test_sub_cmd_8()\n set titlestring=%{TitleString()}", " enew!\n call append(0, ['', 'test_one', 'test_two'])\n call cursor(1,1)\n /^test_one/s/.*/\\=\"foo\\nbar\"/\n call assert_equal('foo', getline(2))\n call assert_equal('bar', getline(3))\n call feedkeys(':/^test_two/s/.*/\\=\"foo\\nbar\"/c', \"t\")\n call feedkeys(\"\\<CR>y\", \"xt\")\n call assert_equal('foo', getline(4))\n call assert_equal('bar', getline(5))", " enew!\n set titlestring&\nendfunc", "func Test_sub_cmd_9()\n new\n let input = ['1 aaa', '2 aaa', '3 aaa']\n call setline(1, input)\n func Foo()\n return submatch(0)\n endfunc\n %s/aaa/\\=Foo()/gn\n call assert_equal(input, getline(1, '$'))\n call assert_equal(1, &modifiable)", " delfunc Foo\n bw!\nendfunc", "func Test_sub_highlight_zero_match()\n CheckRunVimInTerminal", " let lines =<< trim END\n call setline(1, ['one', 'two', 'three'])\n END\n call writefile(lines, 'XscriptSubHighlight', 'D')\n let buf = RunVimInTerminal('-S XscriptSubHighlight', #{rows: 8, cols: 60})\n call term_sendkeys(buf, \":%s/^/ /c\\<CR>\")\n call VerifyScreenDump(buf, 'Test_sub_highlight_zer_match_1', {})", " call term_sendkeys(buf, \"\\<Esc>\")\n call StopVimInTerminal(buf)\nendfunc", "func Test_nocatch_sub_failure_handling()\n \" normal error results in all replacements \n func Foo()\n foobar\n endfunc\n new\n call setline(1, ['1 aaa', '2 aaa', '3 aaa'])\n \" need silent! to avoid a delay when entering Insert mode\n silent! %s/aaa/\\=Foo()/g\n call assert_equal(['1 0', '2 0', '3 0'], getline(1, 3))", " \" Throw without try-catch causes abort after the first line.\n \" We cannot test this, since it would stop executing the test script.", " \" try/catch does not result in any changes\n func! Foo()\n throw 'error'\n endfunc\n call setline(1, ['1 aaa', '2 aaa', '3 aaa'])\n let error_caught = 0\n try\n %s/aaa/\\=Foo()/g\n catch\n let error_caught = 1\n endtry\n call assert_equal(1, error_caught)\n call assert_equal(['1 aaa', '2 aaa', '3 aaa'], getline(1, 3))", " \" Same, but using \"n\" flag so that \"sandbox\" gets set\n call setline(1, ['1 aaa', '2 aaa', '3 aaa'])\n let error_caught = 0\n try\n %s/aaa/\\=Foo()/gn\n catch\n let error_caught = 1\n endtry\n call assert_equal(1, error_caught)\n call assert_equal(['1 aaa', '2 aaa', '3 aaa'], getline(1, 3))", " delfunc Foo\n bwipe!\nendfunc", "\" Test \":s/pat/sub/\" with different ~s in sub.\nfunc Test_replace_with_tilde()\n new\n \" Set the last replace string to empty\n s/^$//\n call append(0, ['- Bug in \"vPPPP\" on this text:'])\n normal gg\n s/u/~u~/\n call assert_equal('- Bug in \"vPPPP\" on this text:', getline(1))\n s/i/~u~/\n call assert_equal('- Bug uuun \"vPPPP\" on this text:', getline(1))\n s/o/~~~/\n call assert_equal('- Bug uuun \"vPPPP\" uuuuuuuuun this text:', getline(1))\n close!\nendfunc", "func Test_replace_keeppatterns()\n new\n a\nfoobar", "substitute foo asdf", "one two\n.", " normal gg\n /^substitute\n s/foo/bar/\n call assert_equal('foo', @/)\n call assert_equal('substitute bar asdf', getline('.'))", " /^substitute\n keeppatterns s/asdf/xyz/\n call assert_equal('^substitute', @/)\n call assert_equal('substitute bar xyz', getline('.'))", " exe \"normal /bar /e\\<CR>\"\n call assert_equal(15, col('.'))\n normal -\n keeppatterns /xyz\n call assert_equal('bar ', @/)\n call assert_equal('substitute bar xyz', getline('.'))\n exe \"normal 0dn\"\n call assert_equal('xyz', getline('.'))", " close!\nendfunc", "func Test_sub_beyond_end()\n new\n call setline(1, '#')\n let @/ = '^#\\n\\zs'\n s///e\n call assert_equal('#', getline(1))\n bwipe!\nendfunc", "\" Test for repeating last substitution using :~ and :&r\nfunc Test_repeat_last_sub()\n new\n call setline(1, ['blue green yellow orange white'])\n s/blue/red/\n let @/ = 'yellow'\n ~\n let @/ = 'white'\n :&r\n let @/ = 'green'\n s//gray\n call assert_equal('red gray red orange red', getline(1))\n close!\nendfunc", "\" Test for Vi compatible substitution:\n\" \\/{string}/, \\?{string}? and \\&{string}&\nfunc Test_sub_vi_compatibility()\n new\n call setline(1, ['blue green yellow orange blue'])\n let @/ = 'orange'\n s\\/white/\n let @/ = 'blue'\n s\\?amber?\n let @/ = 'white'\n s\\&green&\n call assert_equal('amber green yellow white green', getline(1))\n close!", " call assert_fails('vim9cmd s\\/white/', 'E1270:')\n call assert_fails('vim9cmd s\\?white?', 'E1270:')\n call assert_fails('vim9cmd s\\&white&', 'E1270:')\nendfunc", "\" Test for substitute with the new text longer than the original text\nfunc Test_sub_expand_text()\n new\n call setline(1, 'abcabcabcabcabcabcabcabc')\n s/b/\\=repeat('B', 10)/g\n call assert_equal(repeat('aBBBBBBBBBBc', 8), getline(1))\n close!\nendfunc", "\" Test for command failures when the last substitute pattern is not set.\nfunc Test_sub_with_no_last_pat()\n let lines =<< trim [SCRIPT]\n call assert_fails('~', 'E33:')\n call assert_fails('s//abc/g', 'E35:')\n call assert_fails('s\\/bar', 'E35:')\n call assert_fails('s\\&bar&', 'E33:')\n call writefile(v:errors, 'Xresult')\n qall!\n [SCRIPT]\n call writefile(lines, 'Xscript', 'D')\n if RunVim([], [], '--clean -S Xscript')\n call assert_equal([], readfile('Xresult'))\n endif", " let lines =<< trim [SCRIPT]\n set cpo+=/\n call assert_fails('s/abc/%/', 'E33:')\n call writefile(v:errors, 'Xresult')\n qall!\n [SCRIPT]\n call writefile(lines, 'Xscript')\n if RunVim([], [], '--clean -S Xscript')\n call assert_equal([], readfile('Xresult'))\n endif", " call delete('Xresult')\nendfunc", "func Test_substitute()", " call assert_equal('a1a2a3a', substitute('123', '\\zs', 'a', 'g'))", " \" Substitute with special keys\n call assert_equal(\"a\\<End>c\", substitute('abc', \"a.c\", \"a\\<End>c\", ''))\nendfunc", "func Test_substitute_expr()\n let g:val = 'XXX'\n call assert_equal('XXX', substitute('yyy', 'y*', '\\=g:val', ''))\n call assert_equal('XXX', substitute('yyy', 'y*', {-> g:val}, ''))\n call assert_equal(\"-\\u1b \\uf2-\", substitute(\"-%1b %f2-\", '%\\(\\x\\x\\)',\n\t\t\t \\ '\\=nr2char(\"0x\" . submatch(1))', 'g'))\n call assert_equal(\"-\\u1b \\uf2-\", substitute(\"-%1b %f2-\", '%\\(\\x\\x\\)',\n\t\t\t \\ {-> nr2char(\"0x\" . submatch(1))}, 'g'))", " call assert_equal('231', substitute('123', '\\(.\\)\\(.\\)\\(.\\)',\n\t\\ {-> submatch(2) . submatch(3) . submatch(1)}, ''))", " func Recurse()\n return substitute('yyy', 'y\\(.\\)y', {-> submatch(1)}, '')\n endfunc\n \" recursive call works\n call assert_equal('-y-x-', substitute('xxx', 'x\\(.\\)x', {-> '-' . Recurse() . '-' . submatch(1) . '-'}, ''))", " call assert_fails(\"let s=submatch([])\", 'E745:')\n call assert_fails(\"let s=submatch(2, [])\", 'E745:')\nendfunc", "func Test_invalid_submatch()\n \" This was causing invalid memory access in Vim-7.4.2232 and older\n call assert_fails(\"call substitute('x', '.', {-> submatch(10)}, '')\", 'E935:')\n call assert_fails('eval submatch(-1)', 'E935:')\n call assert_equal('', submatch(0))\n call assert_equal('', submatch(1))\n call assert_equal([], submatch(0, 1))\n call assert_equal([], submatch(1, 1))\nendfunc", "func Test_submatch_list_concatenate()\n let pat = 'A\\(.\\)'\n let Rep = {-> string([submatch(0, 1)] + [[submatch(1)]])}\n call substitute('A1', pat, Rep, '')->assert_equal(\"[['A1'], ['1']]\")\nendfunc", "func Test_substitute_expr_arg()\n call assert_equal('123456789-123456789=', substitute('123456789',\n\t\\ '\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)\\(.\\)',\n\t\\ {m -> m[0] . '-' . m[1] . m[2] . m[3] . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))", " call assert_equal('123456-123456=789', substitute('123456789',\n\t\\ '\\(.\\)\\(.\\)\\(.\\)\\(a*\\)\\(n*\\)\\(.\\)\\(.\\)\\(.\\)\\(x*\\)',\n\t\\ {m -> m[0] . '-' . m[1] . m[2] . m[3] . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))", " call assert_equal('123456789-123456789x=', substitute('123456789',\n\t\\ '\\(.\\)\\(.\\)\\(.*\\)',\n\t\\ {m -> m[0] . '-' . m[1] . m[2] . m[3] . 'x' . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))", " call assert_fails(\"call substitute('xxx', '.', {m -> string(add(m, 'x'))}, '')\", 'E742:')\n call assert_fails(\"call substitute('xxx', '.', {m -> string(insert(m, 'x'))}, '')\", 'E742:')\n call assert_fails(\"call substitute('xxx', '.', {m -> string(extend(m, ['x']))}, '')\", 'E742:')\n call assert_fails(\"call substitute('xxx', '.', {m -> string(remove(m, 1))}, '')\", 'E742:')\nendfunc", "\" Test for using a function to supply the substitute string\nfunc Test_substitute_using_func()\n func Xfunc()\n return '1234'\n endfunc\n call assert_equal('a1234f', substitute('abcdef', 'b..e',\n \\ function(\"Xfunc\"), ''))\n delfunc Xfunc\nendfunc", "\" Test for using submatch() with a multiline match\nfunc Test_substitute_multiline_submatch()\n new\n call setline(1, ['line1', 'line2', 'line3', 'line4'])\n %s/^line1\\(\\_.\\+\\)line4$/\\=submatch(1)/\n call assert_equal(['', 'line2', 'line3', ''], getline(1, '$'))\n close!\nendfunc", "func Test_substitute_skipped_range()\n new\n if 0\n /1/5/2/2/\\n\n endif\n call assert_equal([0, 1, 1, 0, 1], getcurpos())\n bwipe!\nendfunc", "\" Test using the 'gdefault' option (when on, flag 'g' is default on).\nfunc Test_substitute_gdefault()\n new", " \" First check without 'gdefault'\n call setline(1, 'foo bar foo')\n s/foo/FOO/\n call assert_equal('FOO bar foo', getline(1))\n call setline(1, 'foo bar foo')\n s/foo/FOO/g\n call assert_equal('FOO bar FOO', getline(1))\n call setline(1, 'foo bar foo')\n s/foo/FOO/gg\n call assert_equal('FOO bar foo', getline(1))", " \" Then check with 'gdefault'\n set gdefault\n call setline(1, 'foo bar foo')\n s/foo/FOO/\n call assert_equal('FOO bar FOO', getline(1))\n call setline(1, 'foo bar foo')\n s/foo/FOO/g\n call assert_equal('FOO bar foo', getline(1))\n call setline(1, 'foo bar foo')\n s/foo/FOO/gg\n call assert_equal('FOO bar FOO', getline(1))", " \" Setting 'compatible' should reset 'gdefault'\n call assert_equal(1, &gdefault)\n set compatible\n call assert_equal(0, &gdefault)\n set nocompatible\n call assert_equal(0, &gdefault)", " bw!\nendfunc", "\" This was using \"old_sub\" after it was freed.\nfunc Test_using_old_sub()\n set compatible maxfuncdepth=10\n new\n call setline(1, 'some text.')\n func Repl()\n ~\n s/\n endfunc\n silent! s/\\%')/\\=Repl()", " delfunc Repl\n bwipe!\n set nocompatible\nendfunc", "\" This was switching windows in between computing the length and using it.\nfunc Test_sub_change_window()\n silent! lfile\n sil! norm o0000000000000000000000000000000000000000000000000000\n func Repl()\n lopen\n endfunc\n silent! s/\\%')/\\=Repl()\n bwipe!\n bwipe!\n delfunc Repl\nendfunc", "\" This was undoign a change in between computing the length and using it.\nfunc Do_Test_sub_undo_change()\n new\n norm o0000000000000000000000000000000000000000000000000000\n silent! s/\\%')/\\=Repl()\n bwipe!\nendfunc", "func Test_sub_undo_change()\n func Repl()\n silent! norm g-\n endfunc\n call Do_Test_sub_undo_change()", " func! Repl()\n silent earlier\n endfunc\n call Do_Test_sub_undo_change()", " delfunc Repl\nendfunc", "\" This was opening a command line window from the expression\nfunc Test_sub_open_cmdline_win()\n \" the error only happens in a very specific setup, run a new Vim instance to\n \" get a clean starting point.\n let lines =<< trim [SCRIPT]\n set vb t_vb=\n norm o0000000000000000000000000000000000000000000000000000\n func Replace()\n norm q/\n endfunc\n s/\\%')/\\=Replace()\n redir >Xresult\n messages\n redir END\n qall!\n [SCRIPT]\n call writefile(lines, 'Xscript', 'D')\n if RunVim([], [], '-u NONE -S Xscript')\n call assert_match('E565: Not allowed to change text or change window',\n \\ readfile('Xresult')->join('XX'))\n endif", " call delete('Xresult')\nendfunc", "\" This was editing a script file from the expression\nfunc Test_sub_edit_scriptfile()\n new\n norm o0000000000000000000000000000000000000000000000000000\n func EditScript()\n silent! scr! Xsedfile\n endfunc\n s/\\%')/\\=EditScript()", " delfunc EditScript\n bwipe!\nendfunc", "\" This was editing another file from the expression.\nfunc Test_sub_expr_goto_other_file()\n call writefile([''], 'Xfileone', 'D')\n enew!\n call setline(1, ['a', 'b', 'c', 'd',\n\t\\ 'Xfileone zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'])", " func g:SplitGotoFile()\n exe \"sil! norm 0\\<C-W>gf\"\n return ''\n endfunc", " $\n s/\\%')/\\=g:SplitGotoFile()", " delfunc g:SplitGotoFile\n bwipe!\nendfunc\n", "func Test_recursive_expr_substitute()\n \" this was reading invalid memory\n let lines =<< trim END\n func Repl(g, n)\n s\n r%:s000\n endfunc\n next 0\n let caught = 0\n s/\\%')/\\=Repl(0, 0)\n qall!\n END\n call writefile(lines, 'XexprSubst', 'D')\n call RunVim([], [], '--clean -S XexprSubst')\nendfunc\n", "\" Test for the 2-letter and 3-letter :substitute commands\nfunc Test_substitute_short_cmd()\n new\n call setline(1, ['one', 'one one one'])\n s/one/two\n call cursor(2, 1)", " \" :sc\n call feedkeys(\":sc\\<CR>y\", 'xt')\n call assert_equal('two one one', getline(2))", " \" :scg\n call setline(2, 'one one one')\n call feedkeys(\":scg\\<CR>nyq\", 'xt')\n call assert_equal('one two one', getline(2))", " \" :sci\n call setline(2, 'ONE One onE')\n call feedkeys(\":sci\\<CR>y\", 'xt')\n call assert_equal('two One onE', getline(2))", " \" :scI\n set ignorecase\n call setline(2, 'ONE One one')\n call feedkeys(\":scI\\<CR>y\", 'xt')\n call assert_equal('ONE One two', getline(2))\n set ignorecase&", " \" :scn\n call setline(2, 'one one one')\n let t = execute('scn')->split(\"\\n\")\n call assert_equal(['1 match on 1 line'], t)\n call assert_equal('one one one', getline(2))", " \" :scp\n call setline(2, \"\\tone one one\")\n redir => output\n call feedkeys(\":scp\\<CR>y\", 'xt')\n redir END\n call assert_equal(' two one one', output->split(\"\\n\")[-1])\n call assert_equal(\"\\ttwo one one\", getline(2))", " \" :scl\n call setline(2, \"\\tone one one\")\n redir => output\n call feedkeys(\":scl\\<CR>y\", 'xt')\n redir END\n call assert_equal(\"^Itwo one one$\", output->split(\"\\n\")[-1])\n call assert_equal(\"\\ttwo one one\", getline(2))", " \" :sgc\n call setline(2, 'one one one one one')\n call feedkeys(\":sgc\\<CR>nyyq\", 'xt')\n call assert_equal('one two two one one', getline(2))", " \" :sg\n call setline(2, 'one one one')\n sg\n call assert_equal('two two two', getline(2))", " \" :sgi\n call setline(2, 'ONE One onE')\n sgi\n call assert_equal('two two two', getline(2))", " \" :sgI\n set ignorecase\n call setline(2, 'ONE One one')\n sgI\n call assert_equal('ONE One two', getline(2))\n set ignorecase&", " \" :sgn\n call setline(2, 'one one one')\n let t = execute('sgn')->split(\"\\n\")\n call assert_equal(['3 matches on 1 line'], t)\n call assert_equal('one one one', getline(2))", " \" :sgp\n call setline(2, \"\\tone one one\")\n redir => output\n sgp\n redir END\n call assert_equal(' two two two', output->split(\"\\n\")[-1])\n call assert_equal(\"\\ttwo two two\", getline(2))", " \" :sgl\n call setline(2, \"\\tone one one\")\n redir => output\n sgl\n redir END\n call assert_equal(\"^Itwo two two$\", output->split(\"\\n\")[-1])\n call assert_equal(\"\\ttwo two two\", getline(2))", " \" :sgr\n call setline(2, \"one one one\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n sgr\n call assert_equal('xyz xyz xyz', getline(2))", " \" :sic\n call cursor(1, 1)\n s/one/two/e\n call setline(2, \"ONE One one\")\n call cursor(2, 1)\n call feedkeys(\":sic\\<CR>y\", 'xt')\n call assert_equal('two One one', getline(2))", " \" :si\n call setline(2, \"ONE One one\")\n si\n call assert_equal('two One one', getline(2))", " \" :siI\n call setline(2, \"ONE One one\")\n siI\n call assert_equal('ONE One two', getline(2))", " \" :sin\n call setline(2, 'ONE One onE')\n let t = execute('sin')->split(\"\\n\")\n call assert_equal(['1 match on 1 line'], t)\n call assert_equal('ONE One onE', getline(2))", " \" :sip\n call setline(2, \"\\tONE One onE\")\n redir => output\n sip\n redir END\n call assert_equal(' two One onE', output->split(\"\\n\")[-1])\n call assert_equal(\"\\ttwo One onE\", getline(2))", " \" :sir\n call setline(2, \"ONE One onE\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n sir\n call assert_equal('xyz One onE', getline(2))", " \" :sIc\n call cursor(1, 1)\n s/one/two/e\n call setline(2, \"ONE One one\")\n call cursor(2, 1)\n call feedkeys(\":sIc\\<CR>y\", 'xt')\n call assert_equal('ONE One two', getline(2))", " \" :sIg\n call setline(2, \"ONE one onE one\")\n sIg\n call assert_equal('ONE two onE two', getline(2))", " \" :sIi\n call setline(2, \"ONE One one\")\n sIi\n call assert_equal('two One one', getline(2))", " \" :sI\n call setline(2, \"ONE One one\")\n sI\n call assert_equal('ONE One two', getline(2))", " \" :sIn\n call setline(2, 'ONE One one')\n let t = execute('sIn')->split(\"\\n\")\n call assert_equal(['1 match on 1 line'], t)\n call assert_equal('ONE One one', getline(2))", " \" :sIp\n call setline(2, \"\\tONE One one\")\n redir => output\n sIp\n redir END\n call assert_equal(' ONE One two', output->split(\"\\n\")[-1])\n call assert_equal(\"\\tONE One two\", getline(2))", " \" :sIl\n call setline(2, \"\\tONE onE one\")\n redir => output\n sIl\n redir END\n call assert_equal(\"^IONE onE two$\", output->split(\"\\n\")[-1])\n call assert_equal(\"\\tONE onE two\", getline(2))", " \" :sIr\n call setline(2, \"ONE one onE\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n sIr\n call assert_equal('ONE xyz onE', getline(2))", " \" :src\n call setline(2, \"ONE one one\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n call feedkeys(\":src\\<CR>y\", 'xt')\n call assert_equal('ONE xyz one', getline(2))", " \" :srg\n call setline(2, \"one one one\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n srg\n call assert_equal('xyz xyz xyz', getline(2))", " \" :sri\n call setline(2, \"ONE one onE\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n sri\n call assert_equal('xyz one onE', getline(2))", " \" :srI\n call setline(2, \"ONE one onE\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n srI\n call assert_equal('ONE xyz onE', getline(2))", " \" :srn\n call setline(2, \"ONE one onE\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n let t = execute('srn')->split(\"\\n\")\n call assert_equal(['1 match on 1 line'], t)\n call assert_equal('ONE one onE', getline(2))", " \" :srp\n call setline(2, \"\\tONE one onE\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n redir => output\n srp\n redir END\n call assert_equal(' ONE xyz onE', output->split(\"\\n\")[-1])\n call assert_equal(\"\\tONE xyz onE\", getline(2))", " \" :srl\n call setline(2, \"\\tONE one onE\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n redir => output\n srl\n redir END\n call assert_equal(\"^IONE xyz onE$\", output->split(\"\\n\")[-1])\n call assert_equal(\"\\tONE xyz onE\", getline(2))", " \" :sr\n call setline(2, \"ONE one onE\")\n call cursor(2, 1)\n s/abc/xyz/e\n let @/ = 'one'\n sr\n call assert_equal('ONE xyz onE', getline(2))", " \" :sce\n s/abc/xyz/e\n call assert_fails(\"sc\", 'E486:')\n sce\n \" :sge\n call assert_fails(\"sg\", 'E486:')\n sge\n \" :sie\n call assert_fails(\"si\", 'E486:')\n sie\n \" :sIe\n call assert_fails(\"sI\", 'E486:')\n sIe", " bw!\nendfunc", "\" This should be done last to reveal a memory leak when vim_regsub_both() is\n\" called to evaluate an expression but it is not used in a second call.\nfunc Test_z_substitute_expr_leak()\n func SubExpr()\n ~n\n endfunc\n silent! s/\\%')/\\=SubExpr()\n delfunc SubExpr\nendfunc", "\" vim: shiftwidth=2 sts=2 expandtab" ]
[ 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, 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, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [7314, 1117, 697], "buggy_code_start_loc": [7314, 883, 697], "filenames": ["src/eval.c", "src/testdir/test_substitute.vim", "src/version.c"], "fixing_code_end_loc": [7320, 1134, 700], "fixing_code_start_loc": [7315, 883, 698], "message": "Out-of-bounds Write in GitHub repository vim/vim prior to 9.0.1145.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "7A64F3DA-66B5-4F73-A776-7457E9CBCE52", "versionEndExcluding": "9.0.1145", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Out-of-bounds Write in GitHub repository vim/vim prior to 9.0.1145."}], "evaluatorComment": null, "id": "CVE-2023-0054", "lastModified": "2023-05-03T12:16:43.723", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.3, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-04T19:15:09.573", "references": [{"source": "security@huntr.dev", "tags": null, "url": "http://seclists.org/fulldisclosure/2023/Mar/17"}, {"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/3ac1d97a1d9353490493d30088256360435f7731"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Third Party Advisory"], "url": "https://huntr.dev/bounties/b289ee0f-fd16-4147-bd01-c6289c45e49d"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}, {"source": "security@huntr.dev", "tags": null, "url": "https://support.apple.com/kb/HT213670"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-787"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/3ac1d97a1d9353490493d30088256360435f7731"}, "type": "CWE-787"}
190
Determine whether the {function_name} code is vulnerable or not.
[ "/* vi:set ts=8 sts=4 sw=4 noet:\n *\n * VIM - Vi IMproved\t\tby Bram Moolenaar\n *\n * Do \":help uganda\" in Vim to read copying and usage conditions.\n * Do \":help credits\" in Vim to see a list of people who contributed.\n * See README.txt for an overview of the Vim source code.\n */", "#include \"vim.h\"", "/*\n * Vim originated from Stevie version 3.6 (Fish disk 217) by GRWalter (Fred)\n * It has been changed beyond recognition since then.\n *\n * Differences between version 8.2 and 9.0 can be found with \":help version9\".\n * Differences between version 7.4 and 8.x can be found with \":help version8\".\n * Differences between version 6.4 and 7.x can be found with \":help version7\".\n * Differences between version 5.8 and 6.x can be found with \":help version6\".\n * Differences between version 4.x and 5.x can be found with \":help version5\".\n * Differences between version 3.0 and 4.x can be found with \":help version4\".\n * All the remarks about older versions have been removed, they are not very\n * interesting.\n */", "#include \"version.h\"", "char\t\t*Version = VIM_VERSION_SHORT;\nstatic char\t*mediumVersion = VIM_VERSION_MEDIUM;", "#if defined(HAVE_DATE_TIME) || defined(PROTO)\n# if (defined(VMS) && defined(VAXC)) || defined(PROTO)\nchar\tlongVersion[sizeof(VIM_VERSION_LONG_DATE) + sizeof(__DATE__)\n\t\t\t\t\t\t + sizeof(__TIME__) + 3];", " void\ninit_longVersion(void)\n{\n /*\n * Construct the long version string. Necessary because\n * VAX C can't concatenate strings in the preprocessor.\n */\n strcpy(longVersion, VIM_VERSION_LONG_DATE);\n#ifdef BUILD_DATE\n strcat(longVersion, BUILD_DATE);\n#else\n strcat(longVersion, __DATE__);\n strcat(longVersion, \" \");\n strcat(longVersion, __TIME__);\n#endif\n strcat(longVersion, \")\");\n}", "# else\nchar\t*longVersion = NULL;", " void\ninit_longVersion(void)\n{\n if (longVersion == NULL)\n {\n#ifdef BUILD_DATE\n\tchar *date_time = BUILD_DATE;\n#else\n\tchar *date_time = __DATE__ \" \" __TIME__;\n#endif\n\tchar *msg = _(\"%s (%s, compiled %s)\");\n\tsize_t len = strlen(msg)\n\t\t + strlen(VIM_VERSION_LONG_ONLY)\n\t\t + strlen(VIM_VERSION_DATE_ONLY)\n\t\t + strlen(date_time);", "\tlongVersion = alloc(len);\n\tif (longVersion == NULL)\n\t longVersion = VIM_VERSION_LONG;\n\telse\n\t vim_snprintf(longVersion, len, msg,\n\t\t VIM_VERSION_LONG_ONLY, VIM_VERSION_DATE_ONLY, date_time);\n }\n}\n# endif\n#else\nchar\t*longVersion = VIM_VERSION_LONG;", " void\ninit_longVersion(void)\n{\n // nothing to do\n}\n#endif", "static char *(features[]) =\n{\n#ifdef HAVE_ACL\n\t\"+acl\",\n#else\n\t\"-acl\",\n#endif\n#ifdef AMIGA\t\t// only for Amiga systems\n# ifdef FEAT_ARP\n\t\"+ARP\",\n# else\n\t\"-ARP\",\n# endif\n#endif\n#ifdef FEAT_ARABIC\n\t\"+arabic\",\n#else\n\t\"-arabic\",\n#endif\n\t\"+autocmd\",\n#ifdef FEAT_AUTOCHDIR\n \"+autochdir\",\n#else\n \"-autochdir\",\n#endif\n#ifdef FEAT_AUTOSERVERNAME\n\t\"+autoservername\",\n#else\n\t\"-autoservername\",\n#endif\n#ifdef FEAT_BEVAL_GUI\n\t\"+balloon_eval\",\n#else\n\t\"-balloon_eval\",\n#endif\n#ifdef FEAT_BEVAL_TERM\n\t\"+balloon_eval_term\",\n#else\n\t\"-balloon_eval_term\",\n#endif\n#ifdef FEAT_BROWSE\n\t\"+browse\",\n#else\n\t\"-browse\",\n#endif\n\t\"++builtin_terms\",\n#ifdef FEAT_BYTEOFF\n\t\"+byte_offset\",\n#else\n\t\"-byte_offset\",\n#endif\n#ifdef FEAT_JOB_CHANNEL\n\t\"+channel\",\n#else\n\t\"-channel\",\n#endif\n\t\"+cindent\",\n#ifdef FEAT_CLIENTSERVER\n\t\"+clientserver\",\n#else\n\t\"-clientserver\",\n#endif\n#ifdef FEAT_CLIPBOARD\n\t\"+clipboard\",\n#else\n\t\"-clipboard\",\n#endif\n\t\"+cmdline_compl\",\n\t\"+cmdline_hist\",\n\t\"+cmdline_info\",\n\t\"+comments\",\n#ifdef FEAT_CONCEAL\n\t\"+conceal\",\n#else\n\t\"-conceal\",\n#endif\n#ifdef FEAT_CRYPT\n\t\"+cryptv\",\n#else\n\t\"-cryptv\",\n#endif\n#ifdef FEAT_CSCOPE\n\t\"+cscope\",\n#else\n\t\"-cscope\",\n#endif\n\t\"+cursorbind\",\n#ifdef CURSOR_SHAPE\n\t\"+cursorshape\",\n#else\n\t\"-cursorshape\",\n#endif\n#if defined(FEAT_CON_DIALOG) && defined(FEAT_GUI_DIALOG)\n\t\"+dialog_con_gui\",\n#else\n# if defined(FEAT_CON_DIALOG)\n\t\"+dialog_con\",\n# else\n# if defined(FEAT_GUI_DIALOG)\n\t\"+dialog_gui\",\n# else\n\t\"-dialog\",\n# endif\n# endif\n#endif\n#ifdef FEAT_DIFF\n\t\"+diff\",\n#else\n\t\"-diff\",\n#endif\n#ifdef FEAT_DIGRAPHS\n\t\"+digraphs\",\n#else\n\t\"-digraphs\",\n#endif\n#ifdef FEAT_GUI_MSWIN\n# ifdef FEAT_DIRECTX\n\t\"+directx\",\n# else\n\t\"-directx\",\n# endif\n#endif\n#ifdef FEAT_DND\n\t\"+dnd\",\n#else\n\t\"-dnd\",\n#endif\n\t\"-ebcdic\",\n#ifdef FEAT_EMACS_TAGS\n\t\"+emacs_tags\",\n#else\n\t\"-emacs_tags\",\n#endif\n#ifdef FEAT_EVAL\n\t\"+eval\",\n#else\n\t\"-eval\",\n#endif\n\t\"+ex_extra\",\n#ifdef FEAT_SEARCH_EXTRA\n\t\"+extra_search\",\n#else\n\t\"-extra_search\",\n#endif\n\t\"-farsi\",\n\t\"+file_in_path\",\n#ifdef FEAT_FIND_ID\n\t\"+find_in_path\",\n#else\n\t\"-find_in_path\",\n#endif\n\t\"+float\",\n#ifdef FEAT_FOLDING\n\t\"+folding\",\n#else\n\t\"-folding\",\n#endif\n\t\"-footer\",\n\t// only interesting on Unix systems\n#if !defined(USE_SYSTEM) && defined(UNIX)\n\t\"+fork()\",\n#endif\n#ifdef FEAT_GETTEXT\n# ifdef DYNAMIC_GETTEXT\n\t\"+gettext/dyn\",\n# else\n\t\"+gettext\",\n# endif\n#else\n\t\"-gettext\",\n#endif\n\t\"-hangul_input\",\n#if (defined(HAVE_ICONV_H) && defined(USE_ICONV)) || defined(DYNAMIC_ICONV)\n# ifdef DYNAMIC_ICONV\n\t\"+iconv/dyn\",\n# else\n\t\"+iconv\",\n# endif\n#else\n\t\"-iconv\",\n#endif\n\t\"+insert_expand\",\n#ifdef FEAT_IPV6\n\t\"+ipv6\",\n#else\n\t\"-ipv6\",\n#endif\n#ifdef FEAT_JOB_CHANNEL\n\t\"+job\",\n#else\n\t\"-job\",\n#endif\n\t\"+jumplist\",\n#ifdef FEAT_KEYMAP\n\t\"+keymap\",\n#else\n\t\"-keymap\",\n#endif\n#ifdef FEAT_EVAL\n\t\"+lambda\",\n#else\n\t\"-lambda\",\n#endif\n#ifdef FEAT_LANGMAP\n\t\"+langmap\",\n#else\n\t\"-langmap\",\n#endif\n#ifdef FEAT_LIBCALL\n\t\"+libcall\",\n#else\n\t\"-libcall\",\n#endif\n#ifdef FEAT_LINEBREAK\n\t\"+linebreak\",\n#else\n\t\"-linebreak\",\n#endif\n\t\"+lispindent\",\n\t\"+listcmds\",\n\t\"+localmap\",\n#ifdef FEAT_LUA\n# ifdef DYNAMIC_LUA\n\t\"+lua/dyn\",\n# else\n\t\"+lua\",\n# endif\n#else\n\t\"-lua\",\n#endif\n#ifdef FEAT_MENU\n\t\"+menu\",\n#else\n\t\"-menu\",\n#endif\n#ifdef FEAT_SESSION\n\t\"+mksession\",\n#else\n\t\"-mksession\",\n#endif\n\t\"+modify_fname\",\n\t\"+mouse\",\n#ifdef FEAT_MOUSESHAPE\n\t\"+mouseshape\",\n#else\n\t\"-mouseshape\",\n#endif", "#if defined(UNIX) || defined(VMS)\n# ifdef FEAT_MOUSE_DEC\n\t\"+mouse_dec\",\n# else\n\t\"-mouse_dec\",\n# endif\n# ifdef FEAT_MOUSE_GPM\n# ifdef DYNAMIC_GPM\n\t\"+mouse_gpm/dyn\",\n# else\n\t\"+mouse_gpm\",\n# endif\n# else\n\t\"-mouse_gpm\",\n# endif\n# ifdef FEAT_MOUSE_JSB\n\t\"+mouse_jsbterm\",\n# else\n\t\"-mouse_jsbterm\",\n# endif\n# ifdef FEAT_MOUSE_NET\n\t\"+mouse_netterm\",\n# else\n\t\"-mouse_netterm\",\n# endif\n#endif", "#ifdef __QNX__\n# ifdef FEAT_MOUSE_PTERM\n\t\"+mouse_pterm\",\n# else\n\t\"-mouse_pterm\",\n# endif\n#endif", "#if defined(UNIX) || defined(VMS)\n\t\"+mouse_sgr\",\n# ifdef FEAT_SYSMOUSE\n\t\"+mouse_sysmouse\",\n# else\n\t\"-mouse_sysmouse\",\n# endif\n# ifdef FEAT_MOUSE_URXVT\n\t\"+mouse_urxvt\",\n# else\n\t\"-mouse_urxvt\",\n# endif\n\t\"+mouse_xterm\",\n#endif", "#ifdef FEAT_MBYTE_IME\n# ifdef DYNAMIC_IME\n\t\"+multi_byte_ime/dyn\",\n# else\n\t\"+multi_byte_ime\",\n# endif\n#else\n\t\"+multi_byte\",\n#endif\n#ifdef FEAT_MULTI_LANG\n\t\"+multi_lang\",\n#else\n\t\"-multi_lang\",\n#endif\n#ifdef FEAT_MZSCHEME\n# ifdef DYNAMIC_MZSCHEME\n\t\"+mzscheme/dyn\",\n# else\n\t\"+mzscheme\",\n# endif\n#else\n\t\"-mzscheme\",\n#endif\n#ifdef FEAT_NETBEANS_INTG\n\t\"+netbeans_intg\",\n#else\n\t\"-netbeans_intg\",\n#endif\n\t\"+num64\",\n#ifdef FEAT_GUI_MSWIN\n# ifdef FEAT_OLE\n\t\"+ole\",\n# else\n\t\"-ole\",\n# endif\n#endif\n#ifdef FEAT_EVAL\n\t\"+packages\",\n#else\n\t\"-packages\",\n#endif\n\t\"+path_extra\",\n#ifdef FEAT_PERL\n# ifdef DYNAMIC_PERL\n\t\"+perl/dyn\",\n# else\n\t\"+perl\",\n# endif\n#else\n\t\"-perl\",\n#endif\n#ifdef FEAT_PERSISTENT_UNDO\n\t\"+persistent_undo\",\n#else\n\t\"-persistent_undo\",\n#endif\n#ifdef FEAT_PROP_POPUP\n\t\"+popupwin\",\n#else\n\t\"-popupwin\",\n#endif\n#ifdef FEAT_PRINTER\n# ifdef FEAT_POSTSCRIPT\n\t\"+postscript\",\n# else\n\t\"-postscript\",\n# endif\n\t\"+printer\",\n#else\n\t\"-printer\",\n#endif\n#ifdef FEAT_PROFILE\n\t\"+profile\",\n#else\n\t\"-profile\",\n#endif\n#ifdef FEAT_PYTHON\n# ifdef DYNAMIC_PYTHON\n\t\"+python/dyn\",\n# else\n\t\"+python\",\n# endif\n#else\n\t\"-python\",\n#endif\n#ifdef FEAT_PYTHON3\n# ifdef DYNAMIC_PYTHON3\n\t\"+python3/dyn\",\n# else\n\t\"+python3\",\n# endif\n#else\n\t\"-python3\",\n#endif\n#ifdef FEAT_QUICKFIX\n\t\"+quickfix\",\n#else\n\t\"-quickfix\",\n#endif\n#ifdef FEAT_RELTIME\n\t\"+reltime\",\n#else\n\t\"-reltime\",\n#endif\n#ifdef FEAT_RIGHTLEFT\n\t\"+rightleft\",\n#else\n\t\"-rightleft\",\n#endif\n#ifdef FEAT_RUBY\n# ifdef DYNAMIC_RUBY\n\t\"+ruby/dyn\",\n# else\n\t\"+ruby\",\n# endif\n#else\n\t\"-ruby\",\n#endif\n\t\"+scrollbind\",\n#ifdef FEAT_SIGNS\n\t\"+signs\",\n#else\n\t\"-signs\",\n#endif\n\t\"+smartindent\",\n#ifdef FEAT_SODIUM\n# ifdef DYNAMIC_SODIUM\n\t\"+sodium/dyn\",\n# else\n\t\"+sodium\",\n# endif\n#else\n\t\"-sodium\",\n#endif\n#ifdef FEAT_SOUND\n\t\"+sound\",\n#else\n\t\"-sound\",\n#endif\n#ifdef FEAT_SPELL\n\t\"+spell\",\n#else\n\t\"-spell\",\n#endif\n#ifdef STARTUPTIME\n\t\"+startuptime\",\n#else\n\t\"-startuptime\",\n#endif\n#ifdef FEAT_STL_OPT\n\t\"+statusline\",\n#else\n\t\"-statusline\",\n#endif\n\t\"-sun_workshop\",\n#ifdef FEAT_SYN_HL\n\t\"+syntax\",\n#else\n\t\"-syntax\",\n#endif\n\t // only interesting on Unix systems\n#if defined(USE_SYSTEM) && defined(UNIX)\n\t\"+system()\",\n#endif\n\t\"+tag_binary\",\n\t\"-tag_old_static\",\n\t\"-tag_any_white\",\n#ifdef FEAT_TCL\n# ifdef DYNAMIC_TCL\n\t\"+tcl/dyn\",\n# else\n\t\"+tcl\",\n# endif\n#else\n\t\"-tcl\",\n#endif\n#ifdef FEAT_TERMGUICOLORS\n\t\"+termguicolors\",\n#else\n\t\"-termguicolors\",\n#endif\n#ifdef FEAT_TERMINAL\n\t\"+terminal\",\n#else\n\t\"-terminal\",\n#endif\n#if defined(UNIX)\n// only Unix can have terminfo instead of termcap\n# ifdef TERMINFO\n\t\"+terminfo\",\n# else\n\t\"-terminfo\",\n# endif\n#endif\n#ifdef FEAT_TERMRESPONSE\n\t\"+termresponse\",\n#else\n\t\"-termresponse\",\n#endif\n\t\"+textobjects\",\n#ifdef FEAT_PROP_POPUP\n\t\"+textprop\",\n#else\n\t\"-textprop\",\n#endif\n#if !defined(UNIX)\n// unix always includes termcap support\n# ifdef HAVE_TGETENT\n\t\"+tgetent\",\n# else\n\t\"-tgetent\",\n# endif\n#endif\n#ifdef FEAT_TIMERS\n\t\"+timers\",\n#else\n\t\"-timers\",\n#endif\n\t\"+title\",\n#ifdef FEAT_TOOLBAR\n\t\"+toolbar\",\n#else\n\t\"-toolbar\",\n#endif\n\t\"+user_commands\",\n#ifdef FEAT_VARTABS\n\t\"+vartabs\",\n#else\n\t\"-vartabs\",\n#endif\n\t\"+vertsplit\",\n\t\"+vim9script\",\n#ifdef FEAT_VIMINFO\n\t\"+viminfo\",\n#else\n\t\"-viminfo\",\n#endif\n\t\"+virtualedit\",\n\t\"+visual\",\n\t\"+visualextra\",\n\t\"+vreplace\",\n#ifdef MSWIN\n# ifdef FEAT_VTP\n\t\"+vtp\",\n# else\n\t\"-vtp\",\n# endif\n#endif\n\t\"+wildignore\",\n\t\"+wildmenu\",\n\t\"+windows\",\n#ifdef FEAT_WRITEBACKUP\n\t\"+writebackup\",\n#else\n\t\"-writebackup\",\n#endif\n#if defined(UNIX) || defined(VMS)\n# ifdef FEAT_X11\n\t\"+X11\",\n# else\n\t\"-X11\",\n# endif\n#endif\n#ifdef FEAT_XFONTSET\n\t\"+xfontset\",\n#else\n\t\"-xfontset\",\n#endif\n#ifdef FEAT_XIM\n\t\"+xim\",\n#else\n\t\"-xim\",\n#endif\n#if defined(MSWIN)\n# ifdef FEAT_XPM_W32\n\t\"+xpm_w32\",\n# else\n\t\"-xpm_w32\",\n# endif\n#elif defined(HAVE_XPM)\n\t\"+xpm\",\n#else\n\t\"-xpm\",\n#endif\n#if defined(UNIX) || defined(VMS)\n# if defined(USE_XSMP_INTERACT)\n\t\"+xsmp_interact\",\n# elif defined(USE_XSMP)\n\t\"+xsmp\",\n# else\n\t\"-xsmp\",\n# endif\n# ifdef FEAT_XCLIPBOARD\n\t\"+xterm_clipboard\",\n# else\n\t\"-xterm_clipboard\",\n# endif\n#endif\n#ifdef FEAT_XTERM_SAVE\n\t\"+xterm_save\",\n#else\n\t\"-xterm_save\",\n#endif\n\tNULL\n};", "static int included_patches[] =\n{ /* Add new patch number below this line */", "", "/**/\n 1144,\n/**/\n 1143,\n/**/\n 1142,\n/**/\n 1141,\n/**/\n 1140,\n/**/\n 1139,\n/**/\n 1138,\n/**/\n 1137,\n/**/\n 1136,\n/**/\n 1135,\n/**/\n 1134,\n/**/\n 1133,\n/**/\n 1132,\n/**/\n 1131,\n/**/\n 1130,\n/**/\n 1129,\n/**/\n 1128,\n/**/\n 1127,\n/**/\n 1126,\n/**/\n 1125,\n/**/\n 1124,\n/**/\n 1123,\n/**/\n 1122,\n/**/\n 1121,\n/**/\n 1120,\n/**/\n 1119,\n/**/\n 1118,\n/**/\n 1117,\n/**/\n 1116,\n/**/\n 1115,\n/**/\n 1114,\n/**/\n 1113,\n/**/\n 1112,\n/**/\n 1111,\n/**/\n 1110,\n/**/\n 1109,\n/**/\n 1108,\n/**/\n 1107,\n/**/\n 1106,\n/**/\n 1105,\n/**/\n 1104,\n/**/\n 1103,\n/**/\n 1102,\n/**/\n 1101,\n/**/\n 1100,\n/**/\n 1099,\n/**/\n 1098,\n/**/\n 1097,\n/**/\n 1096,\n/**/\n 1095,\n/**/\n 1094,\n/**/\n 1093,\n/**/\n 1092,\n/**/\n 1091,\n/**/\n 1090,\n/**/\n 1089,\n/**/\n 1088,\n/**/\n 1087,\n/**/\n 1086,\n/**/\n 1085,\n/**/\n 1084,\n/**/\n 1083,\n/**/\n 1082,\n/**/\n 1081,\n/**/\n 1080,\n/**/\n 1079,\n/**/\n 1078,\n/**/\n 1077,\n/**/\n 1076,\n/**/\n 1075,\n/**/\n 1074,\n/**/\n 1073,\n/**/\n 1072,\n/**/\n 1071,\n/**/\n 1070,\n/**/\n 1069,\n/**/\n 1068,\n/**/\n 1067,\n/**/\n 1066,\n/**/\n 1065,\n/**/\n 1064,\n/**/\n 1063,\n/**/\n 1062,\n/**/\n 1061,\n/**/\n 1060,\n/**/\n 1059,\n/**/\n 1058,\n/**/\n 1057,\n/**/\n 1056,\n/**/\n 1055,\n/**/\n 1054,\n/**/\n 1053,\n/**/\n 1052,\n/**/\n 1051,\n/**/\n 1050,\n/**/\n 1049,\n/**/\n 1048,\n/**/\n 1047,\n/**/\n 1046,\n/**/\n 1045,\n/**/\n 1044,\n/**/\n 1043,\n/**/\n 1042,\n/**/\n 1041,\n/**/\n 1040,\n/**/\n 1039,\n/**/\n 1038,\n/**/\n 1037,\n/**/\n 1036,\n/**/\n 1035,\n/**/\n 1034,\n/**/\n 1033,\n/**/\n 1032,\n/**/\n 1031,\n/**/\n 1030,\n/**/\n 1029,\n/**/\n 1028,\n/**/\n 1027,\n/**/\n 1026,\n/**/\n 1025,\n/**/\n 1024,\n/**/\n 1023,\n/**/\n 1022,\n/**/\n 1021,\n/**/\n 1020,\n/**/\n 1019,\n/**/\n 1018,\n/**/\n 1017,\n/**/\n 1016,\n/**/\n 1015,\n/**/\n 1014,\n/**/\n 1013,\n/**/\n 1012,\n/**/\n 1011,\n/**/\n 1010,\n/**/\n 1009,\n/**/\n 1008,\n/**/\n 1007,\n/**/\n 1006,\n/**/\n 1005,\n/**/\n 1004,\n/**/\n 1003,\n/**/\n 1002,\n/**/\n 1001,\n/**/\n 1000,\n/**/\n 999,\n/**/\n 998,\n/**/\n 997,\n/**/\n 996,\n/**/\n 995,\n/**/\n 994,\n/**/\n 993,\n/**/\n 992,\n/**/\n 991,\n/**/\n 990,\n/**/\n 989,\n/**/\n 988,\n/**/\n 987,\n/**/\n 986,\n/**/\n 985,\n/**/\n 984,\n/**/\n 983,\n/**/\n 982,\n/**/\n 981,\n/**/\n 980,\n/**/\n 979,\n/**/\n 978,\n/**/\n 977,\n/**/\n 976,\n/**/\n 975,\n/**/\n 974,\n/**/\n 973,\n/**/\n 972,\n/**/\n 971,\n/**/\n 970,\n/**/\n 969,\n/**/\n 968,\n/**/\n 967,\n/**/\n 966,\n/**/\n 965,\n/**/\n 964,\n/**/\n 963,\n/**/\n 962,\n/**/\n 961,\n/**/\n 960,\n/**/\n 959,\n/**/\n 958,\n/**/\n 957,\n/**/\n 956,\n/**/\n 955,\n/**/\n 954,\n/**/\n 953,\n/**/\n 952,\n/**/\n 951,\n/**/\n 950,\n/**/\n 949,\n/**/\n 948,\n/**/\n 947,\n/**/\n 946,\n/**/\n 945,\n/**/\n 944,\n/**/\n 943,\n/**/\n 942,\n/**/\n 941,\n/**/\n 940,\n/**/\n 939,\n/**/\n 938,\n/**/\n 937,\n/**/\n 936,\n/**/\n 935,\n/**/\n 934,\n/**/\n 933,\n/**/\n 932,\n/**/\n 931,\n/**/\n 930,\n/**/\n 929,\n/**/\n 928,\n/**/\n 927,\n/**/\n 926,\n/**/\n 925,\n/**/\n 924,\n/**/\n 923,\n/**/\n 922,\n/**/\n 921,\n/**/\n 920,\n/**/\n 919,\n/**/\n 918,\n/**/\n 917,\n/**/\n 916,\n/**/\n 915,\n/**/\n 914,\n/**/\n 913,\n/**/\n 912,\n/**/\n 911,\n/**/\n 910,\n/**/\n 909,\n/**/\n 908,\n/**/\n 907,\n/**/\n 906,\n/**/\n 905,\n/**/\n 904,\n/**/\n 903,\n/**/\n 902,\n/**/\n 901,\n/**/\n 900,\n/**/\n 899,\n/**/\n 898,\n/**/\n 897,\n/**/\n 896,\n/**/\n 895,\n/**/\n 894,\n/**/\n 893,\n/**/\n 892,\n/**/\n 891,\n/**/\n 890,\n/**/\n 889,\n/**/\n 888,\n/**/\n 887,\n/**/\n 886,\n/**/\n 885,\n/**/\n 884,\n/**/\n 883,\n/**/\n 882,\n/**/\n 881,\n/**/\n 880,\n/**/\n 879,\n/**/\n 878,\n/**/\n 877,\n/**/\n 876,\n/**/\n 875,\n/**/\n 874,\n/**/\n 873,\n/**/\n 872,\n/**/\n 871,\n/**/\n 870,\n/**/\n 869,\n/**/\n 868,\n/**/\n 867,\n/**/\n 866,\n/**/\n 865,\n/**/\n 864,\n/**/\n 863,\n/**/\n 862,\n/**/\n 861,\n/**/\n 860,\n/**/\n 859,\n/**/\n 858,\n/**/\n 857,\n/**/\n 856,\n/**/\n 855,\n/**/\n 854,\n/**/\n 853,\n/**/\n 852,\n/**/\n 851,\n/**/\n 850,\n/**/\n 849,\n/**/\n 848,\n/**/\n 847,\n/**/\n 846,\n/**/\n 845,\n/**/\n 844,\n/**/\n 843,\n/**/\n 842,\n/**/\n 841,\n/**/\n 840,\n/**/\n 839,\n/**/\n 838,\n/**/\n 837,\n/**/\n 836,\n/**/\n 835,\n/**/\n 834,\n/**/\n 833,\n/**/\n 832,\n/**/\n 831,\n/**/\n 830,\n/**/\n 829,\n/**/\n 828,\n/**/\n 827,\n/**/\n 826,\n/**/\n 825,\n/**/\n 824,\n/**/\n 823,\n/**/\n 822,\n/**/\n 821,\n/**/\n 820,\n/**/\n 819,\n/**/\n 818,\n/**/\n 817,\n/**/\n 816,\n/**/\n 815,\n/**/\n 814,\n/**/\n 813,\n/**/\n 812,\n/**/\n 811,\n/**/\n 810,\n/**/\n 809,\n/**/\n 808,\n/**/\n 807,\n/**/\n 806,\n/**/\n 805,\n/**/\n 804,\n/**/\n 803,\n/**/\n 802,\n/**/\n 801,\n/**/\n 800,\n/**/\n 799,\n/**/\n 798,\n/**/\n 797,\n/**/\n 796,\n/**/\n 795,\n/**/\n 794,\n/**/\n 793,\n/**/\n 792,\n/**/\n 791,\n/**/\n 790,\n/**/\n 789,\n/**/\n 788,\n/**/\n 787,\n/**/\n 786,\n/**/\n 785,\n/**/\n 784,\n/**/\n 783,\n/**/\n 782,\n/**/\n 781,\n/**/\n 780,\n/**/\n 779,\n/**/\n 778,\n/**/\n 777,\n/**/\n 776,\n/**/\n 775,\n/**/\n 774,\n/**/\n 773,\n/**/\n 772,\n/**/\n 771,\n/**/\n 770,\n/**/\n 769,\n/**/\n 768,\n/**/\n 767,\n/**/\n 766,\n/**/\n 765,\n/**/\n 764,\n/**/\n 763,\n/**/\n 762,\n/**/\n 761,\n/**/\n 760,\n/**/\n 759,\n/**/\n 758,\n/**/\n 757,\n/**/\n 756,\n/**/\n 755,\n/**/\n 754,\n/**/\n 753,\n/**/\n 752,\n/**/\n 751,\n/**/\n 750,\n/**/\n 749,\n/**/\n 748,\n/**/\n 747,\n/**/\n 746,\n/**/\n 745,\n/**/\n 744,\n/**/\n 743,\n/**/\n 742,\n/**/\n 741,\n/**/\n 740,\n/**/\n 739,\n/**/\n 738,\n/**/\n 737,\n/**/\n 736,\n/**/\n 735,\n/**/\n 734,\n/**/\n 733,\n/**/\n 732,\n/**/\n 731,\n/**/\n 730,\n/**/\n 729,\n/**/\n 728,\n/**/\n 727,\n/**/\n 726,\n/**/\n 725,\n/**/\n 724,\n/**/\n 723,\n/**/\n 722,\n/**/\n 721,\n/**/\n 720,\n/**/\n 719,\n/**/\n 718,\n/**/\n 717,\n/**/\n 716,\n/**/\n 715,\n/**/\n 714,\n/**/\n 713,\n/**/\n 712,\n/**/\n 711,\n/**/\n 710,\n/**/\n 709,\n/**/\n 708,\n/**/\n 707,\n/**/\n 706,\n/**/\n 705,\n/**/\n 704,\n/**/\n 703,\n/**/\n 702,\n/**/\n 701,\n/**/\n 700,\n/**/\n 699,\n/**/\n 698,\n/**/\n 697,\n/**/\n 696,\n/**/\n 695,\n/**/\n 694,\n/**/\n 693,\n/**/\n 692,\n/**/\n 691,\n/**/\n 690,\n/**/\n 689,\n/**/\n 688,\n/**/\n 687,\n/**/\n 686,\n/**/\n 685,\n/**/\n 684,\n/**/\n 683,\n/**/\n 682,\n/**/\n 681,\n/**/\n 680,\n/**/\n 679,\n/**/\n 678,\n/**/\n 677,\n/**/\n 676,\n/**/\n 675,\n/**/\n 674,\n/**/\n 673,\n/**/\n 672,\n/**/\n 671,\n/**/\n 670,\n/**/\n 669,\n/**/\n 668,\n/**/\n 667,\n/**/\n 666,\n/**/\n 665,\n/**/\n 664,\n/**/\n 663,\n/**/\n 662,\n/**/\n 661,\n/**/\n 660,\n/**/\n 659,\n/**/\n 658,\n/**/\n 657,\n/**/\n 656,\n/**/\n 655,\n/**/\n 654,\n/**/\n 653,\n/**/\n 652,\n/**/\n 651,\n/**/\n 650,\n/**/\n 649,\n/**/\n 648,\n/**/\n 647,\n/**/\n 646,\n/**/\n 645,\n/**/\n 644,\n/**/\n 643,\n/**/\n 642,\n/**/\n 641,\n/**/\n 640,\n/**/\n 639,\n/**/\n 638,\n/**/\n 637,\n/**/\n 636,\n/**/\n 635,\n/**/\n 634,\n/**/\n 633,\n/**/\n 632,\n/**/\n 631,\n/**/\n 630,\n/**/\n 629,\n/**/\n 628,\n/**/\n 627,\n/**/\n 626,\n/**/\n 625,\n/**/\n 624,\n/**/\n 623,\n/**/\n 622,\n/**/\n 621,\n/**/\n 620,\n/**/\n 619,\n/**/\n 618,\n/**/\n 617,\n/**/\n 616,\n/**/\n 615,\n/**/\n 614,\n/**/\n 613,\n/**/\n 612,\n/**/\n 611,\n/**/\n 610,\n/**/\n 609,\n/**/\n 608,\n/**/\n 607,\n/**/\n 606,\n/**/\n 605,\n/**/\n 604,\n/**/\n 603,\n/**/\n 602,\n/**/\n 601,\n/**/\n 600,\n/**/\n 599,\n/**/\n 598,\n/**/\n 597,\n/**/\n 596,\n/**/\n 595,\n/**/\n 594,\n/**/\n 593,\n/**/\n 592,\n/**/\n 591,\n/**/\n 590,\n/**/\n 589,\n/**/\n 588,\n/**/\n 587,\n/**/\n 586,\n/**/\n 585,\n/**/\n 584,\n/**/\n 583,\n/**/\n 582,\n/**/\n 581,\n/**/\n 580,\n/**/\n 579,\n/**/\n 578,\n/**/\n 577,\n/**/\n 576,\n/**/\n 575,\n/**/\n 574,\n/**/\n 573,\n/**/\n 572,\n/**/\n 571,\n/**/\n 570,\n/**/\n 569,\n/**/\n 568,\n/**/\n 567,\n/**/\n 566,\n/**/\n 565,\n/**/\n 564,\n/**/\n 563,\n/**/\n 562,\n/**/\n 561,\n/**/\n 560,\n/**/\n 559,\n/**/\n 558,\n/**/\n 557,\n/**/\n 556,\n/**/\n 555,\n/**/\n 554,\n/**/\n 553,\n/**/\n 552,\n/**/\n 551,\n/**/\n 550,\n/**/\n 549,\n/**/\n 548,\n/**/\n 547,\n/**/\n 546,\n/**/\n 545,\n/**/\n 544,\n/**/\n 543,\n/**/\n 542,\n/**/\n 541,\n/**/\n 540,\n/**/\n 539,\n/**/\n 538,\n/**/\n 537,\n/**/\n 536,\n/**/\n 535,\n/**/\n 534,\n/**/\n 533,\n/**/\n 532,\n/**/\n 531,\n/**/\n 530,\n/**/\n 529,\n/**/\n 528,\n/**/\n 527,\n/**/\n 526,\n/**/\n 525,\n/**/\n 524,\n/**/\n 523,\n/**/\n 522,\n/**/\n 521,\n/**/\n 520,\n/**/\n 519,\n/**/\n 518,\n/**/\n 517,\n/**/\n 516,\n/**/\n 515,\n/**/\n 514,\n/**/\n 513,\n/**/\n 512,\n/**/\n 511,\n/**/\n 510,\n/**/\n 509,\n/**/\n 508,\n/**/\n 507,\n/**/\n 506,\n/**/\n 505,\n/**/\n 504,\n/**/\n 503,\n/**/\n 502,\n/**/\n 501,\n/**/\n 500,\n/**/\n 499,\n/**/\n 498,\n/**/\n 497,\n/**/\n 496,\n/**/\n 495,\n/**/\n 494,\n/**/\n 493,\n/**/\n 492,\n/**/\n 491,\n/**/\n 490,\n/**/\n 489,\n/**/\n 488,\n/**/\n 487,\n/**/\n 486,\n/**/\n 485,\n/**/\n 484,\n/**/\n 483,\n/**/\n 482,\n/**/\n 481,\n/**/\n 480,\n/**/\n 479,\n/**/\n 478,\n/**/\n 477,\n/**/\n 476,\n/**/\n 475,\n/**/\n 474,\n/**/\n 473,\n/**/\n 472,\n/**/\n 471,\n/**/\n 470,\n/**/\n 469,\n/**/\n 468,\n/**/\n 467,\n/**/\n 466,\n/**/\n 465,\n/**/\n 464,\n/**/\n 463,\n/**/\n 462,\n/**/\n 461,\n/**/\n 460,\n/**/\n 459,\n/**/\n 458,\n/**/\n 457,\n/**/\n 456,\n/**/\n 455,\n/**/\n 454,\n/**/\n 453,\n/**/\n 452,\n/**/\n 451,\n/**/\n 450,\n/**/\n 449,\n/**/\n 448,\n/**/\n 447,\n/**/\n 446,\n/**/\n 445,\n/**/\n 444,\n/**/\n 443,\n/**/\n 442,\n/**/\n 441,\n/**/\n 440,\n/**/\n 439,\n/**/\n 438,\n/**/\n 437,\n/**/\n 436,\n/**/\n 435,\n/**/\n 434,\n/**/\n 433,\n/**/\n 432,\n/**/\n 431,\n/**/\n 430,\n/**/\n 429,\n/**/\n 428,\n/**/\n 427,\n/**/\n 426,\n/**/\n 425,\n/**/\n 424,\n/**/\n 423,\n/**/\n 422,\n/**/\n 421,\n/**/\n 420,\n/**/\n 419,\n/**/\n 418,\n/**/\n 417,\n/**/\n 416,\n/**/\n 415,\n/**/\n 414,\n/**/\n 413,\n/**/\n 412,\n/**/\n 411,\n/**/\n 410,\n/**/\n 409,\n/**/\n 408,\n/**/\n 407,\n/**/\n 406,\n/**/\n 405,\n/**/\n 404,\n/**/\n 403,\n/**/\n 402,\n/**/\n 401,\n/**/\n 400,\n/**/\n 399,\n/**/\n 398,\n/**/\n 397,\n/**/\n 396,\n/**/\n 395,\n/**/\n 394,\n/**/\n 393,\n/**/\n 392,\n/**/\n 391,\n/**/\n 390,\n/**/\n 389,\n/**/\n 388,\n/**/\n 387,\n/**/\n 386,\n/**/\n 385,\n/**/\n 384,\n/**/\n 383,\n/**/\n 382,\n/**/\n 381,\n/**/\n 380,\n/**/\n 379,\n/**/\n 378,\n/**/\n 377,\n/**/\n 376,\n/**/\n 375,\n/**/\n 374,\n/**/\n 373,\n/**/\n 372,\n/**/\n 371,\n/**/\n 370,\n/**/\n 369,\n/**/\n 368,\n/**/\n 367,\n/**/\n 366,\n/**/\n 365,\n/**/\n 364,\n/**/\n 363,\n/**/\n 362,\n/**/\n 361,\n/**/\n 360,\n/**/\n 359,\n/**/\n 358,\n/**/\n 357,\n/**/\n 356,\n/**/\n 355,\n/**/\n 354,\n/**/\n 353,\n/**/\n 352,\n/**/\n 351,\n/**/\n 350,\n/**/\n 349,\n/**/\n 348,\n/**/\n 347,\n/**/\n 346,\n/**/\n 345,\n/**/\n 344,\n/**/\n 343,\n/**/\n 342,\n/**/\n 341,\n/**/\n 340,\n/**/\n 339,\n/**/\n 338,\n/**/\n 337,\n/**/\n 336,\n/**/\n 335,\n/**/\n 334,\n/**/\n 333,\n/**/\n 332,\n/**/\n 331,\n/**/\n 330,\n/**/\n 329,\n/**/\n 328,\n/**/\n 327,\n/**/\n 326,\n/**/\n 325,\n/**/\n 324,\n/**/\n 323,\n/**/\n 322,\n/**/\n 321,\n/**/\n 320,\n/**/\n 319,\n/**/\n 318,\n/**/\n 317,\n/**/\n 316,\n/**/\n 315,\n/**/\n 314,\n/**/\n 313,\n/**/\n 312,\n/**/\n 311,\n/**/\n 310,\n/**/\n 309,\n/**/\n 308,\n/**/\n 307,\n/**/\n 306,\n/**/\n 305,\n/**/\n 304,\n/**/\n 303,\n/**/\n 302,\n/**/\n 301,\n/**/\n 300,\n/**/\n 299,\n/**/\n 298,\n/**/\n 297,\n/**/\n 296,\n/**/\n 295,\n/**/\n 294,\n/**/\n 293,\n/**/\n 292,\n/**/\n 291,\n/**/\n 290,\n/**/\n 289,\n/**/\n 288,\n/**/\n 287,\n/**/\n 286,\n/**/\n 285,\n/**/\n 284,\n/**/\n 283,\n/**/\n 282,\n/**/\n 281,\n/**/\n 280,\n/**/\n 279,\n/**/\n 278,\n/**/\n 277,\n/**/\n 276,\n/**/\n 275,\n/**/\n 274,\n/**/\n 273,\n/**/\n 272,\n/**/\n 271,\n/**/\n 270,\n/**/\n 269,\n/**/\n 268,\n/**/\n 267,\n/**/\n 266,\n/**/\n 265,\n/**/\n 264,\n/**/\n 263,\n/**/\n 262,\n/**/\n 261,\n/**/\n 260,\n/**/\n 259,\n/**/\n 258,\n/**/\n 257,\n/**/\n 256,\n/**/\n 255,\n/**/\n 254,\n/**/\n 253,\n/**/\n 252,\n/**/\n 251,\n/**/\n 250,\n/**/\n 249,\n/**/\n 248,\n/**/\n 247,\n/**/\n 246,\n/**/\n 245,\n/**/\n 244,\n/**/\n 243,\n/**/\n 242,\n/**/\n 241,\n/**/\n 240,\n/**/\n 239,\n/**/\n 238,\n/**/\n 237,\n/**/\n 236,\n/**/\n 235,\n/**/\n 234,\n/**/\n 233,\n/**/\n 232,\n/**/\n 231,\n/**/\n 230,\n/**/\n 229,\n/**/\n 228,\n/**/\n 227,\n/**/\n 226,\n/**/\n 225,\n/**/\n 224,\n/**/\n 223,\n/**/\n 222,\n/**/\n 221,\n/**/\n 220,\n/**/\n 219,\n/**/\n 218,\n/**/\n 217,\n/**/\n 216,\n/**/\n 215,\n/**/\n 214,\n/**/\n 213,\n/**/\n 212,\n/**/\n 211,\n/**/\n 210,\n/**/\n 209,\n/**/\n 208,\n/**/\n 207,\n/**/\n 206,\n/**/\n 205,\n/**/\n 204,\n/**/\n 203,\n/**/\n 202,\n/**/\n 201,\n/**/\n 200,\n/**/\n 199,\n/**/\n 198,\n/**/\n 197,\n/**/\n 196,\n/**/\n 195,\n/**/\n 194,\n/**/\n 193,\n/**/\n 192,\n/**/\n 191,\n/**/\n 190,\n/**/\n 189,\n/**/\n 188,\n/**/\n 187,\n/**/\n 186,\n/**/\n 185,\n/**/\n 184,\n/**/\n 183,\n/**/\n 182,\n/**/\n 181,\n/**/\n 180,\n/**/\n 179,\n/**/\n 178,\n/**/\n 177,\n/**/\n 176,\n/**/\n 175,\n/**/\n 174,\n/**/\n 173,\n/**/\n 172,\n/**/\n 171,\n/**/\n 170,\n/**/\n 169,\n/**/\n 168,\n/**/\n 167,\n/**/\n 166,\n/**/\n 165,\n/**/\n 164,\n/**/\n 163,\n/**/\n 162,\n/**/\n 161,\n/**/\n 160,\n/**/\n 159,\n/**/\n 158,\n/**/\n 157,\n/**/\n 156,\n/**/\n 155,\n/**/\n 154,\n/**/\n 153,\n/**/\n 152,\n/**/\n 151,\n/**/\n 150,\n/**/\n 149,\n/**/\n 148,\n/**/\n 147,\n/**/\n 146,\n/**/\n 145,\n/**/\n 144,\n/**/\n 143,\n/**/\n 142,\n/**/\n 141,\n/**/\n 140,\n/**/\n 139,\n/**/\n 138,\n/**/\n 137,\n/**/\n 136,\n/**/\n 135,\n/**/\n 134,\n/**/\n 133,\n/**/\n 132,\n/**/\n 131,\n/**/\n 130,\n/**/\n 129,\n/**/\n 128,\n/**/\n 127,\n/**/\n 126,\n/**/\n 125,\n/**/\n 124,\n/**/\n 123,\n/**/\n 122,\n/**/\n 121,\n/**/\n 120,\n/**/\n 119,\n/**/\n 118,\n/**/\n 117,\n/**/\n 116,\n/**/\n 115,\n/**/\n 114,\n/**/\n 113,\n/**/\n 112,\n/**/\n 111,\n/**/\n 110,\n/**/\n 109,\n/**/\n 108,\n/**/\n 107,\n/**/\n 106,\n/**/\n 105,\n/**/\n 104,\n/**/\n 103,\n/**/\n 102,\n/**/\n 101,\n/**/\n 100,\n/**/\n 99,\n/**/\n 98,\n/**/\n 97,\n/**/\n 96,\n/**/\n 95,\n/**/\n 94,\n/**/\n 93,\n/**/\n 92,\n/**/\n 91,\n/**/\n 90,\n/**/\n 89,\n/**/\n 88,\n/**/\n 87,\n/**/\n 86,\n/**/\n 85,\n/**/\n 84,\n/**/\n 83,\n/**/\n 82,\n/**/\n 81,\n/**/\n 80,\n/**/\n 79,\n/**/\n 78,\n/**/\n 77,\n/**/\n 76,\n/**/\n 75,\n/**/\n 74,\n/**/\n 73,\n/**/\n 72,\n/**/\n 71,\n/**/\n 70,\n/**/\n 69,\n/**/\n 68,\n/**/\n 67,\n/**/\n 66,\n/**/\n 65,\n/**/\n 64,\n/**/\n 63,\n/**/\n 62,\n/**/\n 61,\n/**/\n 60,\n/**/\n 59,\n/**/\n 58,\n/**/\n 57,\n/**/\n 56,\n/**/\n 55,\n/**/\n 54,\n/**/\n 53,\n/**/\n 52,\n/**/\n 51,\n/**/\n 50,\n/**/\n 49,\n/**/\n 48,\n/**/\n 47,\n/**/\n 46,\n/**/\n 45,\n/**/\n 44,\n/**/\n 43,\n/**/\n 42,\n/**/\n 41,\n/**/\n 40,\n/**/\n 39,\n/**/\n 38,\n/**/\n 37,\n/**/\n 36,\n/**/\n 35,\n/**/\n 34,\n/**/\n 33,\n/**/\n 32,\n/**/\n 31,\n/**/\n 30,\n/**/\n 29,\n/**/\n 28,\n/**/\n 27,\n/**/\n 26,\n/**/\n 25,\n/**/\n 24,\n/**/\n 23,\n/**/\n 22,\n/**/\n 21,\n/**/\n 20,\n/**/\n 19,\n/**/\n 18,\n/**/\n 17,\n/**/\n 16,\n/**/\n 15,\n/**/\n 14,\n/**/\n 13,\n/**/\n 12,\n/**/\n 11,\n/**/\n 10,\n/**/\n 9,\n/**/\n 8,\n/**/\n 7,\n/**/\n 6,\n/**/\n 5,\n/**/\n 4,\n/**/\n 3,\n/**/\n 2,\n/**/\n 1,\n/**/\n 0\n};", "/*\n * Place to put a short description when adding a feature with a patch.\n * Keep it short, e.g.,: \"relative numbers\", \"persistent undo\".\n * Also add a comment marker to separate the lines.\n * See the official Vim patches for the diff format: It must use a context of\n * one line only. Create it by hand or use \"diff -C2\" and edit the patch.\n */\nstatic char *(extra_patches[]) =\n{ /* Add your patch description below this line */\n/**/\n NULL\n};", " int\nhighest_patch(void)\n{\n // this relies on the highest patch number to be the first entry\n return included_patches[0];\n}", "#if defined(FEAT_EVAL) || defined(PROTO)\n/*\n * Return TRUE if patch \"n\" has been included.\n */\n int\nhas_patch(int n)\n{\n int\t\th, m, l;", " // Perform a binary search.\n l = 0;\n h = (int)ARRAY_LENGTH(included_patches) - 1;\n for (;;)\n {\n\tm = (l + h) / 2;\n\tif (included_patches[m] == n)\n\t return TRUE;\n\tif (l == h)\n\t break;\n\tif (included_patches[m] < n)\n\t h = m;\n\telse\n\t l = m + 1;\n }\n return FALSE;\n}\n#endif", " void\nex_version(exarg_T *eap)\n{\n /*\n * Ignore a \":version 9.99\" command.\n */\n if (*eap->arg == NUL)\n {\n\tmsg_putchar('\\n');\n\tlist_version();\n }\n}", "/*\n * Output a string for the version message. If it's going to wrap, output a\n * newline, unless the message is too long to fit on the screen anyway.\n * When \"wrap\" is TRUE wrap the string in [].\n */\n static void\nversion_msg_wrap(char_u *s, int wrap)\n{\n int\t\tlen = vim_strsize(s) + (wrap ? 2 : 0);", " if (!got_int && len < (int)Columns && msg_col + len >= (int)Columns\n\t\t\t\t\t\t\t\t&& *s != '\\n')\n\tmsg_putchar('\\n');\n if (!got_int)\n {\n\tif (wrap)\n\t msg_puts(\"[\");\n\tmsg_puts((char *)s);\n\tif (wrap)\n\t msg_puts(\"]\");\n }\n}", " static void\nversion_msg(char *s)\n{\n version_msg_wrap((char_u *)s, FALSE);\n}", "/*\n * List all features aligned in columns, dictionary style.\n */\n static void\nlist_features(void)\n{\n list_in_columns((char_u **)features, -1, -1);\n}", "/*\n * List string items nicely aligned in columns.\n * When \"size\" is < 0 then the last entry is marked with NULL.\n * The entry with index \"current\" is inclosed in [].\n */\n void\nlist_in_columns(char_u **items, int size, int current)\n{\n int\t\ti;\n int\t\tncol;\n int\t\tnrow;\n int\t\tcur_row = 1;\n int\t\titem_count = 0;\n int\t\twidth = 0;\n#ifdef FEAT_SYN_HL\n int\t\tuse_highlight = (items == (char_u **)features);\n#endif", " // Find the length of the longest item, use that + 1 as the column\n // width.\n for (i = 0; size < 0 ? items[i] != NULL : i < size; ++i)\n {\n\tint l = vim_strsize(items[i]) + (i == current ? 2 : 0);", "\tif (l > width)\n\t width = l;\n\t++item_count;\n }\n width += 1;", " if (Columns < width)\n {\n\t// Not enough screen columns - show one per line\n\tfor (i = 0; i < item_count; ++i)\n\t{\n\t version_msg_wrap(items[i], i == current);\n\t if (msg_col > 0 && i < item_count - 1)\n\t\tmsg_putchar('\\n');\n\t}\n\treturn;\n }", " // The rightmost column doesn't need a separator.\n // Sacrifice it to fit in one more column if possible.\n ncol = (int) (Columns + 1) / width;\n nrow = item_count / ncol + ((item_count % ncol) ? 1 : 0);", " // \"i\" counts columns then rows. \"idx\" counts rows then columns.\n for (i = 0; !got_int && i < nrow * ncol; ++i)\n {\n\tint idx = (i / ncol) + (i % ncol) * nrow;", "\tif (idx < item_count)\n\t{\n\t int last_col = (i + 1) % ncol == 0;", "\t if (idx == current)\n\t\tmsg_putchar('[');\n#ifdef FEAT_SYN_HL\n\t if (use_highlight && items[idx][0] == '-')\n\t\tmsg_puts_attr((char *)items[idx], HL_ATTR(HLF_W));\n\t else\n#endif\n\t\tmsg_puts((char *)items[idx]);\n\t if (idx == current)\n\t\tmsg_putchar(']');\n\t if (last_col)\n\t {\n\t\tif (msg_col > 0 && cur_row < nrow)\n\t\t msg_putchar('\\n');\n\t\t++cur_row;\n\t }\n\t else\n\t {\n\t\twhile (msg_col % width)\n\t\t msg_putchar(' ');\n\t }\n\t}\n\telse\n\t{\n\t // this row is out of items, thus at the end of the row\n\t if (msg_col > 0)\n\t {\n\t\tif (cur_row < nrow)\n\t\t msg_putchar('\\n');\n\t\t++cur_row;\n\t }\n\t}\n }\n}", " void\nlist_version(void)\n{\n int\t\ti;\n int\t\tfirst;\n char\t*s = \"\";", " /*\n * When adding features here, don't forget to update the list of\n * internal variables in eval.c!\n */\n init_longVersion();\n msg(longVersion);\n#ifdef MSWIN\n# ifdef FEAT_GUI_MSWIN\n# ifdef VIMDLL\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit GUI/console version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit GUI/console version\"));\n# endif\n# else\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit GUI version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit GUI version\"));\n# endif\n# endif\n# ifdef FEAT_OLE\n msg_puts(_(\" with OLE support\"));\n# endif\n# else\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit console version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit console version\"));\n# endif\n# endif\n#endif\n#if defined(MACOS_X)\n# if defined(MACOS_X_DARWIN)\n msg_puts(_(\"\\nmacOS version\"));\n# else\n msg_puts(_(\"\\nmacOS version w/o darwin feat.\"));\n# endif\n# if defined(__arm64__)\n msg_puts(\" - arm64\");\n# elif defined(__x86_64__)\n msg_puts(\" - x86_64\");\n# endif\n#endif", "#ifdef VMS\n msg_puts(_(\"\\nOpenVMS version\"));\n# ifdef HAVE_PATHDEF\n if (*compiled_arch != NUL)\n {\n\tmsg_puts(\" - \");\n\tmsg_puts((char *)compiled_arch);\n }\n# endif", "#endif", " // Print the list of patch numbers if there is at least one.\n // Print a range when patches are consecutive: \"1-10, 12, 15-40, 42-45\"\n if (included_patches[0] != 0)\n {\n\tmsg_puts(_(\"\\nIncluded patches: \"));\n\tfirst = -1;\n\ti = (int)ARRAY_LENGTH(included_patches) - 1;\n\twhile (--i >= 0)\n\t{\n\t if (first < 0)\n\t\tfirst = included_patches[i];\n\t if (i == 0 || included_patches[i - 1] != included_patches[i] + 1)\n\t {\n\t\tmsg_puts(s);\n\t\ts = \", \";\n\t\tmsg_outnum((long)first);\n\t\tif (first != included_patches[i])\n\t\t{\n\t\t msg_puts(\"-\");\n\t\t msg_outnum((long)included_patches[i]);\n\t\t}\n\t\tfirst = -1;\n\t }\n\t}\n }", " // Print the list of extra patch descriptions if there is at least one.\n if (extra_patches[0] != NULL)\n {\n\tmsg_puts(_(\"\\nExtra patches: \"));\n\ts = \"\";\n\tfor (i = 0; extra_patches[i] != NULL; ++i)\n\t{\n\t msg_puts(s);\n\t s = \", \";\n\t msg_puts(extra_patches[i]);\n\t}\n }", "#ifdef MODIFIED_BY\n msg_puts(\"\\n\");\n msg_puts(_(\"Modified by \"));\n msg_puts(MODIFIED_BY);\n#endif", "#ifdef HAVE_PATHDEF\n if (*compiled_user != NUL || *compiled_sys != NUL)\n {\n\tmsg_puts(_(\"\\nCompiled \"));\n\tif (*compiled_user != NUL)\n\t{\n\t msg_puts(_(\"by \"));\n\t msg_puts((char *)compiled_user);\n\t}\n\tif (*compiled_sys != NUL)\n\t{\n\t msg_puts(\"@\");\n\t msg_puts((char *)compiled_sys);\n\t}\n }\n#endif", "#if defined(FEAT_HUGE)\n msg_puts(_(\"\\nHuge version \"));\n#elif defined(FEAT_NORMAL)\n msg_puts(_(\"\\nNormal version \"));\n#else\n msg_puts(_(\"\\nTiny version \"));\n#endif\n#if !defined(FEAT_GUI)\n msg_puts(_(\"without GUI.\"));\n#elif defined(FEAT_GUI_GTK)\n# if defined(USE_GTK3)\n msg_puts(_(\"with GTK3 GUI.\"));\n# elif defined(FEAT_GUI_GNOME)\n msg_puts(_(\"with GTK2-GNOME GUI.\"));\n# else\n msg_puts(_(\"with GTK2 GUI.\"));\n# endif\n#elif defined(FEAT_GUI_MOTIF)\n msg_puts(_(\"with X11-Motif GUI.\"));\n#elif defined(FEAT_GUI_HAIKU)\n msg_puts(_(\"with Haiku GUI.\"));\n#elif defined(FEAT_GUI_PHOTON)\n msg_puts(_(\"with Photon GUI.\"));\n#elif defined(MSWIN)\n msg_puts(_(\"with GUI.\"));\n#endif\n version_msg(_(\" Features included (+) or not (-):\\n\"));", " list_features();\n if (msg_col > 0)\n\tmsg_putchar('\\n');", "#ifdef SYS_VIMRC_FILE\n version_msg(_(\" system vimrc file: \\\"\"));\n version_msg(SYS_VIMRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE\n version_msg(_(\" user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE2\n version_msg(_(\" 2nd user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE2);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE3\n version_msg(_(\" 3rd user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE3);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_EXRC_FILE\n version_msg(_(\" user exrc file: \\\"\"));\n version_msg(USR_EXRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_EXRC_FILE2\n version_msg(_(\" 2nd user exrc file: \\\"\"));\n version_msg(USR_EXRC_FILE2);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef FEAT_GUI\n# ifdef SYS_GVIMRC_FILE\n version_msg(_(\" system gvimrc file: \\\"\"));\n version_msg(SYS_GVIMRC_FILE);\n version_msg(\"\\\"\\n\");\n# endif\n version_msg(_(\" user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE);\n version_msg(\"\\\"\\n\");\n# ifdef USR_GVIMRC_FILE2\n version_msg(_(\"2nd user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE2);\n version_msg(\"\\\"\\n\");\n# endif\n# ifdef USR_GVIMRC_FILE3\n version_msg(_(\"3rd user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE3);\n version_msg(\"\\\"\\n\");\n# endif\n#endif\n version_msg(_(\" defaults file: \\\"\"));\n version_msg(VIM_DEFAULTS_FILE);\n version_msg(\"\\\"\\n\");\n#ifdef FEAT_GUI\n# ifdef SYS_MENU_FILE\n version_msg(_(\" system menu file: \\\"\"));\n version_msg(SYS_MENU_FILE);\n version_msg(\"\\\"\\n\");\n# endif\n#endif\n#ifdef HAVE_PATHDEF\n if (*default_vim_dir != NUL)\n {\n\tversion_msg(_(\" fall-back for $VIM: \\\"\"));\n\tversion_msg((char *)default_vim_dir);\n\tversion_msg(\"\\\"\\n\");\n }\n if (*default_vimruntime_dir != NUL)\n {\n\tversion_msg(_(\" f-b for $VIMRUNTIME: \\\"\"));\n\tversion_msg((char *)default_vimruntime_dir);\n\tversion_msg(\"\\\"\\n\");\n }\n version_msg(_(\"Compilation: \"));\n version_msg((char *)all_cflags);\n version_msg(\"\\n\");\n#ifdef VMS\n if (*compiler_version != NUL)\n {\n\tversion_msg(_(\"Compiler: \"));\n\tversion_msg((char *)compiler_version);\n\tversion_msg(\"\\n\");\n }\n#endif\n version_msg(_(\"Linking: \"));\n version_msg((char *)all_lflags);\n#endif\n#ifdef DEBUG\n version_msg(\"\\n\");\n version_msg(_(\" DEBUG BUILD\"));\n#endif\n}", "static void do_intro_line(int row, char_u *mesg, int add_version, int attr);\nstatic void intro_message(int colon);", "/*\n * Show the intro message when not editing a file.\n */\n void\nmaybe_intro_message(void)\n{\n if (BUFEMPTY()\n\t && curbuf->b_fname == NULL\n\t && firstwin->w_next == NULL\n\t && vim_strchr(p_shm, SHM_INTRO) == NULL)\n\tintro_message(FALSE);\n}", "/*\n * Give an introductory message about Vim.\n * Only used when starting Vim on an empty file, without a file name.\n * Or with the \":intro\" command (for Sven :-).\n */\n static void\nintro_message(\n int\t\tcolon)\t\t// TRUE for \":intro\"\n{\n int\t\ti;\n int\t\trow;\n int\t\tblanklines;\n int\t\tsponsor;\n char\t*p;\n static char\t*(lines[]) =\n {\n\tN_(\"VIM - Vi IMproved\"),\n\t\"\",\n\tN_(\"version \"),\n\tN_(\"by Bram Moolenaar et al.\"),\n#ifdef MODIFIED_BY\n\t\" \",\n#endif\n\tN_(\"Vim is open source and freely distributable\"),\n\t\"\",\n\tN_(\"Help poor children in Uganda!\"),\n\tN_(\"type :help iccf<Enter> for information \"),\n\t\"\",\n\tN_(\"type :q<Enter> to exit \"),\n\tN_(\"type :help<Enter> or <F1> for on-line help\"),\n\tN_(\"type :help version9<Enter> for version info\"),\n\tNULL,\n\t\"\",\n\tN_(\"Running in Vi compatible mode\"),\n\tN_(\"type :set nocp<Enter> for Vim defaults\"),\n\tN_(\"type :help cp-default<Enter> for info on this\"),\n };\n#ifdef FEAT_GUI\n static char\t*(gui_lines[]) =\n {\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n#ifdef MODIFIED_BY\n\tNULL,\n#endif\n\tNULL,\n\tNULL,\n\tNULL,\n\tN_(\"menu Help->Orphans for information \"),\n\tNULL,\n\tN_(\"Running modeless, typed text is inserted\"),\n\tN_(\"menu Edit->Global Settings->Toggle Insert Mode \"),\n\tN_(\" for two modes \"),\n\tNULL,\n\tNULL,\n\tNULL,\n\tN_(\"menu Edit->Global Settings->Toggle Vi Compatible\"),\n\tN_(\" for Vim defaults \"),\n };\n#endif", " // blanklines = screen height - # message lines\n blanklines = (int)Rows - (ARRAY_LENGTH(lines) - 1);\n if (!p_cp)\n\tblanklines += 4; // add 4 for not showing \"Vi compatible\" message", " // Don't overwrite a statusline. Depends on 'cmdheight'.\n if (p_ls > 1)\n\tblanklines -= Rows - topframe->fr_height;\n if (blanklines < 0)\n\tblanklines = 0;", " // Show the sponsor and register message one out of four times, the Uganda\n // message two out of four times.\n sponsor = (int)time(NULL);\n sponsor = ((sponsor & 2) == 0) - ((sponsor & 4) == 0);", " // start displaying the message lines after half of the blank lines\n row = blanklines / 2;\n if ((row >= 2 && Columns >= 50) || colon)\n {\n\tfor (i = 0; i < (int)ARRAY_LENGTH(lines); ++i)\n\t{\n\t p = lines[i];\n#ifdef FEAT_GUI\n\t if (p_im && gui.in_use && gui_lines[i] != NULL)\n\t\tp = gui_lines[i];\n#endif\n\t if (p == NULL)\n\t {\n\t\tif (!p_cp)\n\t\t break;\n\t\tcontinue;\n\t }\n\t if (sponsor != 0)\n\t {\n\t\tif (strstr(p, \"children\") != NULL)\n\t\t p = sponsor < 0\n\t\t\t? N_(\"Sponsor Vim development!\")\n\t\t\t: N_(\"Become a registered Vim user!\");\n\t\telse if (strstr(p, \"iccf\") != NULL)\n\t\t p = sponsor < 0\n\t\t\t? N_(\"type :help sponsor<Enter> for information \")\n\t\t\t: N_(\"type :help register<Enter> for information \");\n\t\telse if (strstr(p, \"Orphans\") != NULL)\n\t\t p = N_(\"menu Help->Sponsor/Register for information \");\n\t }\n\t if (*p != NUL)\n\t\tdo_intro_line(row, (char_u *)_(p), i == 2, 0);\n\t ++row;\n\t}\n }", " // Make the wait-return message appear just below the text.\n if (colon)\n\tmsg_row = row;\n}", " static void\ndo_intro_line(\n int\t\trow,\n char_u\t*mesg,\n int\t\tadd_version,\n int\t\tattr)\n{\n char_u\tvers[20];\n int\t\tcol;\n char_u\t*p;\n int\t\tl;\n int\t\tclen;\n#ifdef MODIFIED_BY\n# define MODBY_LEN 150\n char_u\tmodby[MODBY_LEN];", " if (*mesg == ' ')\n {\n\tvim_strncpy(modby, (char_u *)_(\"Modified by \"), MODBY_LEN - 1);\n\tl = (int)STRLEN(modby);\n\tvim_strncpy(modby + l, (char_u *)MODIFIED_BY, MODBY_LEN - l - 1);\n\tmesg = modby;\n }\n#endif", " // Center the message horizontally.\n col = vim_strsize(mesg);\n if (add_version)\n {\n\tSTRCPY(vers, mediumVersion);\n\tif (highest_patch())\n\t{\n\t // Check for 9.9x or 9.9xx, alpha/beta version\n\t if (isalpha((int)vers[3]))\n\t {\n\t\tint len = (isalpha((int)vers[4])) ? 5 : 4;\n\t\tsprintf((char *)vers + len, \".%d%s\", highest_patch(),\n\t\t\t\t\t\t\t mediumVersion + len);\n\t }\n\t else\n\t\tsprintf((char *)vers + 3, \".%d\", highest_patch());\n\t}\n\tcol += (int)STRLEN(vers);\n }\n col = (Columns - col) / 2;\n if (col < 0)\n\tcol = 0;", " // Split up in parts to highlight <> items differently.\n for (p = mesg; *p != NUL; p += l)\n {\n\tclen = 0;\n\tfor (l = 0; p[l] != NUL\n\t\t\t && (l == 0 || (p[l] != '<' && p[l - 1] != '>')); ++l)\n\t{\n\t if (has_mbyte)\n\t {\n\t\tclen += ptr2cells(p + l);\n\t\tl += (*mb_ptr2len)(p + l) - 1;\n\t }\n\t else\n\t\tclen += byte2cells(p[l]);\n\t}\n\tscreen_puts_len(p, l, row, col, *p == '<' ? HL_ATTR(HLF_8) : attr);\n\tcol += clen;\n }", " // Add the version number to the version line.\n if (add_version)\n\tscreen_puts(vers, row, col, 0);\n}", "/*\n * \":intro\": clear screen, display intro screen and wait for return.\n */\n void\nex_intro(exarg_T *eap UNUSED)\n{\n screenclear();\n intro_message(TRUE);\n wait_return(TRUE);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 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 ]
PreciseBugs
{"buggy_code_end_loc": [7314, 1117, 697], "buggy_code_start_loc": [7314, 883, 697], "filenames": ["src/eval.c", "src/testdir/test_substitute.vim", "src/version.c"], "fixing_code_end_loc": [7320, 1134, 700], "fixing_code_start_loc": [7315, 883, 698], "message": "Out-of-bounds Write in GitHub repository vim/vim prior to 9.0.1145.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "7A64F3DA-66B5-4F73-A776-7457E9CBCE52", "versionEndExcluding": "9.0.1145", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Out-of-bounds Write in GitHub repository vim/vim prior to 9.0.1145."}], "evaluatorComment": null, "id": "CVE-2023-0054", "lastModified": "2023-05-03T12:16:43.723", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.3, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-04T19:15:09.573", "references": [{"source": "security@huntr.dev", "tags": null, "url": "http://seclists.org/fulldisclosure/2023/Mar/17"}, {"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/3ac1d97a1d9353490493d30088256360435f7731"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Third Party Advisory"], "url": "https://huntr.dev/bounties/b289ee0f-fd16-4147-bd01-c6289c45e49d"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}, {"source": "security@huntr.dev", "tags": null, "url": "https://support.apple.com/kb/HT213670"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-787"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/3ac1d97a1d9353490493d30088256360435f7731"}, "type": "CWE-787"}
190
Determine whether the {function_name} code is vulnerable or not.
[ "/* vi:set ts=8 sts=4 sw=4 noet:\n *\n * VIM - Vi IMproved\t\tby Bram Moolenaar\n *\n * Do \":help uganda\" in Vim to read copying and usage conditions.\n * Do \":help credits\" in Vim to see a list of people who contributed.\n * See README.txt for an overview of the Vim source code.\n */", "#include \"vim.h\"", "/*\n * Vim originated from Stevie version 3.6 (Fish disk 217) by GRWalter (Fred)\n * It has been changed beyond recognition since then.\n *\n * Differences between version 8.2 and 9.0 can be found with \":help version9\".\n * Differences between version 7.4 and 8.x can be found with \":help version8\".\n * Differences between version 6.4 and 7.x can be found with \":help version7\".\n * Differences between version 5.8 and 6.x can be found with \":help version6\".\n * Differences between version 4.x and 5.x can be found with \":help version5\".\n * Differences between version 3.0 and 4.x can be found with \":help version4\".\n * All the remarks about older versions have been removed, they are not very\n * interesting.\n */", "#include \"version.h\"", "char\t\t*Version = VIM_VERSION_SHORT;\nstatic char\t*mediumVersion = VIM_VERSION_MEDIUM;", "#if defined(HAVE_DATE_TIME) || defined(PROTO)\n# if (defined(VMS) && defined(VAXC)) || defined(PROTO)\nchar\tlongVersion[sizeof(VIM_VERSION_LONG_DATE) + sizeof(__DATE__)\n\t\t\t\t\t\t + sizeof(__TIME__) + 3];", " void\ninit_longVersion(void)\n{\n /*\n * Construct the long version string. Necessary because\n * VAX C can't concatenate strings in the preprocessor.\n */\n strcpy(longVersion, VIM_VERSION_LONG_DATE);\n#ifdef BUILD_DATE\n strcat(longVersion, BUILD_DATE);\n#else\n strcat(longVersion, __DATE__);\n strcat(longVersion, \" \");\n strcat(longVersion, __TIME__);\n#endif\n strcat(longVersion, \")\");\n}", "# else\nchar\t*longVersion = NULL;", " void\ninit_longVersion(void)\n{\n if (longVersion == NULL)\n {\n#ifdef BUILD_DATE\n\tchar *date_time = BUILD_DATE;\n#else\n\tchar *date_time = __DATE__ \" \" __TIME__;\n#endif\n\tchar *msg = _(\"%s (%s, compiled %s)\");\n\tsize_t len = strlen(msg)\n\t\t + strlen(VIM_VERSION_LONG_ONLY)\n\t\t + strlen(VIM_VERSION_DATE_ONLY)\n\t\t + strlen(date_time);", "\tlongVersion = alloc(len);\n\tif (longVersion == NULL)\n\t longVersion = VIM_VERSION_LONG;\n\telse\n\t vim_snprintf(longVersion, len, msg,\n\t\t VIM_VERSION_LONG_ONLY, VIM_VERSION_DATE_ONLY, date_time);\n }\n}\n# endif\n#else\nchar\t*longVersion = VIM_VERSION_LONG;", " void\ninit_longVersion(void)\n{\n // nothing to do\n}\n#endif", "static char *(features[]) =\n{\n#ifdef HAVE_ACL\n\t\"+acl\",\n#else\n\t\"-acl\",\n#endif\n#ifdef AMIGA\t\t// only for Amiga systems\n# ifdef FEAT_ARP\n\t\"+ARP\",\n# else\n\t\"-ARP\",\n# endif\n#endif\n#ifdef FEAT_ARABIC\n\t\"+arabic\",\n#else\n\t\"-arabic\",\n#endif\n\t\"+autocmd\",\n#ifdef FEAT_AUTOCHDIR\n \"+autochdir\",\n#else\n \"-autochdir\",\n#endif\n#ifdef FEAT_AUTOSERVERNAME\n\t\"+autoservername\",\n#else\n\t\"-autoservername\",\n#endif\n#ifdef FEAT_BEVAL_GUI\n\t\"+balloon_eval\",\n#else\n\t\"-balloon_eval\",\n#endif\n#ifdef FEAT_BEVAL_TERM\n\t\"+balloon_eval_term\",\n#else\n\t\"-balloon_eval_term\",\n#endif\n#ifdef FEAT_BROWSE\n\t\"+browse\",\n#else\n\t\"-browse\",\n#endif\n\t\"++builtin_terms\",\n#ifdef FEAT_BYTEOFF\n\t\"+byte_offset\",\n#else\n\t\"-byte_offset\",\n#endif\n#ifdef FEAT_JOB_CHANNEL\n\t\"+channel\",\n#else\n\t\"-channel\",\n#endif\n\t\"+cindent\",\n#ifdef FEAT_CLIENTSERVER\n\t\"+clientserver\",\n#else\n\t\"-clientserver\",\n#endif\n#ifdef FEAT_CLIPBOARD\n\t\"+clipboard\",\n#else\n\t\"-clipboard\",\n#endif\n\t\"+cmdline_compl\",\n\t\"+cmdline_hist\",\n\t\"+cmdline_info\",\n\t\"+comments\",\n#ifdef FEAT_CONCEAL\n\t\"+conceal\",\n#else\n\t\"-conceal\",\n#endif\n#ifdef FEAT_CRYPT\n\t\"+cryptv\",\n#else\n\t\"-cryptv\",\n#endif\n#ifdef FEAT_CSCOPE\n\t\"+cscope\",\n#else\n\t\"-cscope\",\n#endif\n\t\"+cursorbind\",\n#ifdef CURSOR_SHAPE\n\t\"+cursorshape\",\n#else\n\t\"-cursorshape\",\n#endif\n#if defined(FEAT_CON_DIALOG) && defined(FEAT_GUI_DIALOG)\n\t\"+dialog_con_gui\",\n#else\n# if defined(FEAT_CON_DIALOG)\n\t\"+dialog_con\",\n# else\n# if defined(FEAT_GUI_DIALOG)\n\t\"+dialog_gui\",\n# else\n\t\"-dialog\",\n# endif\n# endif\n#endif\n#ifdef FEAT_DIFF\n\t\"+diff\",\n#else\n\t\"-diff\",\n#endif\n#ifdef FEAT_DIGRAPHS\n\t\"+digraphs\",\n#else\n\t\"-digraphs\",\n#endif\n#ifdef FEAT_GUI_MSWIN\n# ifdef FEAT_DIRECTX\n\t\"+directx\",\n# else\n\t\"-directx\",\n# endif\n#endif\n#ifdef FEAT_DND\n\t\"+dnd\",\n#else\n\t\"-dnd\",\n#endif\n\t\"-ebcdic\",\n#ifdef FEAT_EMACS_TAGS\n\t\"+emacs_tags\",\n#else\n\t\"-emacs_tags\",\n#endif\n#ifdef FEAT_EVAL\n\t\"+eval\",\n#else\n\t\"-eval\",\n#endif\n\t\"+ex_extra\",\n#ifdef FEAT_SEARCH_EXTRA\n\t\"+extra_search\",\n#else\n\t\"-extra_search\",\n#endif\n\t\"-farsi\",\n\t\"+file_in_path\",\n#ifdef FEAT_FIND_ID\n\t\"+find_in_path\",\n#else\n\t\"-find_in_path\",\n#endif\n\t\"+float\",\n#ifdef FEAT_FOLDING\n\t\"+folding\",\n#else\n\t\"-folding\",\n#endif\n\t\"-footer\",\n\t// only interesting on Unix systems\n#if !defined(USE_SYSTEM) && defined(UNIX)\n\t\"+fork()\",\n#endif\n#ifdef FEAT_GETTEXT\n# ifdef DYNAMIC_GETTEXT\n\t\"+gettext/dyn\",\n# else\n\t\"+gettext\",\n# endif\n#else\n\t\"-gettext\",\n#endif\n\t\"-hangul_input\",\n#if (defined(HAVE_ICONV_H) && defined(USE_ICONV)) || defined(DYNAMIC_ICONV)\n# ifdef DYNAMIC_ICONV\n\t\"+iconv/dyn\",\n# else\n\t\"+iconv\",\n# endif\n#else\n\t\"-iconv\",\n#endif\n\t\"+insert_expand\",\n#ifdef FEAT_IPV6\n\t\"+ipv6\",\n#else\n\t\"-ipv6\",\n#endif\n#ifdef FEAT_JOB_CHANNEL\n\t\"+job\",\n#else\n\t\"-job\",\n#endif\n\t\"+jumplist\",\n#ifdef FEAT_KEYMAP\n\t\"+keymap\",\n#else\n\t\"-keymap\",\n#endif\n#ifdef FEAT_EVAL\n\t\"+lambda\",\n#else\n\t\"-lambda\",\n#endif\n#ifdef FEAT_LANGMAP\n\t\"+langmap\",\n#else\n\t\"-langmap\",\n#endif\n#ifdef FEAT_LIBCALL\n\t\"+libcall\",\n#else\n\t\"-libcall\",\n#endif\n#ifdef FEAT_LINEBREAK\n\t\"+linebreak\",\n#else\n\t\"-linebreak\",\n#endif\n\t\"+lispindent\",\n\t\"+listcmds\",\n\t\"+localmap\",\n#ifdef FEAT_LUA\n# ifdef DYNAMIC_LUA\n\t\"+lua/dyn\",\n# else\n\t\"+lua\",\n# endif\n#else\n\t\"-lua\",\n#endif\n#ifdef FEAT_MENU\n\t\"+menu\",\n#else\n\t\"-menu\",\n#endif\n#ifdef FEAT_SESSION\n\t\"+mksession\",\n#else\n\t\"-mksession\",\n#endif\n\t\"+modify_fname\",\n\t\"+mouse\",\n#ifdef FEAT_MOUSESHAPE\n\t\"+mouseshape\",\n#else\n\t\"-mouseshape\",\n#endif", "#if defined(UNIX) || defined(VMS)\n# ifdef FEAT_MOUSE_DEC\n\t\"+mouse_dec\",\n# else\n\t\"-mouse_dec\",\n# endif\n# ifdef FEAT_MOUSE_GPM\n# ifdef DYNAMIC_GPM\n\t\"+mouse_gpm/dyn\",\n# else\n\t\"+mouse_gpm\",\n# endif\n# else\n\t\"-mouse_gpm\",\n# endif\n# ifdef FEAT_MOUSE_JSB\n\t\"+mouse_jsbterm\",\n# else\n\t\"-mouse_jsbterm\",\n# endif\n# ifdef FEAT_MOUSE_NET\n\t\"+mouse_netterm\",\n# else\n\t\"-mouse_netterm\",\n# endif\n#endif", "#ifdef __QNX__\n# ifdef FEAT_MOUSE_PTERM\n\t\"+mouse_pterm\",\n# else\n\t\"-mouse_pterm\",\n# endif\n#endif", "#if defined(UNIX) || defined(VMS)\n\t\"+mouse_sgr\",\n# ifdef FEAT_SYSMOUSE\n\t\"+mouse_sysmouse\",\n# else\n\t\"-mouse_sysmouse\",\n# endif\n# ifdef FEAT_MOUSE_URXVT\n\t\"+mouse_urxvt\",\n# else\n\t\"-mouse_urxvt\",\n# endif\n\t\"+mouse_xterm\",\n#endif", "#ifdef FEAT_MBYTE_IME\n# ifdef DYNAMIC_IME\n\t\"+multi_byte_ime/dyn\",\n# else\n\t\"+multi_byte_ime\",\n# endif\n#else\n\t\"+multi_byte\",\n#endif\n#ifdef FEAT_MULTI_LANG\n\t\"+multi_lang\",\n#else\n\t\"-multi_lang\",\n#endif\n#ifdef FEAT_MZSCHEME\n# ifdef DYNAMIC_MZSCHEME\n\t\"+mzscheme/dyn\",\n# else\n\t\"+mzscheme\",\n# endif\n#else\n\t\"-mzscheme\",\n#endif\n#ifdef FEAT_NETBEANS_INTG\n\t\"+netbeans_intg\",\n#else\n\t\"-netbeans_intg\",\n#endif\n\t\"+num64\",\n#ifdef FEAT_GUI_MSWIN\n# ifdef FEAT_OLE\n\t\"+ole\",\n# else\n\t\"-ole\",\n# endif\n#endif\n#ifdef FEAT_EVAL\n\t\"+packages\",\n#else\n\t\"-packages\",\n#endif\n\t\"+path_extra\",\n#ifdef FEAT_PERL\n# ifdef DYNAMIC_PERL\n\t\"+perl/dyn\",\n# else\n\t\"+perl\",\n# endif\n#else\n\t\"-perl\",\n#endif\n#ifdef FEAT_PERSISTENT_UNDO\n\t\"+persistent_undo\",\n#else\n\t\"-persistent_undo\",\n#endif\n#ifdef FEAT_PROP_POPUP\n\t\"+popupwin\",\n#else\n\t\"-popupwin\",\n#endif\n#ifdef FEAT_PRINTER\n# ifdef FEAT_POSTSCRIPT\n\t\"+postscript\",\n# else\n\t\"-postscript\",\n# endif\n\t\"+printer\",\n#else\n\t\"-printer\",\n#endif\n#ifdef FEAT_PROFILE\n\t\"+profile\",\n#else\n\t\"-profile\",\n#endif\n#ifdef FEAT_PYTHON\n# ifdef DYNAMIC_PYTHON\n\t\"+python/dyn\",\n# else\n\t\"+python\",\n# endif\n#else\n\t\"-python\",\n#endif\n#ifdef FEAT_PYTHON3\n# ifdef DYNAMIC_PYTHON3\n\t\"+python3/dyn\",\n# else\n\t\"+python3\",\n# endif\n#else\n\t\"-python3\",\n#endif\n#ifdef FEAT_QUICKFIX\n\t\"+quickfix\",\n#else\n\t\"-quickfix\",\n#endif\n#ifdef FEAT_RELTIME\n\t\"+reltime\",\n#else\n\t\"-reltime\",\n#endif\n#ifdef FEAT_RIGHTLEFT\n\t\"+rightleft\",\n#else\n\t\"-rightleft\",\n#endif\n#ifdef FEAT_RUBY\n# ifdef DYNAMIC_RUBY\n\t\"+ruby/dyn\",\n# else\n\t\"+ruby\",\n# endif\n#else\n\t\"-ruby\",\n#endif\n\t\"+scrollbind\",\n#ifdef FEAT_SIGNS\n\t\"+signs\",\n#else\n\t\"-signs\",\n#endif\n\t\"+smartindent\",\n#ifdef FEAT_SODIUM\n# ifdef DYNAMIC_SODIUM\n\t\"+sodium/dyn\",\n# else\n\t\"+sodium\",\n# endif\n#else\n\t\"-sodium\",\n#endif\n#ifdef FEAT_SOUND\n\t\"+sound\",\n#else\n\t\"-sound\",\n#endif\n#ifdef FEAT_SPELL\n\t\"+spell\",\n#else\n\t\"-spell\",\n#endif\n#ifdef STARTUPTIME\n\t\"+startuptime\",\n#else\n\t\"-startuptime\",\n#endif\n#ifdef FEAT_STL_OPT\n\t\"+statusline\",\n#else\n\t\"-statusline\",\n#endif\n\t\"-sun_workshop\",\n#ifdef FEAT_SYN_HL\n\t\"+syntax\",\n#else\n\t\"-syntax\",\n#endif\n\t // only interesting on Unix systems\n#if defined(USE_SYSTEM) && defined(UNIX)\n\t\"+system()\",\n#endif\n\t\"+tag_binary\",\n\t\"-tag_old_static\",\n\t\"-tag_any_white\",\n#ifdef FEAT_TCL\n# ifdef DYNAMIC_TCL\n\t\"+tcl/dyn\",\n# else\n\t\"+tcl\",\n# endif\n#else\n\t\"-tcl\",\n#endif\n#ifdef FEAT_TERMGUICOLORS\n\t\"+termguicolors\",\n#else\n\t\"-termguicolors\",\n#endif\n#ifdef FEAT_TERMINAL\n\t\"+terminal\",\n#else\n\t\"-terminal\",\n#endif\n#if defined(UNIX)\n// only Unix can have terminfo instead of termcap\n# ifdef TERMINFO\n\t\"+terminfo\",\n# else\n\t\"-terminfo\",\n# endif\n#endif\n#ifdef FEAT_TERMRESPONSE\n\t\"+termresponse\",\n#else\n\t\"-termresponse\",\n#endif\n\t\"+textobjects\",\n#ifdef FEAT_PROP_POPUP\n\t\"+textprop\",\n#else\n\t\"-textprop\",\n#endif\n#if !defined(UNIX)\n// unix always includes termcap support\n# ifdef HAVE_TGETENT\n\t\"+tgetent\",\n# else\n\t\"-tgetent\",\n# endif\n#endif\n#ifdef FEAT_TIMERS\n\t\"+timers\",\n#else\n\t\"-timers\",\n#endif\n\t\"+title\",\n#ifdef FEAT_TOOLBAR\n\t\"+toolbar\",\n#else\n\t\"-toolbar\",\n#endif\n\t\"+user_commands\",\n#ifdef FEAT_VARTABS\n\t\"+vartabs\",\n#else\n\t\"-vartabs\",\n#endif\n\t\"+vertsplit\",\n\t\"+vim9script\",\n#ifdef FEAT_VIMINFO\n\t\"+viminfo\",\n#else\n\t\"-viminfo\",\n#endif\n\t\"+virtualedit\",\n\t\"+visual\",\n\t\"+visualextra\",\n\t\"+vreplace\",\n#ifdef MSWIN\n# ifdef FEAT_VTP\n\t\"+vtp\",\n# else\n\t\"-vtp\",\n# endif\n#endif\n\t\"+wildignore\",\n\t\"+wildmenu\",\n\t\"+windows\",\n#ifdef FEAT_WRITEBACKUP\n\t\"+writebackup\",\n#else\n\t\"-writebackup\",\n#endif\n#if defined(UNIX) || defined(VMS)\n# ifdef FEAT_X11\n\t\"+X11\",\n# else\n\t\"-X11\",\n# endif\n#endif\n#ifdef FEAT_XFONTSET\n\t\"+xfontset\",\n#else\n\t\"-xfontset\",\n#endif\n#ifdef FEAT_XIM\n\t\"+xim\",\n#else\n\t\"-xim\",\n#endif\n#if defined(MSWIN)\n# ifdef FEAT_XPM_W32\n\t\"+xpm_w32\",\n# else\n\t\"-xpm_w32\",\n# endif\n#elif defined(HAVE_XPM)\n\t\"+xpm\",\n#else\n\t\"-xpm\",\n#endif\n#if defined(UNIX) || defined(VMS)\n# if defined(USE_XSMP_INTERACT)\n\t\"+xsmp_interact\",\n# elif defined(USE_XSMP)\n\t\"+xsmp\",\n# else\n\t\"-xsmp\",\n# endif\n# ifdef FEAT_XCLIPBOARD\n\t\"+xterm_clipboard\",\n# else\n\t\"-xterm_clipboard\",\n# endif\n#endif\n#ifdef FEAT_XTERM_SAVE\n\t\"+xterm_save\",\n#else\n\t\"-xterm_save\",\n#endif\n\tNULL\n};", "static int included_patches[] =\n{ /* Add new patch number below this line */", "/**/\n 1145,", "/**/\n 1144,\n/**/\n 1143,\n/**/\n 1142,\n/**/\n 1141,\n/**/\n 1140,\n/**/\n 1139,\n/**/\n 1138,\n/**/\n 1137,\n/**/\n 1136,\n/**/\n 1135,\n/**/\n 1134,\n/**/\n 1133,\n/**/\n 1132,\n/**/\n 1131,\n/**/\n 1130,\n/**/\n 1129,\n/**/\n 1128,\n/**/\n 1127,\n/**/\n 1126,\n/**/\n 1125,\n/**/\n 1124,\n/**/\n 1123,\n/**/\n 1122,\n/**/\n 1121,\n/**/\n 1120,\n/**/\n 1119,\n/**/\n 1118,\n/**/\n 1117,\n/**/\n 1116,\n/**/\n 1115,\n/**/\n 1114,\n/**/\n 1113,\n/**/\n 1112,\n/**/\n 1111,\n/**/\n 1110,\n/**/\n 1109,\n/**/\n 1108,\n/**/\n 1107,\n/**/\n 1106,\n/**/\n 1105,\n/**/\n 1104,\n/**/\n 1103,\n/**/\n 1102,\n/**/\n 1101,\n/**/\n 1100,\n/**/\n 1099,\n/**/\n 1098,\n/**/\n 1097,\n/**/\n 1096,\n/**/\n 1095,\n/**/\n 1094,\n/**/\n 1093,\n/**/\n 1092,\n/**/\n 1091,\n/**/\n 1090,\n/**/\n 1089,\n/**/\n 1088,\n/**/\n 1087,\n/**/\n 1086,\n/**/\n 1085,\n/**/\n 1084,\n/**/\n 1083,\n/**/\n 1082,\n/**/\n 1081,\n/**/\n 1080,\n/**/\n 1079,\n/**/\n 1078,\n/**/\n 1077,\n/**/\n 1076,\n/**/\n 1075,\n/**/\n 1074,\n/**/\n 1073,\n/**/\n 1072,\n/**/\n 1071,\n/**/\n 1070,\n/**/\n 1069,\n/**/\n 1068,\n/**/\n 1067,\n/**/\n 1066,\n/**/\n 1065,\n/**/\n 1064,\n/**/\n 1063,\n/**/\n 1062,\n/**/\n 1061,\n/**/\n 1060,\n/**/\n 1059,\n/**/\n 1058,\n/**/\n 1057,\n/**/\n 1056,\n/**/\n 1055,\n/**/\n 1054,\n/**/\n 1053,\n/**/\n 1052,\n/**/\n 1051,\n/**/\n 1050,\n/**/\n 1049,\n/**/\n 1048,\n/**/\n 1047,\n/**/\n 1046,\n/**/\n 1045,\n/**/\n 1044,\n/**/\n 1043,\n/**/\n 1042,\n/**/\n 1041,\n/**/\n 1040,\n/**/\n 1039,\n/**/\n 1038,\n/**/\n 1037,\n/**/\n 1036,\n/**/\n 1035,\n/**/\n 1034,\n/**/\n 1033,\n/**/\n 1032,\n/**/\n 1031,\n/**/\n 1030,\n/**/\n 1029,\n/**/\n 1028,\n/**/\n 1027,\n/**/\n 1026,\n/**/\n 1025,\n/**/\n 1024,\n/**/\n 1023,\n/**/\n 1022,\n/**/\n 1021,\n/**/\n 1020,\n/**/\n 1019,\n/**/\n 1018,\n/**/\n 1017,\n/**/\n 1016,\n/**/\n 1015,\n/**/\n 1014,\n/**/\n 1013,\n/**/\n 1012,\n/**/\n 1011,\n/**/\n 1010,\n/**/\n 1009,\n/**/\n 1008,\n/**/\n 1007,\n/**/\n 1006,\n/**/\n 1005,\n/**/\n 1004,\n/**/\n 1003,\n/**/\n 1002,\n/**/\n 1001,\n/**/\n 1000,\n/**/\n 999,\n/**/\n 998,\n/**/\n 997,\n/**/\n 996,\n/**/\n 995,\n/**/\n 994,\n/**/\n 993,\n/**/\n 992,\n/**/\n 991,\n/**/\n 990,\n/**/\n 989,\n/**/\n 988,\n/**/\n 987,\n/**/\n 986,\n/**/\n 985,\n/**/\n 984,\n/**/\n 983,\n/**/\n 982,\n/**/\n 981,\n/**/\n 980,\n/**/\n 979,\n/**/\n 978,\n/**/\n 977,\n/**/\n 976,\n/**/\n 975,\n/**/\n 974,\n/**/\n 973,\n/**/\n 972,\n/**/\n 971,\n/**/\n 970,\n/**/\n 969,\n/**/\n 968,\n/**/\n 967,\n/**/\n 966,\n/**/\n 965,\n/**/\n 964,\n/**/\n 963,\n/**/\n 962,\n/**/\n 961,\n/**/\n 960,\n/**/\n 959,\n/**/\n 958,\n/**/\n 957,\n/**/\n 956,\n/**/\n 955,\n/**/\n 954,\n/**/\n 953,\n/**/\n 952,\n/**/\n 951,\n/**/\n 950,\n/**/\n 949,\n/**/\n 948,\n/**/\n 947,\n/**/\n 946,\n/**/\n 945,\n/**/\n 944,\n/**/\n 943,\n/**/\n 942,\n/**/\n 941,\n/**/\n 940,\n/**/\n 939,\n/**/\n 938,\n/**/\n 937,\n/**/\n 936,\n/**/\n 935,\n/**/\n 934,\n/**/\n 933,\n/**/\n 932,\n/**/\n 931,\n/**/\n 930,\n/**/\n 929,\n/**/\n 928,\n/**/\n 927,\n/**/\n 926,\n/**/\n 925,\n/**/\n 924,\n/**/\n 923,\n/**/\n 922,\n/**/\n 921,\n/**/\n 920,\n/**/\n 919,\n/**/\n 918,\n/**/\n 917,\n/**/\n 916,\n/**/\n 915,\n/**/\n 914,\n/**/\n 913,\n/**/\n 912,\n/**/\n 911,\n/**/\n 910,\n/**/\n 909,\n/**/\n 908,\n/**/\n 907,\n/**/\n 906,\n/**/\n 905,\n/**/\n 904,\n/**/\n 903,\n/**/\n 902,\n/**/\n 901,\n/**/\n 900,\n/**/\n 899,\n/**/\n 898,\n/**/\n 897,\n/**/\n 896,\n/**/\n 895,\n/**/\n 894,\n/**/\n 893,\n/**/\n 892,\n/**/\n 891,\n/**/\n 890,\n/**/\n 889,\n/**/\n 888,\n/**/\n 887,\n/**/\n 886,\n/**/\n 885,\n/**/\n 884,\n/**/\n 883,\n/**/\n 882,\n/**/\n 881,\n/**/\n 880,\n/**/\n 879,\n/**/\n 878,\n/**/\n 877,\n/**/\n 876,\n/**/\n 875,\n/**/\n 874,\n/**/\n 873,\n/**/\n 872,\n/**/\n 871,\n/**/\n 870,\n/**/\n 869,\n/**/\n 868,\n/**/\n 867,\n/**/\n 866,\n/**/\n 865,\n/**/\n 864,\n/**/\n 863,\n/**/\n 862,\n/**/\n 861,\n/**/\n 860,\n/**/\n 859,\n/**/\n 858,\n/**/\n 857,\n/**/\n 856,\n/**/\n 855,\n/**/\n 854,\n/**/\n 853,\n/**/\n 852,\n/**/\n 851,\n/**/\n 850,\n/**/\n 849,\n/**/\n 848,\n/**/\n 847,\n/**/\n 846,\n/**/\n 845,\n/**/\n 844,\n/**/\n 843,\n/**/\n 842,\n/**/\n 841,\n/**/\n 840,\n/**/\n 839,\n/**/\n 838,\n/**/\n 837,\n/**/\n 836,\n/**/\n 835,\n/**/\n 834,\n/**/\n 833,\n/**/\n 832,\n/**/\n 831,\n/**/\n 830,\n/**/\n 829,\n/**/\n 828,\n/**/\n 827,\n/**/\n 826,\n/**/\n 825,\n/**/\n 824,\n/**/\n 823,\n/**/\n 822,\n/**/\n 821,\n/**/\n 820,\n/**/\n 819,\n/**/\n 818,\n/**/\n 817,\n/**/\n 816,\n/**/\n 815,\n/**/\n 814,\n/**/\n 813,\n/**/\n 812,\n/**/\n 811,\n/**/\n 810,\n/**/\n 809,\n/**/\n 808,\n/**/\n 807,\n/**/\n 806,\n/**/\n 805,\n/**/\n 804,\n/**/\n 803,\n/**/\n 802,\n/**/\n 801,\n/**/\n 800,\n/**/\n 799,\n/**/\n 798,\n/**/\n 797,\n/**/\n 796,\n/**/\n 795,\n/**/\n 794,\n/**/\n 793,\n/**/\n 792,\n/**/\n 791,\n/**/\n 790,\n/**/\n 789,\n/**/\n 788,\n/**/\n 787,\n/**/\n 786,\n/**/\n 785,\n/**/\n 784,\n/**/\n 783,\n/**/\n 782,\n/**/\n 781,\n/**/\n 780,\n/**/\n 779,\n/**/\n 778,\n/**/\n 777,\n/**/\n 776,\n/**/\n 775,\n/**/\n 774,\n/**/\n 773,\n/**/\n 772,\n/**/\n 771,\n/**/\n 770,\n/**/\n 769,\n/**/\n 768,\n/**/\n 767,\n/**/\n 766,\n/**/\n 765,\n/**/\n 764,\n/**/\n 763,\n/**/\n 762,\n/**/\n 761,\n/**/\n 760,\n/**/\n 759,\n/**/\n 758,\n/**/\n 757,\n/**/\n 756,\n/**/\n 755,\n/**/\n 754,\n/**/\n 753,\n/**/\n 752,\n/**/\n 751,\n/**/\n 750,\n/**/\n 749,\n/**/\n 748,\n/**/\n 747,\n/**/\n 746,\n/**/\n 745,\n/**/\n 744,\n/**/\n 743,\n/**/\n 742,\n/**/\n 741,\n/**/\n 740,\n/**/\n 739,\n/**/\n 738,\n/**/\n 737,\n/**/\n 736,\n/**/\n 735,\n/**/\n 734,\n/**/\n 733,\n/**/\n 732,\n/**/\n 731,\n/**/\n 730,\n/**/\n 729,\n/**/\n 728,\n/**/\n 727,\n/**/\n 726,\n/**/\n 725,\n/**/\n 724,\n/**/\n 723,\n/**/\n 722,\n/**/\n 721,\n/**/\n 720,\n/**/\n 719,\n/**/\n 718,\n/**/\n 717,\n/**/\n 716,\n/**/\n 715,\n/**/\n 714,\n/**/\n 713,\n/**/\n 712,\n/**/\n 711,\n/**/\n 710,\n/**/\n 709,\n/**/\n 708,\n/**/\n 707,\n/**/\n 706,\n/**/\n 705,\n/**/\n 704,\n/**/\n 703,\n/**/\n 702,\n/**/\n 701,\n/**/\n 700,\n/**/\n 699,\n/**/\n 698,\n/**/\n 697,\n/**/\n 696,\n/**/\n 695,\n/**/\n 694,\n/**/\n 693,\n/**/\n 692,\n/**/\n 691,\n/**/\n 690,\n/**/\n 689,\n/**/\n 688,\n/**/\n 687,\n/**/\n 686,\n/**/\n 685,\n/**/\n 684,\n/**/\n 683,\n/**/\n 682,\n/**/\n 681,\n/**/\n 680,\n/**/\n 679,\n/**/\n 678,\n/**/\n 677,\n/**/\n 676,\n/**/\n 675,\n/**/\n 674,\n/**/\n 673,\n/**/\n 672,\n/**/\n 671,\n/**/\n 670,\n/**/\n 669,\n/**/\n 668,\n/**/\n 667,\n/**/\n 666,\n/**/\n 665,\n/**/\n 664,\n/**/\n 663,\n/**/\n 662,\n/**/\n 661,\n/**/\n 660,\n/**/\n 659,\n/**/\n 658,\n/**/\n 657,\n/**/\n 656,\n/**/\n 655,\n/**/\n 654,\n/**/\n 653,\n/**/\n 652,\n/**/\n 651,\n/**/\n 650,\n/**/\n 649,\n/**/\n 648,\n/**/\n 647,\n/**/\n 646,\n/**/\n 645,\n/**/\n 644,\n/**/\n 643,\n/**/\n 642,\n/**/\n 641,\n/**/\n 640,\n/**/\n 639,\n/**/\n 638,\n/**/\n 637,\n/**/\n 636,\n/**/\n 635,\n/**/\n 634,\n/**/\n 633,\n/**/\n 632,\n/**/\n 631,\n/**/\n 630,\n/**/\n 629,\n/**/\n 628,\n/**/\n 627,\n/**/\n 626,\n/**/\n 625,\n/**/\n 624,\n/**/\n 623,\n/**/\n 622,\n/**/\n 621,\n/**/\n 620,\n/**/\n 619,\n/**/\n 618,\n/**/\n 617,\n/**/\n 616,\n/**/\n 615,\n/**/\n 614,\n/**/\n 613,\n/**/\n 612,\n/**/\n 611,\n/**/\n 610,\n/**/\n 609,\n/**/\n 608,\n/**/\n 607,\n/**/\n 606,\n/**/\n 605,\n/**/\n 604,\n/**/\n 603,\n/**/\n 602,\n/**/\n 601,\n/**/\n 600,\n/**/\n 599,\n/**/\n 598,\n/**/\n 597,\n/**/\n 596,\n/**/\n 595,\n/**/\n 594,\n/**/\n 593,\n/**/\n 592,\n/**/\n 591,\n/**/\n 590,\n/**/\n 589,\n/**/\n 588,\n/**/\n 587,\n/**/\n 586,\n/**/\n 585,\n/**/\n 584,\n/**/\n 583,\n/**/\n 582,\n/**/\n 581,\n/**/\n 580,\n/**/\n 579,\n/**/\n 578,\n/**/\n 577,\n/**/\n 576,\n/**/\n 575,\n/**/\n 574,\n/**/\n 573,\n/**/\n 572,\n/**/\n 571,\n/**/\n 570,\n/**/\n 569,\n/**/\n 568,\n/**/\n 567,\n/**/\n 566,\n/**/\n 565,\n/**/\n 564,\n/**/\n 563,\n/**/\n 562,\n/**/\n 561,\n/**/\n 560,\n/**/\n 559,\n/**/\n 558,\n/**/\n 557,\n/**/\n 556,\n/**/\n 555,\n/**/\n 554,\n/**/\n 553,\n/**/\n 552,\n/**/\n 551,\n/**/\n 550,\n/**/\n 549,\n/**/\n 548,\n/**/\n 547,\n/**/\n 546,\n/**/\n 545,\n/**/\n 544,\n/**/\n 543,\n/**/\n 542,\n/**/\n 541,\n/**/\n 540,\n/**/\n 539,\n/**/\n 538,\n/**/\n 537,\n/**/\n 536,\n/**/\n 535,\n/**/\n 534,\n/**/\n 533,\n/**/\n 532,\n/**/\n 531,\n/**/\n 530,\n/**/\n 529,\n/**/\n 528,\n/**/\n 527,\n/**/\n 526,\n/**/\n 525,\n/**/\n 524,\n/**/\n 523,\n/**/\n 522,\n/**/\n 521,\n/**/\n 520,\n/**/\n 519,\n/**/\n 518,\n/**/\n 517,\n/**/\n 516,\n/**/\n 515,\n/**/\n 514,\n/**/\n 513,\n/**/\n 512,\n/**/\n 511,\n/**/\n 510,\n/**/\n 509,\n/**/\n 508,\n/**/\n 507,\n/**/\n 506,\n/**/\n 505,\n/**/\n 504,\n/**/\n 503,\n/**/\n 502,\n/**/\n 501,\n/**/\n 500,\n/**/\n 499,\n/**/\n 498,\n/**/\n 497,\n/**/\n 496,\n/**/\n 495,\n/**/\n 494,\n/**/\n 493,\n/**/\n 492,\n/**/\n 491,\n/**/\n 490,\n/**/\n 489,\n/**/\n 488,\n/**/\n 487,\n/**/\n 486,\n/**/\n 485,\n/**/\n 484,\n/**/\n 483,\n/**/\n 482,\n/**/\n 481,\n/**/\n 480,\n/**/\n 479,\n/**/\n 478,\n/**/\n 477,\n/**/\n 476,\n/**/\n 475,\n/**/\n 474,\n/**/\n 473,\n/**/\n 472,\n/**/\n 471,\n/**/\n 470,\n/**/\n 469,\n/**/\n 468,\n/**/\n 467,\n/**/\n 466,\n/**/\n 465,\n/**/\n 464,\n/**/\n 463,\n/**/\n 462,\n/**/\n 461,\n/**/\n 460,\n/**/\n 459,\n/**/\n 458,\n/**/\n 457,\n/**/\n 456,\n/**/\n 455,\n/**/\n 454,\n/**/\n 453,\n/**/\n 452,\n/**/\n 451,\n/**/\n 450,\n/**/\n 449,\n/**/\n 448,\n/**/\n 447,\n/**/\n 446,\n/**/\n 445,\n/**/\n 444,\n/**/\n 443,\n/**/\n 442,\n/**/\n 441,\n/**/\n 440,\n/**/\n 439,\n/**/\n 438,\n/**/\n 437,\n/**/\n 436,\n/**/\n 435,\n/**/\n 434,\n/**/\n 433,\n/**/\n 432,\n/**/\n 431,\n/**/\n 430,\n/**/\n 429,\n/**/\n 428,\n/**/\n 427,\n/**/\n 426,\n/**/\n 425,\n/**/\n 424,\n/**/\n 423,\n/**/\n 422,\n/**/\n 421,\n/**/\n 420,\n/**/\n 419,\n/**/\n 418,\n/**/\n 417,\n/**/\n 416,\n/**/\n 415,\n/**/\n 414,\n/**/\n 413,\n/**/\n 412,\n/**/\n 411,\n/**/\n 410,\n/**/\n 409,\n/**/\n 408,\n/**/\n 407,\n/**/\n 406,\n/**/\n 405,\n/**/\n 404,\n/**/\n 403,\n/**/\n 402,\n/**/\n 401,\n/**/\n 400,\n/**/\n 399,\n/**/\n 398,\n/**/\n 397,\n/**/\n 396,\n/**/\n 395,\n/**/\n 394,\n/**/\n 393,\n/**/\n 392,\n/**/\n 391,\n/**/\n 390,\n/**/\n 389,\n/**/\n 388,\n/**/\n 387,\n/**/\n 386,\n/**/\n 385,\n/**/\n 384,\n/**/\n 383,\n/**/\n 382,\n/**/\n 381,\n/**/\n 380,\n/**/\n 379,\n/**/\n 378,\n/**/\n 377,\n/**/\n 376,\n/**/\n 375,\n/**/\n 374,\n/**/\n 373,\n/**/\n 372,\n/**/\n 371,\n/**/\n 370,\n/**/\n 369,\n/**/\n 368,\n/**/\n 367,\n/**/\n 366,\n/**/\n 365,\n/**/\n 364,\n/**/\n 363,\n/**/\n 362,\n/**/\n 361,\n/**/\n 360,\n/**/\n 359,\n/**/\n 358,\n/**/\n 357,\n/**/\n 356,\n/**/\n 355,\n/**/\n 354,\n/**/\n 353,\n/**/\n 352,\n/**/\n 351,\n/**/\n 350,\n/**/\n 349,\n/**/\n 348,\n/**/\n 347,\n/**/\n 346,\n/**/\n 345,\n/**/\n 344,\n/**/\n 343,\n/**/\n 342,\n/**/\n 341,\n/**/\n 340,\n/**/\n 339,\n/**/\n 338,\n/**/\n 337,\n/**/\n 336,\n/**/\n 335,\n/**/\n 334,\n/**/\n 333,\n/**/\n 332,\n/**/\n 331,\n/**/\n 330,\n/**/\n 329,\n/**/\n 328,\n/**/\n 327,\n/**/\n 326,\n/**/\n 325,\n/**/\n 324,\n/**/\n 323,\n/**/\n 322,\n/**/\n 321,\n/**/\n 320,\n/**/\n 319,\n/**/\n 318,\n/**/\n 317,\n/**/\n 316,\n/**/\n 315,\n/**/\n 314,\n/**/\n 313,\n/**/\n 312,\n/**/\n 311,\n/**/\n 310,\n/**/\n 309,\n/**/\n 308,\n/**/\n 307,\n/**/\n 306,\n/**/\n 305,\n/**/\n 304,\n/**/\n 303,\n/**/\n 302,\n/**/\n 301,\n/**/\n 300,\n/**/\n 299,\n/**/\n 298,\n/**/\n 297,\n/**/\n 296,\n/**/\n 295,\n/**/\n 294,\n/**/\n 293,\n/**/\n 292,\n/**/\n 291,\n/**/\n 290,\n/**/\n 289,\n/**/\n 288,\n/**/\n 287,\n/**/\n 286,\n/**/\n 285,\n/**/\n 284,\n/**/\n 283,\n/**/\n 282,\n/**/\n 281,\n/**/\n 280,\n/**/\n 279,\n/**/\n 278,\n/**/\n 277,\n/**/\n 276,\n/**/\n 275,\n/**/\n 274,\n/**/\n 273,\n/**/\n 272,\n/**/\n 271,\n/**/\n 270,\n/**/\n 269,\n/**/\n 268,\n/**/\n 267,\n/**/\n 266,\n/**/\n 265,\n/**/\n 264,\n/**/\n 263,\n/**/\n 262,\n/**/\n 261,\n/**/\n 260,\n/**/\n 259,\n/**/\n 258,\n/**/\n 257,\n/**/\n 256,\n/**/\n 255,\n/**/\n 254,\n/**/\n 253,\n/**/\n 252,\n/**/\n 251,\n/**/\n 250,\n/**/\n 249,\n/**/\n 248,\n/**/\n 247,\n/**/\n 246,\n/**/\n 245,\n/**/\n 244,\n/**/\n 243,\n/**/\n 242,\n/**/\n 241,\n/**/\n 240,\n/**/\n 239,\n/**/\n 238,\n/**/\n 237,\n/**/\n 236,\n/**/\n 235,\n/**/\n 234,\n/**/\n 233,\n/**/\n 232,\n/**/\n 231,\n/**/\n 230,\n/**/\n 229,\n/**/\n 228,\n/**/\n 227,\n/**/\n 226,\n/**/\n 225,\n/**/\n 224,\n/**/\n 223,\n/**/\n 222,\n/**/\n 221,\n/**/\n 220,\n/**/\n 219,\n/**/\n 218,\n/**/\n 217,\n/**/\n 216,\n/**/\n 215,\n/**/\n 214,\n/**/\n 213,\n/**/\n 212,\n/**/\n 211,\n/**/\n 210,\n/**/\n 209,\n/**/\n 208,\n/**/\n 207,\n/**/\n 206,\n/**/\n 205,\n/**/\n 204,\n/**/\n 203,\n/**/\n 202,\n/**/\n 201,\n/**/\n 200,\n/**/\n 199,\n/**/\n 198,\n/**/\n 197,\n/**/\n 196,\n/**/\n 195,\n/**/\n 194,\n/**/\n 193,\n/**/\n 192,\n/**/\n 191,\n/**/\n 190,\n/**/\n 189,\n/**/\n 188,\n/**/\n 187,\n/**/\n 186,\n/**/\n 185,\n/**/\n 184,\n/**/\n 183,\n/**/\n 182,\n/**/\n 181,\n/**/\n 180,\n/**/\n 179,\n/**/\n 178,\n/**/\n 177,\n/**/\n 176,\n/**/\n 175,\n/**/\n 174,\n/**/\n 173,\n/**/\n 172,\n/**/\n 171,\n/**/\n 170,\n/**/\n 169,\n/**/\n 168,\n/**/\n 167,\n/**/\n 166,\n/**/\n 165,\n/**/\n 164,\n/**/\n 163,\n/**/\n 162,\n/**/\n 161,\n/**/\n 160,\n/**/\n 159,\n/**/\n 158,\n/**/\n 157,\n/**/\n 156,\n/**/\n 155,\n/**/\n 154,\n/**/\n 153,\n/**/\n 152,\n/**/\n 151,\n/**/\n 150,\n/**/\n 149,\n/**/\n 148,\n/**/\n 147,\n/**/\n 146,\n/**/\n 145,\n/**/\n 144,\n/**/\n 143,\n/**/\n 142,\n/**/\n 141,\n/**/\n 140,\n/**/\n 139,\n/**/\n 138,\n/**/\n 137,\n/**/\n 136,\n/**/\n 135,\n/**/\n 134,\n/**/\n 133,\n/**/\n 132,\n/**/\n 131,\n/**/\n 130,\n/**/\n 129,\n/**/\n 128,\n/**/\n 127,\n/**/\n 126,\n/**/\n 125,\n/**/\n 124,\n/**/\n 123,\n/**/\n 122,\n/**/\n 121,\n/**/\n 120,\n/**/\n 119,\n/**/\n 118,\n/**/\n 117,\n/**/\n 116,\n/**/\n 115,\n/**/\n 114,\n/**/\n 113,\n/**/\n 112,\n/**/\n 111,\n/**/\n 110,\n/**/\n 109,\n/**/\n 108,\n/**/\n 107,\n/**/\n 106,\n/**/\n 105,\n/**/\n 104,\n/**/\n 103,\n/**/\n 102,\n/**/\n 101,\n/**/\n 100,\n/**/\n 99,\n/**/\n 98,\n/**/\n 97,\n/**/\n 96,\n/**/\n 95,\n/**/\n 94,\n/**/\n 93,\n/**/\n 92,\n/**/\n 91,\n/**/\n 90,\n/**/\n 89,\n/**/\n 88,\n/**/\n 87,\n/**/\n 86,\n/**/\n 85,\n/**/\n 84,\n/**/\n 83,\n/**/\n 82,\n/**/\n 81,\n/**/\n 80,\n/**/\n 79,\n/**/\n 78,\n/**/\n 77,\n/**/\n 76,\n/**/\n 75,\n/**/\n 74,\n/**/\n 73,\n/**/\n 72,\n/**/\n 71,\n/**/\n 70,\n/**/\n 69,\n/**/\n 68,\n/**/\n 67,\n/**/\n 66,\n/**/\n 65,\n/**/\n 64,\n/**/\n 63,\n/**/\n 62,\n/**/\n 61,\n/**/\n 60,\n/**/\n 59,\n/**/\n 58,\n/**/\n 57,\n/**/\n 56,\n/**/\n 55,\n/**/\n 54,\n/**/\n 53,\n/**/\n 52,\n/**/\n 51,\n/**/\n 50,\n/**/\n 49,\n/**/\n 48,\n/**/\n 47,\n/**/\n 46,\n/**/\n 45,\n/**/\n 44,\n/**/\n 43,\n/**/\n 42,\n/**/\n 41,\n/**/\n 40,\n/**/\n 39,\n/**/\n 38,\n/**/\n 37,\n/**/\n 36,\n/**/\n 35,\n/**/\n 34,\n/**/\n 33,\n/**/\n 32,\n/**/\n 31,\n/**/\n 30,\n/**/\n 29,\n/**/\n 28,\n/**/\n 27,\n/**/\n 26,\n/**/\n 25,\n/**/\n 24,\n/**/\n 23,\n/**/\n 22,\n/**/\n 21,\n/**/\n 20,\n/**/\n 19,\n/**/\n 18,\n/**/\n 17,\n/**/\n 16,\n/**/\n 15,\n/**/\n 14,\n/**/\n 13,\n/**/\n 12,\n/**/\n 11,\n/**/\n 10,\n/**/\n 9,\n/**/\n 8,\n/**/\n 7,\n/**/\n 6,\n/**/\n 5,\n/**/\n 4,\n/**/\n 3,\n/**/\n 2,\n/**/\n 1,\n/**/\n 0\n};", "/*\n * Place to put a short description when adding a feature with a patch.\n * Keep it short, e.g.,: \"relative numbers\", \"persistent undo\".\n * Also add a comment marker to separate the lines.\n * See the official Vim patches for the diff format: It must use a context of\n * one line only. Create it by hand or use \"diff -C2\" and edit the patch.\n */\nstatic char *(extra_patches[]) =\n{ /* Add your patch description below this line */\n/**/\n NULL\n};", " int\nhighest_patch(void)\n{\n // this relies on the highest patch number to be the first entry\n return included_patches[0];\n}", "#if defined(FEAT_EVAL) || defined(PROTO)\n/*\n * Return TRUE if patch \"n\" has been included.\n */\n int\nhas_patch(int n)\n{\n int\t\th, m, l;", " // Perform a binary search.\n l = 0;\n h = (int)ARRAY_LENGTH(included_patches) - 1;\n for (;;)\n {\n\tm = (l + h) / 2;\n\tif (included_patches[m] == n)\n\t return TRUE;\n\tif (l == h)\n\t break;\n\tif (included_patches[m] < n)\n\t h = m;\n\telse\n\t l = m + 1;\n }\n return FALSE;\n}\n#endif", " void\nex_version(exarg_T *eap)\n{\n /*\n * Ignore a \":version 9.99\" command.\n */\n if (*eap->arg == NUL)\n {\n\tmsg_putchar('\\n');\n\tlist_version();\n }\n}", "/*\n * Output a string for the version message. If it's going to wrap, output a\n * newline, unless the message is too long to fit on the screen anyway.\n * When \"wrap\" is TRUE wrap the string in [].\n */\n static void\nversion_msg_wrap(char_u *s, int wrap)\n{\n int\t\tlen = vim_strsize(s) + (wrap ? 2 : 0);", " if (!got_int && len < (int)Columns && msg_col + len >= (int)Columns\n\t\t\t\t\t\t\t\t&& *s != '\\n')\n\tmsg_putchar('\\n');\n if (!got_int)\n {\n\tif (wrap)\n\t msg_puts(\"[\");\n\tmsg_puts((char *)s);\n\tif (wrap)\n\t msg_puts(\"]\");\n }\n}", " static void\nversion_msg(char *s)\n{\n version_msg_wrap((char_u *)s, FALSE);\n}", "/*\n * List all features aligned in columns, dictionary style.\n */\n static void\nlist_features(void)\n{\n list_in_columns((char_u **)features, -1, -1);\n}", "/*\n * List string items nicely aligned in columns.\n * When \"size\" is < 0 then the last entry is marked with NULL.\n * The entry with index \"current\" is inclosed in [].\n */\n void\nlist_in_columns(char_u **items, int size, int current)\n{\n int\t\ti;\n int\t\tncol;\n int\t\tnrow;\n int\t\tcur_row = 1;\n int\t\titem_count = 0;\n int\t\twidth = 0;\n#ifdef FEAT_SYN_HL\n int\t\tuse_highlight = (items == (char_u **)features);\n#endif", " // Find the length of the longest item, use that + 1 as the column\n // width.\n for (i = 0; size < 0 ? items[i] != NULL : i < size; ++i)\n {\n\tint l = vim_strsize(items[i]) + (i == current ? 2 : 0);", "\tif (l > width)\n\t width = l;\n\t++item_count;\n }\n width += 1;", " if (Columns < width)\n {\n\t// Not enough screen columns - show one per line\n\tfor (i = 0; i < item_count; ++i)\n\t{\n\t version_msg_wrap(items[i], i == current);\n\t if (msg_col > 0 && i < item_count - 1)\n\t\tmsg_putchar('\\n');\n\t}\n\treturn;\n }", " // The rightmost column doesn't need a separator.\n // Sacrifice it to fit in one more column if possible.\n ncol = (int) (Columns + 1) / width;\n nrow = item_count / ncol + ((item_count % ncol) ? 1 : 0);", " // \"i\" counts columns then rows. \"idx\" counts rows then columns.\n for (i = 0; !got_int && i < nrow * ncol; ++i)\n {\n\tint idx = (i / ncol) + (i % ncol) * nrow;", "\tif (idx < item_count)\n\t{\n\t int last_col = (i + 1) % ncol == 0;", "\t if (idx == current)\n\t\tmsg_putchar('[');\n#ifdef FEAT_SYN_HL\n\t if (use_highlight && items[idx][0] == '-')\n\t\tmsg_puts_attr((char *)items[idx], HL_ATTR(HLF_W));\n\t else\n#endif\n\t\tmsg_puts((char *)items[idx]);\n\t if (idx == current)\n\t\tmsg_putchar(']');\n\t if (last_col)\n\t {\n\t\tif (msg_col > 0 && cur_row < nrow)\n\t\t msg_putchar('\\n');\n\t\t++cur_row;\n\t }\n\t else\n\t {\n\t\twhile (msg_col % width)\n\t\t msg_putchar(' ');\n\t }\n\t}\n\telse\n\t{\n\t // this row is out of items, thus at the end of the row\n\t if (msg_col > 0)\n\t {\n\t\tif (cur_row < nrow)\n\t\t msg_putchar('\\n');\n\t\t++cur_row;\n\t }\n\t}\n }\n}", " void\nlist_version(void)\n{\n int\t\ti;\n int\t\tfirst;\n char\t*s = \"\";", " /*\n * When adding features here, don't forget to update the list of\n * internal variables in eval.c!\n */\n init_longVersion();\n msg(longVersion);\n#ifdef MSWIN\n# ifdef FEAT_GUI_MSWIN\n# ifdef VIMDLL\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit GUI/console version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit GUI/console version\"));\n# endif\n# else\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit GUI version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit GUI version\"));\n# endif\n# endif\n# ifdef FEAT_OLE\n msg_puts(_(\" with OLE support\"));\n# endif\n# else\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit console version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit console version\"));\n# endif\n# endif\n#endif\n#if defined(MACOS_X)\n# if defined(MACOS_X_DARWIN)\n msg_puts(_(\"\\nmacOS version\"));\n# else\n msg_puts(_(\"\\nmacOS version w/o darwin feat.\"));\n# endif\n# if defined(__arm64__)\n msg_puts(\" - arm64\");\n# elif defined(__x86_64__)\n msg_puts(\" - x86_64\");\n# endif\n#endif", "#ifdef VMS\n msg_puts(_(\"\\nOpenVMS version\"));\n# ifdef HAVE_PATHDEF\n if (*compiled_arch != NUL)\n {\n\tmsg_puts(\" - \");\n\tmsg_puts((char *)compiled_arch);\n }\n# endif", "#endif", " // Print the list of patch numbers if there is at least one.\n // Print a range when patches are consecutive: \"1-10, 12, 15-40, 42-45\"\n if (included_patches[0] != 0)\n {\n\tmsg_puts(_(\"\\nIncluded patches: \"));\n\tfirst = -1;\n\ti = (int)ARRAY_LENGTH(included_patches) - 1;\n\twhile (--i >= 0)\n\t{\n\t if (first < 0)\n\t\tfirst = included_patches[i];\n\t if (i == 0 || included_patches[i - 1] != included_patches[i] + 1)\n\t {\n\t\tmsg_puts(s);\n\t\ts = \", \";\n\t\tmsg_outnum((long)first);\n\t\tif (first != included_patches[i])\n\t\t{\n\t\t msg_puts(\"-\");\n\t\t msg_outnum((long)included_patches[i]);\n\t\t}\n\t\tfirst = -1;\n\t }\n\t}\n }", " // Print the list of extra patch descriptions if there is at least one.\n if (extra_patches[0] != NULL)\n {\n\tmsg_puts(_(\"\\nExtra patches: \"));\n\ts = \"\";\n\tfor (i = 0; extra_patches[i] != NULL; ++i)\n\t{\n\t msg_puts(s);\n\t s = \", \";\n\t msg_puts(extra_patches[i]);\n\t}\n }", "#ifdef MODIFIED_BY\n msg_puts(\"\\n\");\n msg_puts(_(\"Modified by \"));\n msg_puts(MODIFIED_BY);\n#endif", "#ifdef HAVE_PATHDEF\n if (*compiled_user != NUL || *compiled_sys != NUL)\n {\n\tmsg_puts(_(\"\\nCompiled \"));\n\tif (*compiled_user != NUL)\n\t{\n\t msg_puts(_(\"by \"));\n\t msg_puts((char *)compiled_user);\n\t}\n\tif (*compiled_sys != NUL)\n\t{\n\t msg_puts(\"@\");\n\t msg_puts((char *)compiled_sys);\n\t}\n }\n#endif", "#if defined(FEAT_HUGE)\n msg_puts(_(\"\\nHuge version \"));\n#elif defined(FEAT_NORMAL)\n msg_puts(_(\"\\nNormal version \"));\n#else\n msg_puts(_(\"\\nTiny version \"));\n#endif\n#if !defined(FEAT_GUI)\n msg_puts(_(\"without GUI.\"));\n#elif defined(FEAT_GUI_GTK)\n# if defined(USE_GTK3)\n msg_puts(_(\"with GTK3 GUI.\"));\n# elif defined(FEAT_GUI_GNOME)\n msg_puts(_(\"with GTK2-GNOME GUI.\"));\n# else\n msg_puts(_(\"with GTK2 GUI.\"));\n# endif\n#elif defined(FEAT_GUI_MOTIF)\n msg_puts(_(\"with X11-Motif GUI.\"));\n#elif defined(FEAT_GUI_HAIKU)\n msg_puts(_(\"with Haiku GUI.\"));\n#elif defined(FEAT_GUI_PHOTON)\n msg_puts(_(\"with Photon GUI.\"));\n#elif defined(MSWIN)\n msg_puts(_(\"with GUI.\"));\n#endif\n version_msg(_(\" Features included (+) or not (-):\\n\"));", " list_features();\n if (msg_col > 0)\n\tmsg_putchar('\\n');", "#ifdef SYS_VIMRC_FILE\n version_msg(_(\" system vimrc file: \\\"\"));\n version_msg(SYS_VIMRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE\n version_msg(_(\" user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE2\n version_msg(_(\" 2nd user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE2);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE3\n version_msg(_(\" 3rd user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE3);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_EXRC_FILE\n version_msg(_(\" user exrc file: \\\"\"));\n version_msg(USR_EXRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_EXRC_FILE2\n version_msg(_(\" 2nd user exrc file: \\\"\"));\n version_msg(USR_EXRC_FILE2);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef FEAT_GUI\n# ifdef SYS_GVIMRC_FILE\n version_msg(_(\" system gvimrc file: \\\"\"));\n version_msg(SYS_GVIMRC_FILE);\n version_msg(\"\\\"\\n\");\n# endif\n version_msg(_(\" user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE);\n version_msg(\"\\\"\\n\");\n# ifdef USR_GVIMRC_FILE2\n version_msg(_(\"2nd user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE2);\n version_msg(\"\\\"\\n\");\n# endif\n# ifdef USR_GVIMRC_FILE3\n version_msg(_(\"3rd user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE3);\n version_msg(\"\\\"\\n\");\n# endif\n#endif\n version_msg(_(\" defaults file: \\\"\"));\n version_msg(VIM_DEFAULTS_FILE);\n version_msg(\"\\\"\\n\");\n#ifdef FEAT_GUI\n# ifdef SYS_MENU_FILE\n version_msg(_(\" system menu file: \\\"\"));\n version_msg(SYS_MENU_FILE);\n version_msg(\"\\\"\\n\");\n# endif\n#endif\n#ifdef HAVE_PATHDEF\n if (*default_vim_dir != NUL)\n {\n\tversion_msg(_(\" fall-back for $VIM: \\\"\"));\n\tversion_msg((char *)default_vim_dir);\n\tversion_msg(\"\\\"\\n\");\n }\n if (*default_vimruntime_dir != NUL)\n {\n\tversion_msg(_(\" f-b for $VIMRUNTIME: \\\"\"));\n\tversion_msg((char *)default_vimruntime_dir);\n\tversion_msg(\"\\\"\\n\");\n }\n version_msg(_(\"Compilation: \"));\n version_msg((char *)all_cflags);\n version_msg(\"\\n\");\n#ifdef VMS\n if (*compiler_version != NUL)\n {\n\tversion_msg(_(\"Compiler: \"));\n\tversion_msg((char *)compiler_version);\n\tversion_msg(\"\\n\");\n }\n#endif\n version_msg(_(\"Linking: \"));\n version_msg((char *)all_lflags);\n#endif\n#ifdef DEBUG\n version_msg(\"\\n\");\n version_msg(_(\" DEBUG BUILD\"));\n#endif\n}", "static void do_intro_line(int row, char_u *mesg, int add_version, int attr);\nstatic void intro_message(int colon);", "/*\n * Show the intro message when not editing a file.\n */\n void\nmaybe_intro_message(void)\n{\n if (BUFEMPTY()\n\t && curbuf->b_fname == NULL\n\t && firstwin->w_next == NULL\n\t && vim_strchr(p_shm, SHM_INTRO) == NULL)\n\tintro_message(FALSE);\n}", "/*\n * Give an introductory message about Vim.\n * Only used when starting Vim on an empty file, without a file name.\n * Or with the \":intro\" command (for Sven :-).\n */\n static void\nintro_message(\n int\t\tcolon)\t\t// TRUE for \":intro\"\n{\n int\t\ti;\n int\t\trow;\n int\t\tblanklines;\n int\t\tsponsor;\n char\t*p;\n static char\t*(lines[]) =\n {\n\tN_(\"VIM - Vi IMproved\"),\n\t\"\",\n\tN_(\"version \"),\n\tN_(\"by Bram Moolenaar et al.\"),\n#ifdef MODIFIED_BY\n\t\" \",\n#endif\n\tN_(\"Vim is open source and freely distributable\"),\n\t\"\",\n\tN_(\"Help poor children in Uganda!\"),\n\tN_(\"type :help iccf<Enter> for information \"),\n\t\"\",\n\tN_(\"type :q<Enter> to exit \"),\n\tN_(\"type :help<Enter> or <F1> for on-line help\"),\n\tN_(\"type :help version9<Enter> for version info\"),\n\tNULL,\n\t\"\",\n\tN_(\"Running in Vi compatible mode\"),\n\tN_(\"type :set nocp<Enter> for Vim defaults\"),\n\tN_(\"type :help cp-default<Enter> for info on this\"),\n };\n#ifdef FEAT_GUI\n static char\t*(gui_lines[]) =\n {\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n#ifdef MODIFIED_BY\n\tNULL,\n#endif\n\tNULL,\n\tNULL,\n\tNULL,\n\tN_(\"menu Help->Orphans for information \"),\n\tNULL,\n\tN_(\"Running modeless, typed text is inserted\"),\n\tN_(\"menu Edit->Global Settings->Toggle Insert Mode \"),\n\tN_(\" for two modes \"),\n\tNULL,\n\tNULL,\n\tNULL,\n\tN_(\"menu Edit->Global Settings->Toggle Vi Compatible\"),\n\tN_(\" for Vim defaults \"),\n };\n#endif", " // blanklines = screen height - # message lines\n blanklines = (int)Rows - (ARRAY_LENGTH(lines) - 1);\n if (!p_cp)\n\tblanklines += 4; // add 4 for not showing \"Vi compatible\" message", " // Don't overwrite a statusline. Depends on 'cmdheight'.\n if (p_ls > 1)\n\tblanklines -= Rows - topframe->fr_height;\n if (blanklines < 0)\n\tblanklines = 0;", " // Show the sponsor and register message one out of four times, the Uganda\n // message two out of four times.\n sponsor = (int)time(NULL);\n sponsor = ((sponsor & 2) == 0) - ((sponsor & 4) == 0);", " // start displaying the message lines after half of the blank lines\n row = blanklines / 2;\n if ((row >= 2 && Columns >= 50) || colon)\n {\n\tfor (i = 0; i < (int)ARRAY_LENGTH(lines); ++i)\n\t{\n\t p = lines[i];\n#ifdef FEAT_GUI\n\t if (p_im && gui.in_use && gui_lines[i] != NULL)\n\t\tp = gui_lines[i];\n#endif\n\t if (p == NULL)\n\t {\n\t\tif (!p_cp)\n\t\t break;\n\t\tcontinue;\n\t }\n\t if (sponsor != 0)\n\t {\n\t\tif (strstr(p, \"children\") != NULL)\n\t\t p = sponsor < 0\n\t\t\t? N_(\"Sponsor Vim development!\")\n\t\t\t: N_(\"Become a registered Vim user!\");\n\t\telse if (strstr(p, \"iccf\") != NULL)\n\t\t p = sponsor < 0\n\t\t\t? N_(\"type :help sponsor<Enter> for information \")\n\t\t\t: N_(\"type :help register<Enter> for information \");\n\t\telse if (strstr(p, \"Orphans\") != NULL)\n\t\t p = N_(\"menu Help->Sponsor/Register for information \");\n\t }\n\t if (*p != NUL)\n\t\tdo_intro_line(row, (char_u *)_(p), i == 2, 0);\n\t ++row;\n\t}\n }", " // Make the wait-return message appear just below the text.\n if (colon)\n\tmsg_row = row;\n}", " static void\ndo_intro_line(\n int\t\trow,\n char_u\t*mesg,\n int\t\tadd_version,\n int\t\tattr)\n{\n char_u\tvers[20];\n int\t\tcol;\n char_u\t*p;\n int\t\tl;\n int\t\tclen;\n#ifdef MODIFIED_BY\n# define MODBY_LEN 150\n char_u\tmodby[MODBY_LEN];", " if (*mesg == ' ')\n {\n\tvim_strncpy(modby, (char_u *)_(\"Modified by \"), MODBY_LEN - 1);\n\tl = (int)STRLEN(modby);\n\tvim_strncpy(modby + l, (char_u *)MODIFIED_BY, MODBY_LEN - l - 1);\n\tmesg = modby;\n }\n#endif", " // Center the message horizontally.\n col = vim_strsize(mesg);\n if (add_version)\n {\n\tSTRCPY(vers, mediumVersion);\n\tif (highest_patch())\n\t{\n\t // Check for 9.9x or 9.9xx, alpha/beta version\n\t if (isalpha((int)vers[3]))\n\t {\n\t\tint len = (isalpha((int)vers[4])) ? 5 : 4;\n\t\tsprintf((char *)vers + len, \".%d%s\", highest_patch(),\n\t\t\t\t\t\t\t mediumVersion + len);\n\t }\n\t else\n\t\tsprintf((char *)vers + 3, \".%d\", highest_patch());\n\t}\n\tcol += (int)STRLEN(vers);\n }\n col = (Columns - col) / 2;\n if (col < 0)\n\tcol = 0;", " // Split up in parts to highlight <> items differently.\n for (p = mesg; *p != NUL; p += l)\n {\n\tclen = 0;\n\tfor (l = 0; p[l] != NUL\n\t\t\t && (l == 0 || (p[l] != '<' && p[l - 1] != '>')); ++l)\n\t{\n\t if (has_mbyte)\n\t {\n\t\tclen += ptr2cells(p + l);\n\t\tl += (*mb_ptr2len)(p + l) - 1;\n\t }\n\t else\n\t\tclen += byte2cells(p[l]);\n\t}\n\tscreen_puts_len(p, l, row, col, *p == '<' ? HL_ATTR(HLF_8) : attr);\n\tcol += clen;\n }", " // Add the version number to the version line.\n if (add_version)\n\tscreen_puts(vers, row, col, 0);\n}", "/*\n * \":intro\": clear screen, display intro screen and wait for return.\n */\n void\nex_intro(exarg_T *eap UNUSED)\n{\n screenclear();\n intro_message(TRUE);\n wait_return(TRUE);\n}" ]
[ 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [7314, 1117, 697], "buggy_code_start_loc": [7314, 883, 697], "filenames": ["src/eval.c", "src/testdir/test_substitute.vim", "src/version.c"], "fixing_code_end_loc": [7320, 1134, 700], "fixing_code_start_loc": [7315, 883, 698], "message": "Out-of-bounds Write in GitHub repository vim/vim prior to 9.0.1145.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "7A64F3DA-66B5-4F73-A776-7457E9CBCE52", "versionEndExcluding": "9.0.1145", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Out-of-bounds Write in GitHub repository vim/vim prior to 9.0.1145."}], "evaluatorComment": null, "id": "CVE-2023-0054", "lastModified": "2023-05-03T12:16:43.723", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.3, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-04T19:15:09.573", "references": [{"source": "security@huntr.dev", "tags": null, "url": "http://seclists.org/fulldisclosure/2023/Mar/17"}, {"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/3ac1d97a1d9353490493d30088256360435f7731"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Third Party Advisory"], "url": "https://huntr.dev/bounties/b289ee0f-fd16-4147-bd01-c6289c45e49d"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}, {"source": "security@huntr.dev", "tags": null, "url": "https://support.apple.com/kb/HT213670"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-787"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/3ac1d97a1d9353490493d30088256360435f7731"}, "type": "CWE-787"}
190
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * ---------------------------------------------------------------------\n *\n * GLPI - Gestionnaire Libre de Parc Informatique\n *\n * http://glpi-project.org\n *\n * @copyright 2015-2022 Teclib' and contributors.\n * @copyright 2003-2014 by the INDEPNET Development Team.\n * @licence https://www.gnu.org/licenses/gpl-3.0.html\n *\n * ---------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of GLPI.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <https://www.gnu.org/licenses/>.\n *\n * ---------------------------------------------------------------------\n */", "use Glpi\\Application\\ErrorHandler;\nuse Glpi\\Event;\nuse Glpi\\Plugin\\Hooks;\nuse Glpi\\Toolbox\\Sanitizer;", "/**\n * Identification class used to login\n */\nclass Auth extends CommonGLPI\n{\n /** @var array Array of errors */\n private $errors = [];\n /** @var User User class variable */\n public $user;\n /** @var int External authentication variable */\n public $extauth = 0;\n /** @var array External authentication methods */\n public $authtypes;\n /** @var int Indicates if the user is authenticated or not */\n public $auth_succeded = 0;\n /** @var int Indicates if the user is already present in database */\n public $user_present = 0;\n /** @var int Indicates if the user password expired */\n public $password_expired = false;", " /**\n * Indicated if user was found in the directory.\n * @var boolean\n */\n public $user_found = false;", " /** @var resource|boolean LDAP connection descriptor */\n public $ldap_connection;\n /** @var bool Store user LDAP dn */\n public $user_dn = false;", " const DB_GLPI = 1;\n const MAIL = 2;\n const LDAP = 3;\n const EXTERNAL = 4;\n const CAS = 5;\n const X509 = 6;\n const API = 7;\n const COOKIE = 8;\n const NOT_YET_AUTHENTIFIED = 0;", " const USER_DOESNT_EXIST = 0;\n const USER_EXISTS_WITH_PWD = 1;\n const USER_EXISTS_WITHOUT_PWD = 2;", " /**\n * Constructor\n *\n * @return void\n */\n public function __construct()\n {\n $this->user = new User();\n }", "\n public static function getMenuContent()\n {", " $menu = [];\n if (Config::canUpdate()) {\n $menu['title'] = __('Authentication');\n $menu['page'] = '/front/setup.auth.php';\n $menu['icon'] = self::getIcon();", " $menu['options']['ldap']['icon'] = AuthLDAP::getIcon();\n $menu['options']['ldap']['title'] = AuthLDAP::getTypeName(Session::getPluralNumber());\n $menu['options']['ldap']['page'] = AuthLDAP::getSearchURL(false);\n $menu['options']['ldap']['links']['search'] = AuthLDAP::getSearchURL(false);\n $menu['options']['ldap']['links']['add'] = AuthLDAP::getFormURL(false);", " $menu['options']['imap']['icon'] = AuthMail::getIcon();\n $menu['options']['imap']['title'] = AuthMail::getTypeName(Session::getPluralNumber());\n $menu['options']['imap']['page'] = AuthMail::getSearchURL(false);\n $menu['options']['imap']['links']['search'] = AuthMail::getSearchURL(false);\n $menu['options']['imap']['links']['add'] = AuthMail::getFormURL(false);", " $menu['options']['others']['icon'] = 'ti ti-login';\n $menu['options']['others']['title'] = __('Others');\n $menu['options']['others']['page'] = '/front/auth.others.php';", " $menu['options']['settings']['icon'] = 'ti ti-adjustments';\n $menu['options']['settings']['title'] = __('Setup');\n $menu['options']['settings']['page'] = '/front/auth.settings.php';\n }\n if (count($menu)) {\n return $menu;\n }\n return false;\n }", " /**\n * Check user existence in DB\n *\n * @global DBmysql $DB\n * @param array $options conditions : array('name'=>'glpi')\n * or array('email' => 'test at test.com')\n *\n * @return integer {@link Auth::USER_DOESNT_EXIST}, {@link Auth::USER_EXISTS_WITHOUT_PWD} or {@link Auth::USER_EXISTS_WITH_PWD}\n */\n public function userExists($options = [])\n {\n global $DB;", " $result = $DB->request(\n 'glpi_users',\n ['WHERE' => $options,\n 'LEFT JOIN' => ['glpi_useremails' => ['FKEY' => ['glpi_users' => 'id',\n 'glpi_useremails' => 'users_id'\n ]\n ]\n ]\n ]\n );\n // Check if there is a row\n if ($result->numrows() == 0) {\n $this->addToError(__('Incorrect username or password'));\n return self::USER_DOESNT_EXIST;\n } else {\n // Get the first result...\n $row = $result->current();", " // Check if we have a password...\n if (empty($row['password'])) {\n //If the user has an LDAP DN, then store it in the Auth object\n if ($row['user_dn']) {\n $this->user_dn = $row['user_dn'];\n }\n return self::USER_EXISTS_WITHOUT_PWD;\n }\n return self::USER_EXISTS_WITH_PWD;\n }\n }", " /**\n * Try a IMAP/POP connection\n *\n * @param string $host IMAP/POP host to connect\n * @param string $login Login to try\n * @param string $pass Password to try\n *\n * @return boolean connection success\n */\n public function connection_imap($host, $login, $pass)\n {", " // we prevent some delay...\n if (empty($host)) {\n return false;\n }", " $oldlevel = error_reporting(16);\n // No retry (avoid lock account when password is not correct)\n try {\n $config = Toolbox::parseMailServerConnectString($host);", " $ssl = false;\n if ($config['ssl']) {\n $ssl = 'SSL';\n }\n if ($config['tls']) {\n $ssl = 'TLS';\n }", " $protocol = Toolbox::getMailServerProtocolInstance($config['type']);\n if ($protocol === null) {\n throw new \\RuntimeException(sprintf(__('Unsupported mail server type:%s.'), $config['type']));\n }\n if ($config['validate-cert'] === false) {\n $protocol->setNoValidateCert(true);\n }\n $protocol->connect(\n $config['address'],\n $config['port'],\n $ssl\n );", " return $protocol->login($login, $pass);\n } catch (\\Exception $e) {\n $this->addToError($e->getMessage());\n return false;\n } finally {\n error_reporting($oldlevel);\n }", " return false;\n }", " /**\n * Find a user in a LDAP and return is BaseDN\n * Based on GRR auth system\n *\n * @param string $ldap_method ldap_method array to use\n * @param string $login User Login\n * @param string $password User Password\n *\n * @return string basedn of the user / false if not founded\n */\n public function connection_ldap($ldap_method, $login, $password)\n {", " // we prevent some delay...\n if (empty($ldap_method['host'])) {\n return false;\n }", " $this->ldap_connection = AuthLDAP::tryToConnectToServer($ldap_method, $login, $password);\n $this->user_found = false;", " if ($this->ldap_connection) {\n $params = [\n 'method' => AuthLDAP::IDENTIFIER_LOGIN,\n 'fields' => [\n AuthLDAP::IDENTIFIER_LOGIN => $ldap_method['login_field'],\n ],\n ];\n if (!empty($ldap_method['sync_field'])) {\n $params['fields']['sync_field'] = $ldap_method['sync_field'];\n }\n try {\n $infos = AuthLDAP::searchUserDn($this->ldap_connection, [\n 'basedn' => $ldap_method['basedn'],\n 'login_field' => $ldap_method['login_field'],\n 'search_parameters' => $params,\n 'user_params' => [\n 'method' => AuthLDAP::IDENTIFIER_LOGIN,\n 'value' => $login\n ],\n 'condition' => Sanitizer::unsanitize($ldap_method['condition']),\n 'user_dn' => $this->user_dn\n ]);\n } catch (\\Throwable $e) {\n ErrorHandler::getInstance()->handleException($e, true);\n $this->addToError(__('Unable to connect to the LDAP directory'));\n return false;\n }", " $dn = $infos['dn'];\n $this->user_found = $dn != '';\n if ($this->user_found && @ldap_bind($this->ldap_connection, $dn, $password)) {\n //Hook to implement to restrict access by checking the ldap directory\n if (Plugin::doHookFunction(Hooks::RESTRICT_LDAP_AUTH, $infos)) {\n return $infos;\n }\n $this->addToError(__('User not authorized to connect in GLPI'));\n //Use is present by has no right to connect because of a plugin\n return false;\n } else {\n // Incorrect login\n $this->addToError(__('Incorrect username or password'));\n //Use is not present anymore in the directory!\n return false;\n }\n } else {\n $this->addToError(__('Unable to connect to the LDAP directory'));\n //Directory is not available\n return false;\n }\n }", " /**\n * Check is a password match the stored hash\n *\n * @since 0.85\n *\n * @param string $pass Password (pain-text)\n * @param string $hash Hash\n *\n * @return boolean\n */\n public static function checkPassword($pass, $hash)\n {", " $tmp = password_get_info($hash);", " if (isset($tmp['algo']) && $tmp['algo']) {\n $ok = password_verify($pass, $hash);\n } else if (strlen($hash) == 32) {\n $ok = md5($pass) === $hash;\n } else if (strlen($hash) == 40) {\n $ok = sha1($pass) === $hash;\n } else {\n $salt = substr($hash, 0, 8);\n $ok = ($salt . sha1($salt . $pass) === $hash);\n }", " return $ok;\n }", " /**\n * Is the hash stored need to be regenerated\n *\n * @since 0.85\n *\n * @param string $hash Hash\n *\n * @return boolean\n */\n public static function needRehash($hash)\n {", " return password_needs_rehash($hash, PASSWORD_DEFAULT);\n }", " /**\n * Compute the hash for a password\n *\n * @since 0.85\n *\n * @param string $pass Password\n *\n * @return string\n */\n public static function getPasswordHash($pass)\n {", " return password_hash($pass, PASSWORD_DEFAULT);\n }", " /**\n * Find a user in the GLPI DB\n *\n * try to connect to DB\n * update the instance variable user with the user who has the name $name\n * and the password is $password in the DB.\n * If not found or can't connect to DB updates the instance variable err\n * with an eventual error message\n *\n * @global DBmysql $DB\n * @param string $name User Login\n * @param string $password User Password\n *\n * @return boolean user in GLPI DB with the right password\n */\n public function connection_db($name, $password)\n {\n global $CFG_GLPI, $DB;", " $pass_expiration_delay = (int)$CFG_GLPI['password_expiration_delay'];\n $lock_delay = (int)$CFG_GLPI['password_expiration_lock_delay'];", " // SQL query\n $result = $DB->request(\n [\n 'SELECT' => [\n 'id',\n 'password',\n new QueryExpression(\n sprintf(\n 'ADDDATE(%s, INTERVAL %d DAY) AS ' . $DB->quoteName('password_expiration_date'),\n $DB->quoteName('password_last_update'),\n $pass_expiration_delay\n )\n ),\n new QueryExpression(\n sprintf(\n 'ADDDATE(%s, INTERVAL %d DAY) AS ' . $DB->quoteName('lock_date'),\n $DB->quoteName('password_last_update'),\n $pass_expiration_delay + $lock_delay\n )\n )\n ],\n 'FROM' => User::getTable(),\n 'WHERE' => [\n 'name' => $name,\n 'authtype' => self::DB_GLPI,\n 'auths_id' => 0,\n ]\n ]\n );", " // Have we a result ?\n if ($result->numrows() == 1) {\n $row = $result->current();\n $password_db = $row['password'];", " if (self::checkPassword($password, $password_db)) {\n // Disable account if password expired\n if (\n -1 !== $pass_expiration_delay && -1 !== $lock_delay\n && $row['lock_date'] < $_SESSION['glpi_currenttime']\n ) {\n $user = new User();\n $user->update(\n [\n 'id' => $row['id'],\n 'is_active' => 0,\n ]\n );\n }\n if (\n -1 !== $pass_expiration_delay\n && $row['password_expiration_date'] < $_SESSION['glpi_currenttime']\n ) {\n $this->password_expired = 1;\n }", " // Update password if needed\n if (self::needRehash($password_db)) {\n $input = [\n 'id' => $row['id'],\n ];\n // Set glpiID to allow password update\n $_SESSION['glpiID'] = $input['id'];\n $input['password'] = $password;\n $input['password2'] = $password;\n $user = new User();\n $user->update($input);\n }\n $this->user->getFromDBByCrit(['id' => $row['id']]);\n $this->extauth = 0;\n $this->user_present = 1;\n $this->user->fields[\"authtype\"] = self::DB_GLPI;\n $this->user->fields[\"password\"] = $password;", " // apply rule rights on local user\n $rules = new RuleRightCollection();\n $groups = Group_User::getUserGroups($row['id']);\n $groups_id = array_column($groups, 'id');\n $result = $rules->processAllRules(\n $groups_id,\n $this->user->fields,\n [\n 'type' => Auth::DB_GLPI,\n 'login' => $this->user->fields['name'],\n 'email' => UserEmail::getDefaultForUser($row['id'])\n ]\n );", " $this->user->fields = $result + [\n '_ruleright_process' => true,\n ];", " return true;\n }\n }\n $this->addToError(__('Incorrect username or password'));\n return false;\n }", " /**\n * Try to get login of external auth method\n *\n * @param integer $authtype external auth type (default 0)\n *\n * @return boolean user login success\n */\n public function getAlternateAuthSystemsUserLogin($authtype = 0)\n {\n global $CFG_GLPI;", " switch ($authtype) {\n case self::CAS:\n if (!Toolbox::canUseCAS()) {\n trigger_error(\"CAS lib not installed\", E_USER_WARNING);\n return false;\n }", " phpCAS::client(\n constant($CFG_GLPI[\"cas_version\"]),\n $CFG_GLPI[\"cas_host\"],\n intval($CFG_GLPI[\"cas_port\"]),\n $CFG_GLPI[\"cas_uri\"],\n false\n );", " // no SSL validation for the CAS server\n phpCAS::setNoCasServerValidation();", " // force CAS authentication\n phpCAS::forceAuthentication();\n $this->user->fields['name'] = phpCAS::getUser();", " // extract e-mail information\n if (phpCAS::hasAttribute(\"mail\")) {\n $this->user->fields['_useremails'] = [phpCAS::getAttribute(\"mail\")];\n }", " return true;", " case self::EXTERNAL:\n $ssovariable = Dropdown::getDropdownName(\n 'glpi_ssovariables',\n $CFG_GLPI[\"ssovariables_id\"]\n );\n $login_string = '';\n // MoYo : checking REQUEST create a security hole for me !\n if (isset($_SERVER[$ssovariable])) {\n $login_string = $_SERVER[$ssovariable];\n }\n // else {\n // $login_string = $_REQUEST[$ssovariable];\n // }\n $login = $login_string;\n $pos = stripos($login_string, \"\\\\\");\n if (!$pos === false) {\n $login = substr($login_string, $pos + 1);\n }\n if ($CFG_GLPI['existing_auth_server_field_clean_domain']) {\n $pos = stripos($login, \"@\");\n if (!$pos === false) {\n $login = substr($login, 0, $pos);\n }\n }\n if (self::isValidLogin($login)) {\n $this->user->fields['name'] = $login;\n // Get data from SSO if defined\n $ret = $this->user->getFromSSO();\n if (!$ret) {\n return false;\n }\n return true;\n }\n break;", " case self::X509:\n // From eGroupWare http://www.egroupware.org\n // an X.509 subject looks like:\n // CN=john.doe/OU=Department/O=Company/C=xx/Email=john@comapy.tld/L=City/\n $sslattribs = explode('/', $_SERVER['SSL_CLIENT_S_DN']);\n $sslattributes = [];\n while ($sslattrib = next($sslattribs)) {\n list($key,$val) = explode('=', $sslattrib);\n $sslattributes[$key] = $val;\n }\n if (\n isset($sslattributes[$CFG_GLPI[\"x509_email_field\"]])\n && NotificationMailing::isUserAddressValid($sslattributes[$CFG_GLPI[\"x509_email_field\"]])\n && self::isValidLogin($sslattributes[$CFG_GLPI[\"x509_email_field\"]])\n ) {\n $restrict = false;\n $CFG_GLPI[\"x509_ou_restrict\"] = trim($CFG_GLPI[\"x509_ou_restrict\"]);\n if (!empty($CFG_GLPI[\"x509_ou_restrict\"])) {\n $split = explode('$', $CFG_GLPI[\"x509_ou_restrict\"]);", " if (!in_array($sslattributes['OU'], $split)) {\n $restrict = true;\n }\n }\n $CFG_GLPI[\"x509_o_restrict\"] = trim($CFG_GLPI[\"x509_o_restrict\"]);\n if (!empty($CFG_GLPI[\"x509_o_restrict\"])) {\n $split = explode('$', $CFG_GLPI[\"x509_o_restrict\"]);", " if (!in_array($sslattributes['O'], $split)) {\n $restrict = true;\n }\n }\n $CFG_GLPI[\"x509_cn_restrict\"] = trim($CFG_GLPI[\"x509_cn_restrict\"]);\n if (!empty($CFG_GLPI[\"x509_cn_restrict\"])) {\n $split = explode('$', $CFG_GLPI[\"x509_cn_restrict\"]);", " if (!in_array($sslattributes['CN'], $split)) {\n $restrict = true;\n }\n }", " if (!$restrict) {\n $this->user->fields['name'] = $sslattributes[$CFG_GLPI[\"x509_email_field\"]];", " // Can do other things if need : only add it here\n $this->user->fields['email'] = $this->user->fields['name'];\n return true;\n }\n }\n break;", " case self::API:\n if ($CFG_GLPI['enable_api_login_external_token']) {\n $user = new User();\n if ($user->getFromDBbyToken($_REQUEST['user_token'], 'api_token')) {\n $this->user->fields['name'] = $user->fields['name'];\n return true;\n }\n } else {\n $this->addToError(__(\"Login with external token disabled\"));\n }\n break;\n case self::COOKIE:\n $cookie_name = session_name() . '_rememberme';", " if ($CFG_GLPI[\"login_remember_time\"]) {\n $data = json_decode($_COOKIE[$cookie_name], true);\n if (count($data) === 2) {\n list ($cookie_id, $cookie_token) = $data;", " $user = new User();\n $user->getFromDB($cookie_id);\n $hash = $user->getAuthToken('cookie_token');", " if (Auth::checkPassword($cookie_token, $hash)) {\n $this->user->fields['name'] = $user->fields['name'];\n return true;\n } else {\n $this->addToError(__(\"Invalid cookie data\"));\n }\n }\n } else {\n $this->addToError(__(\"Auto login disabled\"));\n }", " //Remove cookie to allow new login\n Auth::setRememberMeCookie('');\n break;\n }\n return false;\n }", " /**\n * Get the current identification error\n *\n * @return string current identification error\n */\n public function getErr()\n {\n return implode(\"<br>\\n\", $this->getErrors());\n }", " /**\n * Get errors\n *\n * @since 9.4\n *\n * @return array\n */\n public function getErrors()\n {\n return $this->errors;\n }", " /**\n * Get the current user object\n *\n * @return object current user\n */\n public function getUser()\n {\n return $this->user;\n }", " /**\n * Get all the authentication methods parameters\n * and return it as an array\n *\n * @return void\n */\n public function getAuthMethods()\n {", " //Return all the authentication methods in an array\n $this->authtypes = [\n 'ldap' => getAllDataFromTable('glpi_authldaps'),\n 'mail' => getAllDataFromTable('glpi_authmails')\n ];\n }", " /**\n * Add a message to the global identification error message\n *\n * @param string $message the message to add\n *\n * @return void\n */\n public function addToError($message)\n {\n if (!in_array($message, $this->errors)) {\n $this->errors[] = $message;\n }\n }", " /**\n * Manage use authentication and initialize the session\n *\n * @param string $login_name Login\n * @param string $login_password Password\n * @param boolean $noauto (false by default)\n * @param bool $remember_me\n * @param string $login_auth Type of auth - id of the auth\n *\n * @return boolean (success)\n */\n public function login($login_name, $login_password, $noauto = false, $remember_me = false, $login_auth = '')\n {\n global $DB, $CFG_GLPI;", " $this->getAuthMethods();\n $this->user_present = 1;\n $this->auth_succeded = false;\n //In case the user was deleted in the LDAP directory\n $user_deleted_ldap = false;", " // Trim login_name : avoid LDAP search errors\n $login_name = trim($login_name);", " // manage the $login_auth (force the auth source of the user account)\n $this->user->fields[\"auths_id\"] = 0;\n if ($login_auth == 'local') {\n $authtype = self::DB_GLPI;\n $this->user->fields[\"authtype\"] = self::DB_GLPI;", " } else if (strstr($login_auth, '-')) {\n $auths = explode('-', $login_auth);\n $this->user->fields[\"auths_id\"] = $auths[1];\n if ($auths[0] == 'ldap') {", " $authtype = self::LDAP;", " $this->user->fields[\"authtype\"] = self::LDAP;\n } else if ($auths[0] == 'mail') {", " $authtype = self::MAIL;", " $this->user->fields[\"authtype\"] = self::MAIL;\n } else if ($auths[0] == 'external') {", " $authtype = self::EXTERNAL;", " $this->user->fields[\"authtype\"] = self::EXTERNAL;\n }", " }\n if (!$noauto && ($authtype = self::checkAlternateAuthSystems())) {\n if (\n $this->getAlternateAuthSystemsUserLogin($authtype)\n && !empty($this->user->fields['name'])\n ) {\n // Used for log when login process failed\n $login_name = $this->user->fields['name'];\n $this->auth_succeded = true;\n $this->user_present = $this->user->getFromDBbyName(addslashes($login_name));\n $this->extauth = 1;\n $user_dn = false;", " if (array_key_exists('_useremails', $this->user->fields)) {\n $email = $this->user->fields['_useremails'];\n }", " $ldapservers = [];\n //if LDAP enabled too, get user's infos from LDAP\n if (Toolbox::canUseLdap()) {\n //User has already authenticate, at least once : it's ldap server if filled\n if (\n isset($this->user->fields[\"auths_id\"])\n && ($this->user->fields[\"auths_id\"] > 0)\n ) {\n $authldap = new AuthLDAP();\n //If ldap server is enabled\n if (\n $authldap->getFromDB($this->user->fields[\"auths_id\"])\n && $authldap->fields['is_active']\n ) {\n $ldapservers[] = $authldap->fields;\n }\n } else { // User has never been authenticated : try all active ldap server to find the right one\n foreach (getAllDataFromTable('glpi_authldaps', ['is_active' => 1]) as $ldap_config) {\n $ldapservers[] = $ldap_config;\n }\n }", " $ldapservers_status = false;\n foreach ($ldapservers as $ldap_method) {\n $ds = AuthLDAP::connectToServer(\n $ldap_method[\"host\"],\n $ldap_method[\"port\"],\n $ldap_method[\"rootdn\"],\n (new GLPIKey())->decrypt($ldap_method[\"rootdn_passwd\"]),\n $ldap_method[\"use_tls\"],\n $ldap_method[\"deref_option\"],\n $ldap_method[\"tls_certfile\"],\n $ldap_method[\"tls_keyfile\"],\n $ldap_method[\"use_bind\"],\n $ldap_method[\"timeout\"]\n );", " if ($ds) {\n $ldapservers_status = true;\n $params = [\n 'method' => AuthLDAP::IDENTIFIER_LOGIN,\n 'fields' => [\n AuthLDAP::IDENTIFIER_LOGIN => $ldap_method[\"login_field\"],\n ],\n ];\n try {\n $user_dn = AuthLDAP::searchUserDn($ds, [\n 'basedn' => $ldap_method[\"basedn\"],\n 'login_field' => $ldap_method['login_field'],\n 'search_parameters' => $params,\n 'condition' => $ldap_method[\"condition\"],\n 'user_params' => [\n 'method' => AuthLDAP::IDENTIFIER_LOGIN,\n 'value' => $login_name\n ],\n ]);\n } catch (\\RuntimeException $e) {\n ErrorHandler::getInstance()->handleException($e, true);\n $user_dn = false;\n }\n if ($user_dn) {\n $this->user_found = true;\n $this->user->fields['auths_id'] = $ldap_method['id'];\n $this->user->getFromLDAP(\n $ds,\n $ldap_method,\n $user_dn['dn'],\n $login_name,\n !$this->user_present\n );\n break;\n }\n }\n }\n }\n if (\n (count($ldapservers) == 0)\n && ($authtype == self::EXTERNAL)\n ) {\n // Case of using external auth and no LDAP servers, so get data from external auth\n $this->user->getFromSSO();\n } else {\n if ($this->user->fields['authtype'] == self::LDAP) {\n if (!$ldapservers_status) {\n $this->auth_succeded = false;\n $this->addToError(_n(\n 'Connection to LDAP directory failed',\n 'Connection to LDAP directories failed',\n count($ldapservers)\n ));\n } else if (!$user_dn && $this->user_present) {\n //If user is set as present in GLPI but no LDAP DN found : it means that the user\n //is not present in an ldap directory anymore\n $user_deleted_ldap = true;\n $this->addToError(_n(\n 'User not found in LDAP directory',\n 'User not found in LDAP directories',\n count($ldapservers)\n ));\n }\n }\n }\n // Reset to secure it\n $this->user->fields['name'] = $login_name;\n $this->user->fields[\"last_login\"] = $_SESSION[\"glpi_currenttime\"];\n } else {\n $this->addToError(__('Empty login or password'));\n }\n }", " if (!$this->auth_succeded) {\n if (\n empty($login_name) || strstr($login_name, \"\\0\")\n || empty($login_password) || strstr($login_password, \"\\0\")\n ) {\n $this->addToError(__('Empty login or password'));\n } else {\n // Try connect local user if not yet authenticated\n if (\n empty($login_auth)\n || $this->user->fields[\"authtype\"] == $this::DB_GLPI\n ) {\n $this->auth_succeded = $this->connection_db(\n addslashes($login_name),\n $login_password\n );\n }", " // Try to connect LDAP user if not yet authenticated\n if (!$this->auth_succeded) {\n if (\n empty($login_auth)\n || $this->user->fields[\"authtype\"] == $this::CAS\n || $this->user->fields[\"authtype\"] == $this::EXTERNAL\n || $this->user->fields[\"authtype\"] == $this::LDAP\n ) {\n if (Toolbox::canUseLdap()) {\n AuthLDAP::tryLdapAuth(\n $this,\n $login_name,\n $login_password,\n $this->user->fields[\"auths_id\"]\n );\n if ($this->ldap_connection !== false && (!$this->auth_succeded && !$this->user_found)) {\n $search_params = [\n 'name' => addslashes($login_name),\n 'authtype' => $this::LDAP\n ];\n if (!empty($login_auth)) {\n $search_params['auths_id'] = $this->user->fields[\"auths_id\"];\n }\n if ($this->user->getFromDBByCrit($search_params)) {\n $user_deleted_ldap = true;\n };\n }\n }\n }\n }", " // Try connect MAIL server if not yet authenticated\n if (!$this->auth_succeded) {\n if (\n empty($login_auth)\n || $this->user->fields[\"authtype\"] == $this::MAIL\n ) {\n AuthMail::tryMailAuth(\n $this,\n $login_name,\n $login_password,\n $this->user->fields[\"auths_id\"]\n );\n }\n }\n }\n }", " if ($user_deleted_ldap) {\n User::manageDeletedUserInLdap($this->user->fields[\"id\"]);\n $this->auth_succeded = false;\n }\n // Ok, we have gathered sufficient data, if the first return false the user\n // is not present on the DB, so we add him.\n // if not, we update him.\n if ($this->auth_succeded) {\n //Set user an not deleted from LDAP\n $this->user->fields['is_deleted_ldap'] = 0;", " // Prepare data\n $this->user->fields[\"last_login\"] = $_SESSION[\"glpi_currenttime\"];\n if ($this->extauth) {\n $this->user->fields[\"_extauth\"] = 1;\n }", " if ($DB->isSlave()) {\n if (!$this->user_present) { // Can't add in slave mode\n $this->addToError(__('User not authorized to connect in GLPI'));\n $this->auth_succeded = false;\n }\n } else {\n if ($this->user_present) {\n // Add the user e-mail if present\n if (isset($email)) {\n $this->user->fields['_useremails'] = $email;\n }\n $this->user->update(Sanitizer::sanitize($this->user->fields));\n } else if ($CFG_GLPI[\"is_users_auto_add\"]) {\n // Auto add user\n $input = $this->user->fields;\n unset($this->user->fields);\n if ($authtype == self::EXTERNAL && !isset($input[\"authtype\"])) {\n $input[\"authtype\"] = $authtype;\n }\n $this->user->add(Sanitizer::sanitize($input));\n } else {\n // Auto add not enable so auth failed\n $this->addToError(__('User not authorized to connect in GLPI'));\n $this->auth_succeded = false;\n }\n }\n }", " // Log Event (if possible)\n if (!$DB->isSlave()) {\n // GET THE IP OF THE CLIENT\n $ip = getenv(\"HTTP_X_FORWARDED_FOR\") ?\n Sanitizer::encodeHtmlSpecialChars(getenv(\"HTTP_X_FORWARDED_FOR\")) :\n getenv(\"REMOTE_ADDR\");", " if ($this->auth_succeded) {\n if (GLPI_DEMO_MODE) {\n // not translation in GLPI_DEMO_MODE\n Event::log(0, \"system\", 3, \"login\", $login_name . \" log in from \" . $ip);\n } else {\n //TRANS: %1$s is the login of the user and %2$s its IP address\n Event::log(0, \"system\", 3, \"login\", sprintf(\n __('%1$s log in from IP %2$s'),\n $login_name,\n $ip\n ));\n }\n } else {\n if (GLPI_DEMO_MODE) {\n Event::log(\n 0,\n \"system\",\n 3,\n \"login\",\n \"login\",\n \"Connection failed for \" . $login_name . \" ($ip)\"\n );\n } else {\n //TRANS: %1$s is the login of the user and %2$s its IP address\n Event::log(0, \"system\", 3, \"login\", sprintf(\n __('Failed login for %1$s from IP %2$s'),\n $login_name,\n $ip\n ));\n }\n }\n }", " Session::init($this);", " if ($noauto) {\n $_SESSION[\"noAUTO\"] = 1;\n }", " if ($this->auth_succeded && $CFG_GLPI['login_remember_time'] > 0 && $remember_me) {\n $token = $this->user->getAuthToken('cookie_token', true);", " if ($token) {\n $data = json_encode([\n $this->user->fields['id'],\n $token,\n ]);", " //Send cookie to browser\n Auth::setRememberMeCookie($data);\n }\n }", " if ($this->auth_succeded && !empty($this->user->fields['timezone']) && 'null' !== strtolower($this->user->fields['timezone'])) {\n //set user timezone, if any\n $_SESSION['glpi_tz'] = $this->user->fields['timezone'];\n $DB->setTimezone($this->user->fields['timezone']);\n }", " return $this->auth_succeded;\n }", " /**\n * Print all the authentication methods\n *\n * @param array $options Possible options:\n * - name : Name of the select (default is auths_id)\n * - value : Selected value (default 0)\n * - display : If true, the dropdown is displayed instead of returned (default true)\n * - display_emptychoice : If true, an empty option is added (default true)\n * - hide_if_no_elements : boolean / hide dropdown if there is no elements (default false)\n *\n * @return void|string (Based on 'display' option)\n */\n public static function dropdown($options = [])\n {\n global $DB;", " $p = [\n 'name' => 'auths_id',\n 'value' => 0,\n 'display' => true,\n 'display_emptychoice' => true,\n 'hide_if_no_elements' => false,\n ];", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $p[$key] = $val;\n }\n }", " $methods = [\n self::DB_GLPI => __('Authentication on GLPI database'),\n ];", " $result = $DB->request([\n 'FROM' => 'glpi_authldaps',\n 'COUNT' => 'cpt',\n 'WHERE' => [\n 'is_active' => 1\n ]\n ])->current();", " if ($result['cpt'] > 0) {\n $methods[self::LDAP] = __('Authentication on a LDAP directory');\n $methods[self::EXTERNAL] = __('External authentications');\n }", " $result = $DB->request([\n 'FROM' => 'glpi_authmails',\n 'COUNT' => 'cpt',\n 'WHERE' => [\n 'is_active' => 1\n ]\n ])->current();", " if ($result['cpt'] > 0) {\n $methods[self::MAIL] = __('Authentication on mail server');\n }", " return Dropdown::showFromArray($p['name'], $methods, $p);\n }", " /**\n * Builds CAS versions dropdown\n * @param string $value (default 'CAS_VERSION_2_0')\n *\n * @return string\n */\n public static function dropdownCasVersion($value = 'CAS_VERSION_2_0')\n {\n $options['CAS_VERSION_1_0'] = __('Version 1');\n $options['CAS_VERSION_2_0'] = __('Version 2');\n $options['CAS_VERSION_3_0'] = __('Version 3+');\n return Dropdown::showFromArray('cas_version', $options, ['value' => $value]);\n }", " /**\n * Get name of an authentication method\n *\n * @param integer $authtype Authentication method\n * @param integer $auths_id Authentication method ID\n * @param integer $link show links to config page? (default 0)\n * @param string $name override the name if not empty (default '')\n *\n * @return string\n */\n public static function getMethodName($authtype, $auths_id, $link = 0, $name = '')\n {", " switch ($authtype) {\n case self::LDAP:\n $auth = new AuthLDAP();\n if ($auth->getFromDB($auths_id)) {\n //TRANS: %1$s is the auth method type, %2$s the auth method name or link\n return sprintf(__('%1$s: %2$s'), AuthLDAP::getTypeName(1), $auth->getLink());\n }\n return sprintf(__('%1$s: %2$s'), AuthLDAP::getTypeName(1), $name);", " case self::MAIL:\n $auth = new AuthMail();\n if ($auth->getFromDB($auths_id)) {\n //TRANS: %1$s is the auth method type, %2$s the auth method name or link\n return sprintf(__('%1$s: %2$s'), AuthLDAP::getTypeName(1), $auth->getLink());\n }\n return sprintf(__('%1$s: %2$s'), __('Email server'), $name);", " case self::CAS:\n if ($auths_id > 0) {\n $auth = new AuthLDAP();\n if ($auth->getFromDB($auths_id)) {\n return sprintf(\n __('%1$s: %2$s'),\n sprintf(\n __('%1$s + %2$s'),\n __('CAS'),\n AuthLDAP::getTypeName(1)\n ),\n $auth->getLink()\n );\n }\n }\n return __('CAS');", " case self::X509:\n if ($auths_id > 0) {\n $auth = new AuthLDAP();\n if ($auth->getFromDB($auths_id)) {\n return sprintf(\n __('%1$s: %2$s'),\n sprintf(\n __('%1$s + %2$s'),\n __('x509 certificate authentication'),\n AuthLDAP::getTypeName(1)\n ),\n $auth->getLink()\n );\n }\n }\n return __('x509 certificate authentication');", " case self::EXTERNAL:\n if ($auths_id > 0) {\n $auth = new AuthLDAP();\n if ($auth->getFromDB($auths_id)) {\n return sprintf(\n __('%1$s: %2$s'),\n sprintf(\n __('%1$s + %2$s'),\n __('Other'),\n AuthLDAP::getTypeName(1)\n ),\n $auth->getLink()\n );\n }\n }\n return __('Other');", " case self::DB_GLPI:\n return __('GLPI internal database');", " case self::API:\n return __(\"API\");", " case self::NOT_YET_AUTHENTIFIED:\n return __('Not yet authenticated');\n }\n return '';\n }", " /**\n * Get all the authentication methods parameters for a specific authtype\n * and auths_id and return it as an array\n *\n * @param integer $authtype Authentication method\n * @param integer $auths_id Authentication method ID\n *\n * @return mixed\n */\n public static function getMethodsByID($authtype, $auths_id)\n {", " switch ($authtype) {\n case self::X509:\n case self::EXTERNAL:\n case self::CAS:\n case self::LDAP:\n $auth = new AuthLDAP();\n if ($auths_id > 0 && $auth->getFromDB($auths_id)) {\n return ($auth->fields);\n }\n break;", " case self::MAIL:\n $auth = new AuthMail();\n if ($auths_id > 0 && $auth->getFromDB($auths_id)) {\n return ($auth->fields);\n }\n break;\n }\n return [];\n }", " /**\n * Is an external authentication used?\n *\n * @return boolean\n */\n public static function useAuthExt()\n {", " global $CFG_GLPI;", " //Get all the ldap directories\n if (AuthLDAP::useAuthLdap()) {\n return true;\n }", " if (AuthMail::useAuthMail()) {\n return true;\n }", " if (!empty($CFG_GLPI[\"x509_email_field\"])) {\n return true;\n }", " // Existing auth method\n if (!empty($CFG_GLPI[\"ssovariables_id\"])) {\n return true;\n }", " // Using CAS server\n if (!empty($CFG_GLPI[\"cas_host\"])) {\n return true;\n }", " // Using API login with personnal token\n if (!empty($_REQUEST['user_token'])) {\n return true;\n }", " return false;\n }", " /**\n * Is an alternate auth?\n *\n * @param integer $authtype auth type\n *\n * @return boolean\n */\n public static function isAlternateAuth($authtype)\n {\n return in_array($authtype, [self::X509, self::CAS, self::EXTERNAL, self::API, self::COOKIE]);\n }", " /**\n * Check alternate authentication systems\n *\n * @param boolean $redirect need to redirect (true) or get type of Auth system which match\n * (false by default)\n * @param string $redirect_string redirect string if exists (default '')\n *\n * @return void|integer nothing if redirect is true, else Auth system ID\n */\n public static function checkAlternateAuthSystems($redirect = false, $redirect_string = '')\n {\n global $CFG_GLPI;", " if (isset($_GET[\"noAUTO\"]) || isset($_POST[\"noAUTO\"])) {\n return false;\n }\n $redir_string = \"\";\n if (!empty($redirect_string)) {\n $redir_string = \"?redirect=\" . $redirect_string;\n }\n // Using x509 server\n if (\n !empty($CFG_GLPI[\"x509_email_field\"])\n && isset($_SERVER['SSL_CLIENT_S_DN'])\n && strstr($_SERVER['SSL_CLIENT_S_DN'], $CFG_GLPI[\"x509_email_field\"])\n ) {\n if ($redirect) {\n Html::redirect($CFG_GLPI[\"root_doc\"] . \"/front/login.php\" . $redir_string);\n } else {\n return self::X509;\n }\n }\n // Existing auth method\n //Look for the field in $_SERVER AND $_REQUEST\n // MoYo : checking REQUEST create a security hole for me !\n $ssovariable = Dropdown::getDropdownName('glpi_ssovariables', $CFG_GLPI[\"ssovariables_id\"]);\n if (\n $CFG_GLPI[\"ssovariables_id\"]\n && ((isset($_SERVER[$ssovariable]) && !empty($_SERVER[$ssovariable]))\n /*|| (isset($_REQUEST[$ssovariable]) && !empty($_REQUEST[$ssovariable]))*/)\n ) {\n if ($redirect) {\n Html::redirect($CFG_GLPI[\"root_doc\"] . \"/front/login.php\" . $redir_string);\n } else {\n return self::EXTERNAL;\n }\n }", " // using user token for api login\n if (!empty($_REQUEST['user_token'])) {\n return self::API;\n }", " // Using CAS server\n if (!empty($CFG_GLPI[\"cas_host\"])) {\n if ($redirect) {\n Html::redirect($CFG_GLPI[\"root_doc\"] . \"/front/login.php\" . $redir_string);\n } else {\n return self::CAS;\n }\n }", " $cookie_name = session_name() . '_rememberme';\n if ($CFG_GLPI[\"login_remember_time\"] && isset($_COOKIE[$cookie_name])) {\n if ($redirect) {\n Html::redirect($CFG_GLPI[\"root_doc\"] . \"/front/login.php\" . $redir_string);\n } else {\n return self::COOKIE;\n }\n }", " return false;\n }", " /**\n * Redirect user to page if authenticated\n *\n * @param string $redirect redirect string if exists, if null, check in $_POST or $_GET\n *\n * @return void|boolean nothing if redirect is true, else false\n */\n public static function redirectIfAuthenticated($redirect = null)\n {\n global $CFG_GLPI;", " if (!Session::getLoginUserID()) {\n return false;\n }", " if (Session::mustChangePassword()) {\n Html::redirect($CFG_GLPI['root_doc'] . '/front/updatepassword.php');\n }", " if (!$redirect) {\n if (isset($_POST['redirect']) && (strlen($_POST['redirect']) > 0)) {\n $redirect = $_POST['redirect'];\n } else if (isset($_GET['redirect']) && strlen($_GET['redirect']) > 0) {\n $redirect = $_GET['redirect'];\n }\n }", " //Direct redirect\n if ($redirect) {\n Toolbox::manageRedirect($redirect);\n }", " // Redirect to Command Central if not post-only\n if (Session::getCurrentInterface() == \"helpdesk\") {\n if ($_SESSION['glpiactiveprofile']['create_ticket_on_login']) {\n Html::redirect($CFG_GLPI['root_doc'] . \"/front/helpdesk.public.php?create_ticket=1\");\n }\n Html::redirect($CFG_GLPI['root_doc'] . \"/front/helpdesk.public.php\");\n } else {\n if ($_SESSION['glpiactiveprofile']['create_ticket_on_login']) {\n Html::redirect(Ticket::getFormURL());\n }\n Html::redirect($CFG_GLPI['root_doc'] . \"/front/central.php\");\n }\n }", " /**\n * Display refresh button in the user page\n *\n * @param User $user User object\n *\n * @return void\n */\n public static function showSynchronizationForm(User $user)\n {\n global $DB, $CFG_GLPI;", " if (Session::haveRight(\"user\", User::UPDATEAUTHENT)) {\n echo \"<form method='post' action='\" . Toolbox::getItemTypeFormURL('User') . \"'>\";\n echo \"<div class='firstbloc'>\";\n echo \"<input type='hidden' name='id' value='\" . $user->getID() . \"'>\";", " switch ($user->getField('authtype')) {\n case self::CAS:\n case self::EXTERNAL:\n case self::X509:\n case self::LDAP:\n //Look it the auth server still exists !\n // <- Bad idea : id not exists unable to change anything\n $authldap = new AuthLDAP();\n if (\n $authldap->getFromDBByCrit([\n 'id' => $user->getField('auths_id'),\n 'is_active' => 1,\n ])\n ) {\n echo Html::submit(\"<i class='fas fa-sync-alt'></i><span>\" . __s('Force synchronization') . \"</span>\", [\n 'name' => 'force_ldap_resynch'\n ]);", " if (strlen($authldap->fields['sync_field']) > 0) {\n echo Html::submit(\"<i class='fas fa-broom'></i><span>\" . __s('Clean LDAP fields and force synchronisation') . \"</span>\", [\n 'name' => 'clean_ldap_fields'\n ]);\n }\n }\n break;", " case self::DB_GLPI:\n case self::MAIL:\n break;\n }", " echo \"</div>\";", " echo \"<div class='spaced'>\";\n echo \"<h3>\" . __('Change of the authentication method') . \"</h3>\";\n $rand = self::dropdown(['name' => 'authtype']);\n $paramsmassaction = ['authtype' => '__VALUE__',\n 'name' => 'change_auth_method'\n ];\n Ajax::updateItemOnSelectEvent(\n \"dropdown_authtype$rand\",\n \"show_massiveaction_field\",\n $CFG_GLPI[\"root_doc\"] . \"/ajax/dropdownMassiveActionAuthMethods.php\",\n $paramsmassaction\n );\n echo \"<span id='show_massiveaction_field'></span>\";\n echo \"</div>\";\n Html::closeForm();\n }\n }", " /**\n * Check if a login is valid\n *\n * @param string $login login to check\n *\n * @return boolean\n */\n public static function isValidLogin($login)\n {\n return $login !== null && preg_match(\"/^[[:alnum:]'@.\\-_ ]+$/iu\", $login);\n }", " public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0)\n {", " if (!$withtemplate) {\n switch ($item->getType()) {\n case 'User':\n if (Session::haveRight(\"user\", User::UPDATEAUTHENT)) {\n return __('Synchronization');\n }\n break;\n }\n }\n return '';\n }", " /**\n * Show Tab content\n *\n * @since 0.83\n *\n * @param CommonGLPI $item Item instance\n * @param integer $tabnum Unused (default 0)\n * @param integer $withtemplate Unused (default 0)\n *\n * @return boolean\n */\n public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0)\n {", " if ($item->getType() == 'User') {\n self::showSynchronizationForm($item);\n }\n return true;\n }", " /**\n * Show form for authentication configuration.\n *\n * @return void|boolean False if the form is not shown due to right error. Form is directly printed.\n */\n public static function showOtherAuthList()\n {\n global $CFG_GLPI;", " if (!Config::canUpdate()) {\n return false;\n }\n echo \"<form name=cas action='\" . $CFG_GLPI['root_doc'] . \"/front/auth.others.php' method='post'>\";\n echo \"<div class='card'>\";\n echo \"<table class='tab_cadre_fixe'>\";", " // CAS config\n echo \"<tr><th>\" . __('CAS authentication') . '</th><th>';\n if (!empty($CFG_GLPI[\"cas_host\"])) {\n echo _x('authentication', 'Enabled');\n }\n echo \"</th></tr>\";", " if (\n function_exists('curl_init')\n && Toolbox::canUseCAS()\n ) {\n //TRANS: for CAS SSO system\n echo \"<tr class='tab_bg_2'><td class='center'>\" . __('CAS Host') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='cas_host' value=\\\"\" . $CFG_GLPI[\"cas_host\"] . \"\\\"></td></tr>\";\n //TRANS: for CAS SSO system\n echo \"<tr class='tab_bg_2'><td class='center'>\" . __('CAS Version') . \"</td>\";\n echo \"<td>\";\n Auth::dropdownCasVersion($CFG_GLPI[\"cas_version\"]);\n echo \"</td>\";\n echo \"</tr>\";\n //TRANS: for CAS SSO system\n echo \"<tr class='tab_bg_2'><td class='center'>\" . _n('Port', 'Ports', 1) . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='cas_port' value=\\\"\" . $CFG_GLPI[\"cas_port\"] . \"\\\"></td></tr>\";\n //TRANS: for CAS SSO system\n echo \"<tr class='tab_bg_2'><td class='center'>\" . __('Root directory (optional)') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='cas_uri' value=\\\"\" . $CFG_GLPI[\"cas_uri\"] . \"\\\"></td></tr>\";\n //TRANS: for CAS SSO system\n echo \"<tr class='tab_bg_2'><td class='center'>\" . __('Log out fallback URL') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='cas_logout' value=\\\"\" . $CFG_GLPI[\"cas_logout\"] . \"\\\"></td>\" .\n \"</tr>\";\n } else {\n echo \"<tr class='tab_bg_2'><td class='center' colspan='2'>\";\n if (!function_exists('curl_init')) {\n echo \"<p class='red'>\" . __(\"The CURL extension for your PHP parser isn't installed\");\n echo \"</p>\";\n }\n if (!Toolbox::canUseCAS()) {\n echo \"<p class='red'>\" . __(\"The CAS lib isn't available, GLPI doesn't package it anymore for license compatibility issue.\");\n echo \"</p>\";\n }\n echo \"<p>\" . __('Impossible to use CAS as external source of connection') . \"</p>\";\n echo \"<p><strong>\" . GLPINetwork::getSupportPromoteMessage() . \"</strong></p>\";", " echo \"</td></tr>\";\n }\n // X509 config\n echo \"<tr><th>\" . __('x509 certificate authentication') . \"</th><th>\";\n if (!empty($CFG_GLPI[\"x509_email_field\"])) {\n echo _x('authentication', 'Enabled');\n }\n echo \"</th></tr>\";\n echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('Email attribute for x509 authentication') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='x509_email_field' value=\\\"\" . $CFG_GLPI[\"x509_email_field\"] . \"\\\">\";\n echo \"</td></tr>\";\n echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . sprintf(__('Restrict %s field for x509 authentication (separator $)'), 'OU') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='x509_ou_restrict' value=\\\"\" . $CFG_GLPI[\"x509_ou_restrict\"] . \"\\\">\";\n echo \"</td></tr>\";\n echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . sprintf(__('Restrict %s field for x509 authentication (separator $)'), 'CN') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='x509_cn_restrict' value=\\\"\" . $CFG_GLPI[\"x509_cn_restrict\"] . \"\\\">\";\n echo \"</td></tr>\";\n echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . sprintf(__('Restrict %s field for x509 authentication (separator $)'), 'O') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='x509_o_restrict' value=\\\"\" . $CFG_GLPI[\"x509_o_restrict\"] . \"\\\">\";\n echo \"</td></tr>\";", " //Other configuration\n echo \"<tr><th>\" . __('Other authentication sent in the HTTP request') . \"</th><th>\";\n if (!empty($CFG_GLPI[\"ssovariables_id\"])) {\n echo _x('authentication', 'Enabled');\n }\n echo \"</th></tr>\";\n echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . SsoVariable::getTypeName(1) . \"</td>\";\n echo \"<td>\";\n SsoVariable::dropdown(['name' => 'ssovariables_id',\n 'value' => $CFG_GLPI[\"ssovariables_id\"]\n ]);\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('SSO logout url') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='ssologout_url' value='\" .\n $CFG_GLPI['ssologout_url'] . \"'></td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('Remove the domain of logins like login@domain') . \"</td><td>\";\n Dropdown::showYesNo(\n 'existing_auth_server_field_clean_domain',\n $CFG_GLPI['existing_auth_server_field_clean_domain']\n );\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('Surname') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='realname_ssofield' value='\" .\n $CFG_GLPI['realname_ssofield'] . \"'></td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('First name') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='firstname_ssofield' value='\" .\n $CFG_GLPI['firstname_ssofield'] . \"'></td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('Comments') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='comment_ssofield' value='\" .\n $CFG_GLPI['comment_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . _x('user', 'Administrative number') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='registration_number_ssofield' value='\" .\n $CFG_GLPI['registration_number_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . _n('Email', 'Emails', 1) . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='email1_ssofield' value='\" . $CFG_GLPI['email1_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . sprintf(__('%1$s %2$s'), _n('Email', 'Emails', 1), '2') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='email2_ssofield' value='\" . $CFG_GLPI['email2_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . sprintf(__('%1$s %2$s'), _n('Email', 'Emails', 1), '3') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='email3_ssofield' value='\" . $CFG_GLPI['email3_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . sprintf(__('%1$s %2$s'), _n('Email', 'Emails', 1), '4') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='email4_ssofield' value='\" . $CFG_GLPI['email4_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . Phone::getTypeName(1) . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='phone_ssofield' value='\" . $CFG_GLPI['phone_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('Phone 2') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='phone2_ssofield' value='\" . $CFG_GLPI['phone2_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('Mobile phone') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='mobile_ssofield' value='\" . $CFG_GLPI['mobile_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . _x('person', 'Title') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='title_ssofield' value='\" . $CFG_GLPI['title_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . _n('Category', 'Categories', 1) . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='category_ssofield' value='\" .\n $CFG_GLPI['category_ssofield'] . \"'></td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('Language') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='language_ssofield' value='\" .\n $CFG_GLPI['language_ssofield'] . \"'></td></tr>\";", " echo \"<tr class='tab_bg_1'><td class='center' colspan='2'>\";\n echo \"<input type='submit' name='update' class='btn btn-primary' value=\\\"\" . __s('Save') . \"\\\" >\";\n echo \"</td></tr>\";", " echo \"</table></div>\";\n Html::closeForm();\n }", " /**\n * Get authentication methods available\n *\n * @return array\n */\n public static function getLoginAuthMethods()\n {\n global $DB;", " $elements = [\n '_default' => 'local',\n 'local' => __(\"GLPI internal database\")\n ];", " // Get LDAP\n if (Toolbox::canUseLdap()) {\n $iterator = $DB->request([\n 'FROM' => 'glpi_authldaps',\n 'WHERE' => [\n 'is_active' => 1\n ],\n 'ORDER' => ['name']\n ]);\n foreach ($iterator as $data) {\n $elements['ldap-' . $data['id']] = $data['name'];\n if ($data['is_default'] == 1) {\n $elements['_default'] = 'ldap-' . $data['id'];\n }\n }\n }", " // GET Mail servers\n $iterator = $DB->request([\n 'FROM' => 'glpi_authmails',\n 'WHERE' => [\n 'is_active' => 1\n ],\n 'ORDER' => ['name']\n ]);\n foreach ($iterator as $data) {\n $elements['mail-' . $data['id']] = $data['name'];\n }", " return $elements;\n }", " /**\n * Display the authentication source dropdown for login form\n */\n public static function dropdownLogin(bool $display = true)\n {\n $out = \"\";\n $elements = self::getLoginAuthMethods();\n $default = $elements['_default'];\n unset($elements['_default']);\n // show dropdown of login src only when multiple src\n $out .= Dropdown::showFromArray('auth', $elements, [\n 'display' => false,\n 'rand' => '1',\n 'value' => $default,\n 'width' => '100%'\n ]);", " if ($display) {\n echo $out;\n return \"\";\n }", " return $out;\n }", "\n public static function getIcon()\n {\n return \"ti ti-login\";\n }", " /**\n * Defines \"rememberme\" cookie.\n *\n * @param string $cookie_value\n *\n * @return void\n */\n public static function setRememberMeCookie(string $cookie_value): void\n {\n global $CFG_GLPI;", " $cookie_name = session_name() . '_rememberme';\n $cookie_lifetime = empty($cookie_value) ? time() - 3600 : time() + $CFG_GLPI['login_remember_time'];\n $cookie_path = ini_get('session.cookie_path');\n $cookie_domain = ini_get('session.cookie_domain');\n $cookie_secure = (bool)ini_get('session.cookie_secure');", " if (empty($cookie_value) && !isset($_COOKIE[$cookie_name])) {\n return;\n }", " setcookie($cookie_name, $cookie_value, $cookie_lifetime, $cookie_path, $cookie_domain, $cookie_secure, true);", " if (empty($cookie_value)) {\n unset($_COOKIE[$cookie_name]);\n } else {\n $_COOKIE[$cookie_name] = $cookie_value;\n }\n }\n}" ]
[ 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, 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, 0, 1, 0, 1, 0, 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [752], "buggy_code_start_loc": [739], "filenames": ["src/Auth.php"], "fixing_code_end_loc": [749], "fixing_code_start_loc": [739], "message": "GLPI is a Free Asset and IT Management Software package, Data center management, ITIL Service Desk, licenses tracking and software auditing. In affected versions there is a SQL injection vulnerability which is possible on login page. No user credentials are required to exploit this vulnerability. Users are advised to upgrade as soon as possible. There are no known workarounds for this issue.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:*:*:*:*:*:*:*:*", "matchCriteriaId": "0C62EFBE-E0E7-4665-8D9A-8981B554001E", "versionEndExcluding": "9.5.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.3.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:glpi-project:glpi:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CB71059-6156-42BE-8A8D-73F053C080C7", "versionEndExcluding": "10.0.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GLPI is a Free Asset and IT Management Software package, Data center management, ITIL Service Desk, licenses tracking and software auditing. In affected versions there is a SQL injection vulnerability which is possible on login page. No user credentials are required to exploit this vulnerability. Users are advised to upgrade as soon as possible. There are no known workarounds for this issue."}, {"lang": "es", "value": "GLPI es un paquete de software gratuito de administraci\u00f3n de activos y TI, administraci\u00f3n de centros de datos, ITIL Service Desk, seguimiento de licencias y auditor\u00eda de software. En las versiones afectadas se presenta una vulnerabilidad de inyecci\u00f3n SQL que es posible en la p\u00e1gina de inicio de sesi\u00f3n. No son requeridas credenciales de usuario para explotar esta vulnerabilidad. Es recomendado a usuarios actualizar lo antes posible. No se presentan mitigaciones conocidas para este problema"}], "evaluatorComment": null, "id": "CVE-2022-31061", "lastModified": "2022-07-07T16:47:11.150", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-06-28T18:15:08.430", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/commit/21ae07d00d0b3230f6235386e98388cfc5bb0514"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/security/advisories/GHSA-w2gc-v2gm-q7wq"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/glpi-project/glpi/commit/21ae07d00d0b3230f6235386e98388cfc5bb0514"}, "type": "CWE-89"}
191
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * ---------------------------------------------------------------------\n *\n * GLPI - Gestionnaire Libre de Parc Informatique\n *\n * http://glpi-project.org\n *\n * @copyright 2015-2022 Teclib' and contributors.\n * @copyright 2003-2014 by the INDEPNET Development Team.\n * @licence https://www.gnu.org/licenses/gpl-3.0.html\n *\n * ---------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of GLPI.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <https://www.gnu.org/licenses/>.\n *\n * ---------------------------------------------------------------------\n */", "use Glpi\\Application\\ErrorHandler;\nuse Glpi\\Event;\nuse Glpi\\Plugin\\Hooks;\nuse Glpi\\Toolbox\\Sanitizer;", "/**\n * Identification class used to login\n */\nclass Auth extends CommonGLPI\n{\n /** @var array Array of errors */\n private $errors = [];\n /** @var User User class variable */\n public $user;\n /** @var int External authentication variable */\n public $extauth = 0;\n /** @var array External authentication methods */\n public $authtypes;\n /** @var int Indicates if the user is authenticated or not */\n public $auth_succeded = 0;\n /** @var int Indicates if the user is already present in database */\n public $user_present = 0;\n /** @var int Indicates if the user password expired */\n public $password_expired = false;", " /**\n * Indicated if user was found in the directory.\n * @var boolean\n */\n public $user_found = false;", " /** @var resource|boolean LDAP connection descriptor */\n public $ldap_connection;\n /** @var bool Store user LDAP dn */\n public $user_dn = false;", " const DB_GLPI = 1;\n const MAIL = 2;\n const LDAP = 3;\n const EXTERNAL = 4;\n const CAS = 5;\n const X509 = 6;\n const API = 7;\n const COOKIE = 8;\n const NOT_YET_AUTHENTIFIED = 0;", " const USER_DOESNT_EXIST = 0;\n const USER_EXISTS_WITH_PWD = 1;\n const USER_EXISTS_WITHOUT_PWD = 2;", " /**\n * Constructor\n *\n * @return void\n */\n public function __construct()\n {\n $this->user = new User();\n }", "\n public static function getMenuContent()\n {", " $menu = [];\n if (Config::canUpdate()) {\n $menu['title'] = __('Authentication');\n $menu['page'] = '/front/setup.auth.php';\n $menu['icon'] = self::getIcon();", " $menu['options']['ldap']['icon'] = AuthLDAP::getIcon();\n $menu['options']['ldap']['title'] = AuthLDAP::getTypeName(Session::getPluralNumber());\n $menu['options']['ldap']['page'] = AuthLDAP::getSearchURL(false);\n $menu['options']['ldap']['links']['search'] = AuthLDAP::getSearchURL(false);\n $menu['options']['ldap']['links']['add'] = AuthLDAP::getFormURL(false);", " $menu['options']['imap']['icon'] = AuthMail::getIcon();\n $menu['options']['imap']['title'] = AuthMail::getTypeName(Session::getPluralNumber());\n $menu['options']['imap']['page'] = AuthMail::getSearchURL(false);\n $menu['options']['imap']['links']['search'] = AuthMail::getSearchURL(false);\n $menu['options']['imap']['links']['add'] = AuthMail::getFormURL(false);", " $menu['options']['others']['icon'] = 'ti ti-login';\n $menu['options']['others']['title'] = __('Others');\n $menu['options']['others']['page'] = '/front/auth.others.php';", " $menu['options']['settings']['icon'] = 'ti ti-adjustments';\n $menu['options']['settings']['title'] = __('Setup');\n $menu['options']['settings']['page'] = '/front/auth.settings.php';\n }\n if (count($menu)) {\n return $menu;\n }\n return false;\n }", " /**\n * Check user existence in DB\n *\n * @global DBmysql $DB\n * @param array $options conditions : array('name'=>'glpi')\n * or array('email' => 'test at test.com')\n *\n * @return integer {@link Auth::USER_DOESNT_EXIST}, {@link Auth::USER_EXISTS_WITHOUT_PWD} or {@link Auth::USER_EXISTS_WITH_PWD}\n */\n public function userExists($options = [])\n {\n global $DB;", " $result = $DB->request(\n 'glpi_users',\n ['WHERE' => $options,\n 'LEFT JOIN' => ['glpi_useremails' => ['FKEY' => ['glpi_users' => 'id',\n 'glpi_useremails' => 'users_id'\n ]\n ]\n ]\n ]\n );\n // Check if there is a row\n if ($result->numrows() == 0) {\n $this->addToError(__('Incorrect username or password'));\n return self::USER_DOESNT_EXIST;\n } else {\n // Get the first result...\n $row = $result->current();", " // Check if we have a password...\n if (empty($row['password'])) {\n //If the user has an LDAP DN, then store it in the Auth object\n if ($row['user_dn']) {\n $this->user_dn = $row['user_dn'];\n }\n return self::USER_EXISTS_WITHOUT_PWD;\n }\n return self::USER_EXISTS_WITH_PWD;\n }\n }", " /**\n * Try a IMAP/POP connection\n *\n * @param string $host IMAP/POP host to connect\n * @param string $login Login to try\n * @param string $pass Password to try\n *\n * @return boolean connection success\n */\n public function connection_imap($host, $login, $pass)\n {", " // we prevent some delay...\n if (empty($host)) {\n return false;\n }", " $oldlevel = error_reporting(16);\n // No retry (avoid lock account when password is not correct)\n try {\n $config = Toolbox::parseMailServerConnectString($host);", " $ssl = false;\n if ($config['ssl']) {\n $ssl = 'SSL';\n }\n if ($config['tls']) {\n $ssl = 'TLS';\n }", " $protocol = Toolbox::getMailServerProtocolInstance($config['type']);\n if ($protocol === null) {\n throw new \\RuntimeException(sprintf(__('Unsupported mail server type:%s.'), $config['type']));\n }\n if ($config['validate-cert'] === false) {\n $protocol->setNoValidateCert(true);\n }\n $protocol->connect(\n $config['address'],\n $config['port'],\n $ssl\n );", " return $protocol->login($login, $pass);\n } catch (\\Exception $e) {\n $this->addToError($e->getMessage());\n return false;\n } finally {\n error_reporting($oldlevel);\n }", " return false;\n }", " /**\n * Find a user in a LDAP and return is BaseDN\n * Based on GRR auth system\n *\n * @param string $ldap_method ldap_method array to use\n * @param string $login User Login\n * @param string $password User Password\n *\n * @return string basedn of the user / false if not founded\n */\n public function connection_ldap($ldap_method, $login, $password)\n {", " // we prevent some delay...\n if (empty($ldap_method['host'])) {\n return false;\n }", " $this->ldap_connection = AuthLDAP::tryToConnectToServer($ldap_method, $login, $password);\n $this->user_found = false;", " if ($this->ldap_connection) {\n $params = [\n 'method' => AuthLDAP::IDENTIFIER_LOGIN,\n 'fields' => [\n AuthLDAP::IDENTIFIER_LOGIN => $ldap_method['login_field'],\n ],\n ];\n if (!empty($ldap_method['sync_field'])) {\n $params['fields']['sync_field'] = $ldap_method['sync_field'];\n }\n try {\n $infos = AuthLDAP::searchUserDn($this->ldap_connection, [\n 'basedn' => $ldap_method['basedn'],\n 'login_field' => $ldap_method['login_field'],\n 'search_parameters' => $params,\n 'user_params' => [\n 'method' => AuthLDAP::IDENTIFIER_LOGIN,\n 'value' => $login\n ],\n 'condition' => Sanitizer::unsanitize($ldap_method['condition']),\n 'user_dn' => $this->user_dn\n ]);\n } catch (\\Throwable $e) {\n ErrorHandler::getInstance()->handleException($e, true);\n $this->addToError(__('Unable to connect to the LDAP directory'));\n return false;\n }", " $dn = $infos['dn'];\n $this->user_found = $dn != '';\n if ($this->user_found && @ldap_bind($this->ldap_connection, $dn, $password)) {\n //Hook to implement to restrict access by checking the ldap directory\n if (Plugin::doHookFunction(Hooks::RESTRICT_LDAP_AUTH, $infos)) {\n return $infos;\n }\n $this->addToError(__('User not authorized to connect in GLPI'));\n //Use is present by has no right to connect because of a plugin\n return false;\n } else {\n // Incorrect login\n $this->addToError(__('Incorrect username or password'));\n //Use is not present anymore in the directory!\n return false;\n }\n } else {\n $this->addToError(__('Unable to connect to the LDAP directory'));\n //Directory is not available\n return false;\n }\n }", " /**\n * Check is a password match the stored hash\n *\n * @since 0.85\n *\n * @param string $pass Password (pain-text)\n * @param string $hash Hash\n *\n * @return boolean\n */\n public static function checkPassword($pass, $hash)\n {", " $tmp = password_get_info($hash);", " if (isset($tmp['algo']) && $tmp['algo']) {\n $ok = password_verify($pass, $hash);\n } else if (strlen($hash) == 32) {\n $ok = md5($pass) === $hash;\n } else if (strlen($hash) == 40) {\n $ok = sha1($pass) === $hash;\n } else {\n $salt = substr($hash, 0, 8);\n $ok = ($salt . sha1($salt . $pass) === $hash);\n }", " return $ok;\n }", " /**\n * Is the hash stored need to be regenerated\n *\n * @since 0.85\n *\n * @param string $hash Hash\n *\n * @return boolean\n */\n public static function needRehash($hash)\n {", " return password_needs_rehash($hash, PASSWORD_DEFAULT);\n }", " /**\n * Compute the hash for a password\n *\n * @since 0.85\n *\n * @param string $pass Password\n *\n * @return string\n */\n public static function getPasswordHash($pass)\n {", " return password_hash($pass, PASSWORD_DEFAULT);\n }", " /**\n * Find a user in the GLPI DB\n *\n * try to connect to DB\n * update the instance variable user with the user who has the name $name\n * and the password is $password in the DB.\n * If not found or can't connect to DB updates the instance variable err\n * with an eventual error message\n *\n * @global DBmysql $DB\n * @param string $name User Login\n * @param string $password User Password\n *\n * @return boolean user in GLPI DB with the right password\n */\n public function connection_db($name, $password)\n {\n global $CFG_GLPI, $DB;", " $pass_expiration_delay = (int)$CFG_GLPI['password_expiration_delay'];\n $lock_delay = (int)$CFG_GLPI['password_expiration_lock_delay'];", " // SQL query\n $result = $DB->request(\n [\n 'SELECT' => [\n 'id',\n 'password',\n new QueryExpression(\n sprintf(\n 'ADDDATE(%s, INTERVAL %d DAY) AS ' . $DB->quoteName('password_expiration_date'),\n $DB->quoteName('password_last_update'),\n $pass_expiration_delay\n )\n ),\n new QueryExpression(\n sprintf(\n 'ADDDATE(%s, INTERVAL %d DAY) AS ' . $DB->quoteName('lock_date'),\n $DB->quoteName('password_last_update'),\n $pass_expiration_delay + $lock_delay\n )\n )\n ],\n 'FROM' => User::getTable(),\n 'WHERE' => [\n 'name' => $name,\n 'authtype' => self::DB_GLPI,\n 'auths_id' => 0,\n ]\n ]\n );", " // Have we a result ?\n if ($result->numrows() == 1) {\n $row = $result->current();\n $password_db = $row['password'];", " if (self::checkPassword($password, $password_db)) {\n // Disable account if password expired\n if (\n -1 !== $pass_expiration_delay && -1 !== $lock_delay\n && $row['lock_date'] < $_SESSION['glpi_currenttime']\n ) {\n $user = new User();\n $user->update(\n [\n 'id' => $row['id'],\n 'is_active' => 0,\n ]\n );\n }\n if (\n -1 !== $pass_expiration_delay\n && $row['password_expiration_date'] < $_SESSION['glpi_currenttime']\n ) {\n $this->password_expired = 1;\n }", " // Update password if needed\n if (self::needRehash($password_db)) {\n $input = [\n 'id' => $row['id'],\n ];\n // Set glpiID to allow password update\n $_SESSION['glpiID'] = $input['id'];\n $input['password'] = $password;\n $input['password2'] = $password;\n $user = new User();\n $user->update($input);\n }\n $this->user->getFromDBByCrit(['id' => $row['id']]);\n $this->extauth = 0;\n $this->user_present = 1;\n $this->user->fields[\"authtype\"] = self::DB_GLPI;\n $this->user->fields[\"password\"] = $password;", " // apply rule rights on local user\n $rules = new RuleRightCollection();\n $groups = Group_User::getUserGroups($row['id']);\n $groups_id = array_column($groups, 'id');\n $result = $rules->processAllRules(\n $groups_id,\n $this->user->fields,\n [\n 'type' => Auth::DB_GLPI,\n 'login' => $this->user->fields['name'],\n 'email' => UserEmail::getDefaultForUser($row['id'])\n ]\n );", " $this->user->fields = $result + [\n '_ruleright_process' => true,\n ];", " return true;\n }\n }\n $this->addToError(__('Incorrect username or password'));\n return false;\n }", " /**\n * Try to get login of external auth method\n *\n * @param integer $authtype external auth type (default 0)\n *\n * @return boolean user login success\n */\n public function getAlternateAuthSystemsUserLogin($authtype = 0)\n {\n global $CFG_GLPI;", " switch ($authtype) {\n case self::CAS:\n if (!Toolbox::canUseCAS()) {\n trigger_error(\"CAS lib not installed\", E_USER_WARNING);\n return false;\n }", " phpCAS::client(\n constant($CFG_GLPI[\"cas_version\"]),\n $CFG_GLPI[\"cas_host\"],\n intval($CFG_GLPI[\"cas_port\"]),\n $CFG_GLPI[\"cas_uri\"],\n false\n );", " // no SSL validation for the CAS server\n phpCAS::setNoCasServerValidation();", " // force CAS authentication\n phpCAS::forceAuthentication();\n $this->user->fields['name'] = phpCAS::getUser();", " // extract e-mail information\n if (phpCAS::hasAttribute(\"mail\")) {\n $this->user->fields['_useremails'] = [phpCAS::getAttribute(\"mail\")];\n }", " return true;", " case self::EXTERNAL:\n $ssovariable = Dropdown::getDropdownName(\n 'glpi_ssovariables',\n $CFG_GLPI[\"ssovariables_id\"]\n );\n $login_string = '';\n // MoYo : checking REQUEST create a security hole for me !\n if (isset($_SERVER[$ssovariable])) {\n $login_string = $_SERVER[$ssovariable];\n }\n // else {\n // $login_string = $_REQUEST[$ssovariable];\n // }\n $login = $login_string;\n $pos = stripos($login_string, \"\\\\\");\n if (!$pos === false) {\n $login = substr($login_string, $pos + 1);\n }\n if ($CFG_GLPI['existing_auth_server_field_clean_domain']) {\n $pos = stripos($login, \"@\");\n if (!$pos === false) {\n $login = substr($login, 0, $pos);\n }\n }\n if (self::isValidLogin($login)) {\n $this->user->fields['name'] = $login;\n // Get data from SSO if defined\n $ret = $this->user->getFromSSO();\n if (!$ret) {\n return false;\n }\n return true;\n }\n break;", " case self::X509:\n // From eGroupWare http://www.egroupware.org\n // an X.509 subject looks like:\n // CN=john.doe/OU=Department/O=Company/C=xx/Email=john@comapy.tld/L=City/\n $sslattribs = explode('/', $_SERVER['SSL_CLIENT_S_DN']);\n $sslattributes = [];\n while ($sslattrib = next($sslattribs)) {\n list($key,$val) = explode('=', $sslattrib);\n $sslattributes[$key] = $val;\n }\n if (\n isset($sslattributes[$CFG_GLPI[\"x509_email_field\"]])\n && NotificationMailing::isUserAddressValid($sslattributes[$CFG_GLPI[\"x509_email_field\"]])\n && self::isValidLogin($sslattributes[$CFG_GLPI[\"x509_email_field\"]])\n ) {\n $restrict = false;\n $CFG_GLPI[\"x509_ou_restrict\"] = trim($CFG_GLPI[\"x509_ou_restrict\"]);\n if (!empty($CFG_GLPI[\"x509_ou_restrict\"])) {\n $split = explode('$', $CFG_GLPI[\"x509_ou_restrict\"]);", " if (!in_array($sslattributes['OU'], $split)) {\n $restrict = true;\n }\n }\n $CFG_GLPI[\"x509_o_restrict\"] = trim($CFG_GLPI[\"x509_o_restrict\"]);\n if (!empty($CFG_GLPI[\"x509_o_restrict\"])) {\n $split = explode('$', $CFG_GLPI[\"x509_o_restrict\"]);", " if (!in_array($sslattributes['O'], $split)) {\n $restrict = true;\n }\n }\n $CFG_GLPI[\"x509_cn_restrict\"] = trim($CFG_GLPI[\"x509_cn_restrict\"]);\n if (!empty($CFG_GLPI[\"x509_cn_restrict\"])) {\n $split = explode('$', $CFG_GLPI[\"x509_cn_restrict\"]);", " if (!in_array($sslattributes['CN'], $split)) {\n $restrict = true;\n }\n }", " if (!$restrict) {\n $this->user->fields['name'] = $sslattributes[$CFG_GLPI[\"x509_email_field\"]];", " // Can do other things if need : only add it here\n $this->user->fields['email'] = $this->user->fields['name'];\n return true;\n }\n }\n break;", " case self::API:\n if ($CFG_GLPI['enable_api_login_external_token']) {\n $user = new User();\n if ($user->getFromDBbyToken($_REQUEST['user_token'], 'api_token')) {\n $this->user->fields['name'] = $user->fields['name'];\n return true;\n }\n } else {\n $this->addToError(__(\"Login with external token disabled\"));\n }\n break;\n case self::COOKIE:\n $cookie_name = session_name() . '_rememberme';", " if ($CFG_GLPI[\"login_remember_time\"]) {\n $data = json_decode($_COOKIE[$cookie_name], true);\n if (count($data) === 2) {\n list ($cookie_id, $cookie_token) = $data;", " $user = new User();\n $user->getFromDB($cookie_id);\n $hash = $user->getAuthToken('cookie_token');", " if (Auth::checkPassword($cookie_token, $hash)) {\n $this->user->fields['name'] = $user->fields['name'];\n return true;\n } else {\n $this->addToError(__(\"Invalid cookie data\"));\n }\n }\n } else {\n $this->addToError(__(\"Auto login disabled\"));\n }", " //Remove cookie to allow new login\n Auth::setRememberMeCookie('');\n break;\n }\n return false;\n }", " /**\n * Get the current identification error\n *\n * @return string current identification error\n */\n public function getErr()\n {\n return implode(\"<br>\\n\", $this->getErrors());\n }", " /**\n * Get errors\n *\n * @since 9.4\n *\n * @return array\n */\n public function getErrors()\n {\n return $this->errors;\n }", " /**\n * Get the current user object\n *\n * @return object current user\n */\n public function getUser()\n {\n return $this->user;\n }", " /**\n * Get all the authentication methods parameters\n * and return it as an array\n *\n * @return void\n */\n public function getAuthMethods()\n {", " //Return all the authentication methods in an array\n $this->authtypes = [\n 'ldap' => getAllDataFromTable('glpi_authldaps'),\n 'mail' => getAllDataFromTable('glpi_authmails')\n ];\n }", " /**\n * Add a message to the global identification error message\n *\n * @param string $message the message to add\n *\n * @return void\n */\n public function addToError($message)\n {\n if (!in_array($message, $this->errors)) {\n $this->errors[] = $message;\n }\n }", " /**\n * Manage use authentication and initialize the session\n *\n * @param string $login_name Login\n * @param string $login_password Password\n * @param boolean $noauto (false by default)\n * @param bool $remember_me\n * @param string $login_auth Type of auth - id of the auth\n *\n * @return boolean (success)\n */\n public function login($login_name, $login_password, $noauto = false, $remember_me = false, $login_auth = '')\n {\n global $DB, $CFG_GLPI;", " $this->getAuthMethods();\n $this->user_present = 1;\n $this->auth_succeded = false;\n //In case the user was deleted in the LDAP directory\n $user_deleted_ldap = false;", " // Trim login_name : avoid LDAP search errors\n $login_name = trim($login_name);", " // manage the $login_auth (force the auth source of the user account)\n $this->user->fields[\"auths_id\"] = 0;\n if ($login_auth == 'local') {\n $authtype = self::DB_GLPI;\n $this->user->fields[\"authtype\"] = self::DB_GLPI;", " } else if (preg_match('/^(?<type>ldap|mail|external)-(?<id>\\d+)$/', $login_auth, $auth_matches)) {\n $this->user->fields[\"auths_id\"] = (int)$auth_matches['id'];\n if ($auth_matches['type'] == 'ldap') {", " $authtype = self::LDAP;", " } else if ($auth_matches['type'] == 'mail') {", " $authtype = self::MAIL;", " } else if ($auth_matches['type'] == 'external') {", " $authtype = self::EXTERNAL;", " }\n $this->user->fields['authtype'] = $authtype;", " }\n if (!$noauto && ($authtype = self::checkAlternateAuthSystems())) {\n if (\n $this->getAlternateAuthSystemsUserLogin($authtype)\n && !empty($this->user->fields['name'])\n ) {\n // Used for log when login process failed\n $login_name = $this->user->fields['name'];\n $this->auth_succeded = true;\n $this->user_present = $this->user->getFromDBbyName(addslashes($login_name));\n $this->extauth = 1;\n $user_dn = false;", " if (array_key_exists('_useremails', $this->user->fields)) {\n $email = $this->user->fields['_useremails'];\n }", " $ldapservers = [];\n //if LDAP enabled too, get user's infos from LDAP\n if (Toolbox::canUseLdap()) {\n //User has already authenticate, at least once : it's ldap server if filled\n if (\n isset($this->user->fields[\"auths_id\"])\n && ($this->user->fields[\"auths_id\"] > 0)\n ) {\n $authldap = new AuthLDAP();\n //If ldap server is enabled\n if (\n $authldap->getFromDB($this->user->fields[\"auths_id\"])\n && $authldap->fields['is_active']\n ) {\n $ldapservers[] = $authldap->fields;\n }\n } else { // User has never been authenticated : try all active ldap server to find the right one\n foreach (getAllDataFromTable('glpi_authldaps', ['is_active' => 1]) as $ldap_config) {\n $ldapservers[] = $ldap_config;\n }\n }", " $ldapservers_status = false;\n foreach ($ldapservers as $ldap_method) {\n $ds = AuthLDAP::connectToServer(\n $ldap_method[\"host\"],\n $ldap_method[\"port\"],\n $ldap_method[\"rootdn\"],\n (new GLPIKey())->decrypt($ldap_method[\"rootdn_passwd\"]),\n $ldap_method[\"use_tls\"],\n $ldap_method[\"deref_option\"],\n $ldap_method[\"tls_certfile\"],\n $ldap_method[\"tls_keyfile\"],\n $ldap_method[\"use_bind\"],\n $ldap_method[\"timeout\"]\n );", " if ($ds) {\n $ldapservers_status = true;\n $params = [\n 'method' => AuthLDAP::IDENTIFIER_LOGIN,\n 'fields' => [\n AuthLDAP::IDENTIFIER_LOGIN => $ldap_method[\"login_field\"],\n ],\n ];\n try {\n $user_dn = AuthLDAP::searchUserDn($ds, [\n 'basedn' => $ldap_method[\"basedn\"],\n 'login_field' => $ldap_method['login_field'],\n 'search_parameters' => $params,\n 'condition' => $ldap_method[\"condition\"],\n 'user_params' => [\n 'method' => AuthLDAP::IDENTIFIER_LOGIN,\n 'value' => $login_name\n ],\n ]);\n } catch (\\RuntimeException $e) {\n ErrorHandler::getInstance()->handleException($e, true);\n $user_dn = false;\n }\n if ($user_dn) {\n $this->user_found = true;\n $this->user->fields['auths_id'] = $ldap_method['id'];\n $this->user->getFromLDAP(\n $ds,\n $ldap_method,\n $user_dn['dn'],\n $login_name,\n !$this->user_present\n );\n break;\n }\n }\n }\n }\n if (\n (count($ldapservers) == 0)\n && ($authtype == self::EXTERNAL)\n ) {\n // Case of using external auth and no LDAP servers, so get data from external auth\n $this->user->getFromSSO();\n } else {\n if ($this->user->fields['authtype'] == self::LDAP) {\n if (!$ldapservers_status) {\n $this->auth_succeded = false;\n $this->addToError(_n(\n 'Connection to LDAP directory failed',\n 'Connection to LDAP directories failed',\n count($ldapservers)\n ));\n } else if (!$user_dn && $this->user_present) {\n //If user is set as present in GLPI but no LDAP DN found : it means that the user\n //is not present in an ldap directory anymore\n $user_deleted_ldap = true;\n $this->addToError(_n(\n 'User not found in LDAP directory',\n 'User not found in LDAP directories',\n count($ldapservers)\n ));\n }\n }\n }\n // Reset to secure it\n $this->user->fields['name'] = $login_name;\n $this->user->fields[\"last_login\"] = $_SESSION[\"glpi_currenttime\"];\n } else {\n $this->addToError(__('Empty login or password'));\n }\n }", " if (!$this->auth_succeded) {\n if (\n empty($login_name) || strstr($login_name, \"\\0\")\n || empty($login_password) || strstr($login_password, \"\\0\")\n ) {\n $this->addToError(__('Empty login or password'));\n } else {\n // Try connect local user if not yet authenticated\n if (\n empty($login_auth)\n || $this->user->fields[\"authtype\"] == $this::DB_GLPI\n ) {\n $this->auth_succeded = $this->connection_db(\n addslashes($login_name),\n $login_password\n );\n }", " // Try to connect LDAP user if not yet authenticated\n if (!$this->auth_succeded) {\n if (\n empty($login_auth)\n || $this->user->fields[\"authtype\"] == $this::CAS\n || $this->user->fields[\"authtype\"] == $this::EXTERNAL\n || $this->user->fields[\"authtype\"] == $this::LDAP\n ) {\n if (Toolbox::canUseLdap()) {\n AuthLDAP::tryLdapAuth(\n $this,\n $login_name,\n $login_password,\n $this->user->fields[\"auths_id\"]\n );\n if ($this->ldap_connection !== false && (!$this->auth_succeded && !$this->user_found)) {\n $search_params = [\n 'name' => addslashes($login_name),\n 'authtype' => $this::LDAP\n ];\n if (!empty($login_auth)) {\n $search_params['auths_id'] = $this->user->fields[\"auths_id\"];\n }\n if ($this->user->getFromDBByCrit($search_params)) {\n $user_deleted_ldap = true;\n };\n }\n }\n }\n }", " // Try connect MAIL server if not yet authenticated\n if (!$this->auth_succeded) {\n if (\n empty($login_auth)\n || $this->user->fields[\"authtype\"] == $this::MAIL\n ) {\n AuthMail::tryMailAuth(\n $this,\n $login_name,\n $login_password,\n $this->user->fields[\"auths_id\"]\n );\n }\n }\n }\n }", " if ($user_deleted_ldap) {\n User::manageDeletedUserInLdap($this->user->fields[\"id\"]);\n $this->auth_succeded = false;\n }\n // Ok, we have gathered sufficient data, if the first return false the user\n // is not present on the DB, so we add him.\n // if not, we update him.\n if ($this->auth_succeded) {\n //Set user an not deleted from LDAP\n $this->user->fields['is_deleted_ldap'] = 0;", " // Prepare data\n $this->user->fields[\"last_login\"] = $_SESSION[\"glpi_currenttime\"];\n if ($this->extauth) {\n $this->user->fields[\"_extauth\"] = 1;\n }", " if ($DB->isSlave()) {\n if (!$this->user_present) { // Can't add in slave mode\n $this->addToError(__('User not authorized to connect in GLPI'));\n $this->auth_succeded = false;\n }\n } else {\n if ($this->user_present) {\n // Add the user e-mail if present\n if (isset($email)) {\n $this->user->fields['_useremails'] = $email;\n }\n $this->user->update(Sanitizer::sanitize($this->user->fields));\n } else if ($CFG_GLPI[\"is_users_auto_add\"]) {\n // Auto add user\n $input = $this->user->fields;\n unset($this->user->fields);\n if ($authtype == self::EXTERNAL && !isset($input[\"authtype\"])) {\n $input[\"authtype\"] = $authtype;\n }\n $this->user->add(Sanitizer::sanitize($input));\n } else {\n // Auto add not enable so auth failed\n $this->addToError(__('User not authorized to connect in GLPI'));\n $this->auth_succeded = false;\n }\n }\n }", " // Log Event (if possible)\n if (!$DB->isSlave()) {\n // GET THE IP OF THE CLIENT\n $ip = getenv(\"HTTP_X_FORWARDED_FOR\") ?\n Sanitizer::encodeHtmlSpecialChars(getenv(\"HTTP_X_FORWARDED_FOR\")) :\n getenv(\"REMOTE_ADDR\");", " if ($this->auth_succeded) {\n if (GLPI_DEMO_MODE) {\n // not translation in GLPI_DEMO_MODE\n Event::log(0, \"system\", 3, \"login\", $login_name . \" log in from \" . $ip);\n } else {\n //TRANS: %1$s is the login of the user and %2$s its IP address\n Event::log(0, \"system\", 3, \"login\", sprintf(\n __('%1$s log in from IP %2$s'),\n $login_name,\n $ip\n ));\n }\n } else {\n if (GLPI_DEMO_MODE) {\n Event::log(\n 0,\n \"system\",\n 3,\n \"login\",\n \"login\",\n \"Connection failed for \" . $login_name . \" ($ip)\"\n );\n } else {\n //TRANS: %1$s is the login of the user and %2$s its IP address\n Event::log(0, \"system\", 3, \"login\", sprintf(\n __('Failed login for %1$s from IP %2$s'),\n $login_name,\n $ip\n ));\n }\n }\n }", " Session::init($this);", " if ($noauto) {\n $_SESSION[\"noAUTO\"] = 1;\n }", " if ($this->auth_succeded && $CFG_GLPI['login_remember_time'] > 0 && $remember_me) {\n $token = $this->user->getAuthToken('cookie_token', true);", " if ($token) {\n $data = json_encode([\n $this->user->fields['id'],\n $token,\n ]);", " //Send cookie to browser\n Auth::setRememberMeCookie($data);\n }\n }", " if ($this->auth_succeded && !empty($this->user->fields['timezone']) && 'null' !== strtolower($this->user->fields['timezone'])) {\n //set user timezone, if any\n $_SESSION['glpi_tz'] = $this->user->fields['timezone'];\n $DB->setTimezone($this->user->fields['timezone']);\n }", " return $this->auth_succeded;\n }", " /**\n * Print all the authentication methods\n *\n * @param array $options Possible options:\n * - name : Name of the select (default is auths_id)\n * - value : Selected value (default 0)\n * - display : If true, the dropdown is displayed instead of returned (default true)\n * - display_emptychoice : If true, an empty option is added (default true)\n * - hide_if_no_elements : boolean / hide dropdown if there is no elements (default false)\n *\n * @return void|string (Based on 'display' option)\n */\n public static function dropdown($options = [])\n {\n global $DB;", " $p = [\n 'name' => 'auths_id',\n 'value' => 0,\n 'display' => true,\n 'display_emptychoice' => true,\n 'hide_if_no_elements' => false,\n ];", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $p[$key] = $val;\n }\n }", " $methods = [\n self::DB_GLPI => __('Authentication on GLPI database'),\n ];", " $result = $DB->request([\n 'FROM' => 'glpi_authldaps',\n 'COUNT' => 'cpt',\n 'WHERE' => [\n 'is_active' => 1\n ]\n ])->current();", " if ($result['cpt'] > 0) {\n $methods[self::LDAP] = __('Authentication on a LDAP directory');\n $methods[self::EXTERNAL] = __('External authentications');\n }", " $result = $DB->request([\n 'FROM' => 'glpi_authmails',\n 'COUNT' => 'cpt',\n 'WHERE' => [\n 'is_active' => 1\n ]\n ])->current();", " if ($result['cpt'] > 0) {\n $methods[self::MAIL] = __('Authentication on mail server');\n }", " return Dropdown::showFromArray($p['name'], $methods, $p);\n }", " /**\n * Builds CAS versions dropdown\n * @param string $value (default 'CAS_VERSION_2_0')\n *\n * @return string\n */\n public static function dropdownCasVersion($value = 'CAS_VERSION_2_0')\n {\n $options['CAS_VERSION_1_0'] = __('Version 1');\n $options['CAS_VERSION_2_0'] = __('Version 2');\n $options['CAS_VERSION_3_0'] = __('Version 3+');\n return Dropdown::showFromArray('cas_version', $options, ['value' => $value]);\n }", " /**\n * Get name of an authentication method\n *\n * @param integer $authtype Authentication method\n * @param integer $auths_id Authentication method ID\n * @param integer $link show links to config page? (default 0)\n * @param string $name override the name if not empty (default '')\n *\n * @return string\n */\n public static function getMethodName($authtype, $auths_id, $link = 0, $name = '')\n {", " switch ($authtype) {\n case self::LDAP:\n $auth = new AuthLDAP();\n if ($auth->getFromDB($auths_id)) {\n //TRANS: %1$s is the auth method type, %2$s the auth method name or link\n return sprintf(__('%1$s: %2$s'), AuthLDAP::getTypeName(1), $auth->getLink());\n }\n return sprintf(__('%1$s: %2$s'), AuthLDAP::getTypeName(1), $name);", " case self::MAIL:\n $auth = new AuthMail();\n if ($auth->getFromDB($auths_id)) {\n //TRANS: %1$s is the auth method type, %2$s the auth method name or link\n return sprintf(__('%1$s: %2$s'), AuthLDAP::getTypeName(1), $auth->getLink());\n }\n return sprintf(__('%1$s: %2$s'), __('Email server'), $name);", " case self::CAS:\n if ($auths_id > 0) {\n $auth = new AuthLDAP();\n if ($auth->getFromDB($auths_id)) {\n return sprintf(\n __('%1$s: %2$s'),\n sprintf(\n __('%1$s + %2$s'),\n __('CAS'),\n AuthLDAP::getTypeName(1)\n ),\n $auth->getLink()\n );\n }\n }\n return __('CAS');", " case self::X509:\n if ($auths_id > 0) {\n $auth = new AuthLDAP();\n if ($auth->getFromDB($auths_id)) {\n return sprintf(\n __('%1$s: %2$s'),\n sprintf(\n __('%1$s + %2$s'),\n __('x509 certificate authentication'),\n AuthLDAP::getTypeName(1)\n ),\n $auth->getLink()\n );\n }\n }\n return __('x509 certificate authentication');", " case self::EXTERNAL:\n if ($auths_id > 0) {\n $auth = new AuthLDAP();\n if ($auth->getFromDB($auths_id)) {\n return sprintf(\n __('%1$s: %2$s'),\n sprintf(\n __('%1$s + %2$s'),\n __('Other'),\n AuthLDAP::getTypeName(1)\n ),\n $auth->getLink()\n );\n }\n }\n return __('Other');", " case self::DB_GLPI:\n return __('GLPI internal database');", " case self::API:\n return __(\"API\");", " case self::NOT_YET_AUTHENTIFIED:\n return __('Not yet authenticated');\n }\n return '';\n }", " /**\n * Get all the authentication methods parameters for a specific authtype\n * and auths_id and return it as an array\n *\n * @param integer $authtype Authentication method\n * @param integer $auths_id Authentication method ID\n *\n * @return mixed\n */\n public static function getMethodsByID($authtype, $auths_id)\n {", " switch ($authtype) {\n case self::X509:\n case self::EXTERNAL:\n case self::CAS:\n case self::LDAP:\n $auth = new AuthLDAP();\n if ($auths_id > 0 && $auth->getFromDB($auths_id)) {\n return ($auth->fields);\n }\n break;", " case self::MAIL:\n $auth = new AuthMail();\n if ($auths_id > 0 && $auth->getFromDB($auths_id)) {\n return ($auth->fields);\n }\n break;\n }\n return [];\n }", " /**\n * Is an external authentication used?\n *\n * @return boolean\n */\n public static function useAuthExt()\n {", " global $CFG_GLPI;", " //Get all the ldap directories\n if (AuthLDAP::useAuthLdap()) {\n return true;\n }", " if (AuthMail::useAuthMail()) {\n return true;\n }", " if (!empty($CFG_GLPI[\"x509_email_field\"])) {\n return true;\n }", " // Existing auth method\n if (!empty($CFG_GLPI[\"ssovariables_id\"])) {\n return true;\n }", " // Using CAS server\n if (!empty($CFG_GLPI[\"cas_host\"])) {\n return true;\n }", " // Using API login with personnal token\n if (!empty($_REQUEST['user_token'])) {\n return true;\n }", " return false;\n }", " /**\n * Is an alternate auth?\n *\n * @param integer $authtype auth type\n *\n * @return boolean\n */\n public static function isAlternateAuth($authtype)\n {\n return in_array($authtype, [self::X509, self::CAS, self::EXTERNAL, self::API, self::COOKIE]);\n }", " /**\n * Check alternate authentication systems\n *\n * @param boolean $redirect need to redirect (true) or get type of Auth system which match\n * (false by default)\n * @param string $redirect_string redirect string if exists (default '')\n *\n * @return void|integer nothing if redirect is true, else Auth system ID\n */\n public static function checkAlternateAuthSystems($redirect = false, $redirect_string = '')\n {\n global $CFG_GLPI;", " if (isset($_GET[\"noAUTO\"]) || isset($_POST[\"noAUTO\"])) {\n return false;\n }\n $redir_string = \"\";\n if (!empty($redirect_string)) {\n $redir_string = \"?redirect=\" . $redirect_string;\n }\n // Using x509 server\n if (\n !empty($CFG_GLPI[\"x509_email_field\"])\n && isset($_SERVER['SSL_CLIENT_S_DN'])\n && strstr($_SERVER['SSL_CLIENT_S_DN'], $CFG_GLPI[\"x509_email_field\"])\n ) {\n if ($redirect) {\n Html::redirect($CFG_GLPI[\"root_doc\"] . \"/front/login.php\" . $redir_string);\n } else {\n return self::X509;\n }\n }\n // Existing auth method\n //Look for the field in $_SERVER AND $_REQUEST\n // MoYo : checking REQUEST create a security hole for me !\n $ssovariable = Dropdown::getDropdownName('glpi_ssovariables', $CFG_GLPI[\"ssovariables_id\"]);\n if (\n $CFG_GLPI[\"ssovariables_id\"]\n && ((isset($_SERVER[$ssovariable]) && !empty($_SERVER[$ssovariable]))\n /*|| (isset($_REQUEST[$ssovariable]) && !empty($_REQUEST[$ssovariable]))*/)\n ) {\n if ($redirect) {\n Html::redirect($CFG_GLPI[\"root_doc\"] . \"/front/login.php\" . $redir_string);\n } else {\n return self::EXTERNAL;\n }\n }", " // using user token for api login\n if (!empty($_REQUEST['user_token'])) {\n return self::API;\n }", " // Using CAS server\n if (!empty($CFG_GLPI[\"cas_host\"])) {\n if ($redirect) {\n Html::redirect($CFG_GLPI[\"root_doc\"] . \"/front/login.php\" . $redir_string);\n } else {\n return self::CAS;\n }\n }", " $cookie_name = session_name() . '_rememberme';\n if ($CFG_GLPI[\"login_remember_time\"] && isset($_COOKIE[$cookie_name])) {\n if ($redirect) {\n Html::redirect($CFG_GLPI[\"root_doc\"] . \"/front/login.php\" . $redir_string);\n } else {\n return self::COOKIE;\n }\n }", " return false;\n }", " /**\n * Redirect user to page if authenticated\n *\n * @param string $redirect redirect string if exists, if null, check in $_POST or $_GET\n *\n * @return void|boolean nothing if redirect is true, else false\n */\n public static function redirectIfAuthenticated($redirect = null)\n {\n global $CFG_GLPI;", " if (!Session::getLoginUserID()) {\n return false;\n }", " if (Session::mustChangePassword()) {\n Html::redirect($CFG_GLPI['root_doc'] . '/front/updatepassword.php');\n }", " if (!$redirect) {\n if (isset($_POST['redirect']) && (strlen($_POST['redirect']) > 0)) {\n $redirect = $_POST['redirect'];\n } else if (isset($_GET['redirect']) && strlen($_GET['redirect']) > 0) {\n $redirect = $_GET['redirect'];\n }\n }", " //Direct redirect\n if ($redirect) {\n Toolbox::manageRedirect($redirect);\n }", " // Redirect to Command Central if not post-only\n if (Session::getCurrentInterface() == \"helpdesk\") {\n if ($_SESSION['glpiactiveprofile']['create_ticket_on_login']) {\n Html::redirect($CFG_GLPI['root_doc'] . \"/front/helpdesk.public.php?create_ticket=1\");\n }\n Html::redirect($CFG_GLPI['root_doc'] . \"/front/helpdesk.public.php\");\n } else {\n if ($_SESSION['glpiactiveprofile']['create_ticket_on_login']) {\n Html::redirect(Ticket::getFormURL());\n }\n Html::redirect($CFG_GLPI['root_doc'] . \"/front/central.php\");\n }\n }", " /**\n * Display refresh button in the user page\n *\n * @param User $user User object\n *\n * @return void\n */\n public static function showSynchronizationForm(User $user)\n {\n global $DB, $CFG_GLPI;", " if (Session::haveRight(\"user\", User::UPDATEAUTHENT)) {\n echo \"<form method='post' action='\" . Toolbox::getItemTypeFormURL('User') . \"'>\";\n echo \"<div class='firstbloc'>\";\n echo \"<input type='hidden' name='id' value='\" . $user->getID() . \"'>\";", " switch ($user->getField('authtype')) {\n case self::CAS:\n case self::EXTERNAL:\n case self::X509:\n case self::LDAP:\n //Look it the auth server still exists !\n // <- Bad idea : id not exists unable to change anything\n $authldap = new AuthLDAP();\n if (\n $authldap->getFromDBByCrit([\n 'id' => $user->getField('auths_id'),\n 'is_active' => 1,\n ])\n ) {\n echo Html::submit(\"<i class='fas fa-sync-alt'></i><span>\" . __s('Force synchronization') . \"</span>\", [\n 'name' => 'force_ldap_resynch'\n ]);", " if (strlen($authldap->fields['sync_field']) > 0) {\n echo Html::submit(\"<i class='fas fa-broom'></i><span>\" . __s('Clean LDAP fields and force synchronisation') . \"</span>\", [\n 'name' => 'clean_ldap_fields'\n ]);\n }\n }\n break;", " case self::DB_GLPI:\n case self::MAIL:\n break;\n }", " echo \"</div>\";", " echo \"<div class='spaced'>\";\n echo \"<h3>\" . __('Change of the authentication method') . \"</h3>\";\n $rand = self::dropdown(['name' => 'authtype']);\n $paramsmassaction = ['authtype' => '__VALUE__',\n 'name' => 'change_auth_method'\n ];\n Ajax::updateItemOnSelectEvent(\n \"dropdown_authtype$rand\",\n \"show_massiveaction_field\",\n $CFG_GLPI[\"root_doc\"] . \"/ajax/dropdownMassiveActionAuthMethods.php\",\n $paramsmassaction\n );\n echo \"<span id='show_massiveaction_field'></span>\";\n echo \"</div>\";\n Html::closeForm();\n }\n }", " /**\n * Check if a login is valid\n *\n * @param string $login login to check\n *\n * @return boolean\n */\n public static function isValidLogin($login)\n {\n return $login !== null && preg_match(\"/^[[:alnum:]'@.\\-_ ]+$/iu\", $login);\n }", " public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0)\n {", " if (!$withtemplate) {\n switch ($item->getType()) {\n case 'User':\n if (Session::haveRight(\"user\", User::UPDATEAUTHENT)) {\n return __('Synchronization');\n }\n break;\n }\n }\n return '';\n }", " /**\n * Show Tab content\n *\n * @since 0.83\n *\n * @param CommonGLPI $item Item instance\n * @param integer $tabnum Unused (default 0)\n * @param integer $withtemplate Unused (default 0)\n *\n * @return boolean\n */\n public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0)\n {", " if ($item->getType() == 'User') {\n self::showSynchronizationForm($item);\n }\n return true;\n }", " /**\n * Show form for authentication configuration.\n *\n * @return void|boolean False if the form is not shown due to right error. Form is directly printed.\n */\n public static function showOtherAuthList()\n {\n global $CFG_GLPI;", " if (!Config::canUpdate()) {\n return false;\n }\n echo \"<form name=cas action='\" . $CFG_GLPI['root_doc'] . \"/front/auth.others.php' method='post'>\";\n echo \"<div class='card'>\";\n echo \"<table class='tab_cadre_fixe'>\";", " // CAS config\n echo \"<tr><th>\" . __('CAS authentication') . '</th><th>';\n if (!empty($CFG_GLPI[\"cas_host\"])) {\n echo _x('authentication', 'Enabled');\n }\n echo \"</th></tr>\";", " if (\n function_exists('curl_init')\n && Toolbox::canUseCAS()\n ) {\n //TRANS: for CAS SSO system\n echo \"<tr class='tab_bg_2'><td class='center'>\" . __('CAS Host') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='cas_host' value=\\\"\" . $CFG_GLPI[\"cas_host\"] . \"\\\"></td></tr>\";\n //TRANS: for CAS SSO system\n echo \"<tr class='tab_bg_2'><td class='center'>\" . __('CAS Version') . \"</td>\";\n echo \"<td>\";\n Auth::dropdownCasVersion($CFG_GLPI[\"cas_version\"]);\n echo \"</td>\";\n echo \"</tr>\";\n //TRANS: for CAS SSO system\n echo \"<tr class='tab_bg_2'><td class='center'>\" . _n('Port', 'Ports', 1) . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='cas_port' value=\\\"\" . $CFG_GLPI[\"cas_port\"] . \"\\\"></td></tr>\";\n //TRANS: for CAS SSO system\n echo \"<tr class='tab_bg_2'><td class='center'>\" . __('Root directory (optional)') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='cas_uri' value=\\\"\" . $CFG_GLPI[\"cas_uri\"] . \"\\\"></td></tr>\";\n //TRANS: for CAS SSO system\n echo \"<tr class='tab_bg_2'><td class='center'>\" . __('Log out fallback URL') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='cas_logout' value=\\\"\" . $CFG_GLPI[\"cas_logout\"] . \"\\\"></td>\" .\n \"</tr>\";\n } else {\n echo \"<tr class='tab_bg_2'><td class='center' colspan='2'>\";\n if (!function_exists('curl_init')) {\n echo \"<p class='red'>\" . __(\"The CURL extension for your PHP parser isn't installed\");\n echo \"</p>\";\n }\n if (!Toolbox::canUseCAS()) {\n echo \"<p class='red'>\" . __(\"The CAS lib isn't available, GLPI doesn't package it anymore for license compatibility issue.\");\n echo \"</p>\";\n }\n echo \"<p>\" . __('Impossible to use CAS as external source of connection') . \"</p>\";\n echo \"<p><strong>\" . GLPINetwork::getSupportPromoteMessage() . \"</strong></p>\";", " echo \"</td></tr>\";\n }\n // X509 config\n echo \"<tr><th>\" . __('x509 certificate authentication') . \"</th><th>\";\n if (!empty($CFG_GLPI[\"x509_email_field\"])) {\n echo _x('authentication', 'Enabled');\n }\n echo \"</th></tr>\";\n echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('Email attribute for x509 authentication') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='x509_email_field' value=\\\"\" . $CFG_GLPI[\"x509_email_field\"] . \"\\\">\";\n echo \"</td></tr>\";\n echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . sprintf(__('Restrict %s field for x509 authentication (separator $)'), 'OU') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='x509_ou_restrict' value=\\\"\" . $CFG_GLPI[\"x509_ou_restrict\"] . \"\\\">\";\n echo \"</td></tr>\";\n echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . sprintf(__('Restrict %s field for x509 authentication (separator $)'), 'CN') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='x509_cn_restrict' value=\\\"\" . $CFG_GLPI[\"x509_cn_restrict\"] . \"\\\">\";\n echo \"</td></tr>\";\n echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . sprintf(__('Restrict %s field for x509 authentication (separator $)'), 'O') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='x509_o_restrict' value=\\\"\" . $CFG_GLPI[\"x509_o_restrict\"] . \"\\\">\";\n echo \"</td></tr>\";", " //Other configuration\n echo \"<tr><th>\" . __('Other authentication sent in the HTTP request') . \"</th><th>\";\n if (!empty($CFG_GLPI[\"ssovariables_id\"])) {\n echo _x('authentication', 'Enabled');\n }\n echo \"</th></tr>\";\n echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . SsoVariable::getTypeName(1) . \"</td>\";\n echo \"<td>\";\n SsoVariable::dropdown(['name' => 'ssovariables_id',\n 'value' => $CFG_GLPI[\"ssovariables_id\"]\n ]);\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('SSO logout url') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='ssologout_url' value='\" .\n $CFG_GLPI['ssologout_url'] . \"'></td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('Remove the domain of logins like login@domain') . \"</td><td>\";\n Dropdown::showYesNo(\n 'existing_auth_server_field_clean_domain',\n $CFG_GLPI['existing_auth_server_field_clean_domain']\n );\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('Surname') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='realname_ssofield' value='\" .\n $CFG_GLPI['realname_ssofield'] . \"'></td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('First name') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='firstname_ssofield' value='\" .\n $CFG_GLPI['firstname_ssofield'] . \"'></td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('Comments') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='comment_ssofield' value='\" .\n $CFG_GLPI['comment_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . _x('user', 'Administrative number') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='registration_number_ssofield' value='\" .\n $CFG_GLPI['registration_number_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . _n('Email', 'Emails', 1) . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='email1_ssofield' value='\" . $CFG_GLPI['email1_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . sprintf(__('%1$s %2$s'), _n('Email', 'Emails', 1), '2') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='email2_ssofield' value='\" . $CFG_GLPI['email2_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . sprintf(__('%1$s %2$s'), _n('Email', 'Emails', 1), '3') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='email3_ssofield' value='\" . $CFG_GLPI['email3_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . sprintf(__('%1$s %2$s'), _n('Email', 'Emails', 1), '4') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='email4_ssofield' value='\" . $CFG_GLPI['email4_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . Phone::getTypeName(1) . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='phone_ssofield' value='\" . $CFG_GLPI['phone_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('Phone 2') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='phone2_ssofield' value='\" . $CFG_GLPI['phone2_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('Mobile phone') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='mobile_ssofield' value='\" . $CFG_GLPI['mobile_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . _x('person', 'Title') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='title_ssofield' value='\" . $CFG_GLPI['title_ssofield'] . \"'>\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . _n('Category', 'Categories', 1) . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='category_ssofield' value='\" .\n $CFG_GLPI['category_ssofield'] . \"'></td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_2'>\";\n echo \"<td class='center'>\" . __('Language') . \"</td>\";\n echo \"<td><input type='text' class='form-control' name='language_ssofield' value='\" .\n $CFG_GLPI['language_ssofield'] . \"'></td></tr>\";", " echo \"<tr class='tab_bg_1'><td class='center' colspan='2'>\";\n echo \"<input type='submit' name='update' class='btn btn-primary' value=\\\"\" . __s('Save') . \"\\\" >\";\n echo \"</td></tr>\";", " echo \"</table></div>\";\n Html::closeForm();\n }", " /**\n * Get authentication methods available\n *\n * @return array\n */\n public static function getLoginAuthMethods()\n {\n global $DB;", " $elements = [\n '_default' => 'local',\n 'local' => __(\"GLPI internal database\")\n ];", " // Get LDAP\n if (Toolbox::canUseLdap()) {\n $iterator = $DB->request([\n 'FROM' => 'glpi_authldaps',\n 'WHERE' => [\n 'is_active' => 1\n ],\n 'ORDER' => ['name']\n ]);\n foreach ($iterator as $data) {\n $elements['ldap-' . $data['id']] = $data['name'];\n if ($data['is_default'] == 1) {\n $elements['_default'] = 'ldap-' . $data['id'];\n }\n }\n }", " // GET Mail servers\n $iterator = $DB->request([\n 'FROM' => 'glpi_authmails',\n 'WHERE' => [\n 'is_active' => 1\n ],\n 'ORDER' => ['name']\n ]);\n foreach ($iterator as $data) {\n $elements['mail-' . $data['id']] = $data['name'];\n }", " return $elements;\n }", " /**\n * Display the authentication source dropdown for login form\n */\n public static function dropdownLogin(bool $display = true)\n {\n $out = \"\";\n $elements = self::getLoginAuthMethods();\n $default = $elements['_default'];\n unset($elements['_default']);\n // show dropdown of login src only when multiple src\n $out .= Dropdown::showFromArray('auth', $elements, [\n 'display' => false,\n 'rand' => '1',\n 'value' => $default,\n 'width' => '100%'\n ]);", " if ($display) {\n echo $out;\n return \"\";\n }", " return $out;\n }", "\n public static function getIcon()\n {\n return \"ti ti-login\";\n }", " /**\n * Defines \"rememberme\" cookie.\n *\n * @param string $cookie_value\n *\n * @return void\n */\n public static function setRememberMeCookie(string $cookie_value): void\n {\n global $CFG_GLPI;", " $cookie_name = session_name() . '_rememberme';\n $cookie_lifetime = empty($cookie_value) ? time() - 3600 : time() + $CFG_GLPI['login_remember_time'];\n $cookie_path = ini_get('session.cookie_path');\n $cookie_domain = ini_get('session.cookie_domain');\n $cookie_secure = (bool)ini_get('session.cookie_secure');", " if (empty($cookie_value) && !isset($_COOKIE[$cookie_name])) {\n return;\n }", " setcookie($cookie_name, $cookie_value, $cookie_lifetime, $cookie_path, $cookie_domain, $cookie_secure, true);", " if (empty($cookie_value)) {\n unset($_COOKIE[$cookie_name]);\n } else {\n $_COOKIE[$cookie_name] = $cookie_value;\n }\n }\n}" ]
[ 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, 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, 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, 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, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [752], "buggy_code_start_loc": [739], "filenames": ["src/Auth.php"], "fixing_code_end_loc": [749], "fixing_code_start_loc": [739], "message": "GLPI is a Free Asset and IT Management Software package, Data center management, ITIL Service Desk, licenses tracking and software auditing. In affected versions there is a SQL injection vulnerability which is possible on login page. No user credentials are required to exploit this vulnerability. Users are advised to upgrade as soon as possible. There are no known workarounds for this issue.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:*:*:*:*:*:*:*:*", "matchCriteriaId": "0C62EFBE-E0E7-4665-8D9A-8981B554001E", "versionEndExcluding": "9.5.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.3.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:glpi-project:glpi:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CB71059-6156-42BE-8A8D-73F053C080C7", "versionEndExcluding": "10.0.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GLPI is a Free Asset and IT Management Software package, Data center management, ITIL Service Desk, licenses tracking and software auditing. In affected versions there is a SQL injection vulnerability which is possible on login page. No user credentials are required to exploit this vulnerability. Users are advised to upgrade as soon as possible. There are no known workarounds for this issue."}, {"lang": "es", "value": "GLPI es un paquete de software gratuito de administraci\u00f3n de activos y TI, administraci\u00f3n de centros de datos, ITIL Service Desk, seguimiento de licencias y auditor\u00eda de software. En las versiones afectadas se presenta una vulnerabilidad de inyecci\u00f3n SQL que es posible en la p\u00e1gina de inicio de sesi\u00f3n. No son requeridas credenciales de usuario para explotar esta vulnerabilidad. Es recomendado a usuarios actualizar lo antes posible. No se presentan mitigaciones conocidas para este problema"}], "evaluatorComment": null, "id": "CVE-2022-31061", "lastModified": "2022-07-07T16:47:11.150", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-06-28T18:15:08.430", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/commit/21ae07d00d0b3230f6235386e98388cfc5bb0514"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/security/advisories/GHSA-w2gc-v2gm-q7wq"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/glpi-project/glpi/commit/21ae07d00d0b3230f6235386e98388cfc5bb0514"}, "type": "CWE-89"}
191
Determine whether the {function_name} code is vulnerable or not.
[ "package v1", "import (\n\t\"encoding/json\"\n\t\"net/http\"", "\t\"github.com/KubeOperator/KubeOperator/pkg/controller\"\n\t\"github.com/KubeOperator/KubeOperator/pkg/errorf\"\n\t\"github.com/KubeOperator/KubeOperator/pkg/middleware\"\n\t\"github.com/jinzhu/gorm\"\n\t\"github.com/kataras/iris/v12\"\n\t\"github.com/kataras/iris/v12/context\"\n\t\"github.com/kataras/iris/v12/mvc\"\n\t\"github.com/pkg/errors\"\n)", "var AuthScope iris.Party\nvar WhiteScope iris.Party", "func V1(parent iris.Party) {\n\tv1 := parent.Party(\"/v1\")\n\tauthParty := v1.Party(\"/auth\")\n\tmvc.New(authParty.Party(\"/session\")).HandleError(ErrorHandler).Handle(controller.NewSessionController())\n\tmvc.New(v1.Party(\"/user\")).HandleError(ErrorHandler).Handle(controller.NewForgotPasswordController())\n\tAuthScope = v1.Party(\"/\")\n\tAuthScope.Use(middleware.JWTMiddleware().Serve)\n\tAuthScope.Use(middleware.UserMiddleware)\n\tAuthScope.Use(middleware.RBACMiddleware())\n\tAuthScope.Use(middleware.PagerMiddleware)\n\tAuthScope.Use(middleware.ForceMiddleware)\n\tmvc.New(AuthScope.Party(\"/clusters\")).HandleError(ErrorHandler).Handle(controller.NewClusterController())\n\tmvc.New(AuthScope.Party(\"/credentials\")).HandleError(ErrorHandler).Handle(controller.NewCredentialController())\n\tmvc.New(AuthScope.Party(\"/hosts\")).HandleError(ErrorHandler).Handle(controller.NewHostController())\n\tmvc.New(AuthScope.Party(\"/users\")).HandleError(ErrorHandler).Handle(controller.NewUserController())\n\tmvc.New(AuthScope.Party(\"/dashboard\")).HandleError(ErrorHandler).Handle(controller.NewKubePiController())\n\tmvc.New(AuthScope.Party(\"/regions\")).HandleError(ErrorHandler).Handle(controller.NewRegionController())\n\tmvc.New(AuthScope.Party(\"/zones\")).HandleError(ErrorHandler).Handle(controller.NewZoneController())\n\tmvc.New(AuthScope.Party(\"/plans\")).HandleError(ErrorHandler).Handle(controller.NewPlanController())\n\tmvc.New(AuthScope.Party(\"/settings\")).HandleError(ErrorHandler).Handle(controller.NewSystemSettingController())\n\tmvc.New(AuthScope.Party(\"/ntp\")).HandleError(ErrorHandler).Handle(controller.NewNtpServerController())\n\tmvc.New(AuthScope.Party(\"/logs\")).HandleError(ErrorHandler).Handle(controller.NewSystemLogController())\n\tmvc.New(AuthScope.Party(\"/projects\")).HandleError(ErrorHandler).Handle(controller.NewProjectController())\n\tmvc.New(AuthScope.Party(\"/clusters/provisioner\")).HandleError(ErrorHandler).Handle(controller.NewProvisionerController())\n\tmvc.New(AuthScope.Party(\"/kubernetes\")).HandleError(ErrorHandler).Handle(controller.NewKubernetesController())\n\tmvc.New(AuthScope.Party(\"/clusters/tool\")).HandleError(ErrorHandler).Handle(controller.NewClusterToolController())\n\tmvc.New(AuthScope.Party(\"/backupaccounts\")).HandleError(ErrorHandler).Handle(controller.NewBackupAccountController())\n\tmvc.New(AuthScope.Party(\"/clusters/backup\")).HandleError(ErrorHandler).Handle(controller.NewClusterBackupStrategyController())\n\tmvc.New(AuthScope.Party(\"/clusters/monitor\")).HandleError(ErrorHandler).Handle(controller.NewMonitorController())\n\tmvc.New(AuthScope.Party(\"/tasks\")).Handle(ErrorHandler).Handle(controller.NewTaskLogController())\n\tmvc.New(AuthScope.Party(\"/components\")).Handle(ErrorHandler).Handle(controller.NewComponentController())\n\tmvc.New(AuthScope.Party(\"/license\")).Handle(ErrorHandler).Handle(controller.NewLicenseController())\n\tmvc.New(AuthScope.Party(\"/clusters/backup/files\")).HandleError(ErrorHandler).Handle(controller.NewClusterBackupFileController())\n\tmvc.New(AuthScope.Party(\"/clusters/velero/{cluster}/{operate}\")).HandleError(ErrorHandler).Handle(controller.NewClusterVeleroBackupController())\n\tmvc.New(AuthScope.Party(\"/manifests\")).HandleError(ErrorHandler).Handle(controller.NewManifestController())\n\tmvc.New(AuthScope.Party(\"/vmconfigs\")).HandleError(ErrorHandler).Handle(controller.NewVmConfigController())\n\tmvc.New(AuthScope.Party(\"/ippools\")).HandleError(ErrorHandler).Handle(controller.NewIpPoolController())\n\tmvc.New(AuthScope.Party(\"/ippools/{name}/ips\")).HandleError(ErrorHandler).Handle(controller.NewIpController())\n\tmvc.New(AuthScope.Party(\"/projects/{project}/resources\")).HandleError(ErrorHandler).Handle(controller.NewProjectResourceController())\n\tmvc.New(AuthScope.Party(\"/projects/{project}/members\")).HandleError(ErrorHandler).Handle(controller.NewProjectMemberController())\n\tmvc.New(AuthScope.Party(\"/projects/{project}/clusters/{cluster}/members\")).HandleError(ErrorHandler).Handle(controller.NewClusterMemberController())\n\tmvc.New(AuthScope.Party(\"/projects/{project}/clusters/{cluster}/resources\")).HandleError(ErrorHandler).Handle(controller.NewClusterResourceController())\n\tmvc.New(AuthScope.Party(\"/templates\")).HandleError(ErrorHandler).Handle(controller.NewTemplateConfigController())\n\tmvc.New(AuthScope.Party(\"/clusters/grade\")).HandleError(ErrorHandler).Handle(controller.NewGradeController())\n\tmvc.New(AuthScope.Party(\"/ldap\")).HandleError(ErrorHandler).Handle(controller.NewLdapController())\n\tmvc.New(AuthScope.Party(\"/msg/accounts\")).HandleError(ErrorHandler).Handle(controller.NewMessageAccountController())\n\tmvc.New(AuthScope.Party(\"/msg/subscribes\")).HandleError(ErrorHandler).Handle(controller.NewMessageSubscribeController())\n\tmvc.New(AuthScope.Party(\"/user/messages\")).HandleError(ErrorHandler).Handle(controller.NewUserMsgController())\n\tmvc.New(AuthScope.Party(\"/user/settings\")).HandleError(ErrorHandler).Handle(controller.NewUserSettingController())", "", "\tWhiteScope = v1.Party(\"/\")", "\tWhiteScope.Get(\"/clusters/kubeconfig/{name}\", downloadKubeconfig)", "\tWhiteScope.Get(\"/captcha\", generateCaptcha)\n\tmvc.New(WhiteScope.Party(\"/theme\")).HandleError(ErrorHandler).Handle(controller.NewThemeController())", "}", "func ErrorHandler(ctx context.Context, err error) {\n\tif err != nil {\n\t\twarp := struct {\n\t\t\tMsg string `json:\"msg\"`\n\t\t}{err.Error()}\n\t\tvar result string\n\t\tswitch errType := err.(type) {\n\t\tcase gorm.Errors:\n\t\t\terrorSet := make(map[string]string)\n\t\t\tfor _, er := range errType {\n\t\t\t\ttr := ctx.Tr(er.Error())\n\t\t\t\tif tr != \"\" {\n\t\t\t\t\terrorMsg := tr\n\t\t\t\t\terrorSet[er.Error()] = errorMsg\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, set := range errorSet {\n\t\t\t\tresult = result + set + \" \"\n\t\t\t}\n\t\tcase error:\n\t\t\tswitch errRoot := errors.Cause(err).(type) {\n\t\t\tcase errorf.CErrFs:\n\t\t\t\terrs := errRoot.Get()\n\t\t\t\tfor _, er := range errs {\n\t\t\t\t\targs := er.Args.([]interface{})\n\t\t\t\t\ttr := ctx.Tr(er.Msg, args...)\n\t\t\t\t\tif tr != \"\" {\n\t\t\t\t\t\tresult = result + tr + \"\\n \"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\ttr := ctx.Tr(errors.Cause(err).Error())\n\t\t\t\tif tr != \"\" {\n\t\t\t\t\tresult = tr\n\t\t\t\t} else {\n\t\t\t\t\tresult = err.Error()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twarp.Msg = result\n\t\tbf, _ := json.Marshal(&warp)\n\t\tctx.StatusCode(http.StatusBadRequest)\n\t\t_, _ = ctx.WriteString(string(bf))\n\t\tctx.StopExecution()\n\t\treturn\n\t}\n}" ]
[ 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [71], "buggy_code_start_loc": [68], "filenames": ["pkg/router/v1/v1api.go"], "fixing_code_end_loc": [70], "fixing_code_start_loc": [69], "message": "KubeOperator is an open source Kubernetes distribution focused on helping enterprises plan, deploy and operate production-level K8s clusters. In KubeOperator versions 3.16.3 and below, API interfaces with unauthorized entities and can leak sensitive information. This vulnerability could be used to take over the cluster under certain conditions. This issue has been patched in version 3.16.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fit2cloud:kubeoperator:*:*:*:*:*:*:*:*", "matchCriteriaId": "486336C5-5A30-4490-A12B-E79FE102419B", "versionEndExcluding": "3.16.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "KubeOperator is an open source Kubernetes distribution focused on helping enterprises plan, deploy and operate production-level K8s clusters. In KubeOperator versions 3.16.3 and below, API interfaces with unauthorized entities and can leak sensitive information. This vulnerability could be used to take over the cluster under certain conditions. This issue has been patched in version 3.16.4."}], "evaluatorComment": null, "id": "CVE-2023-22480", "lastModified": "2023-01-24T18:40:30.457", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.4, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-01-14T01:15:15.207", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/KubeOperator/KubeOperator/commit/7ef42bf1c16900d13e6376f8be5ecdbfdfb44aaf"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/KubeOperator/KubeOperator/releases/tag/v3.16.4"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/KubeOperator/KubeOperator/security/advisories/GHSA-jxgp-jgh3-8jc8"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-285"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/KubeOperator/KubeOperator/commit/7ef42bf1c16900d13e6376f8be5ecdbfdfb44aaf"}, "type": "CWE-863"}
192
Determine whether the {function_name} code is vulnerable or not.
[ "package v1", "import (\n\t\"encoding/json\"\n\t\"net/http\"", "\t\"github.com/KubeOperator/KubeOperator/pkg/controller\"\n\t\"github.com/KubeOperator/KubeOperator/pkg/errorf\"\n\t\"github.com/KubeOperator/KubeOperator/pkg/middleware\"\n\t\"github.com/jinzhu/gorm\"\n\t\"github.com/kataras/iris/v12\"\n\t\"github.com/kataras/iris/v12/context\"\n\t\"github.com/kataras/iris/v12/mvc\"\n\t\"github.com/pkg/errors\"\n)", "var AuthScope iris.Party\nvar WhiteScope iris.Party", "func V1(parent iris.Party) {\n\tv1 := parent.Party(\"/v1\")\n\tauthParty := v1.Party(\"/auth\")\n\tmvc.New(authParty.Party(\"/session\")).HandleError(ErrorHandler).Handle(controller.NewSessionController())\n\tmvc.New(v1.Party(\"/user\")).HandleError(ErrorHandler).Handle(controller.NewForgotPasswordController())\n\tAuthScope = v1.Party(\"/\")\n\tAuthScope.Use(middleware.JWTMiddleware().Serve)\n\tAuthScope.Use(middleware.UserMiddleware)\n\tAuthScope.Use(middleware.RBACMiddleware())\n\tAuthScope.Use(middleware.PagerMiddleware)\n\tAuthScope.Use(middleware.ForceMiddleware)\n\tmvc.New(AuthScope.Party(\"/clusters\")).HandleError(ErrorHandler).Handle(controller.NewClusterController())\n\tmvc.New(AuthScope.Party(\"/credentials\")).HandleError(ErrorHandler).Handle(controller.NewCredentialController())\n\tmvc.New(AuthScope.Party(\"/hosts\")).HandleError(ErrorHandler).Handle(controller.NewHostController())\n\tmvc.New(AuthScope.Party(\"/users\")).HandleError(ErrorHandler).Handle(controller.NewUserController())\n\tmvc.New(AuthScope.Party(\"/dashboard\")).HandleError(ErrorHandler).Handle(controller.NewKubePiController())\n\tmvc.New(AuthScope.Party(\"/regions\")).HandleError(ErrorHandler).Handle(controller.NewRegionController())\n\tmvc.New(AuthScope.Party(\"/zones\")).HandleError(ErrorHandler).Handle(controller.NewZoneController())\n\tmvc.New(AuthScope.Party(\"/plans\")).HandleError(ErrorHandler).Handle(controller.NewPlanController())\n\tmvc.New(AuthScope.Party(\"/settings\")).HandleError(ErrorHandler).Handle(controller.NewSystemSettingController())\n\tmvc.New(AuthScope.Party(\"/ntp\")).HandleError(ErrorHandler).Handle(controller.NewNtpServerController())\n\tmvc.New(AuthScope.Party(\"/logs\")).HandleError(ErrorHandler).Handle(controller.NewSystemLogController())\n\tmvc.New(AuthScope.Party(\"/projects\")).HandleError(ErrorHandler).Handle(controller.NewProjectController())\n\tmvc.New(AuthScope.Party(\"/clusters/provisioner\")).HandleError(ErrorHandler).Handle(controller.NewProvisionerController())\n\tmvc.New(AuthScope.Party(\"/kubernetes\")).HandleError(ErrorHandler).Handle(controller.NewKubernetesController())\n\tmvc.New(AuthScope.Party(\"/clusters/tool\")).HandleError(ErrorHandler).Handle(controller.NewClusterToolController())\n\tmvc.New(AuthScope.Party(\"/backupaccounts\")).HandleError(ErrorHandler).Handle(controller.NewBackupAccountController())\n\tmvc.New(AuthScope.Party(\"/clusters/backup\")).HandleError(ErrorHandler).Handle(controller.NewClusterBackupStrategyController())\n\tmvc.New(AuthScope.Party(\"/clusters/monitor\")).HandleError(ErrorHandler).Handle(controller.NewMonitorController())\n\tmvc.New(AuthScope.Party(\"/tasks\")).Handle(ErrorHandler).Handle(controller.NewTaskLogController())\n\tmvc.New(AuthScope.Party(\"/components\")).Handle(ErrorHandler).Handle(controller.NewComponentController())\n\tmvc.New(AuthScope.Party(\"/license\")).Handle(ErrorHandler).Handle(controller.NewLicenseController())\n\tmvc.New(AuthScope.Party(\"/clusters/backup/files\")).HandleError(ErrorHandler).Handle(controller.NewClusterBackupFileController())\n\tmvc.New(AuthScope.Party(\"/clusters/velero/{cluster}/{operate}\")).HandleError(ErrorHandler).Handle(controller.NewClusterVeleroBackupController())\n\tmvc.New(AuthScope.Party(\"/manifests\")).HandleError(ErrorHandler).Handle(controller.NewManifestController())\n\tmvc.New(AuthScope.Party(\"/vmconfigs\")).HandleError(ErrorHandler).Handle(controller.NewVmConfigController())\n\tmvc.New(AuthScope.Party(\"/ippools\")).HandleError(ErrorHandler).Handle(controller.NewIpPoolController())\n\tmvc.New(AuthScope.Party(\"/ippools/{name}/ips\")).HandleError(ErrorHandler).Handle(controller.NewIpController())\n\tmvc.New(AuthScope.Party(\"/projects/{project}/resources\")).HandleError(ErrorHandler).Handle(controller.NewProjectResourceController())\n\tmvc.New(AuthScope.Party(\"/projects/{project}/members\")).HandleError(ErrorHandler).Handle(controller.NewProjectMemberController())\n\tmvc.New(AuthScope.Party(\"/projects/{project}/clusters/{cluster}/members\")).HandleError(ErrorHandler).Handle(controller.NewClusterMemberController())\n\tmvc.New(AuthScope.Party(\"/projects/{project}/clusters/{cluster}/resources\")).HandleError(ErrorHandler).Handle(controller.NewClusterResourceController())\n\tmvc.New(AuthScope.Party(\"/templates\")).HandleError(ErrorHandler).Handle(controller.NewTemplateConfigController())\n\tmvc.New(AuthScope.Party(\"/clusters/grade\")).HandleError(ErrorHandler).Handle(controller.NewGradeController())\n\tmvc.New(AuthScope.Party(\"/ldap\")).HandleError(ErrorHandler).Handle(controller.NewLdapController())\n\tmvc.New(AuthScope.Party(\"/msg/accounts\")).HandleError(ErrorHandler).Handle(controller.NewMessageAccountController())\n\tmvc.New(AuthScope.Party(\"/msg/subscribes\")).HandleError(ErrorHandler).Handle(controller.NewMessageSubscribeController())\n\tmvc.New(AuthScope.Party(\"/user/messages\")).HandleError(ErrorHandler).Handle(controller.NewUserMsgController())\n\tmvc.New(AuthScope.Party(\"/user/settings\")).HandleError(ErrorHandler).Handle(controller.NewUserSettingController())", "\tAuthScope.Get(\"/clusters/kubeconfig/{name}\", downloadKubeconfig)", "\tWhiteScope = v1.Party(\"/\")", "", "\tWhiteScope.Get(\"/captcha\", generateCaptcha)\n\tmvc.New(WhiteScope.Party(\"/theme\")).HandleError(ErrorHandler).Handle(controller.NewThemeController())", "}", "func ErrorHandler(ctx context.Context, err error) {\n\tif err != nil {\n\t\twarp := struct {\n\t\t\tMsg string `json:\"msg\"`\n\t\t}{err.Error()}\n\t\tvar result string\n\t\tswitch errType := err.(type) {\n\t\tcase gorm.Errors:\n\t\t\terrorSet := make(map[string]string)\n\t\t\tfor _, er := range errType {\n\t\t\t\ttr := ctx.Tr(er.Error())\n\t\t\t\tif tr != \"\" {\n\t\t\t\t\terrorMsg := tr\n\t\t\t\t\terrorSet[er.Error()] = errorMsg\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, set := range errorSet {\n\t\t\t\tresult = result + set + \" \"\n\t\t\t}\n\t\tcase error:\n\t\t\tswitch errRoot := errors.Cause(err).(type) {\n\t\t\tcase errorf.CErrFs:\n\t\t\t\terrs := errRoot.Get()\n\t\t\t\tfor _, er := range errs {\n\t\t\t\t\targs := er.Args.([]interface{})\n\t\t\t\t\ttr := ctx.Tr(er.Msg, args...)\n\t\t\t\t\tif tr != \"\" {\n\t\t\t\t\t\tresult = result + tr + \"\\n \"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\ttr := ctx.Tr(errors.Cause(err).Error())\n\t\t\t\tif tr != \"\" {\n\t\t\t\t\tresult = tr\n\t\t\t\t} else {\n\t\t\t\t\tresult = err.Error()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twarp.Msg = result\n\t\tbf, _ := json.Marshal(&warp)\n\t\tctx.StatusCode(http.StatusBadRequest)\n\t\t_, _ = ctx.WriteString(string(bf))\n\t\tctx.StopExecution()\n\t\treturn\n\t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [71], "buggy_code_start_loc": [68], "filenames": ["pkg/router/v1/v1api.go"], "fixing_code_end_loc": [70], "fixing_code_start_loc": [69], "message": "KubeOperator is an open source Kubernetes distribution focused on helping enterprises plan, deploy and operate production-level K8s clusters. In KubeOperator versions 3.16.3 and below, API interfaces with unauthorized entities and can leak sensitive information. This vulnerability could be used to take over the cluster under certain conditions. This issue has been patched in version 3.16.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fit2cloud:kubeoperator:*:*:*:*:*:*:*:*", "matchCriteriaId": "486336C5-5A30-4490-A12B-E79FE102419B", "versionEndExcluding": "3.16.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "KubeOperator is an open source Kubernetes distribution focused on helping enterprises plan, deploy and operate production-level K8s clusters. In KubeOperator versions 3.16.3 and below, API interfaces with unauthorized entities and can leak sensitive information. This vulnerability could be used to take over the cluster under certain conditions. This issue has been patched in version 3.16.4."}], "evaluatorComment": null, "id": "CVE-2023-22480", "lastModified": "2023-01-24T18:40:30.457", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.4, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-01-14T01:15:15.207", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/KubeOperator/KubeOperator/commit/7ef42bf1c16900d13e6376f8be5ecdbfdfb44aaf"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/KubeOperator/KubeOperator/releases/tag/v3.16.4"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/KubeOperator/KubeOperator/security/advisories/GHSA-jxgp-jgh3-8jc8"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-285"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/KubeOperator/KubeOperator/commit/7ef42bf1c16900d13e6376f8be5ecdbfdfb44aaf"}, "type": "CWE-863"}
192
Determine whether the {function_name} code is vulnerable or not.
[ "/*****************************************************************\n|\n| AP4 - Atom Based Sample Tables\n|\n| Copyright 2002-2008 Axiomatic Systems, LLC\n|\n|\n| This atom is part of AP4 (MP4 Audio Processing Library).\n|\n| Unless you have obtained Bento4 under a difference license,\n| this version of Bento4 is Bento4|GPL.\n| Bento4|GPL is free software; you can redistribute it and/or modify\n| it under the terms of the GNU General Public License as published by\n| the Free Software Foundation; either version 2, or (at your option)\n| any later version.\n|\n| Bento4|GPL is distributed in the hope that it will be useful,\n| but WITHOUT ANY WARRANTY; without even the implied warranty of\n| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n| GNU General Public License for more details.\n|\n| You should have received a copy of the GNU General Public License\n| along with Bento4|GPL; see the atom COPYING. If not, write to the\n| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA\n| 02111-1307, USA.\n|\n ****************************************************************/", "/*----------------------------------------------------------------------\n| includes\n+---------------------------------------------------------------------*/\n#include \"Ap4AtomSampleTable.h\"\n#include \"Ap4ByteStream.h\"\n#include \"Ap4StsdAtom.h\"\n#include \"Ap4StscAtom.h\"\n#include \"Ap4StcoAtom.h\"\n#include \"Ap4Co64Atom.h\"\n#include \"Ap4StszAtom.h\"\n#include \"Ap4Stz2Atom.h\"\n#include \"Ap4SttsAtom.h\"\n#include \"Ap4CttsAtom.h\"\n#include \"Ap4StssAtom.h\"\n#include \"Ap4Sample.h\"\n#include \"Ap4Atom.h\"", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable Dynamic Cast Anchor\n+---------------------------------------------------------------------*/\nAP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_AtomSampleTable)", "\n/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::AP4_AtomSampleTable\n+---------------------------------------------------------------------*/\nAP4_AtomSampleTable::AP4_AtomSampleTable(AP4_ContainerAtom* stbl, \n AP4_ByteStream& sample_stream) :\n m_SampleStream(sample_stream)\n{\n m_StscAtom = AP4_DYNAMIC_CAST(AP4_StscAtom, stbl->GetChild(AP4_ATOM_TYPE_STSC));\n m_StcoAtom = AP4_DYNAMIC_CAST(AP4_StcoAtom, stbl->GetChild(AP4_ATOM_TYPE_STCO));\n m_StszAtom = AP4_DYNAMIC_CAST(AP4_StszAtom, stbl->GetChild(AP4_ATOM_TYPE_STSZ));\n m_Stz2Atom = AP4_DYNAMIC_CAST(AP4_Stz2Atom, stbl->GetChild(AP4_ATOM_TYPE_STZ2));\n m_CttsAtom = AP4_DYNAMIC_CAST(AP4_CttsAtom, stbl->GetChild(AP4_ATOM_TYPE_CTTS));\n m_SttsAtom = AP4_DYNAMIC_CAST(AP4_SttsAtom, stbl->GetChild(AP4_ATOM_TYPE_STTS));\n m_StssAtom = AP4_DYNAMIC_CAST(AP4_StssAtom, stbl->GetChild(AP4_ATOM_TYPE_STSS));\n m_StsdAtom = AP4_DYNAMIC_CAST(AP4_StsdAtom, stbl->GetChild(AP4_ATOM_TYPE_STSD));\n m_Co64Atom = AP4_DYNAMIC_CAST(AP4_Co64Atom, stbl->GetChild(AP4_ATOM_TYPE_CO64));", " // keep a reference to the sample stream\n m_SampleStream.AddReference();\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::~AP4_AtomSampleTable\n+---------------------------------------------------------------------*/\nAP4_AtomSampleTable::~AP4_AtomSampleTable()\n{\n m_SampleStream.Release();\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetSample\n+---------------------------------------------------------------------*/\nAP4_Result\nAP4_AtomSampleTable::GetSample(AP4_Ordinal index, \n AP4_Sample& sample)\n{\n AP4_Result result;\n", "", " // check that we have a chunk offset table\n if (m_StcoAtom == NULL && m_Co64Atom == NULL) {\n return AP4_ERROR_INVALID_FORMAT;\n }", " // MP4 uses 1-based indexes internally, so adjust by one\n index++;", " // find out in which chunk this sample is located\n AP4_Ordinal chunk, skip, desc;\n result = m_StscAtom->GetChunkForSample(index, chunk, skip, desc);\n if (AP4_FAILED(result)) return result;\n \n // check that the result is within bounds\n if (skip > index) return AP4_ERROR_INTERNAL;", " // get the atom offset for this chunk\n AP4_UI64 offset;\n if (m_StcoAtom) {\n AP4_UI32 offset_32;\n result = m_StcoAtom->GetChunkOffset(chunk, offset_32);\n offset = offset_32;\n } else {\n result = m_Co64Atom->GetChunkOffset(chunk, offset);\n }\n if (AP4_FAILED(result)) return result;\n \n // compute the additional offset inside the chunk\n for (unsigned int i = index-skip; i < index; i++) {\n AP4_Size size = 0;\n if (m_StszAtom) {\n result = m_StszAtom->GetSampleSize(i, size); \n } else if (m_Stz2Atom) {\n result = m_Stz2Atom->GetSampleSize(i, size); \n } else {\n result = AP4_ERROR_INVALID_FORMAT;\n }\n if (AP4_FAILED(result)) return result;\n offset += size;\n }", " // set the description index\n sample.SetDescriptionIndex(desc-1); // adjust for 0-based indexes", " // set the dts and cts\n AP4_UI32 cts_offset = 0;\n AP4_UI64 dts = 0;\n AP4_UI32 duration = 0;\n result = m_SttsAtom->GetDts(index, dts, &duration);\n if (AP4_FAILED(result)) return result;\n sample.SetDuration(duration);\n sample.SetDts(dts);\n if (m_CttsAtom == NULL) {\n sample.SetCts(dts);\n } else {\n result = m_CttsAtom->GetCtsOffset(index, cts_offset); \n\t if (AP4_FAILED(result)) return result;\n sample.SetCtsDelta(cts_offset);\n } ", " // set the size\n AP4_Size sample_size = 0;\n if (m_StszAtom) {\n result = m_StszAtom->GetSampleSize(index, sample_size); \n } else if (m_Stz2Atom) {\n result = m_Stz2Atom->GetSampleSize(index, sample_size); \n } else {\n result = AP4_ERROR_INVALID_FORMAT;\n }\n if (AP4_FAILED(result)) return result;\n sample.SetSize(sample_size);", " // set the sync flag\n if (m_StssAtom == NULL) {\n sample.SetSync(true);\n } else {\n sample.SetSync(m_StssAtom->IsSampleSync(index));\n }", " // set the offset\n sample.SetOffset(offset);", " // set the data stream\n sample.SetDataStream(m_SampleStream);", "\n return AP4_SUCCESS;\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetSampleCount\n+---------------------------------------------------------------------*/\nAP4_Cardinal\nAP4_AtomSampleTable::GetSampleCount()\n{\n if (m_StszAtom) {\n return m_StszAtom->GetSampleCount();\n } else if (m_Stz2Atom) {\n return m_Stz2Atom->GetSampleCount();\n } else {\n return 0;\n }\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetSampleDescription\n+---------------------------------------------------------------------*/\nAP4_SampleDescription*\nAP4_AtomSampleTable::GetSampleDescription(AP4_Ordinal index)\n{\n return m_StsdAtom ? m_StsdAtom->GetSampleDescription(index) : NULL;\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetSampleDescriptionCount\n+---------------------------------------------------------------------*/\nAP4_Cardinal\nAP4_AtomSampleTable::GetSampleDescriptionCount()\n{\n return m_StsdAtom ? m_StsdAtom->GetSampleDescriptionCount() : 0;\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetSampleChunkPosition\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_AtomSampleTable::GetSampleChunkPosition(AP4_Ordinal sample_index, \n AP4_Ordinal& chunk_index,\n AP4_Ordinal& position_in_chunk)\n{\n // default values\n chunk_index = 0;\n position_in_chunk = 0;\n \n AP4_Ordinal sample_description_index;\n return GetChunkForSample(sample_index, \n chunk_index, \n position_in_chunk, \n sample_description_index);\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetChunkForSample\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_AtomSampleTable::GetChunkForSample(AP4_Ordinal sample_index,\n AP4_Ordinal& chunk_index,\n AP4_Ordinal& position_in_chunk,\n AP4_Ordinal& sample_description_index)\n{\n // default values\n chunk_index = 0;\n position_in_chunk = 0;\n sample_description_index = 0;", " // check that we an stsc atom\n if (m_StscAtom == NULL) return AP4_ERROR_INVALID_STATE;\n \n // get the chunk info from the stsc atom\n AP4_Ordinal chunk = 0;\n AP4_Result result = m_StscAtom->GetChunkForSample(sample_index+1, // the atom API is 1-based \n chunk, \n position_in_chunk, \n sample_description_index);\n if (AP4_FAILED(result)) return result;\n if (chunk == 0) return AP4_ERROR_INTERNAL;", " // the atom sample and chunk indexes are 1-based, so we need to translate\n chunk_index = chunk-1;\n \n return AP4_SUCCESS;\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetChunkOffset\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_AtomSampleTable::GetChunkOffset(AP4_Ordinal chunk_index, \n AP4_Position& offset)\n{\n if (m_StcoAtom) {\n AP4_UI32 offset_32;\n AP4_Result result = m_StcoAtom->GetChunkOffset(chunk_index+1, offset_32);\n if (AP4_SUCCEEDED(result)) {\n offset = offset_32;\n } else {\n offset = 0;\n }\n return result;\n } else if (m_Co64Atom) {\n return m_Co64Atom->GetChunkOffset(chunk_index+1, offset);\n } else {\n offset = 0;\n return AP4_FAILURE;\n }\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::SetChunkOffset\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_AtomSampleTable::SetChunkOffset(AP4_Ordinal chunk_index, \n AP4_Position offset)\n{\n if (m_StcoAtom) {\n if ((offset >> 32) != 0) return AP4_ERROR_OUT_OF_RANGE;\n return m_StcoAtom->SetChunkOffset(chunk_index+1, (AP4_UI32)offset);\n } else if (m_Co64Atom) {\n return m_Co64Atom->SetChunkOffset(chunk_index+1, offset);\n } else {\n return AP4_FAILURE;\n }\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::SetSampleSize\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_AtomSampleTable::SetSampleSize(AP4_Ordinal sample_index, AP4_Size size)\n{\n if (m_StszAtom) {\n return m_StszAtom->SetSampleSize(sample_index+1, size);\n } else if (m_Stz2Atom) {\n return m_Stz2Atom->SetSampleSize(sample_index+1, size);\n } else { \n return AP4_FAILURE;\n }\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetSampleIndexForTimeStamp\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_AtomSampleTable::GetSampleIndexForTimeStamp(AP4_UI64 ts, \n AP4_Ordinal& sample_index)\n{\n return m_SttsAtom ? m_SttsAtom->GetSampleIndexForTimeStamp(ts, sample_index) \n : AP4_FAILURE;\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetNearestSyncSampleIndex\n+---------------------------------------------------------------------*/\nAP4_Ordinal \nAP4_AtomSampleTable::GetNearestSyncSampleIndex(AP4_Ordinal sample_index, bool before)\n{\n // if we don't have an stss table, all samples match\n if (m_StssAtom == NULL) return sample_index;\n \n sample_index += 1; // the table is 1-based\n AP4_Cardinal entry_count = m_StssAtom->GetEntries().ItemCount();\n if (before) {\n AP4_Ordinal cursor = 0; \n for (unsigned int i=0; i<entry_count; i++) {\n if (m_StssAtom->GetEntries()[i] >= sample_index) return cursor;\n if (m_StssAtom->GetEntries()[i]) cursor = m_StssAtom->GetEntries()[i]-1;\n }", " // not found?\n return cursor;\n } else {\n for (unsigned int i=0; i<entry_count; i++) {\n if (m_StssAtom->GetEntries()[i] >= sample_index) {\n return m_StssAtom->GetEntries()[i]?m_StssAtom->GetEntries()[i]-1:sample_index-1;\n }\n }", " // not found?\n return GetSampleCount();\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 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 ]
PreciseBugs
{"buggy_code_end_loc": [89, 274, 556, 42], "buggy_code_start_loc": [89, 273, 556, 40], "filenames": ["Source/C++/Core/Ap4AtomSampleTable.cpp", "Source/C++/Core/Ap4AvccAtom.cpp", "Source/C++/Core/Ap4Processor.cpp", "Source/C++/Core/Ap4Version.h"], "fixing_code_end_loc": [95, 274, 558, 42], "fixing_code_start_loc": [90, 273, 557, 40], "message": "The AP4_AvccAtom::InspectFields function in Core/Ap4AvccAtom.cpp in Bento4 mp4dump before 1.5.0-616 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted mp4 file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:bento4:bento4:*:*:*:*:*:*:*:*", "matchCriteriaId": "03DB20DA-7153-4678-A2D6-01464B589FC8", "versionEndExcluding": null, "versionEndIncluding": "1.5.0-615", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The AP4_AvccAtom::InspectFields function in Core/Ap4AvccAtom.cpp in Bento4 mp4dump before 1.5.0-616 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted mp4 file."}, {"lang": "es", "value": "La funci\u00f3n AP4_AvccAtom::InspectFields en Core/Ap4AvccAtom.cpp en Bento4 mp4dump en versiones anteriores a la 1.5.0-616 permite que atacantes remotos provoquen una denegaci\u00f3n de servicio (desreferencia de puntero NULL y bloqueo de aplicaci\u00f3n) mediante un archivo mp4 manipulado."}], "evaluatorComment": null, "id": "CVE-2017-12476", "lastModified": "2017-09-07T17:17:01.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-09-06T08:29:00.277", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://drive.google.com/open?id=0B6wBkDmxMGMKUjNscThnbTlSZ2s"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://drive.google.com/open?id=0B9DojFnTUSNGZ1JfNUc1am9pcnc"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e"}, "type": "CWE-476"}
193
Determine whether the {function_name} code is vulnerable or not.
[ "/*****************************************************************\n|\n| AP4 - Atom Based Sample Tables\n|\n| Copyright 2002-2008 Axiomatic Systems, LLC\n|\n|\n| This atom is part of AP4 (MP4 Audio Processing Library).\n|\n| Unless you have obtained Bento4 under a difference license,\n| this version of Bento4 is Bento4|GPL.\n| Bento4|GPL is free software; you can redistribute it and/or modify\n| it under the terms of the GNU General Public License as published by\n| the Free Software Foundation; either version 2, or (at your option)\n| any later version.\n|\n| Bento4|GPL is distributed in the hope that it will be useful,\n| but WITHOUT ANY WARRANTY; without even the implied warranty of\n| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n| GNU General Public License for more details.\n|\n| You should have received a copy of the GNU General Public License\n| along with Bento4|GPL; see the atom COPYING. If not, write to the\n| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA\n| 02111-1307, USA.\n|\n ****************************************************************/", "/*----------------------------------------------------------------------\n| includes\n+---------------------------------------------------------------------*/\n#include \"Ap4AtomSampleTable.h\"\n#include \"Ap4ByteStream.h\"\n#include \"Ap4StsdAtom.h\"\n#include \"Ap4StscAtom.h\"\n#include \"Ap4StcoAtom.h\"\n#include \"Ap4Co64Atom.h\"\n#include \"Ap4StszAtom.h\"\n#include \"Ap4Stz2Atom.h\"\n#include \"Ap4SttsAtom.h\"\n#include \"Ap4CttsAtom.h\"\n#include \"Ap4StssAtom.h\"\n#include \"Ap4Sample.h\"\n#include \"Ap4Atom.h\"", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable Dynamic Cast Anchor\n+---------------------------------------------------------------------*/\nAP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_AtomSampleTable)", "\n/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::AP4_AtomSampleTable\n+---------------------------------------------------------------------*/\nAP4_AtomSampleTable::AP4_AtomSampleTable(AP4_ContainerAtom* stbl, \n AP4_ByteStream& sample_stream) :\n m_SampleStream(sample_stream)\n{\n m_StscAtom = AP4_DYNAMIC_CAST(AP4_StscAtom, stbl->GetChild(AP4_ATOM_TYPE_STSC));\n m_StcoAtom = AP4_DYNAMIC_CAST(AP4_StcoAtom, stbl->GetChild(AP4_ATOM_TYPE_STCO));\n m_StszAtom = AP4_DYNAMIC_CAST(AP4_StszAtom, stbl->GetChild(AP4_ATOM_TYPE_STSZ));\n m_Stz2Atom = AP4_DYNAMIC_CAST(AP4_Stz2Atom, stbl->GetChild(AP4_ATOM_TYPE_STZ2));\n m_CttsAtom = AP4_DYNAMIC_CAST(AP4_CttsAtom, stbl->GetChild(AP4_ATOM_TYPE_CTTS));\n m_SttsAtom = AP4_DYNAMIC_CAST(AP4_SttsAtom, stbl->GetChild(AP4_ATOM_TYPE_STTS));\n m_StssAtom = AP4_DYNAMIC_CAST(AP4_StssAtom, stbl->GetChild(AP4_ATOM_TYPE_STSS));\n m_StsdAtom = AP4_DYNAMIC_CAST(AP4_StsdAtom, stbl->GetChild(AP4_ATOM_TYPE_STSD));\n m_Co64Atom = AP4_DYNAMIC_CAST(AP4_Co64Atom, stbl->GetChild(AP4_ATOM_TYPE_CO64));", " // keep a reference to the sample stream\n m_SampleStream.AddReference();\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::~AP4_AtomSampleTable\n+---------------------------------------------------------------------*/\nAP4_AtomSampleTable::~AP4_AtomSampleTable()\n{\n m_SampleStream.Release();\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetSample\n+---------------------------------------------------------------------*/\nAP4_Result\nAP4_AtomSampleTable::GetSample(AP4_Ordinal index, \n AP4_Sample& sample)\n{\n AP4_Result result;\n", " // check that we have an stsc atom\n if (!m_StscAtom) {\n return AP4_ERROR_INVALID_FORMAT;\n }\n ", " // check that we have a chunk offset table\n if (m_StcoAtom == NULL && m_Co64Atom == NULL) {\n return AP4_ERROR_INVALID_FORMAT;\n }", " // MP4 uses 1-based indexes internally, so adjust by one\n index++;", " // find out in which chunk this sample is located\n AP4_Ordinal chunk, skip, desc;\n result = m_StscAtom->GetChunkForSample(index, chunk, skip, desc);\n if (AP4_FAILED(result)) return result;\n \n // check that the result is within bounds\n if (skip > index) return AP4_ERROR_INTERNAL;", " // get the atom offset for this chunk\n AP4_UI64 offset;\n if (m_StcoAtom) {\n AP4_UI32 offset_32;\n result = m_StcoAtom->GetChunkOffset(chunk, offset_32);\n offset = offset_32;\n } else {\n result = m_Co64Atom->GetChunkOffset(chunk, offset);\n }\n if (AP4_FAILED(result)) return result;\n \n // compute the additional offset inside the chunk\n for (unsigned int i = index-skip; i < index; i++) {\n AP4_Size size = 0;\n if (m_StszAtom) {\n result = m_StszAtom->GetSampleSize(i, size); \n } else if (m_Stz2Atom) {\n result = m_Stz2Atom->GetSampleSize(i, size); \n } else {\n result = AP4_ERROR_INVALID_FORMAT;\n }\n if (AP4_FAILED(result)) return result;\n offset += size;\n }", " // set the description index\n sample.SetDescriptionIndex(desc-1); // adjust for 0-based indexes", " // set the dts and cts\n AP4_UI32 cts_offset = 0;\n AP4_UI64 dts = 0;\n AP4_UI32 duration = 0;\n result = m_SttsAtom->GetDts(index, dts, &duration);\n if (AP4_FAILED(result)) return result;\n sample.SetDuration(duration);\n sample.SetDts(dts);\n if (m_CttsAtom == NULL) {\n sample.SetCts(dts);\n } else {\n result = m_CttsAtom->GetCtsOffset(index, cts_offset); \n\t if (AP4_FAILED(result)) return result;\n sample.SetCtsDelta(cts_offset);\n } ", " // set the size\n AP4_Size sample_size = 0;\n if (m_StszAtom) {\n result = m_StszAtom->GetSampleSize(index, sample_size); \n } else if (m_Stz2Atom) {\n result = m_Stz2Atom->GetSampleSize(index, sample_size); \n } else {\n result = AP4_ERROR_INVALID_FORMAT;\n }\n if (AP4_FAILED(result)) return result;\n sample.SetSize(sample_size);", " // set the sync flag\n if (m_StssAtom == NULL) {\n sample.SetSync(true);\n } else {\n sample.SetSync(m_StssAtom->IsSampleSync(index));\n }", " // set the offset\n sample.SetOffset(offset);", " // set the data stream\n sample.SetDataStream(m_SampleStream);", "\n return AP4_SUCCESS;\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetSampleCount\n+---------------------------------------------------------------------*/\nAP4_Cardinal\nAP4_AtomSampleTable::GetSampleCount()\n{\n if (m_StszAtom) {\n return m_StszAtom->GetSampleCount();\n } else if (m_Stz2Atom) {\n return m_Stz2Atom->GetSampleCount();\n } else {\n return 0;\n }\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetSampleDescription\n+---------------------------------------------------------------------*/\nAP4_SampleDescription*\nAP4_AtomSampleTable::GetSampleDescription(AP4_Ordinal index)\n{\n return m_StsdAtom ? m_StsdAtom->GetSampleDescription(index) : NULL;\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetSampleDescriptionCount\n+---------------------------------------------------------------------*/\nAP4_Cardinal\nAP4_AtomSampleTable::GetSampleDescriptionCount()\n{\n return m_StsdAtom ? m_StsdAtom->GetSampleDescriptionCount() : 0;\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetSampleChunkPosition\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_AtomSampleTable::GetSampleChunkPosition(AP4_Ordinal sample_index, \n AP4_Ordinal& chunk_index,\n AP4_Ordinal& position_in_chunk)\n{\n // default values\n chunk_index = 0;\n position_in_chunk = 0;\n \n AP4_Ordinal sample_description_index;\n return GetChunkForSample(sample_index, \n chunk_index, \n position_in_chunk, \n sample_description_index);\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetChunkForSample\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_AtomSampleTable::GetChunkForSample(AP4_Ordinal sample_index,\n AP4_Ordinal& chunk_index,\n AP4_Ordinal& position_in_chunk,\n AP4_Ordinal& sample_description_index)\n{\n // default values\n chunk_index = 0;\n position_in_chunk = 0;\n sample_description_index = 0;", " // check that we an stsc atom\n if (m_StscAtom == NULL) return AP4_ERROR_INVALID_STATE;\n \n // get the chunk info from the stsc atom\n AP4_Ordinal chunk = 0;\n AP4_Result result = m_StscAtom->GetChunkForSample(sample_index+1, // the atom API is 1-based \n chunk, \n position_in_chunk, \n sample_description_index);\n if (AP4_FAILED(result)) return result;\n if (chunk == 0) return AP4_ERROR_INTERNAL;", " // the atom sample and chunk indexes are 1-based, so we need to translate\n chunk_index = chunk-1;\n \n return AP4_SUCCESS;\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetChunkOffset\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_AtomSampleTable::GetChunkOffset(AP4_Ordinal chunk_index, \n AP4_Position& offset)\n{\n if (m_StcoAtom) {\n AP4_UI32 offset_32;\n AP4_Result result = m_StcoAtom->GetChunkOffset(chunk_index+1, offset_32);\n if (AP4_SUCCEEDED(result)) {\n offset = offset_32;\n } else {\n offset = 0;\n }\n return result;\n } else if (m_Co64Atom) {\n return m_Co64Atom->GetChunkOffset(chunk_index+1, offset);\n } else {\n offset = 0;\n return AP4_FAILURE;\n }\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::SetChunkOffset\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_AtomSampleTable::SetChunkOffset(AP4_Ordinal chunk_index, \n AP4_Position offset)\n{\n if (m_StcoAtom) {\n if ((offset >> 32) != 0) return AP4_ERROR_OUT_OF_RANGE;\n return m_StcoAtom->SetChunkOffset(chunk_index+1, (AP4_UI32)offset);\n } else if (m_Co64Atom) {\n return m_Co64Atom->SetChunkOffset(chunk_index+1, offset);\n } else {\n return AP4_FAILURE;\n }\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::SetSampleSize\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_AtomSampleTable::SetSampleSize(AP4_Ordinal sample_index, AP4_Size size)\n{\n if (m_StszAtom) {\n return m_StszAtom->SetSampleSize(sample_index+1, size);\n } else if (m_Stz2Atom) {\n return m_Stz2Atom->SetSampleSize(sample_index+1, size);\n } else { \n return AP4_FAILURE;\n }\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetSampleIndexForTimeStamp\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_AtomSampleTable::GetSampleIndexForTimeStamp(AP4_UI64 ts, \n AP4_Ordinal& sample_index)\n{\n return m_SttsAtom ? m_SttsAtom->GetSampleIndexForTimeStamp(ts, sample_index) \n : AP4_FAILURE;\n}", "/*----------------------------------------------------------------------\n| AP4_AtomSampleTable::GetNearestSyncSampleIndex\n+---------------------------------------------------------------------*/\nAP4_Ordinal \nAP4_AtomSampleTable::GetNearestSyncSampleIndex(AP4_Ordinal sample_index, bool before)\n{\n // if we don't have an stss table, all samples match\n if (m_StssAtom == NULL) return sample_index;\n \n sample_index += 1; // the table is 1-based\n AP4_Cardinal entry_count = m_StssAtom->GetEntries().ItemCount();\n if (before) {\n AP4_Ordinal cursor = 0; \n for (unsigned int i=0; i<entry_count; i++) {\n if (m_StssAtom->GetEntries()[i] >= sample_index) return cursor;\n if (m_StssAtom->GetEntries()[i]) cursor = m_StssAtom->GetEntries()[i]-1;\n }", " // not found?\n return cursor;\n } else {\n for (unsigned int i=0; i<entry_count; i++) {\n if (m_StssAtom->GetEntries()[i] >= sample_index) {\n return m_StssAtom->GetEntries()[i]?m_StssAtom->GetEntries()[i]-1:sample_index-1;\n }\n }", " // not found?\n return GetSampleCount();\n }\n}" ]
[ 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 ]
PreciseBugs
{"buggy_code_end_loc": [89, 274, 556, 42], "buggy_code_start_loc": [89, 273, 556, 40], "filenames": ["Source/C++/Core/Ap4AtomSampleTable.cpp", "Source/C++/Core/Ap4AvccAtom.cpp", "Source/C++/Core/Ap4Processor.cpp", "Source/C++/Core/Ap4Version.h"], "fixing_code_end_loc": [95, 274, 558, 42], "fixing_code_start_loc": [90, 273, 557, 40], "message": "The AP4_AvccAtom::InspectFields function in Core/Ap4AvccAtom.cpp in Bento4 mp4dump before 1.5.0-616 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted mp4 file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:bento4:bento4:*:*:*:*:*:*:*:*", "matchCriteriaId": "03DB20DA-7153-4678-A2D6-01464B589FC8", "versionEndExcluding": null, "versionEndIncluding": "1.5.0-615", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The AP4_AvccAtom::InspectFields function in Core/Ap4AvccAtom.cpp in Bento4 mp4dump before 1.5.0-616 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted mp4 file."}, {"lang": "es", "value": "La funci\u00f3n AP4_AvccAtom::InspectFields en Core/Ap4AvccAtom.cpp en Bento4 mp4dump en versiones anteriores a la 1.5.0-616 permite que atacantes remotos provoquen una denegaci\u00f3n de servicio (desreferencia de puntero NULL y bloqueo de aplicaci\u00f3n) mediante un archivo mp4 manipulado."}], "evaluatorComment": null, "id": "CVE-2017-12476", "lastModified": "2017-09-07T17:17:01.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-09-06T08:29:00.277", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://drive.google.com/open?id=0B6wBkDmxMGMKUjNscThnbTlSZ2s"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://drive.google.com/open?id=0B9DojFnTUSNGZ1JfNUc1am9pcnc"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e"}, "type": "CWE-476"}
193
Determine whether the {function_name} code is vulnerable or not.
[ "/*****************************************************************\n|\n| AP4 - avcC Atoms \n|\n| Copyright 2002-2008 Axiomatic Systems, LLC\n|\n|\n| This file is part of Bento4/AP4 (MP4 Atom Processing Library).\n|\n| Unless you have obtained Bento4 under a difference license,\n| this version of Bento4 is Bento4|GPL.\n| Bento4|GPL is free software; you can redistribute it and/or modify\n| it under the terms of the GNU General Public License as published by\n| the Free Software Foundation; either version 2, or (at your option)\n| any later version.\n|\n| Bento4|GPL is distributed in the hope that it will be useful,\n| but WITHOUT ANY WARRANTY; without even the implied warranty of\n| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n| GNU General Public License for more details.\n|\n| You should have received a copy of the GNU General Public License\n| along with Bento4|GPL; see the file COPYING. If not, write to the\n| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA\n| 02111-1307, USA.\n|\n****************************************************************/", "/*----------------------------------------------------------------------\n| includes\n+---------------------------------------------------------------------*/\n#include \"Ap4AvccAtom.h\"\n#include \"Ap4AtomFactory.h\"\n#include \"Ap4Utils.h\"\n#include \"Ap4Types.h\"", "/*----------------------------------------------------------------------\n| dynamic cast support\n+---------------------------------------------------------------------*/\nAP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_AvccAtom)", "/*----------------------------------------------------------------------\n| AP4_AvccAtom::GetProfileName\n+---------------------------------------------------------------------*/\nconst char*\nAP4_AvccAtom::GetProfileName(AP4_UI08 profile)\n{\n switch (profile) {\n case AP4_AVC_PROFILE_BASELINE: return \"Baseline\"; \n case AP4_AVC_PROFILE_MAIN: return \"Main\";\n case AP4_AVC_PROFILE_EXTENDED: return \"Extended\";\n case AP4_AVC_PROFILE_HIGH: return \"High\";\n case AP4_AVC_PROFILE_HIGH_10: return \"High 10\";\n case AP4_AVC_PROFILE_HIGH_422: return \"High 4:2:2\";\n case AP4_AVC_PROFILE_HIGH_444: return \"High 4:4:4\";\n }", " return NULL;\n}", "/*----------------------------------------------------------------------\n| AP4_AvccAtom::Create\n+---------------------------------------------------------------------*/\nAP4_AvccAtom* \nAP4_AvccAtom::Create(AP4_Size size, AP4_ByteStream& stream)\n{\n // read the raw bytes in a buffer\n unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE;\n AP4_DataBuffer payload_data(payload_size);\n AP4_Result result = stream.Read(payload_data.UseData(), payload_size);\n if (AP4_FAILED(result)) return NULL;\n \n // check the version\n const AP4_UI08* payload = payload_data.GetData();\n if (payload[0] != 1) {\n return NULL;\n }", " // check the size\n if (payload_size < 6) return NULL;\n unsigned int num_seq_params = payload[5]&31;\n unsigned int cursor = 6;\n for (unsigned int i=0; i<num_seq_params; i++) {\n if (cursor+2 > payload_size) return NULL;\n cursor += 2+AP4_BytesToInt16BE(&payload[cursor]);\n if (cursor > payload_size) return NULL;\n }\n unsigned int num_pic_params = payload[cursor++];\n if (cursor > payload_size) return NULL;\n for (unsigned int i=0; i<num_pic_params; i++) {\n if (cursor+2 > payload_size) return NULL;\n cursor += 2+AP4_BytesToInt16BE(&payload[cursor]);\n if (cursor > payload_size) return NULL;\n }\n return new AP4_AvccAtom(size, payload);\n}", "/*----------------------------------------------------------------------\n| AP4_AvccAtom::AP4_AvccAtom\n+---------------------------------------------------------------------*/\nAP4_AvccAtom::AP4_AvccAtom() :\n AP4_Atom(AP4_ATOM_TYPE_AVCC, AP4_ATOM_HEADER_SIZE),\n m_ConfigurationVersion(1),\n m_Profile(0),\n m_Level(0),\n m_ProfileCompatibility(0),\n m_NaluLengthSize(0)\n{\n UpdateRawBytes();\n m_Size32 += m_RawBytes.GetDataSize();\n}", "/*----------------------------------------------------------------------\n| AP4_AvccAtom::AP4_AvccAtom\n+---------------------------------------------------------------------*/\nAP4_AvccAtom::AP4_AvccAtom(const AP4_AvccAtom& other) :\n AP4_Atom(AP4_ATOM_TYPE_AVCC, other.m_Size32),\n m_ConfigurationVersion(other.m_ConfigurationVersion),\n m_Profile(other.m_Profile),\n m_Level(other.m_Level),\n m_ProfileCompatibility(other.m_ProfileCompatibility),\n m_NaluLengthSize(other.m_NaluLengthSize),\n m_RawBytes(other.m_RawBytes)\n{\n // deep copy of the parameters\n unsigned int i = 0;\n for (i=0; i<other.m_SequenceParameters.ItemCount(); i++) {\n m_SequenceParameters.Append(other.m_SequenceParameters[i]);\n }\n for (i=0; i<other.m_PictureParameters.ItemCount(); i++) {\n m_PictureParameters.Append(other.m_PictureParameters[i]);\n } \n}", "/*----------------------------------------------------------------------\n| AP4_AvccAtom::AP4_AvccAtom\n+---------------------------------------------------------------------*/\nAP4_AvccAtom::AP4_AvccAtom(AP4_UI32 size, const AP4_UI08* payload) :\n AP4_Atom(AP4_ATOM_TYPE_AVCC, size)\n{\n // make a copy of our configuration bytes\n unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE;\n m_RawBytes.SetData(payload, payload_size);", " // parse the payload\n m_ConfigurationVersion = payload[0];\n m_Profile = payload[1];\n m_ProfileCompatibility = payload[2];\n m_Level = payload[3];\n m_NaluLengthSize = 1+(payload[4]&3);\n AP4_UI08 num_seq_params = payload[5]&31;\n m_SequenceParameters.EnsureCapacity(num_seq_params);\n unsigned int cursor = 6;\n for (unsigned int i=0; i<num_seq_params; i++) {\n m_SequenceParameters.Append(AP4_DataBuffer());\n AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]);\n m_SequenceParameters[i].SetData(&payload[cursor]+2, param_length);\n cursor += 2+param_length;\n }\n AP4_UI08 num_pic_params = payload[cursor++];\n m_PictureParameters.EnsureCapacity(num_pic_params);\n for (unsigned int i=0; i<num_pic_params; i++) {\n m_PictureParameters.Append(AP4_DataBuffer());\n AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]);\n m_PictureParameters[i].SetData(&payload[cursor]+2, param_length);\n cursor += 2+param_length;\n }\n}", "\n/*----------------------------------------------------------------------\n| AP4_AvccAtom::AP4_AvccAtom\n+---------------------------------------------------------------------*/\nAP4_AvccAtom::AP4_AvccAtom(AP4_UI08 profile, \n AP4_UI08 level, \n AP4_UI08 profile_compatibility, \n AP4_UI08 length_size, \n const AP4_Array<AP4_DataBuffer>& sequence_parameters, \n const AP4_Array<AP4_DataBuffer>& picture_parameters) :\n AP4_Atom(AP4_ATOM_TYPE_AVCC, AP4_ATOM_HEADER_SIZE),\n m_ConfigurationVersion(1),\n m_Profile(profile),\n m_Level(level),\n m_ProfileCompatibility(profile_compatibility),\n m_NaluLengthSize(length_size)\n{\n // deep copy of the parameters\n unsigned int i = 0;\n for (i=0; i<sequence_parameters.ItemCount(); i++) {\n m_SequenceParameters.Append(sequence_parameters[i]);\n }\n for (i=0; i<picture_parameters.ItemCount(); i++) {\n m_PictureParameters.Append(picture_parameters[i]);\n } ", " // compute the raw bytes\n UpdateRawBytes();", " // update the size\n m_Size32 += m_RawBytes.GetDataSize();\n}", "/*----------------------------------------------------------------------\n| AP4_AvccAtom::UpdateRawBytes\n+---------------------------------------------------------------------*/\nvoid\nAP4_AvccAtom::UpdateRawBytes()\n{\n // compute the payload size\n unsigned int payload_size = 6; \n for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {\n payload_size += 2+m_SequenceParameters[i].GetDataSize();\n }\n ++payload_size;\n for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) {\n payload_size += 2+m_PictureParameters[i].GetDataSize();\n }\n m_RawBytes.SetDataSize(payload_size);\n AP4_UI08* payload = m_RawBytes.UseData();", " payload[0] = m_ConfigurationVersion;\n payload[1] = m_Profile;\n payload[2] = m_ProfileCompatibility;\n payload[3] = m_Level;\n payload[4] = 0xFC | (m_NaluLengthSize-1);\n payload[5] = 0xE0 | (AP4_UI08)m_SequenceParameters.ItemCount();\n unsigned int cursor = 6;\n for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {\n AP4_UI16 param_length = (AP4_UI16)m_SequenceParameters[i].GetDataSize();\n AP4_BytesFromUInt16BE(&payload[cursor], param_length);\n cursor += 2;\n AP4_CopyMemory(&payload[cursor], m_SequenceParameters[i].GetData(), param_length);\n cursor += param_length;\n }\n payload[cursor++] = (AP4_UI08)m_PictureParameters.ItemCount();\n for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) {\n AP4_UI16 param_length = (AP4_UI16)m_PictureParameters[i].GetDataSize();\n AP4_BytesFromUInt16BE(&payload[cursor], param_length);\n cursor += 2;\n AP4_CopyMemory(&payload[cursor], m_PictureParameters[i].GetData(), param_length);\n cursor += param_length;\n }\n}", "/*----------------------------------------------------------------------\n| AP4_AvccAtom::WriteFields\n+---------------------------------------------------------------------*/\nAP4_Result\nAP4_AvccAtom::WriteFields(AP4_ByteStream& stream)\n{\n return stream.Write(m_RawBytes.GetData(), m_RawBytes.GetDataSize());\n}", "/*----------------------------------------------------------------------\n| AP4_AvccAtom::InspectFields\n+---------------------------------------------------------------------*/\nAP4_Result\nAP4_AvccAtom::InspectFields(AP4_AtomInspector& inspector)\n{\n inspector.AddField(\"Configuration Version\", m_ConfigurationVersion);\n const char* profile_name = GetProfileName(m_Profile);\n if (profile_name) {\n inspector.AddField(\"Profile\", profile_name);\n } else {\n inspector.AddField(\"Profile\", m_Profile);\n }\n inspector.AddField(\"Profile Compatibility\", m_ProfileCompatibility, AP4_AtomInspector::HINT_HEX);\n inspector.AddField(\"Level\", m_Level);\n inspector.AddField(\"NALU Length Size\", m_NaluLengthSize);\n for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {\n inspector.AddField(\"Sequence Parameter\", m_SequenceParameters[i].GetData(), m_SequenceParameters[i].GetDataSize());\n }", " for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {", " inspector.AddField(\"Picture Parameter\", m_PictureParameters[i].GetData(), m_PictureParameters[i].GetDataSize());\n }\n return AP4_SUCCESS;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [89, 274, 556, 42], "buggy_code_start_loc": [89, 273, 556, 40], "filenames": ["Source/C++/Core/Ap4AtomSampleTable.cpp", "Source/C++/Core/Ap4AvccAtom.cpp", "Source/C++/Core/Ap4Processor.cpp", "Source/C++/Core/Ap4Version.h"], "fixing_code_end_loc": [95, 274, 558, 42], "fixing_code_start_loc": [90, 273, 557, 40], "message": "The AP4_AvccAtom::InspectFields function in Core/Ap4AvccAtom.cpp in Bento4 mp4dump before 1.5.0-616 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted mp4 file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:bento4:bento4:*:*:*:*:*:*:*:*", "matchCriteriaId": "03DB20DA-7153-4678-A2D6-01464B589FC8", "versionEndExcluding": null, "versionEndIncluding": "1.5.0-615", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The AP4_AvccAtom::InspectFields function in Core/Ap4AvccAtom.cpp in Bento4 mp4dump before 1.5.0-616 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted mp4 file."}, {"lang": "es", "value": "La funci\u00f3n AP4_AvccAtom::InspectFields en Core/Ap4AvccAtom.cpp en Bento4 mp4dump en versiones anteriores a la 1.5.0-616 permite que atacantes remotos provoquen una denegaci\u00f3n de servicio (desreferencia de puntero NULL y bloqueo de aplicaci\u00f3n) mediante un archivo mp4 manipulado."}], "evaluatorComment": null, "id": "CVE-2017-12476", "lastModified": "2017-09-07T17:17:01.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-09-06T08:29:00.277", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://drive.google.com/open?id=0B6wBkDmxMGMKUjNscThnbTlSZ2s"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://drive.google.com/open?id=0B9DojFnTUSNGZ1JfNUc1am9pcnc"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e"}, "type": "CWE-476"}
193
Determine whether the {function_name} code is vulnerable or not.
[ "/*****************************************************************\n|\n| AP4 - avcC Atoms \n|\n| Copyright 2002-2008 Axiomatic Systems, LLC\n|\n|\n| This file is part of Bento4/AP4 (MP4 Atom Processing Library).\n|\n| Unless you have obtained Bento4 under a difference license,\n| this version of Bento4 is Bento4|GPL.\n| Bento4|GPL is free software; you can redistribute it and/or modify\n| it under the terms of the GNU General Public License as published by\n| the Free Software Foundation; either version 2, or (at your option)\n| any later version.\n|\n| Bento4|GPL is distributed in the hope that it will be useful,\n| but WITHOUT ANY WARRANTY; without even the implied warranty of\n| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n| GNU General Public License for more details.\n|\n| You should have received a copy of the GNU General Public License\n| along with Bento4|GPL; see the file COPYING. If not, write to the\n| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA\n| 02111-1307, USA.\n|\n****************************************************************/", "/*----------------------------------------------------------------------\n| includes\n+---------------------------------------------------------------------*/\n#include \"Ap4AvccAtom.h\"\n#include \"Ap4AtomFactory.h\"\n#include \"Ap4Utils.h\"\n#include \"Ap4Types.h\"", "/*----------------------------------------------------------------------\n| dynamic cast support\n+---------------------------------------------------------------------*/\nAP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_AvccAtom)", "/*----------------------------------------------------------------------\n| AP4_AvccAtom::GetProfileName\n+---------------------------------------------------------------------*/\nconst char*\nAP4_AvccAtom::GetProfileName(AP4_UI08 profile)\n{\n switch (profile) {\n case AP4_AVC_PROFILE_BASELINE: return \"Baseline\"; \n case AP4_AVC_PROFILE_MAIN: return \"Main\";\n case AP4_AVC_PROFILE_EXTENDED: return \"Extended\";\n case AP4_AVC_PROFILE_HIGH: return \"High\";\n case AP4_AVC_PROFILE_HIGH_10: return \"High 10\";\n case AP4_AVC_PROFILE_HIGH_422: return \"High 4:2:2\";\n case AP4_AVC_PROFILE_HIGH_444: return \"High 4:4:4\";\n }", " return NULL;\n}", "/*----------------------------------------------------------------------\n| AP4_AvccAtom::Create\n+---------------------------------------------------------------------*/\nAP4_AvccAtom* \nAP4_AvccAtom::Create(AP4_Size size, AP4_ByteStream& stream)\n{\n // read the raw bytes in a buffer\n unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE;\n AP4_DataBuffer payload_data(payload_size);\n AP4_Result result = stream.Read(payload_data.UseData(), payload_size);\n if (AP4_FAILED(result)) return NULL;\n \n // check the version\n const AP4_UI08* payload = payload_data.GetData();\n if (payload[0] != 1) {\n return NULL;\n }", " // check the size\n if (payload_size < 6) return NULL;\n unsigned int num_seq_params = payload[5]&31;\n unsigned int cursor = 6;\n for (unsigned int i=0; i<num_seq_params; i++) {\n if (cursor+2 > payload_size) return NULL;\n cursor += 2+AP4_BytesToInt16BE(&payload[cursor]);\n if (cursor > payload_size) return NULL;\n }\n unsigned int num_pic_params = payload[cursor++];\n if (cursor > payload_size) return NULL;\n for (unsigned int i=0; i<num_pic_params; i++) {\n if (cursor+2 > payload_size) return NULL;\n cursor += 2+AP4_BytesToInt16BE(&payload[cursor]);\n if (cursor > payload_size) return NULL;\n }\n return new AP4_AvccAtom(size, payload);\n}", "/*----------------------------------------------------------------------\n| AP4_AvccAtom::AP4_AvccAtom\n+---------------------------------------------------------------------*/\nAP4_AvccAtom::AP4_AvccAtom() :\n AP4_Atom(AP4_ATOM_TYPE_AVCC, AP4_ATOM_HEADER_SIZE),\n m_ConfigurationVersion(1),\n m_Profile(0),\n m_Level(0),\n m_ProfileCompatibility(0),\n m_NaluLengthSize(0)\n{\n UpdateRawBytes();\n m_Size32 += m_RawBytes.GetDataSize();\n}", "/*----------------------------------------------------------------------\n| AP4_AvccAtom::AP4_AvccAtom\n+---------------------------------------------------------------------*/\nAP4_AvccAtom::AP4_AvccAtom(const AP4_AvccAtom& other) :\n AP4_Atom(AP4_ATOM_TYPE_AVCC, other.m_Size32),\n m_ConfigurationVersion(other.m_ConfigurationVersion),\n m_Profile(other.m_Profile),\n m_Level(other.m_Level),\n m_ProfileCompatibility(other.m_ProfileCompatibility),\n m_NaluLengthSize(other.m_NaluLengthSize),\n m_RawBytes(other.m_RawBytes)\n{\n // deep copy of the parameters\n unsigned int i = 0;\n for (i=0; i<other.m_SequenceParameters.ItemCount(); i++) {\n m_SequenceParameters.Append(other.m_SequenceParameters[i]);\n }\n for (i=0; i<other.m_PictureParameters.ItemCount(); i++) {\n m_PictureParameters.Append(other.m_PictureParameters[i]);\n } \n}", "/*----------------------------------------------------------------------\n| AP4_AvccAtom::AP4_AvccAtom\n+---------------------------------------------------------------------*/\nAP4_AvccAtom::AP4_AvccAtom(AP4_UI32 size, const AP4_UI08* payload) :\n AP4_Atom(AP4_ATOM_TYPE_AVCC, size)\n{\n // make a copy of our configuration bytes\n unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE;\n m_RawBytes.SetData(payload, payload_size);", " // parse the payload\n m_ConfigurationVersion = payload[0];\n m_Profile = payload[1];\n m_ProfileCompatibility = payload[2];\n m_Level = payload[3];\n m_NaluLengthSize = 1+(payload[4]&3);\n AP4_UI08 num_seq_params = payload[5]&31;\n m_SequenceParameters.EnsureCapacity(num_seq_params);\n unsigned int cursor = 6;\n for (unsigned int i=0; i<num_seq_params; i++) {\n m_SequenceParameters.Append(AP4_DataBuffer());\n AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]);\n m_SequenceParameters[i].SetData(&payload[cursor]+2, param_length);\n cursor += 2+param_length;\n }\n AP4_UI08 num_pic_params = payload[cursor++];\n m_PictureParameters.EnsureCapacity(num_pic_params);\n for (unsigned int i=0; i<num_pic_params; i++) {\n m_PictureParameters.Append(AP4_DataBuffer());\n AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]);\n m_PictureParameters[i].SetData(&payload[cursor]+2, param_length);\n cursor += 2+param_length;\n }\n}", "\n/*----------------------------------------------------------------------\n| AP4_AvccAtom::AP4_AvccAtom\n+---------------------------------------------------------------------*/\nAP4_AvccAtom::AP4_AvccAtom(AP4_UI08 profile, \n AP4_UI08 level, \n AP4_UI08 profile_compatibility, \n AP4_UI08 length_size, \n const AP4_Array<AP4_DataBuffer>& sequence_parameters, \n const AP4_Array<AP4_DataBuffer>& picture_parameters) :\n AP4_Atom(AP4_ATOM_TYPE_AVCC, AP4_ATOM_HEADER_SIZE),\n m_ConfigurationVersion(1),\n m_Profile(profile),\n m_Level(level),\n m_ProfileCompatibility(profile_compatibility),\n m_NaluLengthSize(length_size)\n{\n // deep copy of the parameters\n unsigned int i = 0;\n for (i=0; i<sequence_parameters.ItemCount(); i++) {\n m_SequenceParameters.Append(sequence_parameters[i]);\n }\n for (i=0; i<picture_parameters.ItemCount(); i++) {\n m_PictureParameters.Append(picture_parameters[i]);\n } ", " // compute the raw bytes\n UpdateRawBytes();", " // update the size\n m_Size32 += m_RawBytes.GetDataSize();\n}", "/*----------------------------------------------------------------------\n| AP4_AvccAtom::UpdateRawBytes\n+---------------------------------------------------------------------*/\nvoid\nAP4_AvccAtom::UpdateRawBytes()\n{\n // compute the payload size\n unsigned int payload_size = 6; \n for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {\n payload_size += 2+m_SequenceParameters[i].GetDataSize();\n }\n ++payload_size;\n for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) {\n payload_size += 2+m_PictureParameters[i].GetDataSize();\n }\n m_RawBytes.SetDataSize(payload_size);\n AP4_UI08* payload = m_RawBytes.UseData();", " payload[0] = m_ConfigurationVersion;\n payload[1] = m_Profile;\n payload[2] = m_ProfileCompatibility;\n payload[3] = m_Level;\n payload[4] = 0xFC | (m_NaluLengthSize-1);\n payload[5] = 0xE0 | (AP4_UI08)m_SequenceParameters.ItemCount();\n unsigned int cursor = 6;\n for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {\n AP4_UI16 param_length = (AP4_UI16)m_SequenceParameters[i].GetDataSize();\n AP4_BytesFromUInt16BE(&payload[cursor], param_length);\n cursor += 2;\n AP4_CopyMemory(&payload[cursor], m_SequenceParameters[i].GetData(), param_length);\n cursor += param_length;\n }\n payload[cursor++] = (AP4_UI08)m_PictureParameters.ItemCount();\n for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) {\n AP4_UI16 param_length = (AP4_UI16)m_PictureParameters[i].GetDataSize();\n AP4_BytesFromUInt16BE(&payload[cursor], param_length);\n cursor += 2;\n AP4_CopyMemory(&payload[cursor], m_PictureParameters[i].GetData(), param_length);\n cursor += param_length;\n }\n}", "/*----------------------------------------------------------------------\n| AP4_AvccAtom::WriteFields\n+---------------------------------------------------------------------*/\nAP4_Result\nAP4_AvccAtom::WriteFields(AP4_ByteStream& stream)\n{\n return stream.Write(m_RawBytes.GetData(), m_RawBytes.GetDataSize());\n}", "/*----------------------------------------------------------------------\n| AP4_AvccAtom::InspectFields\n+---------------------------------------------------------------------*/\nAP4_Result\nAP4_AvccAtom::InspectFields(AP4_AtomInspector& inspector)\n{\n inspector.AddField(\"Configuration Version\", m_ConfigurationVersion);\n const char* profile_name = GetProfileName(m_Profile);\n if (profile_name) {\n inspector.AddField(\"Profile\", profile_name);\n } else {\n inspector.AddField(\"Profile\", m_Profile);\n }\n inspector.AddField(\"Profile Compatibility\", m_ProfileCompatibility, AP4_AtomInspector::HINT_HEX);\n inspector.AddField(\"Level\", m_Level);\n inspector.AddField(\"NALU Length Size\", m_NaluLengthSize);\n for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {\n inspector.AddField(\"Sequence Parameter\", m_SequenceParameters[i].GetData(), m_SequenceParameters[i].GetDataSize());\n }", " for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) {", " inspector.AddField(\"Picture Parameter\", m_PictureParameters[i].GetData(), m_PictureParameters[i].GetDataSize());\n }\n return AP4_SUCCESS;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [89, 274, 556, 42], "buggy_code_start_loc": [89, 273, 556, 40], "filenames": ["Source/C++/Core/Ap4AtomSampleTable.cpp", "Source/C++/Core/Ap4AvccAtom.cpp", "Source/C++/Core/Ap4Processor.cpp", "Source/C++/Core/Ap4Version.h"], "fixing_code_end_loc": [95, 274, 558, 42], "fixing_code_start_loc": [90, 273, 557, 40], "message": "The AP4_AvccAtom::InspectFields function in Core/Ap4AvccAtom.cpp in Bento4 mp4dump before 1.5.0-616 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted mp4 file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:bento4:bento4:*:*:*:*:*:*:*:*", "matchCriteriaId": "03DB20DA-7153-4678-A2D6-01464B589FC8", "versionEndExcluding": null, "versionEndIncluding": "1.5.0-615", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The AP4_AvccAtom::InspectFields function in Core/Ap4AvccAtom.cpp in Bento4 mp4dump before 1.5.0-616 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted mp4 file."}, {"lang": "es", "value": "La funci\u00f3n AP4_AvccAtom::InspectFields en Core/Ap4AvccAtom.cpp en Bento4 mp4dump en versiones anteriores a la 1.5.0-616 permite que atacantes remotos provoquen una denegaci\u00f3n de servicio (desreferencia de puntero NULL y bloqueo de aplicaci\u00f3n) mediante un archivo mp4 manipulado."}], "evaluatorComment": null, "id": "CVE-2017-12476", "lastModified": "2017-09-07T17:17:01.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-09-06T08:29:00.277", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://drive.google.com/open?id=0B6wBkDmxMGMKUjNscThnbTlSZ2s"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://drive.google.com/open?id=0B9DojFnTUSNGZ1JfNUc1am9pcnc"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e"}, "type": "CWE-476"}
193
Determine whether the {function_name} code is vulnerable or not.
[ "/*****************************************************************\n|\n| AP4 - File Processor\n|\n| Copyright 2002-2008 Axiomatic Systems, LLC\n|\n|\n| This file is part of Bento4/AP4 (MP4 Atom Processing Library).\n|\n| Unless you have obtained Bento4 under a difference license,\n| this version of Bento4 is Bento4|GPL.\n| Bento4|GPL is free software; you can redistribute it and/or modify\n| it under the terms of the GNU General Public License as published by\n| the Free Software Foundation; either version 2, or (at your option)\n| any later version.\n|\n| Bento4|GPL is distributed in the hope that it will be useful,\n| but WITHOUT ANY WARRANTY; without even the implied warranty of\n| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n| GNU General Public License for more details.\n|\n| You should have received a copy of the GNU General Public License\n| along with Bento4|GPL; see the file COPYING. If not, write to the\n| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA\n| 02111-1307, USA.\n|\n****************************************************************/", "/*----------------------------------------------------------------------\n| includes\n+---------------------------------------------------------------------*/\n#include \"Ap4Processor.h\"\n#include \"Ap4AtomSampleTable.h\"\n#include \"Ap4MovieFragment.h\"\n#include \"Ap4FragmentSampleTable.h\"\n#include \"Ap4TfhdAtom.h\"\n#include \"Ap4AtomFactory.h\"\n#include \"Ap4Movie.h\"\n#include \"Ap4Array.h\"\n#include \"Ap4Sample.h\"\n#include \"Ap4TrakAtom.h\"\n#include \"Ap4TfraAtom.h\"\n#include \"Ap4TrunAtom.h\"\n#include \"Ap4TrexAtom.h\"\n#include \"Ap4TkhdAtom.h\"\n#include \"Ap4SidxAtom.h\"\n#include \"Ap4DataBuffer.h\"\n#include \"Ap4Debug.h\"", "/*----------------------------------------------------------------------\n| types\n+---------------------------------------------------------------------*/\nstruct AP4_SampleLocator {\n AP4_SampleLocator() : \n m_TrakIndex(0), \n m_SampleTable(NULL), \n m_SampleIndex(0), \n m_ChunkIndex(0) {}\n AP4_Ordinal m_TrakIndex;\n AP4_AtomSampleTable* m_SampleTable;\n AP4_Ordinal m_SampleIndex;\n AP4_Ordinal m_ChunkIndex;\n AP4_Sample m_Sample;\n};", "struct AP4_SampleCursor {\n AP4_SampleCursor() : m_EndReached(false) {}\n AP4_SampleLocator m_Locator;\n bool m_EndReached;\n};", "struct AP4_AtomLocator {\n AP4_AtomLocator(AP4_Atom* atom, AP4_UI64 offset) : \n m_Atom(atom),\n m_Offset(offset) {}\n AP4_Atom* m_Atom;\n AP4_UI64 m_Offset;\n};", "/*----------------------------------------------------------------------\n| AP4_DefaultFragmentHandler\n+---------------------------------------------------------------------*/\nclass AP4_DefaultFragmentHandler: public AP4_Processor::FragmentHandler {\npublic:\n AP4_DefaultFragmentHandler(AP4_Processor::TrackHandler* track_handler) :\n m_TrackHandler(track_handler) {}\n AP4_Result ProcessSample(AP4_DataBuffer& data_in,\n AP4_DataBuffer& data_out);\n \nprivate:\n AP4_Processor::TrackHandler* m_TrackHandler;\n};", "/*----------------------------------------------------------------------\n| AP4_DefaultFragmentHandler::ProcessSample\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_DefaultFragmentHandler::ProcessSample(AP4_DataBuffer& data_in, AP4_DataBuffer& data_out)\n{\n if (m_TrackHandler == NULL) {\n data_out.SetData(data_in.GetData(), data_in.GetDataSize());\n return AP4_SUCCESS;\n }\n return m_TrackHandler->ProcessSample(data_in, data_out);\n}", "/*----------------------------------------------------------------------\n| FragmentMapEntry\n+---------------------------------------------------------------------*/\ntypedef struct {\n AP4_UI64 before;\n AP4_UI64 after;\n} FragmentMapEntry;", "/*----------------------------------------------------------------------\n| FindFragmentMapEntry\n+---------------------------------------------------------------------*/\nstatic const FragmentMapEntry*\nFindFragmentMapEntry(AP4_Array<FragmentMapEntry>& fragment_map, AP4_UI64 fragment_offset) {\n int first = 0;\n int last = fragment_map.ItemCount();\n while (first < last) {\n int middle = (last+first)/2;\n AP4_UI64 middle_value = fragment_map[middle].before;\n if (fragment_offset < middle_value) {\n last = middle;\n } else if (fragment_offset > middle_value) {\n first = middle+1;\n } else {\n return &fragment_map[middle];\n }\n }\n \n return NULL;\n}", "/*----------------------------------------------------------------------\n| AP4_Processor::ProcessFragments\n+---------------------------------------------------------------------*/\nAP4_Result\nAP4_Processor::ProcessFragments(AP4_MoovAtom* moov, \n AP4_List<AP4_AtomLocator>& atoms, \n AP4_ContainerAtom* mfra,\n AP4_SidxAtom* sidx,\n AP4_Position sidx_position,\n AP4_ByteStream& input, \n AP4_ByteStream& output)\n{\n unsigned int fragment_index = 0;\n AP4_Array<FragmentMapEntry> fragment_map;\n \n for (AP4_List<AP4_AtomLocator>::Item* item = atoms.FirstItem();\n item;\n item = item->GetNext(), ++fragment_index) {\n AP4_AtomLocator* locator = item->GetData();\n AP4_Atom* atom = locator->m_Atom;\n AP4_UI64 atom_offset = locator->m_Offset;\n AP4_UI64 mdat_payload_offset = atom_offset+atom->GetSize()+AP4_ATOM_HEADER_SIZE;\n AP4_Sample sample;\n AP4_DataBuffer sample_data_in;\n AP4_DataBuffer sample_data_out;\n AP4_Result result;\n \n // if this is not a moof atom, just write it back and continue\n if (atom->GetType() != AP4_ATOM_TYPE_MOOF) {\n result = atom->Write(output);\n if (AP4_FAILED(result)) return result;\n continue;\n }\n \n // parse the moof\n AP4_ContainerAtom* moof = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);\n AP4_MovieFragment* fragment = new AP4_MovieFragment(moof);", " // process all the traf atoms\n AP4_Array<AP4_Processor::FragmentHandler*> handlers;\n AP4_Array<AP4_FragmentSampleTable*> sample_tables;\n for (;AP4_Atom* child = moof->GetChild(AP4_ATOM_TYPE_TRAF, handlers.ItemCount());) {\n AP4_ContainerAtom* traf = AP4_DYNAMIC_CAST(AP4_ContainerAtom, child);\n AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD));\n \n // find the 'trak' for this track\n AP4_TrakAtom* trak = NULL;\n for (AP4_List<AP4_Atom>::Item* child_item = moov->GetChildren().FirstItem();\n child_item;\n child_item = child_item->GetNext()) {\n AP4_Atom* child_atom = child_item->GetData();\n if (child_atom->GetType() == AP4_ATOM_TYPE_TRAK) {\n trak = AP4_DYNAMIC_CAST(AP4_TrakAtom, child_atom);\n if (trak) {\n AP4_TkhdAtom* tkhd = AP4_DYNAMIC_CAST(AP4_TkhdAtom, trak->GetChild(AP4_ATOM_TYPE_TKHD));\n if (tkhd && tkhd->GetTrackId() == tfhd->GetTrackId()) {\n break;\n }\n }\n trak = NULL;\n }\n }\n \n // find the 'trex' for this track\n AP4_ContainerAtom* mvex = NULL;\n AP4_TrexAtom* trex = NULL;\n mvex = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moov->GetChild(AP4_ATOM_TYPE_MVEX));\n if (mvex) {\n for (AP4_List<AP4_Atom>::Item* child_item = mvex->GetChildren().FirstItem();\n child_item;\n child_item = child_item->GetNext()) {\n AP4_Atom* child_atom = child_item->GetData();\n if (child_atom->GetType() == AP4_ATOM_TYPE_TREX) {\n trex = AP4_DYNAMIC_CAST(AP4_TrexAtom, child_atom);\n if (trex && trex->GetTrackId() == tfhd->GetTrackId()) {\n break;\n }\n trex = NULL;\n }\n }\n }", " // create the handler for this traf\n AP4_Processor::FragmentHandler* handler = CreateFragmentHandler(trak, trex, traf, input, atom_offset);\n if (handler) {\n result = handler->ProcessFragment();\n if (AP4_FAILED(result)) return result;\n }\n handlers.Append(handler);\n \n // create a sample table object so we can read the sample data\n AP4_FragmentSampleTable* sample_table = NULL;\n result = fragment->CreateSampleTable(moov, tfhd->GetTrackId(), &input, atom_offset, mdat_payload_offset, 0, sample_table);\n if (AP4_FAILED(result)) return result;\n sample_tables.Append(sample_table);\n \n // let the handler look at the samples before we process them\n if (handler) result = handler->PrepareForSamples(sample_table);\n if (AP4_FAILED(result)) return result;\n }\n \n // write the moof\n AP4_UI64 moof_out_start = 0;\n output.Tell(moof_out_start);\n moof->Write(output);\n \n // remember the location of this fragment\n FragmentMapEntry map_entry = {atom_offset, moof_out_start};\n fragment_map.Append(map_entry);", " // write an mdat header\n AP4_Position mdat_out_start;\n AP4_UI64 mdat_size = AP4_ATOM_HEADER_SIZE;\n output.Tell(mdat_out_start);\n output.WriteUI32(0);\n output.WriteUI32(AP4_ATOM_TYPE_MDAT);", " // process all track runs\n for (unsigned int i=0; i<handlers.ItemCount(); i++) {\n AP4_Processor::FragmentHandler* handler = handlers[i];", " // get the track ID\n AP4_ContainerAtom* traf = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moof->GetChild(AP4_ATOM_TYPE_TRAF, i));\n if (traf == NULL) continue;\n AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD));\n \n // compute the base data offset\n AP4_UI64 base_data_offset;\n if (tfhd->GetFlags() & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT) {\n base_data_offset = mdat_out_start+AP4_ATOM_HEADER_SIZE;\n } else {\n base_data_offset = moof_out_start;\n }\n \n // build a list of all trun atoms\n AP4_Array<AP4_TrunAtom*> truns;\n for (AP4_List<AP4_Atom>::Item* child_item = traf->GetChildren().FirstItem();\n child_item;\n child_item = child_item->GetNext()) {\n AP4_Atom* child_atom = child_item->GetData();\n if (child_atom->GetType() == AP4_ATOM_TYPE_TRUN) {\n AP4_TrunAtom* trun = AP4_DYNAMIC_CAST(AP4_TrunAtom, child_atom);\n truns.Append(trun);\n }\n } \n AP4_Ordinal trun_index = 0;\n AP4_Ordinal trun_sample_index = 0;\n AP4_TrunAtom* trun = truns[0];\n trun->SetDataOffset((AP4_SI32)((mdat_out_start+mdat_size)-base_data_offset));\n \n // write the mdat\n for (unsigned int j=0; j<sample_tables[i]->GetSampleCount(); j++, trun_sample_index++) {\n // advance the trun index if necessary\n if (trun_sample_index >= trun->GetEntries().ItemCount()) {\n trun = truns[++trun_index];\n trun->SetDataOffset((AP4_SI32)((mdat_out_start+mdat_size)-base_data_offset));\n trun_sample_index = 0;\n }\n \n // get the next sample\n result = sample_tables[i]->GetSample(j, sample);\n if (AP4_FAILED(result)) return result;\n sample.ReadData(sample_data_in);\n \n // process the sample data\n if (handler) {\n result = handler->ProcessSample(sample_data_in, sample_data_out);\n if (AP4_FAILED(result)) return result;", " // write the sample data\n result = output.Write(sample_data_out.GetData(), sample_data_out.GetDataSize());\n if (AP4_FAILED(result)) return result;", " // update the mdat size\n mdat_size += sample_data_out.GetDataSize();\n \n // update the trun entry\n trun->UseEntries()[trun_sample_index].sample_size = sample_data_out.GetDataSize();\n } else {\n // write the sample data (unmodified)\n result = output.Write(sample_data_in.GetData(), sample_data_in.GetDataSize());\n if (AP4_FAILED(result)) return result;", " // update the mdat size\n mdat_size += sample_data_in.GetDataSize();\n }\n }", " if (handler) {\n // update the tfhd header\n if (tfhd->GetFlags() & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT) {\n tfhd->SetBaseDataOffset(mdat_out_start+AP4_ATOM_HEADER_SIZE);\n }\n if (tfhd->GetFlags() & AP4_TFHD_FLAG_DEFAULT_SAMPLE_SIZE_PRESENT) {\n tfhd->SetDefaultSampleSize(trun->GetEntries()[0].sample_size);\n }\n \n // give the handler a chance to update the atoms\n handler->FinishFragment();\n }\n }", " // update the mdat header\n AP4_Position mdat_out_end;\n output.Tell(mdat_out_end);\n#if defined(AP4_DEBUG)\n AP4_ASSERT(mdat_out_end-mdat_out_start == mdat_size);\n#endif\n output.Seek(mdat_out_start);\n output.WriteUI32((AP4_UI32)mdat_size);\n output.Seek(mdat_out_end);\n \n // update the moof if needed\n output.Seek(moof_out_start);\n moof->Write(output);\n output.Seek(mdat_out_end);\n \n // update the sidx if we have one\n if (sidx && fragment_index < sidx->GetReferences().ItemCount()) {\n if (fragment_index == 0) {\n sidx->SetFirstOffset(moof_out_start-(sidx_position+sidx->GetSize()));\n }\n AP4_LargeSize fragment_size = mdat_out_end-moof_out_start;\n AP4_SidxAtom::Reference& sidx_ref = sidx->UseReferences()[fragment_index];\n sidx_ref.m_ReferencedSize = (AP4_UI32)fragment_size;\n }\n \n // cleanup\n delete fragment;\n \n for (unsigned int i=0; i<handlers.ItemCount(); i++) {\n delete handlers[i];\n }\n for (unsigned int i=0; i<sample_tables.ItemCount(); i++) {\n delete sample_tables[i];\n }\n }\n \n // update the mfra if we have one\n if (mfra) {\n for (AP4_List<AP4_Atom>::Item* mfra_item = mfra->GetChildren().FirstItem();\n mfra_item;\n mfra_item = mfra_item->GetNext()) {\n if (mfra_item->GetData()->GetType() != AP4_ATOM_TYPE_TFRA) continue;\n AP4_TfraAtom* tfra = AP4_DYNAMIC_CAST(AP4_TfraAtom, mfra_item->GetData());\n if (tfra == NULL) continue;\n AP4_Array<AP4_TfraAtom::Entry>& entries = tfra->GetEntries();\n AP4_Cardinal entry_count = entries.ItemCount();\n for (unsigned int i=0; i<entry_count; i++) {\n const FragmentMapEntry* found = FindFragmentMapEntry(fragment_map, entries[i].m_MoofOffset);\n if (found) {\n entries[i].m_MoofOffset = found->after;\n }\n }\n }\n }\n \n return AP4_SUCCESS;\n}", "/*----------------------------------------------------------------------\n| AP4_Processor::CreateFragmentHandler\n+---------------------------------------------------------------------*/\nAP4_Processor::FragmentHandler* \nAP4_Processor::CreateFragmentHandler(AP4_TrakAtom* /* trak */,\n AP4_TrexAtom* /* trex */,\n AP4_ContainerAtom* traf,\n AP4_ByteStream& /* moof_data */,\n AP4_Position /* moof_offset */)\n{\n // find the matching track handler\n for (unsigned int i=0; i<m_TrackIds.ItemCount(); i++) {\n AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD));\n if (tfhd && m_TrackIds[i] == tfhd->GetTrackId()) {\n return new AP4_DefaultFragmentHandler(m_TrackHandlers[i]);\n }\n }\n \n return NULL;\n}", "/*----------------------------------------------------------------------\n| AP4_Processor::Process\n+---------------------------------------------------------------------*/\nAP4_Result\nAP4_Processor::Process(AP4_ByteStream& input, \n AP4_ByteStream& output,\n AP4_ByteStream* fragments,\n ProgressListener* listener,\n AP4_AtomFactory& atom_factory)\n{\n // read all atoms.\n // keep all atoms except [mdat]\n // keep a ref to [moov]\n // put [moof] atoms in a separate list\n AP4_AtomParent top_level;\n AP4_MoovAtom* moov = NULL;\n AP4_ContainerAtom* mfra = NULL;\n AP4_SidxAtom* sidx = NULL;\n AP4_List<AP4_AtomLocator> frags;\n AP4_UI64 stream_offset = 0;\n bool in_fragments = false;\n unsigned int sidx_count = 0;\n for (AP4_Atom* atom = NULL;\n AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(input, atom));\n input.Tell(stream_offset)) {\n if (atom->GetType() == AP4_ATOM_TYPE_MDAT) {\n delete atom;\n continue;\n } else if (atom->GetType() == AP4_ATOM_TYPE_MOOV) {\n moov = AP4_DYNAMIC_CAST(AP4_MoovAtom, atom);\n if (fragments) break;\n } else if (atom->GetType() == AP4_ATOM_TYPE_MFRA) {\n mfra = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);\n continue;\n } else if (atom->GetType() == AP4_ATOM_TYPE_SIDX) {\n // don't keep the index, it is likely to be invalidated, we will recompute it later\n ++sidx_count;\n if (sidx == NULL) {\n sidx = AP4_DYNAMIC_CAST(AP4_SidxAtom, atom);\n } else {\n delete atom;\n continue;\n }\n } else if (atom->GetType() == AP4_ATOM_TYPE_SSIX) {\n // don't keep the index, it is likely to be invalidated\n delete atom;\n continue;\n } else if (!fragments && (in_fragments || atom->GetType() == AP4_ATOM_TYPE_MOOF)) {\n in_fragments = true;\n frags.Add(new AP4_AtomLocator(atom, stream_offset));\n continue;\n }\n top_level.AddChild(atom);\n }", " // check that we have at most one sidx (we can't deal with multi-sidx streams here\n if (sidx_count > 1) {\n top_level.RemoveChild(sidx);\n delete sidx;\n sidx = NULL;\n }\n \n // if we have a fragments stream, get the fragment locators from there\n if (fragments) {\n stream_offset = 0;\n for (AP4_Atom* atom = NULL;\n AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(*fragments, atom));\n fragments->Tell(stream_offset)) {\n if (atom->GetType() == AP4_ATOM_TYPE_MDAT) {\n delete atom;\n continue;\n }\n frags.Add(new AP4_AtomLocator(atom, stream_offset));\n }\n }\n \n // initialize the processor\n AP4_Result result = Initialize(top_level, input);\n if (AP4_FAILED(result)) return result;", " // process the tracks if we have a moov atom\n AP4_Array<AP4_SampleLocator> locators;\n AP4_Cardinal track_count = 0;\n AP4_List<AP4_TrakAtom>* trak_atoms = NULL;\n AP4_LargeSize mdat_payload_size = 0;\n AP4_SampleCursor* cursors = NULL;\n if (moov) {\n // build an array of track sample locators\n trak_atoms = &moov->GetTrakAtoms();\n track_count = trak_atoms->ItemCount();\n cursors = new AP4_SampleCursor[track_count];\n m_TrackHandlers.SetItemCount(track_count);\n m_TrackIds.SetItemCount(track_count);\n for (AP4_Ordinal i=0; i<track_count; i++) {\n m_TrackHandlers[i] = NULL;\n m_TrackIds[i] = 0;\n }\n \n unsigned int index = 0;\n for (AP4_List<AP4_TrakAtom>::Item* item = trak_atoms->FirstItem(); item; item=item->GetNext()) {\n AP4_TrakAtom* trak = item->GetData();", " // find the stsd atom\n AP4_ContainerAtom* stbl = AP4_DYNAMIC_CAST(AP4_ContainerAtom, trak->FindChild(\"mdia/minf/stbl\"));\n if (stbl == NULL) continue;\n \n // see if there's an external data source for this track\n AP4_ByteStream* trak_data_stream = &input;\n for (AP4_List<ExternalTrackData>::Item* ditem = m_ExternalTrackData.FirstItem(); ditem; ditem=ditem->GetNext()) {\n ExternalTrackData* tdata = ditem->GetData();\n if (tdata->m_TrackId == trak->GetId()) {\n trak_data_stream = tdata->m_MediaData;\n break;\n }\n }", " // create the track handler \n m_TrackHandlers[index] = CreateTrackHandler(trak);\n m_TrackIds[index] = trak->GetId();\n cursors[index].m_Locator.m_TrakIndex = index;\n cursors[index].m_Locator.m_SampleTable = new AP4_AtomSampleTable(stbl, *trak_data_stream);\n cursors[index].m_Locator.m_SampleIndex = 0;\n cursors[index].m_Locator.m_ChunkIndex = 0;\n if (cursors[index].m_Locator.m_SampleTable->GetSampleCount()) {\n cursors[index].m_Locator.m_SampleTable->GetSample(0, cursors[index].m_Locator.m_Sample);\n } else {\n cursors[index].m_EndReached = true;\n }", " index++; \n }", " // figure out the layout of the chunks\n for (;;) {\n // see which is the next sample to write\n AP4_UI64 min_offset = (AP4_UI64)(-1);\n int cursor = -1;\n for (unsigned int i=0; i<track_count; i++) {\n if (!cursors[i].m_EndReached &&", "", " cursors[i].m_Locator.m_Sample.GetOffset() <= min_offset) {\n min_offset = cursors[i].m_Locator.m_Sample.GetOffset();\n cursor = i;\n }\n }", " // stop if all cursors are exhausted\n if (cursor == -1) break;", " // append this locator to the layout list\n AP4_SampleLocator& locator = cursors[cursor].m_Locator;\n locators.Append(locator);", " // move the cursor to the next sample\n locator.m_SampleIndex++;\n if (locator.m_SampleIndex == locator.m_SampleTable->GetSampleCount()) {\n // mark this track as completed\n cursors[cursor].m_EndReached = true;\n } else {\n // get the next sample info\n locator.m_SampleTable->GetSample(locator.m_SampleIndex, locator.m_Sample);\n AP4_Ordinal skip, sdesc;\n locator.m_SampleTable->GetChunkForSample(locator.m_SampleIndex,\n locator.m_ChunkIndex,\n skip, sdesc);\n }\n }", " // update the stbl atoms and compute the mdat size\n int current_track = -1;\n int current_chunk = -1;\n AP4_Position current_chunk_offset = 0;\n AP4_Size current_chunk_size = 0;\n for (AP4_Ordinal i=0; i<locators.ItemCount(); i++) {\n AP4_SampleLocator& locator = locators[i];\n if ((int)locator.m_TrakIndex != current_track ||\n (int)locator.m_ChunkIndex != current_chunk) {\n // start a new chunk for this track\n current_chunk_offset += current_chunk_size;\n current_chunk_size = 0;\n current_track = locator.m_TrakIndex;\n current_chunk = locator.m_ChunkIndex;\n locator.m_SampleTable->SetChunkOffset(locator.m_ChunkIndex, current_chunk_offset);\n } \n AP4_Size sample_size;\n TrackHandler* handler = m_TrackHandlers[locator.m_TrakIndex];\n if (handler) {\n sample_size = handler->GetProcessedSampleSize(locator.m_Sample);\n locator.m_SampleTable->SetSampleSize(locator.m_SampleIndex, sample_size);\n } else {\n sample_size = locator.m_Sample.GetSize();\n }\n current_chunk_size += sample_size;\n mdat_payload_size += sample_size;\n }", " // process the tracks (ex: sample descriptions processing)\n for (AP4_Ordinal i=0; i<track_count; i++) {\n TrackHandler* handler = m_TrackHandlers[i];\n if (handler) handler->ProcessTrack();\n }\n }", " // finalize the processor\n Finalize(top_level);", " if (!fragments) {\n // calculate the size of all atoms combined\n AP4_UI64 atoms_size = 0;\n top_level.GetChildren().Apply(AP4_AtomSizeAdder(atoms_size));", " // see if we need a 64-bit or 32-bit mdat\n AP4_Size mdat_header_size = AP4_ATOM_HEADER_SIZE;\n if (mdat_payload_size+mdat_header_size > 0xFFFFFFFF) {\n // we need a 64-bit size\n mdat_header_size += 8;\n }\n \n // adjust the chunk offsets\n for (AP4_Ordinal i=0; i<track_count; i++) {\n AP4_TrakAtom* trak;\n trak_atoms->Get(i, trak);\n trak->AdjustChunkOffsets(atoms_size+mdat_header_size);\n }", " // write all atoms\n top_level.GetChildren().Apply(AP4_AtomListWriter(output));", " // write mdat header\n if (mdat_payload_size) {\n if (mdat_header_size == AP4_ATOM_HEADER_SIZE) {\n // 32-bit size\n output.WriteUI32((AP4_UI32)(mdat_header_size+mdat_payload_size));\n output.WriteUI32(AP4_ATOM_TYPE_MDAT);\n } else {\n // 64-bit size\n output.WriteUI32(1);\n output.WriteUI32(AP4_ATOM_TYPE_MDAT);\n output.WriteUI64(mdat_header_size+mdat_payload_size);\n }\n } \n }\n \n // write the samples\n if (moov) {\n if (!fragments) {\n#if defined(AP4_DEBUG)\n AP4_Position before;\n output.Tell(before);\n#endif\n AP4_Sample sample;\n AP4_DataBuffer data_in;\n AP4_DataBuffer data_out;\n for (unsigned int i=0; i<locators.ItemCount(); i++) {\n AP4_SampleLocator& locator = locators[i];\n locator.m_Sample.ReadData(data_in);\n TrackHandler* handler = m_TrackHandlers[locator.m_TrakIndex];\n if (handler) {\n result = handler->ProcessSample(data_in, data_out);\n if (AP4_FAILED(result)) return result;\n output.Write(data_out.GetData(), data_out.GetDataSize());\n } else {\n output.Write(data_in.GetData(), data_in.GetDataSize()); \n }", " // notify the progress listener\n if (listener) {\n listener->OnProgress(i+1, locators.ItemCount());\n }\n }", "#if defined(AP4_DEBUG)\n AP4_Position after;\n output.Tell(after);\n AP4_ASSERT(after-before == mdat_payload_size);\n#endif\n }\n \n // find the position of the sidx atom\n AP4_Position sidx_position = 0;\n if (sidx) {\n for (AP4_List<AP4_Atom>::Item* item = top_level.GetChildren().FirstItem();\n item;\n item = item->GetNext()) {\n AP4_Atom* atom = item->GetData();\n if (atom->GetType() == AP4_ATOM_TYPE_SIDX) {\n break;\n }\n sidx_position += atom->GetSize();\n }\n }\n \n // process the fragments, if any\n result = ProcessFragments(moov, frags, mfra, sidx, sidx_position, fragments?*fragments:input, output);\n if (AP4_FAILED(result)) return result;\n \n // update and re-write the sidx if we have one\n if (sidx && sidx_position) {\n AP4_Position where = 0;\n output.Tell(where);\n output.Seek(sidx_position);\n result = sidx->Write(output);\n if (AP4_FAILED(result)) return result;\n output.Seek(where);\n }\n \n if (!fragments) {\n // write the mfra atom at the end if we have one\n if (mfra) {\n mfra->Write(output);\n }\n }\n \n // cleanup\n for (AP4_Ordinal i=0; i<track_count; i++) {\n delete cursors[i].m_Locator.m_SampleTable;\n delete m_TrackHandlers[i];\n }\n m_TrackHandlers.Clear();\n delete[] cursors;\n }", " // cleanup\n frags.DeleteReferences();\n delete mfra;\n \n return AP4_SUCCESS;\n}", "/*----------------------------------------------------------------------\n| AP4_Processor::Process\n+---------------------------------------------------------------------*/\nAP4_Result\nAP4_Processor::Process(AP4_ByteStream& input, \n AP4_ByteStream& output,\n ProgressListener* listener,\n AP4_AtomFactory& atom_factory)\n{\n return Process(input, output, NULL, listener, atom_factory);\n}", "/*----------------------------------------------------------------------\n| AP4_Processor::Process\n+---------------------------------------------------------------------*/\nAP4_Result\nAP4_Processor::Process(AP4_ByteStream& fragments, \n AP4_ByteStream& output,\n AP4_ByteStream& init,\n ProgressListener* listener,\n AP4_AtomFactory& atom_factory)\n{\n return Process(init, output, &fragments, listener, atom_factory);\n}", "/*----------------------------------------------------------------------\n| AP4_Processor:Initialize\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_Processor::Initialize(AP4_AtomParent& /* top_level */,\n AP4_ByteStream& /* stream */,\n ProgressListener* /* listener */)\n{\n // default implementation: do nothing\n return AP4_SUCCESS;\n}", "/*----------------------------------------------------------------------\n| AP4_Processor:Finalize\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_Processor::Finalize(AP4_AtomParent& /* top_level */,\n ProgressListener* /* listener */ )\n{\n // default implementation: do nothing\n return AP4_SUCCESS;\n}", "/*----------------------------------------------------------------------\n| AP4_Processor::TrackHandler Dynamic Cast Anchor\n+---------------------------------------------------------------------*/\nAP4_DEFINE_DYNAMIC_CAST_ANCHOR_S(AP4_Processor::TrackHandler, TrackHandler)" ]
[ 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [89, 274, 556, 42], "buggy_code_start_loc": [89, 273, 556, 40], "filenames": ["Source/C++/Core/Ap4AtomSampleTable.cpp", "Source/C++/Core/Ap4AvccAtom.cpp", "Source/C++/Core/Ap4Processor.cpp", "Source/C++/Core/Ap4Version.h"], "fixing_code_end_loc": [95, 274, 558, 42], "fixing_code_start_loc": [90, 273, 557, 40], "message": "The AP4_AvccAtom::InspectFields function in Core/Ap4AvccAtom.cpp in Bento4 mp4dump before 1.5.0-616 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted mp4 file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:bento4:bento4:*:*:*:*:*:*:*:*", "matchCriteriaId": "03DB20DA-7153-4678-A2D6-01464B589FC8", "versionEndExcluding": null, "versionEndIncluding": "1.5.0-615", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The AP4_AvccAtom::InspectFields function in Core/Ap4AvccAtom.cpp in Bento4 mp4dump before 1.5.0-616 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted mp4 file."}, {"lang": "es", "value": "La funci\u00f3n AP4_AvccAtom::InspectFields en Core/Ap4AvccAtom.cpp en Bento4 mp4dump en versiones anteriores a la 1.5.0-616 permite que atacantes remotos provoquen una denegaci\u00f3n de servicio (desreferencia de puntero NULL y bloqueo de aplicaci\u00f3n) mediante un archivo mp4 manipulado."}], "evaluatorComment": null, "id": "CVE-2017-12476", "lastModified": "2017-09-07T17:17:01.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-09-06T08:29:00.277", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://drive.google.com/open?id=0B6wBkDmxMGMKUjNscThnbTlSZ2s"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://drive.google.com/open?id=0B9DojFnTUSNGZ1JfNUc1am9pcnc"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e"}, "type": "CWE-476"}
193
Determine whether the {function_name} code is vulnerable or not.
[ "/*****************************************************************\n|\n| AP4 - File Processor\n|\n| Copyright 2002-2008 Axiomatic Systems, LLC\n|\n|\n| This file is part of Bento4/AP4 (MP4 Atom Processing Library).\n|\n| Unless you have obtained Bento4 under a difference license,\n| this version of Bento4 is Bento4|GPL.\n| Bento4|GPL is free software; you can redistribute it and/or modify\n| it under the terms of the GNU General Public License as published by\n| the Free Software Foundation; either version 2, or (at your option)\n| any later version.\n|\n| Bento4|GPL is distributed in the hope that it will be useful,\n| but WITHOUT ANY WARRANTY; without even the implied warranty of\n| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n| GNU General Public License for more details.\n|\n| You should have received a copy of the GNU General Public License\n| along with Bento4|GPL; see the file COPYING. If not, write to the\n| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA\n| 02111-1307, USA.\n|\n****************************************************************/", "/*----------------------------------------------------------------------\n| includes\n+---------------------------------------------------------------------*/\n#include \"Ap4Processor.h\"\n#include \"Ap4AtomSampleTable.h\"\n#include \"Ap4MovieFragment.h\"\n#include \"Ap4FragmentSampleTable.h\"\n#include \"Ap4TfhdAtom.h\"\n#include \"Ap4AtomFactory.h\"\n#include \"Ap4Movie.h\"\n#include \"Ap4Array.h\"\n#include \"Ap4Sample.h\"\n#include \"Ap4TrakAtom.h\"\n#include \"Ap4TfraAtom.h\"\n#include \"Ap4TrunAtom.h\"\n#include \"Ap4TrexAtom.h\"\n#include \"Ap4TkhdAtom.h\"\n#include \"Ap4SidxAtom.h\"\n#include \"Ap4DataBuffer.h\"\n#include \"Ap4Debug.h\"", "/*----------------------------------------------------------------------\n| types\n+---------------------------------------------------------------------*/\nstruct AP4_SampleLocator {\n AP4_SampleLocator() : \n m_TrakIndex(0), \n m_SampleTable(NULL), \n m_SampleIndex(0), \n m_ChunkIndex(0) {}\n AP4_Ordinal m_TrakIndex;\n AP4_AtomSampleTable* m_SampleTable;\n AP4_Ordinal m_SampleIndex;\n AP4_Ordinal m_ChunkIndex;\n AP4_Sample m_Sample;\n};", "struct AP4_SampleCursor {\n AP4_SampleCursor() : m_EndReached(false) {}\n AP4_SampleLocator m_Locator;\n bool m_EndReached;\n};", "struct AP4_AtomLocator {\n AP4_AtomLocator(AP4_Atom* atom, AP4_UI64 offset) : \n m_Atom(atom),\n m_Offset(offset) {}\n AP4_Atom* m_Atom;\n AP4_UI64 m_Offset;\n};", "/*----------------------------------------------------------------------\n| AP4_DefaultFragmentHandler\n+---------------------------------------------------------------------*/\nclass AP4_DefaultFragmentHandler: public AP4_Processor::FragmentHandler {\npublic:\n AP4_DefaultFragmentHandler(AP4_Processor::TrackHandler* track_handler) :\n m_TrackHandler(track_handler) {}\n AP4_Result ProcessSample(AP4_DataBuffer& data_in,\n AP4_DataBuffer& data_out);\n \nprivate:\n AP4_Processor::TrackHandler* m_TrackHandler;\n};", "/*----------------------------------------------------------------------\n| AP4_DefaultFragmentHandler::ProcessSample\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_DefaultFragmentHandler::ProcessSample(AP4_DataBuffer& data_in, AP4_DataBuffer& data_out)\n{\n if (m_TrackHandler == NULL) {\n data_out.SetData(data_in.GetData(), data_in.GetDataSize());\n return AP4_SUCCESS;\n }\n return m_TrackHandler->ProcessSample(data_in, data_out);\n}", "/*----------------------------------------------------------------------\n| FragmentMapEntry\n+---------------------------------------------------------------------*/\ntypedef struct {\n AP4_UI64 before;\n AP4_UI64 after;\n} FragmentMapEntry;", "/*----------------------------------------------------------------------\n| FindFragmentMapEntry\n+---------------------------------------------------------------------*/\nstatic const FragmentMapEntry*\nFindFragmentMapEntry(AP4_Array<FragmentMapEntry>& fragment_map, AP4_UI64 fragment_offset) {\n int first = 0;\n int last = fragment_map.ItemCount();\n while (first < last) {\n int middle = (last+first)/2;\n AP4_UI64 middle_value = fragment_map[middle].before;\n if (fragment_offset < middle_value) {\n last = middle;\n } else if (fragment_offset > middle_value) {\n first = middle+1;\n } else {\n return &fragment_map[middle];\n }\n }\n \n return NULL;\n}", "/*----------------------------------------------------------------------\n| AP4_Processor::ProcessFragments\n+---------------------------------------------------------------------*/\nAP4_Result\nAP4_Processor::ProcessFragments(AP4_MoovAtom* moov, \n AP4_List<AP4_AtomLocator>& atoms, \n AP4_ContainerAtom* mfra,\n AP4_SidxAtom* sidx,\n AP4_Position sidx_position,\n AP4_ByteStream& input, \n AP4_ByteStream& output)\n{\n unsigned int fragment_index = 0;\n AP4_Array<FragmentMapEntry> fragment_map;\n \n for (AP4_List<AP4_AtomLocator>::Item* item = atoms.FirstItem();\n item;\n item = item->GetNext(), ++fragment_index) {\n AP4_AtomLocator* locator = item->GetData();\n AP4_Atom* atom = locator->m_Atom;\n AP4_UI64 atom_offset = locator->m_Offset;\n AP4_UI64 mdat_payload_offset = atom_offset+atom->GetSize()+AP4_ATOM_HEADER_SIZE;\n AP4_Sample sample;\n AP4_DataBuffer sample_data_in;\n AP4_DataBuffer sample_data_out;\n AP4_Result result;\n \n // if this is not a moof atom, just write it back and continue\n if (atom->GetType() != AP4_ATOM_TYPE_MOOF) {\n result = atom->Write(output);\n if (AP4_FAILED(result)) return result;\n continue;\n }\n \n // parse the moof\n AP4_ContainerAtom* moof = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);\n AP4_MovieFragment* fragment = new AP4_MovieFragment(moof);", " // process all the traf atoms\n AP4_Array<AP4_Processor::FragmentHandler*> handlers;\n AP4_Array<AP4_FragmentSampleTable*> sample_tables;\n for (;AP4_Atom* child = moof->GetChild(AP4_ATOM_TYPE_TRAF, handlers.ItemCount());) {\n AP4_ContainerAtom* traf = AP4_DYNAMIC_CAST(AP4_ContainerAtom, child);\n AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD));\n \n // find the 'trak' for this track\n AP4_TrakAtom* trak = NULL;\n for (AP4_List<AP4_Atom>::Item* child_item = moov->GetChildren().FirstItem();\n child_item;\n child_item = child_item->GetNext()) {\n AP4_Atom* child_atom = child_item->GetData();\n if (child_atom->GetType() == AP4_ATOM_TYPE_TRAK) {\n trak = AP4_DYNAMIC_CAST(AP4_TrakAtom, child_atom);\n if (trak) {\n AP4_TkhdAtom* tkhd = AP4_DYNAMIC_CAST(AP4_TkhdAtom, trak->GetChild(AP4_ATOM_TYPE_TKHD));\n if (tkhd && tkhd->GetTrackId() == tfhd->GetTrackId()) {\n break;\n }\n }\n trak = NULL;\n }\n }\n \n // find the 'trex' for this track\n AP4_ContainerAtom* mvex = NULL;\n AP4_TrexAtom* trex = NULL;\n mvex = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moov->GetChild(AP4_ATOM_TYPE_MVEX));\n if (mvex) {\n for (AP4_List<AP4_Atom>::Item* child_item = mvex->GetChildren().FirstItem();\n child_item;\n child_item = child_item->GetNext()) {\n AP4_Atom* child_atom = child_item->GetData();\n if (child_atom->GetType() == AP4_ATOM_TYPE_TREX) {\n trex = AP4_DYNAMIC_CAST(AP4_TrexAtom, child_atom);\n if (trex && trex->GetTrackId() == tfhd->GetTrackId()) {\n break;\n }\n trex = NULL;\n }\n }\n }", " // create the handler for this traf\n AP4_Processor::FragmentHandler* handler = CreateFragmentHandler(trak, trex, traf, input, atom_offset);\n if (handler) {\n result = handler->ProcessFragment();\n if (AP4_FAILED(result)) return result;\n }\n handlers.Append(handler);\n \n // create a sample table object so we can read the sample data\n AP4_FragmentSampleTable* sample_table = NULL;\n result = fragment->CreateSampleTable(moov, tfhd->GetTrackId(), &input, atom_offset, mdat_payload_offset, 0, sample_table);\n if (AP4_FAILED(result)) return result;\n sample_tables.Append(sample_table);\n \n // let the handler look at the samples before we process them\n if (handler) result = handler->PrepareForSamples(sample_table);\n if (AP4_FAILED(result)) return result;\n }\n \n // write the moof\n AP4_UI64 moof_out_start = 0;\n output.Tell(moof_out_start);\n moof->Write(output);\n \n // remember the location of this fragment\n FragmentMapEntry map_entry = {atom_offset, moof_out_start};\n fragment_map.Append(map_entry);", " // write an mdat header\n AP4_Position mdat_out_start;\n AP4_UI64 mdat_size = AP4_ATOM_HEADER_SIZE;\n output.Tell(mdat_out_start);\n output.WriteUI32(0);\n output.WriteUI32(AP4_ATOM_TYPE_MDAT);", " // process all track runs\n for (unsigned int i=0; i<handlers.ItemCount(); i++) {\n AP4_Processor::FragmentHandler* handler = handlers[i];", " // get the track ID\n AP4_ContainerAtom* traf = AP4_DYNAMIC_CAST(AP4_ContainerAtom, moof->GetChild(AP4_ATOM_TYPE_TRAF, i));\n if (traf == NULL) continue;\n AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD));\n \n // compute the base data offset\n AP4_UI64 base_data_offset;\n if (tfhd->GetFlags() & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT) {\n base_data_offset = mdat_out_start+AP4_ATOM_HEADER_SIZE;\n } else {\n base_data_offset = moof_out_start;\n }\n \n // build a list of all trun atoms\n AP4_Array<AP4_TrunAtom*> truns;\n for (AP4_List<AP4_Atom>::Item* child_item = traf->GetChildren().FirstItem();\n child_item;\n child_item = child_item->GetNext()) {\n AP4_Atom* child_atom = child_item->GetData();\n if (child_atom->GetType() == AP4_ATOM_TYPE_TRUN) {\n AP4_TrunAtom* trun = AP4_DYNAMIC_CAST(AP4_TrunAtom, child_atom);\n truns.Append(trun);\n }\n } \n AP4_Ordinal trun_index = 0;\n AP4_Ordinal trun_sample_index = 0;\n AP4_TrunAtom* trun = truns[0];\n trun->SetDataOffset((AP4_SI32)((mdat_out_start+mdat_size)-base_data_offset));\n \n // write the mdat\n for (unsigned int j=0; j<sample_tables[i]->GetSampleCount(); j++, trun_sample_index++) {\n // advance the trun index if necessary\n if (trun_sample_index >= trun->GetEntries().ItemCount()) {\n trun = truns[++trun_index];\n trun->SetDataOffset((AP4_SI32)((mdat_out_start+mdat_size)-base_data_offset));\n trun_sample_index = 0;\n }\n \n // get the next sample\n result = sample_tables[i]->GetSample(j, sample);\n if (AP4_FAILED(result)) return result;\n sample.ReadData(sample_data_in);\n \n // process the sample data\n if (handler) {\n result = handler->ProcessSample(sample_data_in, sample_data_out);\n if (AP4_FAILED(result)) return result;", " // write the sample data\n result = output.Write(sample_data_out.GetData(), sample_data_out.GetDataSize());\n if (AP4_FAILED(result)) return result;", " // update the mdat size\n mdat_size += sample_data_out.GetDataSize();\n \n // update the trun entry\n trun->UseEntries()[trun_sample_index].sample_size = sample_data_out.GetDataSize();\n } else {\n // write the sample data (unmodified)\n result = output.Write(sample_data_in.GetData(), sample_data_in.GetDataSize());\n if (AP4_FAILED(result)) return result;", " // update the mdat size\n mdat_size += sample_data_in.GetDataSize();\n }\n }", " if (handler) {\n // update the tfhd header\n if (tfhd->GetFlags() & AP4_TFHD_FLAG_BASE_DATA_OFFSET_PRESENT) {\n tfhd->SetBaseDataOffset(mdat_out_start+AP4_ATOM_HEADER_SIZE);\n }\n if (tfhd->GetFlags() & AP4_TFHD_FLAG_DEFAULT_SAMPLE_SIZE_PRESENT) {\n tfhd->SetDefaultSampleSize(trun->GetEntries()[0].sample_size);\n }\n \n // give the handler a chance to update the atoms\n handler->FinishFragment();\n }\n }", " // update the mdat header\n AP4_Position mdat_out_end;\n output.Tell(mdat_out_end);\n#if defined(AP4_DEBUG)\n AP4_ASSERT(mdat_out_end-mdat_out_start == mdat_size);\n#endif\n output.Seek(mdat_out_start);\n output.WriteUI32((AP4_UI32)mdat_size);\n output.Seek(mdat_out_end);\n \n // update the moof if needed\n output.Seek(moof_out_start);\n moof->Write(output);\n output.Seek(mdat_out_end);\n \n // update the sidx if we have one\n if (sidx && fragment_index < sidx->GetReferences().ItemCount()) {\n if (fragment_index == 0) {\n sidx->SetFirstOffset(moof_out_start-(sidx_position+sidx->GetSize()));\n }\n AP4_LargeSize fragment_size = mdat_out_end-moof_out_start;\n AP4_SidxAtom::Reference& sidx_ref = sidx->UseReferences()[fragment_index];\n sidx_ref.m_ReferencedSize = (AP4_UI32)fragment_size;\n }\n \n // cleanup\n delete fragment;\n \n for (unsigned int i=0; i<handlers.ItemCount(); i++) {\n delete handlers[i];\n }\n for (unsigned int i=0; i<sample_tables.ItemCount(); i++) {\n delete sample_tables[i];\n }\n }\n \n // update the mfra if we have one\n if (mfra) {\n for (AP4_List<AP4_Atom>::Item* mfra_item = mfra->GetChildren().FirstItem();\n mfra_item;\n mfra_item = mfra_item->GetNext()) {\n if (mfra_item->GetData()->GetType() != AP4_ATOM_TYPE_TFRA) continue;\n AP4_TfraAtom* tfra = AP4_DYNAMIC_CAST(AP4_TfraAtom, mfra_item->GetData());\n if (tfra == NULL) continue;\n AP4_Array<AP4_TfraAtom::Entry>& entries = tfra->GetEntries();\n AP4_Cardinal entry_count = entries.ItemCount();\n for (unsigned int i=0; i<entry_count; i++) {\n const FragmentMapEntry* found = FindFragmentMapEntry(fragment_map, entries[i].m_MoofOffset);\n if (found) {\n entries[i].m_MoofOffset = found->after;\n }\n }\n }\n }\n \n return AP4_SUCCESS;\n}", "/*----------------------------------------------------------------------\n| AP4_Processor::CreateFragmentHandler\n+---------------------------------------------------------------------*/\nAP4_Processor::FragmentHandler* \nAP4_Processor::CreateFragmentHandler(AP4_TrakAtom* /* trak */,\n AP4_TrexAtom* /* trex */,\n AP4_ContainerAtom* traf,\n AP4_ByteStream& /* moof_data */,\n AP4_Position /* moof_offset */)\n{\n // find the matching track handler\n for (unsigned int i=0; i<m_TrackIds.ItemCount(); i++) {\n AP4_TfhdAtom* tfhd = AP4_DYNAMIC_CAST(AP4_TfhdAtom, traf->GetChild(AP4_ATOM_TYPE_TFHD));\n if (tfhd && m_TrackIds[i] == tfhd->GetTrackId()) {\n return new AP4_DefaultFragmentHandler(m_TrackHandlers[i]);\n }\n }\n \n return NULL;\n}", "/*----------------------------------------------------------------------\n| AP4_Processor::Process\n+---------------------------------------------------------------------*/\nAP4_Result\nAP4_Processor::Process(AP4_ByteStream& input, \n AP4_ByteStream& output,\n AP4_ByteStream* fragments,\n ProgressListener* listener,\n AP4_AtomFactory& atom_factory)\n{\n // read all atoms.\n // keep all atoms except [mdat]\n // keep a ref to [moov]\n // put [moof] atoms in a separate list\n AP4_AtomParent top_level;\n AP4_MoovAtom* moov = NULL;\n AP4_ContainerAtom* mfra = NULL;\n AP4_SidxAtom* sidx = NULL;\n AP4_List<AP4_AtomLocator> frags;\n AP4_UI64 stream_offset = 0;\n bool in_fragments = false;\n unsigned int sidx_count = 0;\n for (AP4_Atom* atom = NULL;\n AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(input, atom));\n input.Tell(stream_offset)) {\n if (atom->GetType() == AP4_ATOM_TYPE_MDAT) {\n delete atom;\n continue;\n } else if (atom->GetType() == AP4_ATOM_TYPE_MOOV) {\n moov = AP4_DYNAMIC_CAST(AP4_MoovAtom, atom);\n if (fragments) break;\n } else if (atom->GetType() == AP4_ATOM_TYPE_MFRA) {\n mfra = AP4_DYNAMIC_CAST(AP4_ContainerAtom, atom);\n continue;\n } else if (atom->GetType() == AP4_ATOM_TYPE_SIDX) {\n // don't keep the index, it is likely to be invalidated, we will recompute it later\n ++sidx_count;\n if (sidx == NULL) {\n sidx = AP4_DYNAMIC_CAST(AP4_SidxAtom, atom);\n } else {\n delete atom;\n continue;\n }\n } else if (atom->GetType() == AP4_ATOM_TYPE_SSIX) {\n // don't keep the index, it is likely to be invalidated\n delete atom;\n continue;\n } else if (!fragments && (in_fragments || atom->GetType() == AP4_ATOM_TYPE_MOOF)) {\n in_fragments = true;\n frags.Add(new AP4_AtomLocator(atom, stream_offset));\n continue;\n }\n top_level.AddChild(atom);\n }", " // check that we have at most one sidx (we can't deal with multi-sidx streams here\n if (sidx_count > 1) {\n top_level.RemoveChild(sidx);\n delete sidx;\n sidx = NULL;\n }\n \n // if we have a fragments stream, get the fragment locators from there\n if (fragments) {\n stream_offset = 0;\n for (AP4_Atom* atom = NULL;\n AP4_SUCCEEDED(atom_factory.CreateAtomFromStream(*fragments, atom));\n fragments->Tell(stream_offset)) {\n if (atom->GetType() == AP4_ATOM_TYPE_MDAT) {\n delete atom;\n continue;\n }\n frags.Add(new AP4_AtomLocator(atom, stream_offset));\n }\n }\n \n // initialize the processor\n AP4_Result result = Initialize(top_level, input);\n if (AP4_FAILED(result)) return result;", " // process the tracks if we have a moov atom\n AP4_Array<AP4_SampleLocator> locators;\n AP4_Cardinal track_count = 0;\n AP4_List<AP4_TrakAtom>* trak_atoms = NULL;\n AP4_LargeSize mdat_payload_size = 0;\n AP4_SampleCursor* cursors = NULL;\n if (moov) {\n // build an array of track sample locators\n trak_atoms = &moov->GetTrakAtoms();\n track_count = trak_atoms->ItemCount();\n cursors = new AP4_SampleCursor[track_count];\n m_TrackHandlers.SetItemCount(track_count);\n m_TrackIds.SetItemCount(track_count);\n for (AP4_Ordinal i=0; i<track_count; i++) {\n m_TrackHandlers[i] = NULL;\n m_TrackIds[i] = 0;\n }\n \n unsigned int index = 0;\n for (AP4_List<AP4_TrakAtom>::Item* item = trak_atoms->FirstItem(); item; item=item->GetNext()) {\n AP4_TrakAtom* trak = item->GetData();", " // find the stsd atom\n AP4_ContainerAtom* stbl = AP4_DYNAMIC_CAST(AP4_ContainerAtom, trak->FindChild(\"mdia/minf/stbl\"));\n if (stbl == NULL) continue;\n \n // see if there's an external data source for this track\n AP4_ByteStream* trak_data_stream = &input;\n for (AP4_List<ExternalTrackData>::Item* ditem = m_ExternalTrackData.FirstItem(); ditem; ditem=ditem->GetNext()) {\n ExternalTrackData* tdata = ditem->GetData();\n if (tdata->m_TrackId == trak->GetId()) {\n trak_data_stream = tdata->m_MediaData;\n break;\n }\n }", " // create the track handler \n m_TrackHandlers[index] = CreateTrackHandler(trak);\n m_TrackIds[index] = trak->GetId();\n cursors[index].m_Locator.m_TrakIndex = index;\n cursors[index].m_Locator.m_SampleTable = new AP4_AtomSampleTable(stbl, *trak_data_stream);\n cursors[index].m_Locator.m_SampleIndex = 0;\n cursors[index].m_Locator.m_ChunkIndex = 0;\n if (cursors[index].m_Locator.m_SampleTable->GetSampleCount()) {\n cursors[index].m_Locator.m_SampleTable->GetSample(0, cursors[index].m_Locator.m_Sample);\n } else {\n cursors[index].m_EndReached = true;\n }", " index++; \n }", " // figure out the layout of the chunks\n for (;;) {\n // see which is the next sample to write\n AP4_UI64 min_offset = (AP4_UI64)(-1);\n int cursor = -1;\n for (unsigned int i=0; i<track_count; i++) {\n if (!cursors[i].m_EndReached &&", " cursors[i].m_Locator.m_SampleTable &&", " cursors[i].m_Locator.m_Sample.GetOffset() <= min_offset) {\n min_offset = cursors[i].m_Locator.m_Sample.GetOffset();\n cursor = i;\n }\n }", " // stop if all cursors are exhausted\n if (cursor == -1) break;", " // append this locator to the layout list\n AP4_SampleLocator& locator = cursors[cursor].m_Locator;\n locators.Append(locator);", " // move the cursor to the next sample\n locator.m_SampleIndex++;\n if (locator.m_SampleIndex == locator.m_SampleTable->GetSampleCount()) {\n // mark this track as completed\n cursors[cursor].m_EndReached = true;\n } else {\n // get the next sample info\n locator.m_SampleTable->GetSample(locator.m_SampleIndex, locator.m_Sample);\n AP4_Ordinal skip, sdesc;\n locator.m_SampleTable->GetChunkForSample(locator.m_SampleIndex,\n locator.m_ChunkIndex,\n skip, sdesc);\n }\n }", " // update the stbl atoms and compute the mdat size\n int current_track = -1;\n int current_chunk = -1;\n AP4_Position current_chunk_offset = 0;\n AP4_Size current_chunk_size = 0;\n for (AP4_Ordinal i=0; i<locators.ItemCount(); i++) {\n AP4_SampleLocator& locator = locators[i];\n if ((int)locator.m_TrakIndex != current_track ||\n (int)locator.m_ChunkIndex != current_chunk) {\n // start a new chunk for this track\n current_chunk_offset += current_chunk_size;\n current_chunk_size = 0;\n current_track = locator.m_TrakIndex;\n current_chunk = locator.m_ChunkIndex;\n locator.m_SampleTable->SetChunkOffset(locator.m_ChunkIndex, current_chunk_offset);\n } \n AP4_Size sample_size;\n TrackHandler* handler = m_TrackHandlers[locator.m_TrakIndex];\n if (handler) {\n sample_size = handler->GetProcessedSampleSize(locator.m_Sample);\n locator.m_SampleTable->SetSampleSize(locator.m_SampleIndex, sample_size);\n } else {\n sample_size = locator.m_Sample.GetSize();\n }\n current_chunk_size += sample_size;\n mdat_payload_size += sample_size;\n }", " // process the tracks (ex: sample descriptions processing)\n for (AP4_Ordinal i=0; i<track_count; i++) {\n TrackHandler* handler = m_TrackHandlers[i];\n if (handler) handler->ProcessTrack();\n }\n }", " // finalize the processor\n Finalize(top_level);", " if (!fragments) {\n // calculate the size of all atoms combined\n AP4_UI64 atoms_size = 0;\n top_level.GetChildren().Apply(AP4_AtomSizeAdder(atoms_size));", " // see if we need a 64-bit or 32-bit mdat\n AP4_Size mdat_header_size = AP4_ATOM_HEADER_SIZE;\n if (mdat_payload_size+mdat_header_size > 0xFFFFFFFF) {\n // we need a 64-bit size\n mdat_header_size += 8;\n }\n \n // adjust the chunk offsets\n for (AP4_Ordinal i=0; i<track_count; i++) {\n AP4_TrakAtom* trak;\n trak_atoms->Get(i, trak);\n trak->AdjustChunkOffsets(atoms_size+mdat_header_size);\n }", " // write all atoms\n top_level.GetChildren().Apply(AP4_AtomListWriter(output));", " // write mdat header\n if (mdat_payload_size) {\n if (mdat_header_size == AP4_ATOM_HEADER_SIZE) {\n // 32-bit size\n output.WriteUI32((AP4_UI32)(mdat_header_size+mdat_payload_size));\n output.WriteUI32(AP4_ATOM_TYPE_MDAT);\n } else {\n // 64-bit size\n output.WriteUI32(1);\n output.WriteUI32(AP4_ATOM_TYPE_MDAT);\n output.WriteUI64(mdat_header_size+mdat_payload_size);\n }\n } \n }\n \n // write the samples\n if (moov) {\n if (!fragments) {\n#if defined(AP4_DEBUG)\n AP4_Position before;\n output.Tell(before);\n#endif\n AP4_Sample sample;\n AP4_DataBuffer data_in;\n AP4_DataBuffer data_out;\n for (unsigned int i=0; i<locators.ItemCount(); i++) {\n AP4_SampleLocator& locator = locators[i];\n locator.m_Sample.ReadData(data_in);\n TrackHandler* handler = m_TrackHandlers[locator.m_TrakIndex];\n if (handler) {\n result = handler->ProcessSample(data_in, data_out);\n if (AP4_FAILED(result)) return result;\n output.Write(data_out.GetData(), data_out.GetDataSize());\n } else {\n output.Write(data_in.GetData(), data_in.GetDataSize()); \n }", " // notify the progress listener\n if (listener) {\n listener->OnProgress(i+1, locators.ItemCount());\n }\n }", "#if defined(AP4_DEBUG)\n AP4_Position after;\n output.Tell(after);\n AP4_ASSERT(after-before == mdat_payload_size);\n#endif\n }\n \n // find the position of the sidx atom\n AP4_Position sidx_position = 0;\n if (sidx) {\n for (AP4_List<AP4_Atom>::Item* item = top_level.GetChildren().FirstItem();\n item;\n item = item->GetNext()) {\n AP4_Atom* atom = item->GetData();\n if (atom->GetType() == AP4_ATOM_TYPE_SIDX) {\n break;\n }\n sidx_position += atom->GetSize();\n }\n }\n \n // process the fragments, if any\n result = ProcessFragments(moov, frags, mfra, sidx, sidx_position, fragments?*fragments:input, output);\n if (AP4_FAILED(result)) return result;\n \n // update and re-write the sidx if we have one\n if (sidx && sidx_position) {\n AP4_Position where = 0;\n output.Tell(where);\n output.Seek(sidx_position);\n result = sidx->Write(output);\n if (AP4_FAILED(result)) return result;\n output.Seek(where);\n }\n \n if (!fragments) {\n // write the mfra atom at the end if we have one\n if (mfra) {\n mfra->Write(output);\n }\n }\n \n // cleanup\n for (AP4_Ordinal i=0; i<track_count; i++) {\n delete cursors[i].m_Locator.m_SampleTable;\n delete m_TrackHandlers[i];\n }\n m_TrackHandlers.Clear();\n delete[] cursors;\n }", " // cleanup\n frags.DeleteReferences();\n delete mfra;\n \n return AP4_SUCCESS;\n}", "/*----------------------------------------------------------------------\n| AP4_Processor::Process\n+---------------------------------------------------------------------*/\nAP4_Result\nAP4_Processor::Process(AP4_ByteStream& input, \n AP4_ByteStream& output,\n ProgressListener* listener,\n AP4_AtomFactory& atom_factory)\n{\n return Process(input, output, NULL, listener, atom_factory);\n}", "/*----------------------------------------------------------------------\n| AP4_Processor::Process\n+---------------------------------------------------------------------*/\nAP4_Result\nAP4_Processor::Process(AP4_ByteStream& fragments, \n AP4_ByteStream& output,\n AP4_ByteStream& init,\n ProgressListener* listener,\n AP4_AtomFactory& atom_factory)\n{\n return Process(init, output, &fragments, listener, atom_factory);\n}", "/*----------------------------------------------------------------------\n| AP4_Processor:Initialize\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_Processor::Initialize(AP4_AtomParent& /* top_level */,\n AP4_ByteStream& /* stream */,\n ProgressListener* /* listener */)\n{\n // default implementation: do nothing\n return AP4_SUCCESS;\n}", "/*----------------------------------------------------------------------\n| AP4_Processor:Finalize\n+---------------------------------------------------------------------*/\nAP4_Result \nAP4_Processor::Finalize(AP4_AtomParent& /* top_level */,\n ProgressListener* /* listener */ )\n{\n // default implementation: do nothing\n return AP4_SUCCESS;\n}", "/*----------------------------------------------------------------------\n| AP4_Processor::TrackHandler Dynamic Cast Anchor\n+---------------------------------------------------------------------*/\nAP4_DEFINE_DYNAMIC_CAST_ANCHOR_S(AP4_Processor::TrackHandler, TrackHandler)" ]
[ 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 ]
PreciseBugs
{"buggy_code_end_loc": [89, 274, 556, 42], "buggy_code_start_loc": [89, 273, 556, 40], "filenames": ["Source/C++/Core/Ap4AtomSampleTable.cpp", "Source/C++/Core/Ap4AvccAtom.cpp", "Source/C++/Core/Ap4Processor.cpp", "Source/C++/Core/Ap4Version.h"], "fixing_code_end_loc": [95, 274, 558, 42], "fixing_code_start_loc": [90, 273, 557, 40], "message": "The AP4_AvccAtom::InspectFields function in Core/Ap4AvccAtom.cpp in Bento4 mp4dump before 1.5.0-616 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted mp4 file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:bento4:bento4:*:*:*:*:*:*:*:*", "matchCriteriaId": "03DB20DA-7153-4678-A2D6-01464B589FC8", "versionEndExcluding": null, "versionEndIncluding": "1.5.0-615", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The AP4_AvccAtom::InspectFields function in Core/Ap4AvccAtom.cpp in Bento4 mp4dump before 1.5.0-616 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted mp4 file."}, {"lang": "es", "value": "La funci\u00f3n AP4_AvccAtom::InspectFields en Core/Ap4AvccAtom.cpp en Bento4 mp4dump en versiones anteriores a la 1.5.0-616 permite que atacantes remotos provoquen una denegaci\u00f3n de servicio (desreferencia de puntero NULL y bloqueo de aplicaci\u00f3n) mediante un archivo mp4 manipulado."}], "evaluatorComment": null, "id": "CVE-2017-12476", "lastModified": "2017-09-07T17:17:01.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-09-06T08:29:00.277", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://drive.google.com/open?id=0B6wBkDmxMGMKUjNscThnbTlSZ2s"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://drive.google.com/open?id=0B9DojFnTUSNGZ1JfNUc1am9pcnc"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e"}, "type": "CWE-476"}
193
Determine whether the {function_name} code is vulnerable or not.
[ "/*****************************************************************\n|\n| AP4 - Version Numbers\n|\n| Copyright 2002-2008 Axiomatic Systems, LLC\n|\n|\n| This file is part of Bento4/AP4 (MP4 Atom Processing Library).\n|\n| Unless you have obtained Bento4 under a difference license,\n| this version of Bento4 is Bento4|GPL.\n| Unless you have obtained Bento4 under a difference license,\n| this version of Bento4 is Bento4|GPL.\n| Bento4|GPL is free software; you can redistribute it and/or modify\n| it under the terms of the GNU General Public License as published by\n| the Free Software Foundation; either version 2, or (at your option)\n| any later version.\n|\n| Bento4|GPL is distributed in the hope that it will be useful,\n| but WITHOUT ANY WARRANTY; without even the implied warranty of\n| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n| GNU General Public License for more details.\n|\n| You should have received a copy of the GNU General Public License\n| along with Bento4|GPL; see the file COPYING. If not, write to the\n| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA\n| 02111-1307, USA.\n|\n****************************************************************/", "#ifndef _AP4_VERSION_H_\n#define _AP4_VERSION_H_", "/*----------------------------------------------------------------------\n| version constants\n+---------------------------------------------------------------------*/\n/**\n * Version number of the SDK\n */", "#define AP4_VERSION 0x01050000\n#define AP4_VERSION_STRING \"1.5.0.0\"", "\n#endif // _AP4_VERSION_H_" ]
[ 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [89, 274, 556, 42], "buggy_code_start_loc": [89, 273, 556, 40], "filenames": ["Source/C++/Core/Ap4AtomSampleTable.cpp", "Source/C++/Core/Ap4AvccAtom.cpp", "Source/C++/Core/Ap4Processor.cpp", "Source/C++/Core/Ap4Version.h"], "fixing_code_end_loc": [95, 274, 558, 42], "fixing_code_start_loc": [90, 273, 557, 40], "message": "The AP4_AvccAtom::InspectFields function in Core/Ap4AvccAtom.cpp in Bento4 mp4dump before 1.5.0-616 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted mp4 file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:bento4:bento4:*:*:*:*:*:*:*:*", "matchCriteriaId": "03DB20DA-7153-4678-A2D6-01464B589FC8", "versionEndExcluding": null, "versionEndIncluding": "1.5.0-615", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The AP4_AvccAtom::InspectFields function in Core/Ap4AvccAtom.cpp in Bento4 mp4dump before 1.5.0-616 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted mp4 file."}, {"lang": "es", "value": "La funci\u00f3n AP4_AvccAtom::InspectFields en Core/Ap4AvccAtom.cpp en Bento4 mp4dump en versiones anteriores a la 1.5.0-616 permite que atacantes remotos provoquen una denegaci\u00f3n de servicio (desreferencia de puntero NULL y bloqueo de aplicaci\u00f3n) mediante un archivo mp4 manipulado."}], "evaluatorComment": null, "id": "CVE-2017-12476", "lastModified": "2017-09-07T17:17:01.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-09-06T08:29:00.277", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://drive.google.com/open?id=0B6wBkDmxMGMKUjNscThnbTlSZ2s"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://drive.google.com/open?id=0B9DojFnTUSNGZ1JfNUc1am9pcnc"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e"}, "type": "CWE-476"}
193
Determine whether the {function_name} code is vulnerable or not.
[ "/*****************************************************************\n|\n| AP4 - Version Numbers\n|\n| Copyright 2002-2008 Axiomatic Systems, LLC\n|\n|\n| This file is part of Bento4/AP4 (MP4 Atom Processing Library).\n|\n| Unless you have obtained Bento4 under a difference license,\n| this version of Bento4 is Bento4|GPL.\n| Unless you have obtained Bento4 under a difference license,\n| this version of Bento4 is Bento4|GPL.\n| Bento4|GPL is free software; you can redistribute it and/or modify\n| it under the terms of the GNU General Public License as published by\n| the Free Software Foundation; either version 2, or (at your option)\n| any later version.\n|\n| Bento4|GPL is distributed in the hope that it will be useful,\n| but WITHOUT ANY WARRANTY; without even the implied warranty of\n| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n| GNU General Public License for more details.\n|\n| You should have received a copy of the GNU General Public License\n| along with Bento4|GPL; see the file COPYING. If not, write to the\n| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA\n| 02111-1307, USA.\n|\n****************************************************************/", "#ifndef _AP4_VERSION_H_\n#define _AP4_VERSION_H_", "/*----------------------------------------------------------------------\n| version constants\n+---------------------------------------------------------------------*/\n/**\n * Version number of the SDK\n */", "#define AP4_VERSION 0x01050001\n#define AP4_VERSION_STRING \"1.5.0.1\"", "\n#endif // _AP4_VERSION_H_" ]
[ 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [89, 274, 556, 42], "buggy_code_start_loc": [89, 273, 556, 40], "filenames": ["Source/C++/Core/Ap4AtomSampleTable.cpp", "Source/C++/Core/Ap4AvccAtom.cpp", "Source/C++/Core/Ap4Processor.cpp", "Source/C++/Core/Ap4Version.h"], "fixing_code_end_loc": [95, 274, 558, 42], "fixing_code_start_loc": [90, 273, 557, 40], "message": "The AP4_AvccAtom::InspectFields function in Core/Ap4AvccAtom.cpp in Bento4 mp4dump before 1.5.0-616 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted mp4 file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:bento4:bento4:*:*:*:*:*:*:*:*", "matchCriteriaId": "03DB20DA-7153-4678-A2D6-01464B589FC8", "versionEndExcluding": null, "versionEndIncluding": "1.5.0-615", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The AP4_AvccAtom::InspectFields function in Core/Ap4AvccAtom.cpp in Bento4 mp4dump before 1.5.0-616 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted mp4 file."}, {"lang": "es", "value": "La funci\u00f3n AP4_AvccAtom::InspectFields en Core/Ap4AvccAtom.cpp en Bento4 mp4dump en versiones anteriores a la 1.5.0-616 permite que atacantes remotos provoquen una denegaci\u00f3n de servicio (desreferencia de puntero NULL y bloqueo de aplicaci\u00f3n) mediante un archivo mp4 manipulado."}], "evaluatorComment": null, "id": "CVE-2017-12476", "lastModified": "2017-09-07T17:17:01.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-09-06T08:29:00.277", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://drive.google.com/open?id=0B6wBkDmxMGMKUjNscThnbTlSZ2s"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://drive.google.com/open?id=0B9DojFnTUSNGZ1JfNUc1am9pcnc"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/axiomatic-systems/Bento4/commit/4d3f0bebd5f8518fd775f671c12bea58c68e814e"}, "type": "CWE-476"}
193
Determine whether the {function_name} code is vulnerable or not.
[ "user_agent_parsers:\n #### SPECIAL CASES TOP ####", " # CFNetwork Podcast catcher Applications\n - regex: '^(Luminary)[Stage]+/(\\d+) CFNetwork'\n - regex: '(ESPN)[%20| ]+Radio/(\\d+)\\.(\\d+)\\.(\\d+) CFNetwork'\n - regex: '(Antenna)/(\\d+) CFNetwork'\n family_replacement: 'AntennaPod'\n - regex: '(TopPodcasts)Pro/(\\d+) CFNetwork'\n - regex: '(MusicDownloader)Lite/(\\d+)\\.(\\d+)\\.(\\d+) CFNetwork'\n - regex: '^(.*)-iPad\\/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)(?:\\.(\\d+)|) CFNetwork'\n - regex: '^(.*)-iPhone/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)(?:\\.(\\d+)|) CFNetwork'\n - regex: '^(.*)/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)(?:\\.(\\d+)|) CFNetwork'", " # Podcast catchers\n - regex: '^(Luminary)/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'\n - regex: '(espn\\.go)'\n family_replacement: 'ESPN'\n - regex: '(espnradio\\.com)'\n family_replacement: 'ESPN'\n - regex: 'ESPN APP$'\n family_replacement: 'ESPN'\n - regex: '(audioboom\\.com)'\n family_replacement: 'AudioBoom'\n - regex: ' (Rivo) RHYTHM'", " # @note: iOS / OSX Applications\n - regex: '(CFNetwork)(?:/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)|)'\n family_replacement: 'CFNetwork'", " # Pingdom\n - regex: '(Pingdom\\.com_bot_version_)(\\d+)\\.(\\d+)'\n family_replacement: 'PingdomBot'\n # 'Mozilla/5.0 (Unknown; Linux x86_64) AppleWebKit/534.34 (KHTML, like Gecko) PingdomTMS/0.8.5 Safari/534.34'\n - regex: '(PingdomTMS)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'PingdomBot'", " # PTST / WebPageTest.org crawlers\n - regex: ' (PTST)/(\\d+)(?:\\.(\\d+)|)$'\n family_replacement: 'WebPageTest.org bot'", " # Datanyze.com spider\n - regex: 'X11; (Datanyze); Linux'", " # New Relic Pinger\n - regex: '(NewRelicPinger)/(\\d+)\\.(\\d+)'\n family_replacement: 'NewRelicPingerBot'", " # Tableau\n - regex: '(Tableau)/(\\d+)\\.(\\d+)'\n family_replacement: 'Tableau'", " # Adobe CreativeCloud\n - regex: 'AppleWebKit/\\d+\\.\\d+.* Safari.* (CreativeCloud)/(\\d+)\\.(\\d+).(\\d+)'\n family_replacement: 'Adobe CreativeCloud'", " # Salesforce\n - regex: '(Salesforce)(?:.)\\/(\\d+)\\.(\\d?)'", " #StatusCake\n - regex: '(\\(StatusCake\\))'\n family_replacement: 'StatusCakeBot'", " # Facebook\n - regex: '(facebookexternalhit)/(\\d+)\\.(\\d+)'\n family_replacement: 'FacebookBot'", " # Google Plus\n - regex: 'Google.*/\\+/web/snippet'\n family_replacement: 'GooglePlusBot'", " # Gmail\n - regex: 'via ggpht\\.com GoogleImageProxy'\n family_replacement: 'GmailImageProxy'", " # Yahoo\n - regex: 'YahooMailProxy; https://help\\.yahoo\\.com/kb/yahoo-mail-proxy-SLN28749\\.html'\n family_replacement: 'YahooMailProxy'", " # Twitter\n - regex: '(Twitterbot)/(\\d+)\\.(\\d+)'\n family_replacement: 'Twitterbot'", " # Bots Pattern 'name/0.0.0'\n - regex: '/((?:Ant-|)Nutch|[A-z]+[Bb]ot|[A-z]+[Ss]pider|Axtaris|fetchurl|Isara|ShopSalad|Tailsweep)[ \\-](\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'\n # Bots Pattern 'name/0.0.0'\n - regex: '\\b(008|Altresium|Argus|BaiduMobaider|BoardReader|DNSGroup|DataparkSearch|EDI|Goodzer|Grub|INGRID|Infohelfer|LinkedInBot|LOOQ|Nutch|OgScrper|PathDefender|Peew|PostPost|Steeler|Twitterbot|VSE|WebCrunch|WebZIP|Y!J-BR[A-Z]|YahooSeeker|envolk|sproose|wminer)/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'", " # MSIECrawler\n - regex: '(MSIE) (\\d+)\\.(\\d+)([a-z]\\d|[a-z]|);.* MSIECrawler'\n family_replacement: 'MSIECrawler'", " # DAVdroid\n - regex: '(DAVdroid)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'", " # Downloader ...\n - regex: '(Google-HTTP-Java-Client|Apache-HttpClient|Go-http-client|scalaj-http|http%20client|Python-urllib|HttpMonitor|TLSProber|WinHTTP|JNLP|okhttp|aihttp|reqwest|axios|unirest-(?:java|python|ruby|nodejs|php|net))(?:[ /](\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)|)'", " # Pinterestbot\n - regex: '(Pinterest(?:bot|))/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)[;\\s(]+\\+https://www.pinterest.com/bot.html'\n family_replacement: 'Pinterestbot'", " # Bots\n - regex: '(CSimpleSpider|Cityreview Robot|CrawlDaddy|CrawlFire|Finderbots|Index crawler|Job Roboter|KiwiStatus Spider|Lijit Crawler|QuerySeekerSpider|ScollSpider|Trends Crawler|USyd-NLP-Spider|SiteCat Webbot|BotName\\/\\$BotVersion|123metaspider-Bot|1470\\.net crawler|50\\.nu|8bo Crawler Bot|Aboundex|Accoona-[A-z]{1,30}-Agent|AdsBot-Google(?:-[a-z]{1,30}|)|altavista|AppEngine-Google|archive.{0,30}\\.org_bot|archiver|Ask Jeeves|[Bb]ai[Dd]u[Ss]pider(?:-[A-Za-z]{1,30})(?:-[A-Za-z]{1,30}|)|bingbot|BingPreview|blitzbot|BlogBridge|Bloglovin|BoardReader Blog Indexer|BoardReader Favicon Fetcher|boitho.com-dc|BotSeer|BUbiNG|\\b\\w{0,30}favicon\\w{0,30}\\b|\\bYeti(?:-[a-z]{1,30}|)|Catchpoint(?: bot|)|[Cc]harlotte|Checklinks|clumboot|Comodo HTTP\\(S\\) Crawler|Comodo-Webinspector-Crawler|ConveraCrawler|CRAWL-E|CrawlConvera|Daumoa(?:-feedfetcher|)|Feed Seeker Bot|Feedbin|findlinks|Flamingo_SearchEngine|FollowSite Bot|furlbot|Genieo|gigabot|GomezAgent|gonzo1|(?:[a-zA-Z]{1,30}-|)Googlebot(?:-[a-zA-Z]{1,30}|)|Google SketchUp|grub-client|gsa-crawler|heritrix|HiddenMarket|holmes|HooWWWer|htdig|ia_archiver|ICC-Crawler|Icarus6j|ichiro(?:/mobile|)|IconSurf|IlTrovatore(?:-Setaccio|)|InfuzApp|Innovazion Crawler|InternetArchive|IP2[a-z]{1,30}Bot|jbot\\b|KaloogaBot|Kraken|Kurzor|larbin|LEIA|LesnikBot|Linguee Bot|LinkAider|LinkedInBot|Lite Bot|Llaut|lycos|Mail\\.RU_Bot|masscan|masidani_bot|Mediapartners-Google|Microsoft .{0,30} Bot|mogimogi|mozDex|MJ12bot|msnbot(?:-media {0,2}|)|msrbot|Mtps Feed Aggregation System|netresearch|Netvibes|NewsGator[^/]{0,30}|^NING|Nutch[^/]{0,30}|Nymesis|ObjectsSearch|OgScrper|Orbiter|OOZBOT|PagePeeker|PagesInventory|PaxleFramework|Peeplo Screenshot Bot|PlantyNet_WebRobot|Pompos|Qwantify|Read%20Later|Reaper|RedCarpet|Retreiver|Riddler|Rival IQ|scooter|Scrapy|Scrubby|searchsight|seekbot|semanticdiscovery|SemrushBot|Simpy|SimplePie|SEOstats|SimpleRSS|SiteCon|Slackbot-LinkExpanding|Slack-ImgProxy|Slurp|snappy|Speedy Spider|Squrl Java|Stringer|TheUsefulbot|ThumbShotsBot|Thumbshots\\.ru|Tiny Tiny RSS|Twitterbot|WhatsApp|URL2PNG|Vagabondo|VoilaBot|^vortex|Votay bot|^voyager|WASALive.Bot|Web-sniffer|WebThumb|WeSEE:[A-z]{1,30}|WhatWeb|WIRE|WordPress|Wotbox|www\\.almaden\\.ibm\\.com|Xenu(?:.s|) Link Sleuth|Xerka [A-z]{1,30}Bot|yacy(?:bot|)|YahooSeeker|Yahoo! Slurp|Yandex\\w{1,30}|YodaoBot(?:-[A-z]{1,30}|)|YottaaMonitor|Yowedo|^Zao|^Zao-Crawler|ZeBot_www\\.ze\\.bz|ZooShot|ZyBorg)(?:[ /]v?(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)|)|)|)'", " # AWS S3 Clients\n # must come before \"Bots General matcher\" to catch \"boto\"/\"boto3\" before \"bot\"\n - regex: '\\b(Boto3?|JetS3t|aws-(?:cli|sdk-(?:cpp|go|java|nodejs|ruby2?|dotnet-(?:\\d{1,2}|core)))|s3fs)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'", " # Facebook\n # Must come before \"Bots General matcher\" to catch OrangeBotswana\n # Facebook Messenger must go before Facebook\n - regex: '\\[(FBAN/MessengerForiOS|FB_IAB/MESSENGER);FBAV/(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)|)|)'\n family_replacement: 'Facebook Messenger'\n # Facebook\n - regex: '\\[FB.*;(FBAV)/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'\n family_replacement: 'Facebook'\n # Sometimes Facebook does not specify a version (FBAV)\n - regex: '\\[FB.*;'\n family_replacement: 'Facebook'", " # Bots General matcher 'name/0.0'\n - regex: '(?:\\/[A-Za-z0-9\\.]+|) {0,5}([A-Za-z0-9 \\-_\\!\\[\\]:]{0,50}(?:[Aa]rchiver|[Ii]ndexer|[Ss]craper|[Bb]ot|[Ss]pider|[Cc]rawl[a-z]{0,50}))[/ ](\\d+)(?:\\.(\\d+)(?:\\.(\\d+)|)|)'\n # Bots containing bot(but not CUBOT)\n - regex: '((?:[A-Za-z][A-Za-z0-9 -]{0,50}|)[^C][^Uu][Bb]ot)\\b(?:(?:[ /]| v)(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)|)'\n # Bots containing spider|scrape|Crawl\n - regex: '((?:[A-z0-9]{1,50}|[A-z\\-]{1,50} ?|)(?: the |)(?:[Ss][Pp][Ii][Dd][Ee][Rr]|[Ss]crape|[Cc][Rr][Aa][Ww][Ll])[A-z0-9]{0,50})(?:(?:[ /]| v)(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)|)'", " # HbbTV standard defines what features the browser should understand.\n # but it's like targeting \"HTML5 browsers\", effective browser support depends on the model\n # See os_parsers if you want to target a specific TV\n - regex: '(HbbTV)/(\\d+)\\.(\\d+)\\.(\\d+) \\('", " # must go before Firefox to catch Chimera/SeaMonkey/Camino/Waterfox\n - regex: '(Chimera|SeaMonkey|Camino|Waterfox)/(\\d+)\\.(\\d+)\\.?([ab]?\\d+[a-z]*|)'", " # must be before Firefox / Gecko to catch SailfishBrowser properly\n - regex: '(SailfishBrowser)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Sailfish Browser'", " # Social Networks (non-Facebook)\n # Pinterest\n - regex: '\\[(Pinterest)/[^\\]]+\\]'\n - regex: '(Pinterest)(?: for Android(?: Tablet|)|)/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'\n # Instagram app\n - regex: 'Mozilla.*Mobile.*(Instagram).(\\d+)\\.(\\d+)\\.(\\d+)'\n # Flipboard app\n - regex: 'Mozilla.*Mobile.*(Flipboard).(\\d+)\\.(\\d+)\\.(\\d+)'\n # Flipboard-briefing app\n - regex: 'Mozilla.*Mobile.*(Flipboard-Briefing).(\\d+)\\.(\\d+)\\.(\\d+)'\n # Onefootball app\n - regex: 'Mozilla.*Mobile.*(Onefootball)\\/Android.(\\d+)\\.(\\d+)\\.(\\d+)'\n # Snapchat\n - regex: '(Snapchat)\\/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n # Twitter\n - regex: '(Twitter for (?:iPhone|iPad)|TwitterAndroid)(?:\\/(\\d+)\\.(\\d+)|)'\n family_replacement: 'Twitter'", " # Basilisk\n - regex: '(Firefox)/(\\d+)\\.(\\d+) Basilisk/(\\d+)'\n family_replacement: 'Basilisk'", " # Pale Moon\n - regex: '(PaleMoon)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Pale Moon'", " # Firefox\n - regex: '(Fennec)/(\\d+)\\.(\\d+)\\.?([ab]?\\d+[a-z]*)'\n family_replacement: 'Firefox Mobile'\n - regex: '(Fennec)/(\\d+)\\.(\\d+)(pre)'\n family_replacement: 'Firefox Mobile'\n - regex: '(Fennec)/(\\d+)\\.(\\d+)'\n family_replacement: 'Firefox Mobile'\n - regex: '(?:Mobile|Tablet);.*(Firefox)/(\\d+)\\.(\\d+)'\n family_replacement: 'Firefox Mobile'\n - regex: '(Namoroka|Shiretoko|Minefield)/(\\d+)\\.(\\d+)\\.(\\d+(?:pre|))'\n family_replacement: 'Firefox ($1)'\n - regex: '(Firefox)/(\\d+)\\.(\\d+)(a\\d+[a-z]*)'\n family_replacement: 'Firefox Alpha'\n - regex: '(Firefox)/(\\d+)\\.(\\d+)(b\\d+[a-z]*)'\n family_replacement: 'Firefox Beta'\n - regex: '(Firefox)-(?:\\d+\\.\\d+|)/(\\d+)\\.(\\d+)(a\\d+[a-z]*)'\n family_replacement: 'Firefox Alpha'\n - regex: '(Firefox)-(?:\\d+\\.\\d+|)/(\\d+)\\.(\\d+)(b\\d+[a-z]*)'\n family_replacement: 'Firefox Beta'\n - regex: '(Namoroka|Shiretoko|Minefield)/(\\d+)\\.(\\d+)([ab]\\d+[a-z]*|)'\n family_replacement: 'Firefox ($1)'\n - regex: '(Firefox).*Tablet browser (\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'MicroB'\n - regex: '(MozillaDeveloperPreview)/(\\d+)\\.(\\d+)([ab]\\d+[a-z]*|)'\n - regex: '(FxiOS)/(\\d+)\\.(\\d+)(\\.(\\d+)|)(\\.(\\d+)|)'\n family_replacement: 'Firefox iOS'", " # e.g.: Flock/2.0b2\n - regex: '(Flock)/(\\d+)\\.(\\d+)(b\\d+?)'", " # RockMelt\n - regex: '(RockMelt)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # e.g.: Fennec/0.9pre\n - regex: '(Navigator)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Netscape'", " - regex: '(Navigator)/(\\d+)\\.(\\d+)([ab]\\d+)'\n family_replacement: 'Netscape'", " - regex: '(Netscape6)/(\\d+)\\.(\\d+)\\.?([ab]?\\d+|)'\n family_replacement: 'Netscape'", " - regex: '(MyIBrow)/(\\d+)\\.(\\d+)'\n family_replacement: 'My Internet Browser'", " # UC Browser\n # we need check it before opera. In other case case UC Browser detected look like Opera Mini\n - regex: '(UC? ?Browser|UCWEB|U3)[ /]?(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'UC Browser'", " # Opera will stop at 9.80 and hide the real version in the Version string.\n # see: http://dev.opera.com/articles/view/opera-ua-string-changes/\n - regex: '(Opera Tablet).*Version/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n - regex: '(Opera Mini)(?:/att|)/?(\\d+|)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'\n - regex: '(Opera)/.+Opera Mobi.+Version/(\\d+)\\.(\\d+)'\n family_replacement: 'Opera Mobile'\n - regex: '(Opera)/(\\d+)\\.(\\d+).+Opera Mobi'\n family_replacement: 'Opera Mobile'\n - regex: 'Opera Mobi.+(Opera)(?:/|\\s+)(\\d+)\\.(\\d+)'\n family_replacement: 'Opera Mobile'\n - regex: 'Opera Mobi'\n family_replacement: 'Opera Mobile'\n - regex: '(Opera)/9.80.*Version/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'", " # Opera 14 for Android uses a WebKit render engine.\n - regex: '(?:Mobile Safari).*(OPR)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Opera Mobile'", " # Opera >=15 for Desktop is similar to Chrome but includes an \"OPR\" Version string.\n - regex: '(?:Chrome).*(OPR)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Opera'", " # Opera Coast\n - regex: '(Coast)/(\\d+).(\\d+).(\\d+)'\n family_replacement: 'Opera Coast'", " # Opera Mini for iOS (from version 8.0.0)\n - regex: '(OPiOS)/(\\d+).(\\d+).(\\d+)'\n family_replacement: 'Opera Mini'", " # Opera Neon\n - regex: 'Chrome/.+( MMS)/(\\d+).(\\d+).(\\d+)'\n family_replacement: 'Opera Neon'", " # Palm WebOS looks a lot like Safari.\n - regex: '(hpw|web)OS/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'webOS Browser'", " # LuaKit has no version info.\n # http://luakit.org/projects/luakit/\n - regex: '(luakit)'\n family_replacement: 'LuaKit'", " # Snowshoe\n - regex: '(Snowshoe)/(\\d+)\\.(\\d+).(\\d+)'", " # Lightning (for Thunderbird)\n # http://www.mozilla.org/projects/calendar/lightning/\n - regex: 'Gecko/\\d+ (Lightning)/(\\d+)\\.(\\d+)\\.?((?:[ab]?\\d+[a-z]*)|(?:\\d*))'", " # Swiftfox\n - regex: '(Firefox)/(\\d+)\\.(\\d+)\\.(\\d+(?:pre|)) \\(Swiftfox\\)'\n family_replacement: 'Swiftfox'\n - regex: '(Firefox)/(\\d+)\\.(\\d+)([ab]\\d+[a-z]*|) \\(Swiftfox\\)'\n family_replacement: 'Swiftfox'", " # Rekonq\n - regex: '(rekonq)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|) Safari'\n family_replacement: 'Rekonq'\n - regex: 'rekonq'\n family_replacement: 'Rekonq'", " # Conkeror lowercase/uppercase\n # http://conkeror.org/\n - regex: '(conkeror|Conkeror)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Conkeror'", " # catches lower case konqueror\n - regex: '(konqueror)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Konqueror'", " - regex: '(WeTab)-Browser'", " - regex: '(Comodo_Dragon)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Comodo Dragon'", " - regex: '(Symphony) (\\d+).(\\d+)'", " - regex: 'PLAYSTATION 3.+WebKit'\n family_replacement: 'NetFront NX'\n - regex: 'PLAYSTATION 3'\n family_replacement: 'NetFront'\n - regex: '(PlayStation Portable)'\n family_replacement: 'NetFront'\n - regex: '(PlayStation Vita)'\n family_replacement: 'NetFront NX'", " - regex: 'AppleWebKit.+ (NX)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'NetFront NX'\n - regex: '(Nintendo 3DS)'\n family_replacement: 'NetFront NX'", " # Amazon Silk, should go before Safari and Chrome Mobile\n - regex: '(Silk)/(\\d+)\\.(\\d+)(?:\\.([0-9\\-]+)|)'\n family_replacement: 'Amazon Silk'", " # @ref: http://www.puffinbrowser.com\n - regex: '(Puffin)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'", " # Edge Mobile\n - regex: 'Windows Phone .*(Edge)/(\\d+)\\.(\\d+)'\n family_replacement: 'Edge Mobile'\n - regex: '(EdgA)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Edge Mobile'\n - regex: '(EdgiOS)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Edge Mobile'", " # Samsung Internet (based on Chrome, but lacking some features)\n - regex: '(SamsungBrowser)/(\\d+)\\.(\\d+)'\n family_replacement: 'Samsung Internet'", " # Seznam.cz browser (based on WebKit)\n - regex: '(SznProhlizec)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Seznam prohlížeč'", " # Coc Coc browser, based on Chrome (used in Vietnam)\n - regex: '(coc_coc_browser)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Coc Coc'", " # Baidu Browsers (desktop spoofs chrome & IE, explorer is mobile)\n - regex: '(baidubrowser)[/\\s](\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'\n family_replacement: 'Baidu Browser'\n - regex: '(FlyFlow)/(\\d+)\\.(\\d+)'\n family_replacement: 'Baidu Explorer'", " # MxBrowser is Maxthon. Must go before Mobile Chrome for Android\n - regex: '(MxBrowser)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Maxthon'", " # Crosswalk must go before Mobile Chrome for Android\n - regex: '(Crosswalk)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'", " # LINE https://line.me/en/\n # Must go before Mobile Chrome for Android\n - regex: '(Line)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'LINE'", " # MiuiBrowser should got before Mobile Chrome for Android\n - regex: '(MiuiBrowser)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'MiuiBrowser'", " # Mint Browser should got before Mobile Chrome for Android\n - regex: '(Mint Browser)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Mint Browser'", " # TopBuzz Android must go before Chrome Mobile WebView\n - regex: '(TopBuzz)/(\\d+).(\\d+).(\\d+)'\n family_replacement: 'TopBuzz'", " # Google Search App on Android, eg:\n - regex: 'Mozilla.+Android.+(GSA)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Google'", " # QQ Browsers\n - regex: '(MQQBrowser/Mini)(?:(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)|)'\n family_replacement: 'QQ Browser Mini'\n - regex: '(MQQBrowser)(?:/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)|)'\n family_replacement: 'QQ Browser Mobile'\n - regex: '(QQBrowser)(?:/(\\d+)(?:\\.(\\d+)\\.(\\d+)(?:\\.(\\d+)|)|)|)'\n family_replacement: 'QQ Browser'", " # Chrome Mobile\n - regex: 'Version/.+(Chrome)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Chrome Mobile WebView'\n - regex: '; wv\\).+(Chrome)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Chrome Mobile WebView'\n - regex: '(CrMo)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Chrome Mobile'\n - regex: '(CriOS)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Chrome Mobile iOS'\n - regex: '(Chrome)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+) Mobile(?:[ /]|$)'\n family_replacement: 'Chrome Mobile'\n - regex: ' Mobile .*(Chrome)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Chrome Mobile'", " # Chrome Frame must come before MSIE.\n - regex: '(chromeframe)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Chrome Frame'", " # Tizen Browser (second case included in browser/major.minor regex)\n - regex: '(SLP Browser)/(\\d+)\\.(\\d+)'\n family_replacement: 'Tizen Browser'", " # Sogou Explorer 2.X\n - regex: '(SE 2\\.X) MetaSr (\\d+)\\.(\\d+)'\n family_replacement: 'Sogou Explorer'", " # Rackspace Monitoring\n - regex: '(Rackspace Monitoring)/(\\d+)\\.(\\d+)'\n family_replacement: 'RackspaceBot'", " # PyAMF\n - regex: '(PyAMF)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # Yandex Browser\n - regex: '(YaBrowser)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Yandex Browser'", " # Mail.ru Amigo/Internet Browser (Chromium-based)\n - regex: '(Chrome)/(\\d+)\\.(\\d+)\\.(\\d+).* MRCHROME'\n family_replacement: 'Mail.ru Chromium Browser'", " # AOL Browser (IE-based)\n - regex: '(AOL) (\\d+)\\.(\\d+); AOLBuild (\\d+)'", " # Podcast catcher Applications using iTunes\n - regex: '(PodCruncher|Downcast)[ /]?(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'", " # Box Notes https://www.box.com/resources/downloads\n # Must be before Electron\n - regex: ' (BoxNotes)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # Whale\n - regex: '(Whale)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+) Mobile(?:[ /]|$)'\n family_replacement: 'Whale'", " - regex: '(Whale)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Whale'", " # 1Password\n - regex: '(1Password)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # Ghost\n # @ref: http://www.ghost.org\n - regex: '(Ghost)/(\\d+)\\.(\\d+)\\.(\\d+)'", " #### END SPECIAL CASES TOP ####", " #### MAIN CASES - this catches > 50% of all browsers ####", "\n # Slack desktop client (needs to be before Apple Mail, Electron, and Chrome as it gets wrongly detected on Mac OS otherwise)\n - regex: '(Slack_SSB)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Slack Desktop Client'", " # HipChat provides a version on Mac, but not on Windows.\n # Needs to be before Chrome on Windows, and AppleMail on Mac.\n - regex: '(HipChat)/?(\\d+|)'\n family_replacement: 'HipChat Desktop Client'", " # Browser/major_version.minor_version.beta_version\n - regex: '\\b(MobileIron|FireWeb|Jasmine|ANTGalio|Midori|Fresco|Lobo|PaleMoon|Maxthon|Lynx|OmniWeb|Dillo|Camino|Demeter|Fluid|Fennec|Epiphany|Shiira|Sunrise|Spotify|Flock|Netscape|Lunascape|WebPilot|NetFront|Netfront|Konqueror|SeaMonkey|Kazehakase|Vienna|Iceape|Iceweasel|IceWeasel|Iron|K-Meleon|Sleipnir|Galeon|GranParadiso|Opera Mini|iCab|NetNewsWire|ThunderBrowse|Iris|UP\\.Browser|Bunjalloo|Google Earth|Raven for Mac|Openwave|MacOutlook|Electron|OktaMobile)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # Outlook 2007\n - regex: 'Microsoft Office Outlook 12\\.\\d+\\.\\d+|MSOffice 12'\n family_replacement: 'Outlook'\n v1_replacement: '2007'", " # Outlook 2010\n - regex: 'Microsoft Outlook 14\\.\\d+\\.\\d+|MSOffice 14'\n family_replacement: 'Outlook'\n v1_replacement: '2010'", " # Outlook 2013\n - regex: 'Microsoft Outlook 15\\.\\d+\\.\\d+'\n family_replacement: 'Outlook'\n v1_replacement: '2013'", " # Outlook 2016\n - regex: 'Microsoft Outlook (?:Mail )?16\\.\\d+\\.\\d+|MSOffice 16'\n family_replacement: 'Outlook'\n v1_replacement: '2016'", " # Word 2014\n - regex: 'Microsoft Office (Word) 2014'", " # Windows Live Mail\n - regex: 'Outlook-Express\\/7\\.0.*'\n family_replacement: 'Windows Live Mail'", " # Apple Air Mail\n - regex: '(Airmail) (\\d+)\\.(\\d+)(?:\\.(\\d+)|)'", " # Thunderbird\n - regex: '(Thunderbird)/(\\d+)\\.(\\d+)(?:\\.(\\d+(?:pre|))|)'\n family_replacement: 'Thunderbird'", " # Postbox\n - regex: '(Postbox)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Postbox'", " # Barca\n - regex: '(Barca(?:Pro)?)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Barca'", " # Lotus Notes\n - regex: '(Lotus-Notes)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Lotus Notes'", " # Superhuman Mail Client\n # @ref: https://www.superhuman.com\n - regex: 'Superhuman'\n family_replacement: 'Superhuman'", " # Vivaldi uses \"Vivaldi\"\n - regex: '(Vivaldi)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # Edge/major_version.minor_version\n # Edge with chromium Edg/major_version.minor_version.patch.minor_patch\n - regex: '(Edge?)/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'\n family_replacement: 'Edge'", " # Brave Browser https://brave.com/\n - regex: '(brave)/(\\d+)\\.(\\d+)\\.(\\d+) Chrome'\n family_replacement: 'Brave'", " # Iron Browser ~since version 50\n - regex: '(Chrome)/(\\d+)\\.(\\d+)\\.(\\d+)[\\d.]* Iron[^/]'\n family_replacement: 'Iron'", " # Dolphin Browser\n # @ref: http://www.dolphin.com\n - regex: '\\b(Dolphin)(?: |HDCN/|/INT\\-)(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'", " # Headless Chrome\n # https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md\n - regex: '(HeadlessChrome)(?:/(\\d+)\\.(\\d+)\\.(\\d+)|)'", " # Evolution Mail CardDav/CalDav integration\n - regex: '(Evolution)/(\\d+)\\.(\\d+)\\.(\\d+\\.\\d+)'", " # Roundcube Mail CardDav plugin\n - regex: '(RCM CardDAV plugin)/(\\d+)\\.(\\d+)\\.(\\d+(?:-dev|))'", " # Browser/major_version.minor_version\n - regex: '(bingbot|Bolt|AdobeAIR|Jasmine|IceCat|Skyfire|Midori|Maxthon|Lynx|Arora|IBrowse|Dillo|Camino|Shiira|Fennec|Phoenix|Flock|Netscape|Lunascape|Epiphany|WebPilot|Opera Mini|Opera|NetFront|Netfront|Konqueror|Googlebot|SeaMonkey|Kazehakase|Vienna|Iceape|Iceweasel|IceWeasel|Iron|K-Meleon|Sleipnir|Galeon|GranParadiso|iCab|iTunes|MacAppStore|NetNewsWire|Space Bison|Stainless|Orca|Dolfin|BOLT|Minimo|Tizen Browser|Polaris|Abrowser|Planetweb|ICE Browser|mDolphin|qutebrowser|Otter|QupZilla|MailBar|kmail2|YahooMobileMail|ExchangeWebServices|ExchangeServicesClient|Dragon|Outlook-iOS-Android)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'", " # Chrome/Chromium/major_version.minor_version\n - regex: '(Chromium|Chrome)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'", " ##########\n # IE Mobile needs to happen before Android to catch cases such as:\n # Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920)...\n # Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920; ANZ821)...\n # Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920; Orange)...\n # Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920; Vodafone)...\n ##########", " # IE Mobile\n - regex: '(IEMobile)[ /](\\d+)\\.(\\d+)'\n family_replacement: 'IE Mobile'", " # Baca Berita App News Reader\n - regex: '(BacaBerita App)\\/(\\d+)\\.(\\d+)\\.(\\d+)'", " # Podcast catchers\n - regex: '^(bPod|Pocket Casts|Player FM)$'\n - regex: '^(AlexaMediaPlayer|VLC)/(\\d+)\\.(\\d+)\\.([^.\\s]+)'\n - regex: '^(AntennaPod|WMPlayer|Zune|Podkicker|Radio|ExoPlayerDemo|Overcast|PocketTunes|NSPlayer|okhttp|DoggCatcher|QuickNews|QuickTime|Peapod|Podcasts|GoldenPod|VLC|Spotify|Miro|MediaGo|Juice|iPodder|gPodder|Banshee)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'\n - regex: '^(Peapod|Liferea)/([^.\\s]+)\\.([^.\\s]+|)\\.?([^.\\s]+|)'\n - regex: '^(bPod|Player FM) BMID/(\\S+)'\n - regex: '^(Podcast ?Addict)/v(\\d+) '\n - regex: '^(Podcast ?Addict) '\n family_replacement: 'PodcastAddict'\n - regex: '(Replay) AV'\n - regex: '(VOX) Music Player'\n - regex: '(CITA) RSS Aggregator/(\\d+)\\.(\\d+)'\n - regex: '(Pocket Casts)$'\n - regex: '(Player FM)$'\n - regex: '(LG Player|Doppler|FancyMusic|MediaMonkey|Clementine) (\\d+)\\.(\\d+)\\.?([^.\\s]+|)\\.?([^.\\s]+|)'\n - regex: '(philpodder)/(\\d+)\\.(\\d+)\\.?([^.\\s]+|)\\.?([^.\\s]+|)'\n - regex: '(Player FM|Pocket Casts|DoggCatcher|Spotify|MediaMonkey|MediaGo|BashPodder)'\n - regex: '(QuickTime)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n - regex: '(Kinoma)(\\d+)'\n - regex: '(Fancy) Cloud Music (\\d+)\\.(\\d+)'\n family_replacement: 'FancyMusic'\n - regex: 'EspnDownloadManager'\n family_replacement: 'ESPN'\n - regex: '(ESPN) Radio (\\d+)\\.(\\d+)(?:\\.(\\d+)|) ?(?:rv:(\\d+)|) '\n - regex: '(podracer|jPodder) v ?(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n - regex: '(ZDM)/(\\d+)\\.(\\d+)[; ]?'\n - regex: '(Zune|BeyondPod) (\\d+)(?:\\.(\\d+)|)[\\);]'\n - regex: '(WMPlayer)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n - regex: '^(Lavf)'\n family_replacement: 'WMPlayer'\n - regex: '^(RSSRadio)[ /]?(\\d+|)'\n - regex: '(RSS_Radio) (\\d+)\\.(\\d+)'\n family_replacement: 'RSSRadio'\n - regex: '(Podkicker) \\S+/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Podkicker'\n - regex: '^(HTC) Streaming Player \\S+ / \\S+ / \\S+ / (\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n - regex: '^(Stitcher)/iOS'\n - regex: '^(Stitcher)/Android'\n - regex: '^(VLC) .*version (\\d+)\\.(\\d+)\\.(\\d+)'\n - regex: ' (VLC) for'\n - regex: '(vlc)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'VLC'\n - regex: '^(foobar)\\S+/([^.\\s]+)\\.([^.\\s]+|)\\.?([^.\\s]+|)'\n - regex: '^(Clementine)\\S+ ([^.\\s]+)\\.([^.\\s]+|)\\.?([^.\\s]+|)'\n - regex: '(amarok)/([^.\\s]+)\\.([^.\\s]+|)\\.?([^.\\s]+|)'\n family_replacement: 'Amarok'\n - regex: '(Custom)-Feed Reader'", " # Browser major_version.minor_version.beta_version (space instead of slash)\n - regex: '(iRider|Crazy Browser|SkipStone|iCab|Lunascape|Sleipnir|Maemo Browser) (\\d+)\\.(\\d+)\\.(\\d+)'\n # Browser major_version.minor_version (space instead of slash)\n - regex: '(iCab|Lunascape|Opera|Android|Jasmine|Polaris|Microsoft SkyDriveSync|The Bat!) (\\d+)\\.(\\d+)(?:\\.(\\d+)|)'", " # Kindle WebKit\n - regex: '(Kindle)/(\\d+)\\.(\\d+)'", " # weird android UAs\n - regex: '(Android) Donut'\n v1_replacement: '1'\n v2_replacement: '2'", " - regex: '(Android) Eclair'\n v1_replacement: '2'\n v2_replacement: '1'", " - regex: '(Android) Froyo'\n v1_replacement: '2'\n v2_replacement: '2'", " - regex: '(Android) Gingerbread'\n v1_replacement: '2'\n v2_replacement: '3'", " - regex: '(Android) Honeycomb'\n v1_replacement: '3'", " # desktop mode\n # http://www.anandtech.com/show/3982/windows-phone-7-review\n - regex: '(MSIE) (\\d+)\\.(\\d+).*XBLWP7'\n family_replacement: 'IE Large Screen'", " # Nextcloud desktop sync client\n - regex: '(Nextcloud)'", " # Generic mirall client\n - regex: '(mirall)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # Nextcloud/Owncloud android client\n - regex: '(ownCloud-android)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Owncloud'", " # Skype for Business\n - regex: '(OC)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+) \\(Skype for Business\\)'\n family_replacement: 'Skype'", " #### END MAIN CASES ####", " #### SPECIAL CASES ####\n - regex: '(Obigo)InternetBrowser'\n - regex: '(Obigo)\\-Browser'\n - regex: '(Obigo|OBIGO)[^\\d]*(\\d+)(?:.(\\d+)|)'\n family_replacement: 'Obigo'", " - regex: '(MAXTHON|Maxthon) (\\d+)\\.(\\d+)'\n family_replacement: 'Maxthon'\n - regex: '(Maxthon|MyIE2|Uzbl|Shiira)'\n v1_replacement: '0'", " - regex: '(BrowseX) \\((\\d+)\\.(\\d+)\\.(\\d+)'", " - regex: '(NCSA_Mosaic)/(\\d+)\\.(\\d+)'\n family_replacement: 'NCSA Mosaic'", " # Polaris/d.d is above\n - regex: '(POLARIS)/(\\d+)\\.(\\d+)'\n family_replacement: 'Polaris'\n - regex: '(Embider)/(\\d+)\\.(\\d+)'\n family_replacement: 'Polaris'", " - regex: '(BonEcho)/(\\d+)\\.(\\d+)\\.?([ab]?\\d+|)'\n family_replacement: 'Bon Echo'", " # topbuzz on IOS\n - regex: '(TopBuzz) com.alex.NewsMaster/(\\d+).(\\d+).(\\d+)'\n family_replacement: 'TopBuzz'\n - regex: '(TopBuzz) com.mobilesrepublic.newsrepublic/(\\d+).(\\d+).(\\d+)'\n family_replacement: 'TopBuzz'\n - regex: '(TopBuzz) com.topbuzz.videoen/(\\d+).(\\d+).(\\d+)'\n family_replacement: 'TopBuzz'", " # @note: iOS / OSX Applications\n - regex: '(iPod|iPhone|iPad).+GSA/(\\d+)\\.(\\d+)\\.(\\d+) Mobile'\n family_replacement: 'Google'\n - regex: '(iPod|iPhone|iPad).+Version/(\\d+)\\.(\\d+)(?:\\.(\\d+)|).*[ +]Safari'\n family_replacement: 'Mobile Safari'\n - regex: '(iPod|iPod touch|iPhone|iPad);.*CPU.*OS[ +](\\d+)_(\\d+)(?:_(\\d+)|).* AppleNews\\/\\d+\\.\\d+\\.\\d+?'\n family_replacement: 'Mobile Safari UI/WKWebView'\n - regex: '(iPod|iPhone|iPad).+Version/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Mobile Safari UI/WKWebView'\n - regex: '(iPod|iPod touch|iPhone|iPad).* Safari'\n family_replacement: 'Mobile Safari'\n - regex: '(iPod|iPod touch|iPhone|iPad)'\n family_replacement: 'Mobile Safari UI/WKWebView'\n - regex: '(Watch)(\\d+),(\\d+)'\n family_replacement: 'Apple $1 App'", " ##########################\n # Outlook on iOS >= 2.62.0\n ##########################\n - regex: '(Outlook-iOS)/\\d+\\.\\d+\\.prod\\.iphone \\((\\d+)\\.(\\d+)\\.(\\d+)\\)'", " - regex: '(AvantGo) (\\d+).(\\d+)'", " - regex: '(OneBrowser)/(\\d+).(\\d+)'\n family_replacement: 'ONE Browser'", " - regex: '(Avant)'\n v1_replacement: '1'", " # This is the Tesla Model S (see similar entry in device parsers)\n - regex: '(QtCarBrowser)'\n v1_replacement: '1'", " - regex: '^(iBrowser/Mini)(\\d+).(\\d+)'\n family_replacement: 'iBrowser Mini'\n - regex: '^(iBrowser|iRAPP)/(\\d+).(\\d+)'", " # nokia browsers\n # based on: http://www.developer.nokia.com/Community/Wiki/User-Agent_headers_for_Nokia_devices\n - regex: '^(Nokia)'\n family_replacement: 'Nokia Services (WAP) Browser'\n - regex: '(NokiaBrowser)/(\\d+)\\.(\\d+).(\\d+)\\.(\\d+)'\n family_replacement: 'Nokia Browser'\n - regex: '(NokiaBrowser)/(\\d+)\\.(\\d+).(\\d+)'\n family_replacement: 'Nokia Browser'\n - regex: '(NokiaBrowser)/(\\d+)\\.(\\d+)'\n family_replacement: 'Nokia Browser'\n - regex: '(BrowserNG)/(\\d+)\\.(\\d+).(\\d+)'\n family_replacement: 'Nokia Browser'\n - regex: '(Series60)/5\\.0'\n family_replacement: 'Nokia Browser'\n v1_replacement: '7'\n v2_replacement: '0'\n - regex: '(Series60)/(\\d+)\\.(\\d+)'\n family_replacement: 'Nokia OSS Browser'\n - regex: '(S40OviBrowser)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Ovi Browser'\n - regex: '(Nokia)[EN]?(\\d+)'", " # BlackBerry devices\n - regex: '(PlayBook).+RIM Tablet OS (\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'BlackBerry WebKit'\n - regex: '(Black[bB]erry|BB10).+Version/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'BlackBerry WebKit'\n - regex: '(Black[bB]erry)\\s?(\\d+)'\n family_replacement: 'BlackBerry'", " - regex: '(OmniWeb)/v(\\d+)\\.(\\d+)'", " - regex: '(Blazer)/(\\d+)\\.(\\d+)'\n family_replacement: 'Palm Blazer'", " - regex: '(Pre)/(\\d+)\\.(\\d+)'\n family_replacement: 'Palm Pre'", " # fork of Links\n - regex: '(ELinks)/(\\d+)\\.(\\d+)'\n - regex: '(ELinks) \\((\\d+)\\.(\\d+)'\n - regex: '(Links) \\((\\d+)\\.(\\d+)'", " - regex: '(QtWeb) Internet Browser/(\\d+)\\.(\\d+)'", " #- regex: '\\(iPad;.+(Version)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|).*Safari/'\n # family_replacement: 'iPad'", " # Phantomjs, should go before Safari\n - regex: '(PhantomJS)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # WebKit Nightly\n - regex: '(AppleWebKit)/(\\d+)(?:\\.(\\d+)|)\\+ .* Safari'\n family_replacement: 'WebKit Nightly'", " # Safari\n - regex: '(Version)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|).*Safari/'\n family_replacement: 'Safari'\n # Safari didn't provide \"Version/d.d.d\" prior to 3.0\n - regex: '(Safari)/\\d+'", " - regex: '(OLPC)/Update(\\d+)\\.(\\d+)'", " - regex: '(OLPC)/Update()\\.(\\d+)'\n v1_replacement: '0'", " - regex: '(SEMC\\-Browser)/(\\d+)\\.(\\d+)'", " - regex: '(Teleca)'\n family_replacement: 'Teleca Browser'", " - regex: '(Phantom)/V(\\d+)\\.(\\d+)'\n family_replacement: 'Phantom Browser'", " - regex: '(Trident)/(7|8)\\.(0)'\n family_replacement: 'IE'\n v1_replacement: '11'", " - regex: '(Trident)/(6)\\.(0)'\n family_replacement: 'IE'\n v1_replacement: '10'", " - regex: '(Trident)/(5)\\.(0)'\n family_replacement: 'IE'\n v1_replacement: '9'", " - regex: '(Trident)/(4)\\.(0)'\n family_replacement: 'IE'\n v1_replacement: '8'", " # Espial\n - regex: '(Espial)/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'", " # Apple Mail", " # apple mail - not directly detectable, have it after Safari stuff\n - regex: '(AppleWebKit)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Apple Mail'", " # AFTER THE EDGE CASES ABOVE!\n # AFTER IE11\n # BEFORE all other IE\n - regex: '(Firefox)/(\\d+)\\.(\\d+)\\.(\\d+)'\n - regex: '(Firefox)/(\\d+)\\.(\\d+)(pre|[ab]\\d+[a-z]*|)'", " - regex: '([MS]?IE) (\\d+)\\.(\\d+)'\n family_replacement: 'IE'", " - regex: '(python-requests)/(\\d+)\\.(\\d+)'\n family_replacement: 'Python Requests'", " # headless user-agents\n - regex: '\\b(Windows-Update-Agent|Microsoft-CryptoAPI|SophosUpdateManager|SophosAgent|Debian APT-HTTP|Ubuntu APT-HTTP|libcurl-agent|libwww-perl|urlgrabber|curl|PycURL|Wget|aria2|Axel|OpenBSD ftp|lftp|jupdate|insomnia|fetch libfetch|akka-http|got)(?:[ /](\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)|)'", " # Asynchronous HTTP Client/Server for asyncio and Python (https://aiohttp.readthedocs.io/)\n - regex: '(Python/3\\.\\d{1,3} aiohttp)/(\\d+)\\.(\\d+)\\.(\\d+)'\n # Asynchronous HTTP Client/Server for asyncio and Python (https://aiohttp.readthedocs.io/)\n - regex: '(Python/3\\.\\d{1,3} aiohttp)/(\\d+)\\.(\\d+)\\.(\\d+)'", " - regex: '(Java)[/ ]{0,1}\\d+\\.(\\d+)\\.(\\d+)[_-]*([a-zA-Z0-9]+|)'", " # Cloud Storage Clients\n - regex: '^(Cyberduck)/(\\d+)\\.(\\d+)\\.(\\d+)(?:\\.\\d+|)'\n - regex: '^(S3 Browser) (\\d+)-(\\d+)-(\\d+)(?:\\s*http://s3browser\\.com|)'\n - regex: '(S3Gof3r)'\n # IBM COS (Cloud Object Storage) API\n - regex: '\\b(ibm-cos-sdk-(?:core|java|js|python))/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n # rusoto - Rusoto - AWS SDK for Rust - https://github.com/rusoto/rusoto\n - regex: '^(rusoto)/(\\d+)\\.(\\d+)\\.(\\d+)'\n # rclone - rsync for cloud storage - https://rclone.org/\n - regex: '^(rclone)/v(\\d+)\\.(\\d+)'", " # Roku Digital-Video-Players https://www.roku.com/\n - regex: '^(Roku)/DVP-(\\d+)\\.(\\d+)'", " # Kurio App News Reader https://kurio.co.id/\n - regex: '(Kurio)\\/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Kurio App'", " # Box Drive and Box Sync https://www.box.com/resources/downloads\n - regex: '^(Box(?: Sync)?)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # ViaFree streaming app https://www.viafree.{dk|se|no}\n - regex: '^(ViaFree|Viafree)-(?:tvOS-)?[A-Z]{2}/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'ViaFree'", "os_parsers:\n ##########\n # HbbTV vendors\n ##########", " # starts with the easy one : Panasonic seems consistent across years, hope it will continue\n #HbbTV/1.1.1 (;Panasonic;VIERA 2011;f.532;0071-0802 2000-0000;)\n #HbbTV/1.1.1 (;Panasonic;VIERA 2012;1.261;0071-3103 2000-0000;)\n #HbbTV/1.2.1 (;Panasonic;VIERA 2013;3.672;4101-0003 0002-0000;)\n #- regex: 'HbbTV/\\d+\\.\\d+\\.\\d+ \\(;(Panasonic);VIERA ([0-9]{4});'", " # Sony is consistent too but do not place year like the other\n # Opera/9.80 (Linux armv7l; HbbTV/1.1.1 (; Sony; KDL32W650A; PKG3.211EUA; 2013;); ) Presto/2.12.362 Version/12.11\n # Opera/9.80 (Linux mips; U; HbbTV/1.1.1 (; Sony; KDL40HX751; PKG1.902EUA; 2012;);; en) Presto/2.10.250 Version/11.60\n # Opera/9.80 (Linux mips; U; HbbTV/1.1.1 (; Sony; KDL22EX320; PKG4.017EUA; 2011;);; en) Presto/2.7.61 Version/11.00\n #- regex: 'HbbTV/\\d+\\.\\d+\\.\\d+ \\(; (Sony);.*;.*; ([0-9]{4});\\)'", "\n # LG is consistent too, but we need to add manually the year model\n #Mozilla/5.0 (Unknown; Linux armv7l) AppleWebKit/537.1+ (KHTML, like Gecko) Safari/537.1+ HbbTV/1.1.1 ( ;LGE ;NetCast 4.0 ;03.20.30 ;1.0M ;)\n #Mozilla/5.0 (DirectFB; Linux armv7l) AppleWebKit/534.26+ (KHTML, like Gecko) Version/5.0 Safari/534.26+ HbbTV/1.1.1 ( ;LGE ;NetCast 3.0 ;1.0 ;1.0M ;)\n - regex: 'HbbTV/\\d+\\.\\d+\\.\\d+ \\( ;(LG)E ;NetCast 4.0'\n os_v1_replacement: '2013'\n - regex: 'HbbTV/\\d+\\.\\d+\\.\\d+ \\( ;(LG)E ;NetCast 3.0'\n os_v1_replacement: '2012'", " # Samsung is on its way of normalizing their user-agent\n # HbbTV/1.1.1 (;Samsung;SmartTV2013;T-FXPDEUC-1102.2;;) WebKit\n # HbbTV/1.1.1 (;Samsung;SmartTV2013;T-MST12DEUC-1102.1;;) WebKit\n # HbbTV/1.1.1 (;Samsung;SmartTV2012;;;) WebKit\n # HbbTV/1.1.1 (;;;;;) Maple_2011\n - regex: 'HbbTV/1.1.1 \\(;;;;;\\) Maple_2011'\n os_replacement: 'Samsung'\n os_v1_replacement: '2011'\n # manage the two models of 2013\n - regex: 'HbbTV/\\d+\\.\\d+\\.\\d+ \\(;(Samsung);SmartTV([0-9]{4});.*FXPDEUC'\n os_v2_replacement: 'UE40F7000'\n - regex: 'HbbTV/\\d+\\.\\d+\\.\\d+ \\(;(Samsung);SmartTV([0-9]{4});.*MST12DEUC'\n os_v2_replacement: 'UE32F4500'\n # generic Samsung (works starting in 2012)\n #- regex: 'HbbTV/\\d+\\.\\d+\\.\\d+ \\(;(Samsung);SmartTV([0-9]{4});'", " # Philips : not found any other way than a manual mapping\n # Opera/9.80 (Linux mips; U; HbbTV/1.1.1 (; Philips; ; ; ; ) CE-HTML/1.0 NETTV/4.1.3 PHILIPSTV/1.1.1; en) Presto/2.10.250 Version/11.60\n # Opera/9.80 (Linux mips ; U; HbbTV/1.1.1 (; Philips; ; ; ; ) CE-HTML/1.0 NETTV/3.2.1; en) Presto/2.6.33 Version/10.70\n - regex: 'HbbTV/1\\.1\\.1 \\(; (Philips);.*NETTV/4'\n os_v1_replacement: '2013'\n - regex: 'HbbTV/1\\.1\\.1 \\(; (Philips);.*NETTV/3'\n os_v1_replacement: '2012'\n - regex: 'HbbTV/1\\.1\\.1 \\(; (Philips);.*NETTV/2'\n os_v1_replacement: '2011'", " # the HbbTV emulator developers use HbbTV/1.1.1 (;;;;;) firetv-firefox-plugin 1.1.20\n - regex: 'HbbTV/\\d+\\.\\d+\\.\\d+.*(firetv)-firefox-plugin (\\d+).(\\d+).(\\d+)'\n os_replacement: 'FireHbbTV'", " # generic HbbTV, hoping to catch manufacturer name (always after 2nd comma) and the first string that looks like a 2011-2019 year\n - regex: 'HbbTV/\\d+\\.\\d+\\.\\d+ \\(.*; ?([a-zA-Z]+) ?;.*(201[1-9]).*\\)'", " ##########\n # @note: Windows Phone needs to come before Windows NT 6.1 *and* before Android to catch cases such as:\n # Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920)...\n # Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920; ANZ821)...\n # Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920; Orange)...\n # Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920; Vodafone)...\n ##########", " - regex: '(Windows Phone) (?:OS[ /])?(\\d+)\\.(\\d+)'", " # Again a MS-special one: iPhone.*Outlook-iOS-Android/x.x is erroneously detected as Android\n - regex: '(CPU[ +]OS|iPhone[ +]OS|CPU[ +]iPhone)[ +]+(\\d+)[_\\.](\\d+)(?:[_\\.](\\d+)|).*Outlook-iOS-Android'\n os_replacement: 'iOS'", " ##########\n # Android\n # can actually detect rooted android os. do we care?\n ##########\n - regex: '(Android)[ \\-/](\\d+)(?:\\.(\\d+)|)(?:[.\\-]([a-z0-9]+)|)'", " - regex: '(Android) Donut'\n os_v1_replacement: '1'\n os_v2_replacement: '2'", " - regex: '(Android) Eclair'\n os_v1_replacement: '2'\n os_v2_replacement: '1'", " - regex: '(Android) Froyo'\n os_v1_replacement: '2'\n os_v2_replacement: '2'", " - regex: '(Android) Gingerbread'\n os_v1_replacement: '2'\n os_v2_replacement: '3'", " - regex: '(Android) Honeycomb'\n os_v1_replacement: '3'", " # Android 9; Android 10;\n - regex: '(Android) (\\d+);'", " # UCWEB\n - regex: '^UCWEB.*; (Adr) (\\d+)\\.(\\d+)(?:[.\\-]([a-z0-9]+)|);'\n os_replacement: 'Android'\n - regex: '^UCWEB.*; (iPad|iPh|iPd) OS (\\d+)_(\\d+)(?:_(\\d+)|);'\n os_replacement: 'iOS'\n - regex: '^UCWEB.*; (wds) (\\d+)\\.(\\d+)(?:\\.(\\d+)|);'\n os_replacement: 'Windows Phone'\n # JUC\n - regex: '^(JUC).*; ?U; ?(?:Android|)(\\d+)\\.(\\d+)(?:[\\.\\-]([a-z0-9]+)|)'\n os_replacement: 'Android'", " # Salesforce\n - regex: '(android)\\s(?:mobile\\/)(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)|)|)'\n os_replacement: 'Android'", " ##########\n # Kindle Android\n ##########\n - regex: '(Silk-Accelerated=[a-z]{4,5})'\n os_replacement: 'Android'", " # Citrix Chrome App on Chrome OS\n # Note, this needs to come before the windows parsers as the app doesn't\n # properly identify as Chrome OS\n #\n # ex: Mozilla/5.0 (X11; Windows aarch64 10718.88.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.118 Safari/537.36 CitrixChromeApp\n - regex: '(x86_64|aarch64)\\ (\\d+)\\.(\\d+)\\.(\\d+).*Chrome.*(?:CitrixChromeApp)$'\n os_replacement: 'Chrome OS'", " ##########\n # Windows\n # http://en.wikipedia.org/wiki/Windows_NT#Releases\n # possibility of false positive when different marketing names share same NT kernel\n # e.g. windows server 2003 and windows xp\n # lots of ua strings have Windows NT 4.1 !?!?!?!? !?!? !? !????!?! !!! ??? !?!?! ?\n # (very) roughly ordered in terms of frequency of occurence of regex (win xp currently most frequent, etc)\n ##########", " # ie mobile desktop mode\n # spoofs nt 6.1. must come before windows 7\n - regex: '(XBLWP7)'\n os_replacement: 'Windows Phone'", " # @note: This needs to come before Windows NT 6.1\n - regex: '(Windows ?Mobile)'\n os_replacement: 'Windows Mobile'", " - regex: '(Windows 10)'\n os_replacement: 'Windows'\n os_v1_replacement: '10'", " - regex: '(Windows (?:NT 5\\.2|NT 5\\.1))'\n os_replacement: 'Windows'\n os_v1_replacement: 'XP'", " - regex: '(Windows NT 6\\.1)'\n os_replacement: 'Windows'\n os_v1_replacement: '7'", " - regex: '(Windows NT 6\\.0)'\n os_replacement: 'Windows'\n os_v1_replacement: 'Vista'", " - regex: '(Win 9x 4\\.90)'\n os_replacement: 'Windows'\n os_v1_replacement: 'ME'", " - regex: '(Windows NT 6\\.2; ARM;)'\n os_replacement: 'Windows'\n os_v1_replacement: 'RT'", " - regex: '(Windows NT 6\\.2)'\n os_replacement: 'Windows'\n os_v1_replacement: '8'", " - regex: '(Windows NT 6\\.3; ARM;)'\n os_replacement: 'Windows'\n os_v1_replacement: 'RT 8'\n os_v2_replacement: '1'", " - regex: '(Windows NT 6\\.3)'\n os_replacement: 'Windows'\n os_v1_replacement: '8'\n os_v2_replacement: '1'", " - regex: '(Windows NT 6\\.4)'\n os_replacement: 'Windows'\n os_v1_replacement: '10'", " - regex: '(Windows NT 10\\.0)'\n os_replacement: 'Windows'\n os_v1_replacement: '10'", " - regex: '(Windows NT 5\\.0)'\n os_replacement: 'Windows'\n os_v1_replacement: '2000'", " - regex: '(WinNT4.0)'\n os_replacement: 'Windows'\n os_v1_replacement: 'NT 4.0'", " - regex: '(Windows ?CE)'\n os_replacement: 'Windows'\n os_v1_replacement: 'CE'", " - regex: 'Win(?:dows)? ?(95|98|3.1|NT|ME|2000|XP|Vista|7|CE)'\n os_replacement: 'Windows'\n os_v1_replacement: '$1'", " - regex: 'Win16'\n os_replacement: 'Windows'\n os_v1_replacement: '3.1'", " - regex: 'Win32'\n os_replacement: 'Windows'\n os_v1_replacement: '95'", " # Box apps (Drive, Sync, Notes) on Windows https://www.box.com/resources/downloads\n - regex: '^Box.*Windows/([\\d.]+);'\n os_replacement: 'Windows'\n os_v1_replacement: '$1'", " ##########\n # Tizen OS from Samsung\n # spoofs Android so pushing it above\n ##########\n - regex: '(Tizen)[/ ](\\d+)\\.(\\d+)'", " ##########\n # Mac OS\n # @ref: http://en.wikipedia.org/wiki/Mac_OS_X#Versions\n # @ref: http://www.puredarwin.org/curious/versions\n ##########\n - regex: '((?:Mac[ +]?|; )OS[ +]X)[\\s+/](?:(\\d+)[_.](\\d+)(?:[_.](\\d+)|)|Mach-O)'\n os_replacement: 'Mac OS X'\n - regex: '\\w+\\s+Mac OS X\\s+\\w+\\s+(\\d+).(\\d+).(\\d+).*'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '$1'\n os_v2_replacement: '$2'\n os_v3_replacement: '$3'\n # Leopard\n - regex: ' (Dar)(win)/(9).(\\d+).*\\((?:i386|x86_64|Power Macintosh)\\)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '5'\n # Snow Leopard\n - regex: ' (Dar)(win)/(10).(\\d+).*\\((?:i386|x86_64)\\)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '6'\n # Lion\n - regex: ' (Dar)(win)/(11).(\\d+).*\\((?:i386|x86_64)\\)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '7'\n # Mountain Lion\n - regex: ' (Dar)(win)/(12).(\\d+).*\\((?:i386|x86_64)\\)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '8'\n # Mavericks\n - regex: ' (Dar)(win)/(13).(\\d+).*\\((?:i386|x86_64)\\)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '9'\n # Yosemite is Darwin/14.x but patch versions are inconsistent in the Darwin string;\n # more accurately covered by CFNetwork regexes downstream", " # IE on Mac doesn't specify version number\n - regex: 'Mac_PowerPC'\n os_replacement: 'Mac OS'", " # builds before tiger don't seem to specify version?", " # ios devices spoof (mac os x), so including intel/ppc prefixes\n - regex: '(?:PPC|Intel) (Mac OS X)'", " # Box Drive and Box Sync on Mac OS X use OSX version numbers, not Darwin\n - regex: '^Box.*;(Darwin)/(10)\\.(1\\d)(?:\\.(\\d+)|)'\n os_replacement: 'Mac OS X'", " ##########\n # iOS\n # http://en.wikipedia.org/wiki/IOS_version_history\n ##########\n # keep this above generic iOS, since AppleTV UAs contain 'CPU OS'\n - regex: '(Apple\\s?TV)(?:/(\\d+)\\.(\\d+)|)'\n os_replacement: 'ATV OS X'", " - regex: '(CPU[ +]OS|iPhone[ +]OS|CPU[ +]iPhone|CPU IPhone OS)[ +]+(\\d+)[_\\.](\\d+)(?:[_\\.](\\d+)|)'\n os_replacement: 'iOS'", " # remaining cases are mostly only opera uas, so catch opera as to not catch iphone spoofs\n - regex: '(iPhone|iPad|iPod); Opera'\n os_replacement: 'iOS'", " # few more stragglers\n - regex: '(iPhone|iPad|iPod).*Mac OS X.*Version/(\\d+)\\.(\\d+)'\n os_replacement: 'iOS'", " # CFNetwork/Darwin - The specific CFNetwork or Darwin version determines\n # whether the os maps to Mac OS, or iOS, or just Darwin.\n # See: http://user-agents.me/cfnetwork-version-list\n - regex: '(CFNetwork)/(5)48\\.0\\.3.* Darwin/11\\.0\\.0'\n os_replacement: 'iOS'\n - regex: '(CFNetwork)/(5)48\\.(0)\\.4.* Darwin/(1)1\\.0\\.0'\n os_replacement: 'iOS'\n - regex: '(CFNetwork)/(5)48\\.(1)\\.4'\n os_replacement: 'iOS'\n - regex: '(CFNetwork)/(4)85\\.1(3)\\.9'\n os_replacement: 'iOS'\n - regex: '(CFNetwork)/(6)09\\.(1)\\.4'\n os_replacement: 'iOS'\n - regex: '(CFNetwork)/(6)(0)9'\n os_replacement: 'iOS'\n - regex: '(CFNetwork)/6(7)2\\.(1)\\.13'\n os_replacement: 'iOS'\n - regex: '(CFNetwork)/6(7)2\\.(1)\\.(1)4'\n os_replacement: 'iOS'\n - regex: '(CF)(Network)/6(7)(2)\\.1\\.15'\n os_replacement: 'iOS'\n os_v1_replacement: '7'\n os_v2_replacement: '1'\n - regex: '(CFNetwork)/6(7)2\\.(0)\\.(?:2|8)'\n os_replacement: 'iOS'\n - regex: '(CFNetwork)/709\\.1'\n os_replacement: 'iOS'\n os_v1_replacement: '8'\n os_v2_replacement: '0.b5'\n - regex: '(CF)(Network)/711\\.(\\d)'\n os_replacement: 'iOS'\n os_v1_replacement: '8'\n - regex: '(CF)(Network)/(720)\\.(\\d)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '10'\n - regex: '(CF)(Network)/(760)\\.(\\d)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '11'\n - regex: 'CFNetwork/7.* Darwin/15\\.4\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '9'\n os_v2_replacement: '3'\n os_v3_replacement: '1'\n - regex: 'CFNetwork/7.* Darwin/15\\.5\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '9'\n os_v2_replacement: '3'\n os_v3_replacement: '2'\n - regex: 'CFNetwork/7.* Darwin/15\\.6\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '9'\n os_v2_replacement: '3'\n os_v3_replacement: '5'\n - regex: '(CF)(Network)/758\\.(\\d)'\n os_replacement: 'iOS'\n os_v1_replacement: '9'\n - regex: 'CFNetwork/808\\.3 Darwin/16\\.3\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '10'\n os_v2_replacement: '2'\n os_v3_replacement: '1'\n - regex: '(CF)(Network)/808\\.(\\d)'\n os_replacement: 'iOS'\n os_v1_replacement: '10'", " ##########\n # CFNetwork macOS Apps (must be before CFNetwork iOS Apps\n # @ref: https://en.wikipedia.org/wiki/Darwin_(operating_system)#Release_history\n ##########\n - regex: 'CFNetwork/.* Darwin/17\\.\\d+.*\\(x86_64\\)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '13'\n - regex: 'CFNetwork/.* Darwin/16\\.\\d+.*\\(x86_64\\)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '12'\n - regex: 'CFNetwork/8.* Darwin/15\\.\\d+.*\\(x86_64\\)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '11'\n ##########\n # CFNetwork iOS Apps\n # @ref: https://en.wikipedia.org/wiki/Darwin_(operating_system)#Release_history\n ##########\n - regex: 'CFNetwork/.* Darwin/(9)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '1'\n - regex: 'CFNetwork/.* Darwin/(10)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '4'\n - regex: 'CFNetwork/.* Darwin/(11)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '5'\n - regex: 'CFNetwork/.* Darwin/(13)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '6'\n - regex: 'CFNetwork/6.* Darwin/(14)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '7'\n - regex: 'CFNetwork/7.* Darwin/(14)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '8'\n os_v2_replacement: '0'\n - regex: 'CFNetwork/7.* Darwin/(15)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '9'\n os_v2_replacement: '0'\n - regex: 'CFNetwork/8.* Darwin/16\\.5\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '10'\n os_v2_replacement: '3'\n - regex: 'CFNetwork/8.* Darwin/16\\.6\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '10'\n os_v2_replacement: '3'\n os_v3_replacement: '2'\n - regex: 'CFNetwork/8.* Darwin/16\\.7\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '10'\n os_v2_replacement: '3'\n os_v3_replacement: '3'\n - regex: 'CFNetwork/8.* Darwin/(16)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '10'\n - regex: 'CFNetwork/8.* Darwin/17\\.0\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '11'\n os_v2_replacement: '0'\n - regex: 'CFNetwork/8.* Darwin/17\\.2\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '11'\n os_v2_replacement: '1'\n - regex: 'CFNetwork/8.* Darwin/17\\.3\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '11'\n os_v2_replacement: '2'\n - regex: 'CFNetwork/8.* Darwin/17\\.4\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '11'\n os_v2_replacement: '2'\n os_v3_replacement: '6'\n - regex: 'CFNetwork/8.* Darwin/17\\.5\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '11'\n os_v2_replacement: '3'\n - regex: 'CFNetwork/9.* Darwin/17\\.6\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '11'\n os_v2_replacement: '4'\n - regex: 'CFNetwork/9.* Darwin/17\\.7\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '11'\n os_v2_replacement: '4'\n os_v3_replacement: '1'\n - regex: 'CFNetwork/8.* Darwin/(17)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '11'\n - regex: 'CFNetwork/9.* Darwin/18\\.0\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '12'\n os_v2_replacement: '0'\n - regex: 'CFNetwork/9.* Darwin/(18)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '12'\n - regex: 'CFNetwork/.* Darwin/'\n os_replacement: 'iOS'", " # iOS Apps\n - regex: '\\b(iOS[ /]|iOS; |iPhone(?:/| v|[ _]OS[/,]|; | OS : |\\d,\\d/|\\d,\\d; )|iPad/)(\\d{1,2})[_\\.](\\d{1,2})(?:[_\\.](\\d+)|)'\n os_replacement: 'iOS'\n - regex: '\\((iOS);'", " ##########\n # Apple Watch\n ##########\n - regex: '(watchOS)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n os_replacement: 'WatchOS'", " ##########################\n # Outlook on iOS >= 2.62.0\n ##########################\n - regex: 'Outlook-(iOS)/\\d+\\.\\d+\\.prod\\.iphone'", " ##########################\n # iOS devices, the same regex matches mobile safari webviews\n ##########################\n - regex: '(iPod|iPhone|iPad)'\n os_replacement: 'iOS'", " ##########\n # Apple TV\n ##########\n - regex: '(tvOS)[/ ](\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n os_replacement: 'tvOS'", " ##########\n # Chrome OS\n # if version 0.0.0, probably this stuff:\n # http://code.google.com/p/chromium-os/issues/detail?id=11573\n # http://code.google.com/p/chromium-os/issues/detail?id=13790\n ##########\n - regex: '(CrOS) [a-z0-9_]+ (\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n os_replacement: 'Chrome OS'", " ##########\n # Linux distros\n ##########\n - regex: '([Dd]ebian)'\n os_replacement: 'Debian'\n - regex: '(Linux Mint)(?:/(\\d+)|)'\n - regex: '(Mandriva)(?: Linux|)/(?:[\\d.-]+m[a-z]{2}(\\d+).(\\d)|)'", " ##########\n # Symbian + Symbian OS\n # http://en.wikipedia.org/wiki/History_of_Symbian\n ##########\n - regex: '(Symbian[Oo][Ss])[/ ](\\d+)\\.(\\d+)'\n os_replacement: 'Symbian OS'\n - regex: '(Symbian/3).+NokiaBrowser/7\\.3'\n os_replacement: 'Symbian^3 Anna'\n - regex: '(Symbian/3).+NokiaBrowser/7\\.4'\n os_replacement: 'Symbian^3 Belle'\n - regex: '(Symbian/3)'\n os_replacement: 'Symbian^3'\n - regex: '\\b(Series 60|SymbOS|S60Version|S60V\\d|S60\\b)'\n os_replacement: 'Symbian OS'\n - regex: '(MeeGo)'\n - regex: 'Symbian [Oo][Ss]'\n os_replacement: 'Symbian OS'\n - regex: 'Series40;'\n os_replacement: 'Nokia Series 40'\n - regex: 'Series30Plus;'\n os_replacement: 'Nokia Series 30 Plus'", " ##########\n # BlackBerry devices\n ##########\n - regex: '(BB10);.+Version/(\\d+)\\.(\\d+)\\.(\\d+)'\n os_replacement: 'BlackBerry OS'\n - regex: '(Black[Bb]erry)[0-9a-z]+/(\\d+)\\.(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n os_replacement: 'BlackBerry OS'\n - regex: '(Black[Bb]erry).+Version/(\\d+)\\.(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n os_replacement: 'BlackBerry OS'\n - regex: '(RIM Tablet OS) (\\d+)\\.(\\d+)\\.(\\d+)'\n os_replacement: 'BlackBerry Tablet OS'\n - regex: '(Play[Bb]ook)'\n os_replacement: 'BlackBerry Tablet OS'\n - regex: '(Black[Bb]erry)'\n os_replacement: 'BlackBerry OS'", " ##########\n # KaiOS\n ##########\n - regex: '(K[Aa][Ii]OS)\\/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n os_replacement: 'KaiOS'", " ##########\n # Firefox OS\n ##########\n - regex: '\\((?:Mobile|Tablet);.+Gecko/18.0 Firefox/\\d+\\.\\d+'\n os_replacement: 'Firefox OS'\n os_v1_replacement: '1'\n os_v2_replacement: '0'\n os_v3_replacement: '1'", " - regex: '\\((?:Mobile|Tablet);.+Gecko/18.1 Firefox/\\d+\\.\\d+'\n os_replacement: 'Firefox OS'\n os_v1_replacement: '1'\n os_v2_replacement: '1'", " - regex: '\\((?:Mobile|Tablet);.+Gecko/26.0 Firefox/\\d+\\.\\d+'\n os_replacement: 'Firefox OS'\n os_v1_replacement: '1'\n os_v2_replacement: '2'", " - regex: '\\((?:Mobile|Tablet);.+Gecko/28.0 Firefox/\\d+\\.\\d+'\n os_replacement: 'Firefox OS'\n os_v1_replacement: '1'\n os_v2_replacement: '3'", " - regex: '\\((?:Mobile|Tablet);.+Gecko/30.0 Firefox/\\d+\\.\\d+'\n os_replacement: 'Firefox OS'\n os_v1_replacement: '1'\n os_v2_replacement: '4'", " - regex: '\\((?:Mobile|Tablet);.+Gecko/32.0 Firefox/\\d+\\.\\d+'\n os_replacement: 'Firefox OS'\n os_v1_replacement: '2'\n os_v2_replacement: '0'", " - regex: '\\((?:Mobile|Tablet);.+Gecko/34.0 Firefox/\\d+\\.\\d+'\n os_replacement: 'Firefox OS'\n os_v1_replacement: '2'\n os_v2_replacement: '1'", " # Firefox OS Generic\n - regex: '\\((?:Mobile|Tablet);.+Firefox/\\d+\\.\\d+'\n os_replacement: 'Firefox OS'", "\n ##########\n # BREW\n # yes, Brew is lower-cased for Brew MP\n ##########\n - regex: '(BREW)[ /](\\d+)\\.(\\d+)\\.(\\d+)'\n - regex: '(BREW);'\n - regex: '(Brew MP|BMP)[ /](\\d+)\\.(\\d+)\\.(\\d+)'\n os_replacement: 'Brew MP'\n - regex: 'BMP;'\n os_replacement: 'Brew MP'", " ##########\n # Google TV\n ##########\n - regex: '(GoogleTV)(?: (\\d+)\\.(\\d+)(?:\\.(\\d+)|)|/[\\da-z]+)'", " - regex: '(WebTV)/(\\d+).(\\d+)'", " ##########\n # Chromecast\n ##########\n - regex: '(CrKey)(?:[/](\\d+)\\.(\\d+)(?:\\.(\\d+)|)|)'\n os_replacement: 'Chromecast'", " ##########\n # Misc mobile\n ##########\n - regex: '(hpw|web)OS/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n os_replacement: 'webOS'\n - regex: '(VRE);'", " ##########\n # Generic patterns\n # since the majority of os cases are very specific, these go last\n ##########\n - regex: '(Fedora|Red Hat|PCLinuxOS|Puppy|Ubuntu|Kindle|Bada|Sailfish|Lubuntu|BackTrack|Slackware|(?:Free|Open|Net|\\b)BSD)[/ ](\\d+)\\.(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'", " # Gentoo Linux + Kernel Version\n - regex: '(Linux)[ /](\\d+)\\.(\\d+)(?:\\.(\\d+)|).*gentoo'\n os_replacement: 'Gentoo'", " # Opera Mini Bada\n - regex: '\\((Bada);'", " # just os\n - regex: '(Windows|Android|WeTab|Maemo|Web0S)'\n - regex: '(Ubuntu|Kubuntu|Arch Linux|CentOS|Slackware|Gentoo|openSUSE|SUSE|Red Hat|Fedora|PCLinuxOS|Mageia|(?:Free|Open|Net|\\b)BSD)'\n # Linux + Kernel Version\n - regex: '(Linux)(?:[ /](\\d+)\\.(\\d+)(?:\\.(\\d+)|)|)'\n - regex: 'SunOS'\n os_replacement: 'Solaris'\n # Wget/x.x.x (linux-gnu)\n - regex: '\\(linux-gnu\\)'\n os_replacement: 'Linux'\n - regex: '\\(x86_64-redhat-linux-gnu\\)'\n os_replacement: 'Red Hat'\n - regex: '\\((freebsd)(\\d+)\\.(\\d+)\\)'\n os_replacement: 'FreeBSD'\n - regex: 'linux'\n os_replacement: 'Linux'", " # Roku Digital-Video-Players https://www.roku.com/\n - regex: '^(Roku)/DVP-(\\d+)\\.(\\d+)'", "device_parsers:", " #########\n # Mobile Spiders\n # Catch the mobile crawler before checking for iPhones / Androids.\n #########\n - regex: '(?:(?:iPhone|Windows CE|Windows Phone|Android).*(?:(?:Bot|Yeti)-Mobile|YRSpider|BingPreview|bots?/\\d|(?:bot|spider)\\.html)|AdsBot-Google-Mobile.*iPhone)'\n regex_flag: 'i'\n device_replacement: 'Spider'\n brand_replacement: 'Spider'\n model_replacement: 'Smartphone'\n - regex: '(?:DoCoMo|\\bMOT\\b|\\bLG\\b|Nokia|Samsung|SonyEricsson).*(?:(?:Bot|Yeti)-Mobile|bots?/\\d|(?:bot|crawler)\\.html|(?:jump|google|Wukong)bot|ichiro/mobile|/spider|YahooSeeker)'\n regex_flag: 'i'\n device_replacement: 'Spider'\n brand_replacement: 'Spider'\n model_replacement: 'Feature Phone'", " # PTST / WebPageTest.org crawlers\n - regex: ' PTST/\\d+(?:\\.)?\\d+$'\n device_replacement: 'Spider'\n brand_replacement: 'Spider'", " # Datanyze.com spider\n - regex: 'X11; Datanyze; Linux'\n device_replacement: 'Spider'\n brand_replacement: 'Spider'", " #########\n # WebBrowser for SmartWatch\n # @ref: https://play.google.com/store/apps/details?id=se.vaggan.webbrowser&hl=en\n #########", " - regex: '\\bSmartWatch *\\( *([^;]+) *; *([^;]+) *;'", " device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " ######################################################################\n # Android parsers\n #\n # @ref: https://support.google.com/googleplay/answer/1727131?hl=en\n ######################################################################", " # Android Application\n - regex: 'Android Application[^\\-]+ - (Sony) ?(Ericsson|) (.+) \\w+ - '\n device_replacement: '$1 $2'\n brand_replacement: '$1$2'\n model_replacement: '$3'\n - regex: 'Android Application[^\\-]+ - (?:HTC|HUAWEI|LGE|LENOVO|MEDION|TCT) (HTC|HUAWEI|LG|LENOVO|MEDION|ALCATEL)[ _\\-](.+) \\w+ - '\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'\n - regex: 'Android Application[^\\-]+ - ([^ ]+) (.+) \\w+ - '\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " #########\n # 3Q\n # @ref: http://www.3q-int.com/\n #########\n - regex: '; *([BLRQ]C\\d{4}[A-Z]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '3Q $1'\n brand_replacement: '3Q'\n model_replacement: '$1'\n - regex: '; *(?:3Q_)([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '3Q $1'\n brand_replacement: '3Q'\n model_replacement: '$1'", " #########\n # Acer\n # @ref: http://us.acer.com/ac/en/US/content/group/tablets\n #########\n - regex: 'Android [34].*; *(A100|A101|A110|A200|A210|A211|A500|A501|A510|A511|A700(?: Lite| 3G|)|A701|B1-A71|A1-\\d{3}|B1-\\d{3}|V360|V370|W500|W500P|W501|W501P|W510|W511|W700|Slider SL101|DA22[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Acer'\n model_replacement: '$1'\n - regex: '; *Acer Iconia Tab ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Acer'\n model_replacement: '$1'\n - regex: '; *(Z1[1235]0|E320[^/]*|S500|S510|Liquid[^;/]*|Iconia A\\d+)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Acer'\n model_replacement: '$1'\n - regex: '; *(Acer |ACER )([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Acer'\n model_replacement: '$2'", " #########\n # Advent\n # @ref: https://en.wikipedia.org/wiki/Advent_Vega\n # @note: VegaBean and VegaComb (names derived from jellybean, honeycomb) are\n # custom ROM builds for Vega\n #########\n - regex: '; *(Advent |)(Vega(?:Bean|Comb|)).*?(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Advent'\n model_replacement: '$2'", " #########\n # Ainol\n # @ref: http://www.ainol.com/plugin.php?identifier=ainol&module=product\n #########\n - regex: '; *(Ainol |)((?:NOVO|[Nn]ovo)[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Ainol'\n model_replacement: '$2'", " #########\n # Airis\n # @ref: http://airis.es/Tienda/Default.aspx?idG=001\n #########\n - regex: '; *AIRIS[ _\\-]?([^/;\\)]+) *(?:;|\\)|Build)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Airis'\n model_replacement: '$1'\n - regex: '; *(OnePAD[^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Airis'\n model_replacement: '$1'", " #########\n # Airpad\n # @ref: ??\n #########\n - regex: '; *Airpad[ \\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Airpad $1'\n brand_replacement: 'Airpad'\n model_replacement: '$1'", " #########\n # Alcatel - TCT\n # @ref: http://www.alcatelonetouch.com/global-en/products/smartphones.html\n #########\n - regex: '; *(one ?touch) (EVO7|T10|T20)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Alcatel One Touch $2'\n brand_replacement: 'Alcatel'\n model_replacement: 'One Touch $2'\n - regex: '; *(?:alcatel[ _]|)(?:(?:one[ _]?touch[ _])|ot[ \\-])([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Alcatel One Touch $1'\n brand_replacement: 'Alcatel'\n model_replacement: 'One Touch $1'\n - regex: '; *(TCL)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'\n # operator specific models\n - regex: '; *(Vodafone Smart II|Optimus_Madrid)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Alcatel $1'\n brand_replacement: 'Alcatel'\n model_replacement: '$1'\n - regex: '; *BASE_Lutea_3(?: Build|\\) AppleWebKit)'\n device_replacement: 'Alcatel One Touch 998'\n brand_replacement: 'Alcatel'\n model_replacement: 'One Touch 998'\n - regex: '; *BASE_Varia(?: Build|\\) AppleWebKit)'\n device_replacement: 'Alcatel One Touch 918D'\n brand_replacement: 'Alcatel'\n model_replacement: 'One Touch 918D'", " #########\n # Allfine\n # @ref: http://www.myallfine.com/Products.asp\n #########\n - regex: '; *((?:FINE|Fine)\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Allfine'\n model_replacement: '$1'", " #########\n # Allview\n # @ref: http://www.allview.ro/produse/droseries/lista-tablete-pc/\n #########\n - regex: '; *(ALLVIEW[ _]?|Allview[ _]?)((?:Speed|SPEED).*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Allview'\n model_replacement: '$2'\n - regex: '; *(ALLVIEW[ _]?|Allview[ _]?|)(AX1_Shine|AX2_Frenzy)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Allview'\n model_replacement: '$2'\n - regex: '; *(ALLVIEW[ _]?|Allview[ _]?)([^;/]*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Allview'\n model_replacement: '$2'", " #########\n # Allwinner\n # @ref: http://www.allwinner.com/\n # @models: A31 (13.3\"),A20,A10,\n #########\n - regex: '; *(A13-MID)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Allwinner'\n model_replacement: '$1'\n - regex: '; *(Allwinner)[ _\\-]?([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Allwinner'\n model_replacement: '$1'", " #########\n # Amaway\n # @ref: http://www.amaway.cn/\n #########\n - regex: '; *(A651|A701B?|A702|A703|A705|A706|A707|A711|A712|A713|A717|A722|A785|A801|A802|A803|A901|A902|A1002|A1003|A1006|A1007|A9701|A9703|Q710|Q80)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Amaway'\n model_replacement: '$1'", " #########\n # Amoi\n # @ref: http://www.amoi.com/en/prd/prd_index.jspx\n #########\n - regex: '; *(?:AMOI|Amoi)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Amoi $1'\n brand_replacement: 'Amoi'\n model_replacement: '$1'\n - regex: '^(?:AMOI|Amoi)[ _]([^;/]+?) Linux'\n device_replacement: 'Amoi $1'\n brand_replacement: 'Amoi'\n model_replacement: '$1'", " #########\n # Aoc\n # @ref: http://latin.aoc.com/media_tablet\n #########\n - regex: '; *(MW(?:0[789]|10)[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Aoc'\n model_replacement: '$1'", " #########\n # Aoson\n # @ref: http://www.luckystar.com.cn/en/mid.aspx?page=1\n # @ref: http://www.luckystar.com.cn/en/mobiletel.aspx?page=1\n # @note: brand owned by luckystar\n #########\n - regex: '; *(G7|M1013|M1015G|M11[CG]?|M-?12[B]?|M15|M19[G]?|M30[ACQ]?|M31[GQ]|M32|M33[GQ]|M36|M37|M38|M701T|M710|M712B|M713|M715G|M716G|M71(?:G|GS|T|)|M72[T]?|M73[T]?|M75[GT]?|M77G|M79T|M7L|M7LN|M81|M810|M81T|M82|M92|M92KS|M92S|M717G|M721|M722G|M723|M725G|M739|M785|M791|M92SK|M93D)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Aoson $1'\n brand_replacement: 'Aoson'\n model_replacement: '$1'\n - regex: '; *Aoson ([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Aoson $1'\n brand_replacement: 'Aoson'\n model_replacement: '$1'", " #########\n # Apanda\n # @ref: http://www.apanda.com.cn/\n #########\n - regex: '; *[Aa]panda[ _\\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Apanda $1'\n brand_replacement: 'Apanda'\n model_replacement: '$1'", " #########\n # Archos\n # @ref: http://www.archos.com/de/products/tablets.html\n # @ref: http://www.archos.com/de/products/smartphones/index.html\n #########\n - regex: '; *(?:ARCHOS|Archos) ?(GAMEPAD.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Archos $1'\n brand_replacement: 'Archos'\n model_replacement: '$1'\n - regex: 'ARCHOS; GOGI; ([^;]+);'\n device_replacement: 'Archos $1'\n brand_replacement: 'Archos'\n model_replacement: '$1'\n - regex: '(?:ARCHOS|Archos)[ _]?(.*?)(?: Build|[;/\\(\\)\\-]|$)'\n device_replacement: 'Archos $1'\n brand_replacement: 'Archos'\n model_replacement: '$1'\n - regex: '; *(AN(?:7|8|9|10|13)[A-Z0-9]{1,4})(?: Build|\\) AppleWebKit)'\n device_replacement: 'Archos $1'\n brand_replacement: 'Archos'\n model_replacement: '$1'\n - regex: '; *(A28|A32|A43|A70(?:BHT|CHT|HB|S|X)|A101(?:B|C|IT)|A7EB|A7EB-WK|101G9|80G9)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Archos $1'\n brand_replacement: 'Archos'\n model_replacement: '$1'", " #########\n # A-rival\n # @ref: http://www.a-rival.de/de/\n #########\n - regex: '; *(PAD-FMD[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Arival'\n model_replacement: '$1'\n - regex: '; *(BioniQ) ?([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Arival'\n model_replacement: '$1 $2'", " #########\n # Arnova\n # @ref: http://arnovatech.com/\n #########\n - regex: '; *(AN\\d[^;/]+|ARCHM\\d+)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Arnova $1'\n brand_replacement: 'Arnova'\n model_replacement: '$1'\n - regex: '; *(?:ARNOVA|Arnova) ?([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Arnova $1'\n brand_replacement: 'Arnova'\n model_replacement: '$1'", " #########\n # Assistant\n # @ref: http://www.assistant.ua\n #########\n - regex: '; *(?:ASSISTANT |)(AP)-?([1789]\\d{2}[A-Z]{0,2}|80104)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Assistant $1-$2'\n brand_replacement: 'Assistant'\n model_replacement: '$1-$2'", " #########\n # Asus\n # @ref: http://www.asus.com/uk/Tablets_Mobile/\n #########\n - regex: '; *(ME17\\d[^;/]*|ME3\\d{2}[^;/]+|K00[A-Z]|Nexus 10|Nexus 7(?: 2013|)|PadFone[^;/]*|Transformer[^;/]*|TF\\d{3}[^;/]*|eeepc)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Asus $1'\n brand_replacement: 'Asus'\n model_replacement: '$1'\n - regex: '; *ASUS[ _]*([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Asus $1'\n brand_replacement: 'Asus'\n model_replacement: '$1'", " #########\n # Garmin-Asus\n #########\n - regex: '; *Garmin-Asus ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Garmin-Asus $1'\n brand_replacement: 'Garmin-Asus'\n model_replacement: '$1'\n - regex: '; *(Garminfone)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Garmin $1'\n brand_replacement: 'Garmin-Asus'\n model_replacement: '$1'", " #########\n # Attab\n # @ref: http://www.theattab.com/\n #########\n - regex: '; (@TAB-[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Attab'\n model_replacement: '$1'", " #########\n # Audiosonic\n # @ref: ??\n # @note: Take care with Docomo T-01 Toshiba\n #########\n - regex: '; *(T-(?:07|[^0]\\d)[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Audiosonic'\n model_replacement: '$1'", " #########\n # Axioo\n # @ref: http://www.axiooworld.com/ww/index.php\n #########\n - regex: '; *(?:Axioo[ _\\-]([^;/]+?)|(picopad)[ _\\-]([^;/]+?))(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Axioo $1$2 $3'\n brand_replacement: 'Axioo'\n model_replacement: '$1$2 $3'", " #########\n # Azend\n # @ref: http://azendcorp.com/index.php/products/portable-electronics\n #########\n - regex: '; *(V(?:100|700|800)[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Azend'\n model_replacement: '$1'", " #########\n # Bak\n # @ref: http://www.bakinternational.com/produtos.php?cat=80\n #########\n - regex: '; *(IBAK\\-[^;/]*)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Bak'\n model_replacement: '$1'", " #########\n # Bedove\n # @ref: http://www.bedove.com/product.html\n # @models: HY6501|HY5001|X12|X21|I5\n #########\n - regex: '; *(HY5001|HY6501|X12|X21|I5)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Bedove $1'\n brand_replacement: 'Bedove'\n model_replacement: '$1'", " #########\n # Benss\n # @ref: http://www.benss.net/\n #########\n - regex: '; *(JC-[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Benss $1'\n brand_replacement: 'Benss'\n model_replacement: '$1'", " #########\n # Blackberry\n # @ref: http://uk.blackberry.com/\n # @note: Android Apps seams to be used here\n #########\n - regex: '; *(BB) ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Blackberry'\n model_replacement: '$2'", " #########\n # Blackbird\n # @ref: http://iblackbird.co.kr\n #########\n - regex: '; *(BlackBird)[ _](I8.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'\n - regex: '; *(BlackBird)[ _](.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " #########\n # Blaupunkt\n # @ref: http://www.blaupunkt.com\n #########\n # Endeavour\n - regex: '; *([0-9]+BP[EM][^;/]*|Endeavour[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Blaupunkt $1'\n brand_replacement: 'Blaupunkt'\n model_replacement: '$1'", " #########\n # Blu\n # @ref: http://bluproducts.com\n #########\n - regex: '; *((?:BLU|Blu)[ _\\-])([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Blu'\n model_replacement: '$2'\n # BMOBILE = operator branded device\n - regex: '; *(?:BMOBILE )?(Blu|BLU|DASH [^;/]+|VIVO 4\\.3|TANK 4\\.5)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Blu'\n model_replacement: '$1'", " #########\n # Blusens\n # @ref: http://www.blusens.com/es/?sg=1&sv=al&roc=1\n #########\n # tablet\n - regex: '; *(TOUCH\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Blusens'\n model_replacement: '$1'", " #########\n # Bmobile\n # @ref: http://bmobile.eu.com/?categoria=smartphones-2\n # @note: Might collide with Maxx as AX is used also there.\n #########\n # smartphone\n - regex: '; *(AX5\\d+)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Bmobile'\n model_replacement: '$1'", " #########\n # bq\n # @ref: http://bqreaders.com\n #########\n - regex: '; *([Bb]q) ([^;/]+?);?(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'bq'\n model_replacement: '$2'\n - regex: '; *(Maxwell [^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'bq'\n model_replacement: '$1'", " #########\n # Braun Phototechnik\n # @ref: http://www.braun-phototechnik.de/en/products/list/~pcat.250/Tablet-PC.html\n #########\n - regex: '; *((?:B-Tab|B-TAB) ?\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Braun'\n model_replacement: '$1'", " #########\n # Broncho\n # @ref: http://www.broncho.cn/\n #########\n - regex: '; *(Broncho) ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " #########\n # Captiva\n # @ref: http://www.captiva-power.de\n #########\n - regex: '; *CAPTIVA ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Captiva $1'\n brand_replacement: 'Captiva'\n model_replacement: '$1'", " #########\n # Casio\n # @ref: http://www.casiogzone.com/\n #########\n - regex: '; *(C771|CAL21|IS11CA)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Casio'\n model_replacement: '$1'", " #########\n # Cat\n # @ref: http://www.cat-sound.com\n #########\n - regex: '; *(?:Cat|CAT) ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Cat $1'\n brand_replacement: 'Cat'\n model_replacement: '$1'\n - regex: '; *(?:Cat)(Nova.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Cat $1'\n brand_replacement: 'Cat'\n model_replacement: '$1'\n - regex: '; *(INM8002KP|ADM8000KP_[AB])(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Cat'\n model_replacement: 'Tablet PHOENIX 8.1J0'", " #########\n # Celkon\n # @ref: http://www.celkonmobiles.com/?_a=products\n # @models: A10, A19Q, A101, A105, A107, A107\\+, A112, A118, A119, A119Q, A15, A19, A20, A200, A220, A225, A22 Race, A27, A58, A59, A60, A62, A63, A64, A66, A67, A69, A75, A77, A79, A8\\+, A83, A85, A86, A87, A89 Ultima, A9\\+, A90, A900, A95, A97i, A98, AR 40, AR 45, AR 50, ML5\n #########\n - regex: '; *(?:[Cc]elkon[ _\\*]|CELKON[ _\\*])([^;/\\)]+) ?(?:Build|;|\\))'\n device_replacement: '$1'\n brand_replacement: 'Celkon'\n model_replacement: '$1'\n - regex: 'Build/(?:[Cc]elkon)+_?([^;/_\\)]+)'\n device_replacement: '$1'\n brand_replacement: 'Celkon'\n model_replacement: '$1'\n - regex: '; *(CT)-?(\\d+)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Celkon'\n model_replacement: '$1$2'\n # smartphones\n - regex: '; *(A19|A19Q|A105|A107[^;/\\)]*) ?(?:Build|;|\\))'\n device_replacement: '$1'\n brand_replacement: 'Celkon'\n model_replacement: '$1'", " #########\n # ChangJia\n # @ref: http://www.cjshowroom.com/eproducts.aspx?classcode=004001001\n # @brief: China manufacturer makes tablets for different small brands\n # (eg. http://www.zeepad.net/index.html)\n #########\n - regex: '; *(TPC[0-9]{4,5})(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'ChangJia'\n model_replacement: '$1'", " #########\n # Cloudfone\n # @ref: http://www.cloudfonemobile.com/\n #########\n - regex: '; *(Cloudfone)[ _](Excite)([^ ][^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2 $3'\n brand_replacement: 'Cloudfone'\n model_replacement: '$1 $2 $3'\n - regex: '; *(Excite|ICE)[ _](\\d+[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Cloudfone $1 $2'\n brand_replacement: 'Cloudfone'\n model_replacement: 'Cloudfone $1 $2'\n - regex: '; *(Cloudfone|CloudPad)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Cloudfone'\n model_replacement: '$1 $2'", " #########\n # Cmx\n # @ref: http://cmx.at/de/\n #########\n - regex: '; *((?:Aquila|Clanga|Rapax)[^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Cmx'\n model_replacement: '$1'", " #########\n # CobyKyros\n # @ref: http://cobykyros.com\n # @note: Be careful with MID\\d{3} from MpMan or Manta\n #########\n - regex: '; *(?:CFW-|Kyros )?(MID[0-9]{4}(?:[ABC]|SR|TV)?)(\\(3G\\)-4G| GB 8K| 3G| 8K| GB)? *(?:Build|[;\\)])'\n device_replacement: 'CobyKyros $1$2'\n brand_replacement: 'CobyKyros'\n model_replacement: '$1$2'", " #########\n # Coolpad\n # @ref: ??\n #########\n - regex: '; *([^;/]*)Coolpad[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Coolpad'\n model_replacement: '$1$2'", " #########\n # Cube\n # @ref: http://www.cube-tablet.com/buy-products.html\n #########\n - regex: '; *(CUBE[ _])?([KU][0-9]+ ?GT.*?|A5300)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1$2'\n brand_replacement: 'Cube'\n model_replacement: '$2'", " #########\n # Cubot\n # @ref: http://www.cubotmall.com/\n #########\n - regex: '; *CUBOT ([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Cubot'\n model_replacement: '$1'\n - regex: '; *(BOBBY)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Cubot'\n model_replacement: '$1'", " #########\n # Danew\n # @ref: http://www.danew.com/produits-tablette.php\n #########\n - regex: '; *(Dslide [^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Danew'\n model_replacement: '$1'", " #########\n # Dell\n # @ref: http://www.dell.com\n # @ref: http://www.softbank.jp/mobile/support/product/101dl/\n # @ref: http://www.softbank.jp/mobile/support/product/001dl/\n # @ref: http://developer.emnet.ne.jp/android.html\n # @ref: http://www.dell.com/in/p/mobile-xcd28/pd\n # @ref: http://www.dell.com/in/p/mobile-xcd35/pd\n #########\n - regex: '; *(XCD)[ _]?(28|35)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1$2'\n brand_replacement: 'Dell'\n model_replacement: '$1$2'\n - regex: '; *(001DL)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: 'Streak'\n - regex: '; *(?:Dell|DELL) (Streak)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: 'Streak'\n - regex: '; *(101DL|GS01|Streak Pro[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: 'Streak Pro'\n - regex: '; *([Ss]treak ?7)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: 'Streak 7'\n - regex: '; *(Mini-3iX)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: '$1'\n - regex: '; *(?:Dell|DELL)[ _](Aero|Venue|Thunder|Mini.*?|Streak[ _]Pro)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: '$1'\n - regex: '; *Dell[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: '$1'\n - regex: '; *Dell ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: '$1'", " #########\n # Denver\n # @ref: http://www.denver-electronics.com/tablets1/\n #########\n - regex: '; *(TA[CD]-\\d+[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Denver'\n model_replacement: '$1'", " #########\n # Dex\n # @ref: http://dex.ua/\n #########\n - regex: '; *(iP[789]\\d{2}(?:-3G)?|IP10\\d{2}(?:-8GB)?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Dex'\n model_replacement: '$1'", " #########\n # DNS AirTab\n # @ref: http://www.dns-shop.ru/\n #########\n - regex: '; *(AirTab)[ _\\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'DNS'\n model_replacement: '$1 $2'", " #########\n # Docomo (Operator Branded Device)\n # @ref: http://www.ipentec.com/document/document.aspx?page=android-useragent\n #########\n - regex: '; *(F\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Fujitsu'\n model_replacement: '$1'\n - regex: '; *(HT-03A)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: 'Magic'\n - regex: '; *(HT\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: '$1'\n - regex: '; *(L\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'LG'\n model_replacement: '$1'\n - regex: '; *(N\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Nec'\n model_replacement: '$1'\n - regex: '; *(P\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Panasonic'\n model_replacement: '$1'\n - regex: '; *(SC\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n - regex: '; *(SH\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Sharp'\n model_replacement: '$1'\n - regex: '; *(SO\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'SonyEricsson'\n model_replacement: '$1'\n - regex: '; *(T\\-0[12][^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Toshiba'\n model_replacement: '$1'", " #########\n # DOOV\n # @ref: http://www.doov.com.cn/\n #########\n - regex: '; *(DOOV)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'DOOV'\n model_replacement: '$2'", " #########\n # Enot\n # @ref: http://www.enot.ua/\n #########\n - regex: '; *(Enot|ENOT)[ -]?([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Enot'\n model_replacement: '$2'", " #########\n # Evercoss\n # @ref: http://evercoss.com/android/\n #########\n - regex: '; *[^;/]+ Build/(?:CROSS|Cross)+[ _\\-]([^\\)]+)'\n device_replacement: 'CROSS $1'\n brand_replacement: 'Evercoss'\n model_replacement: 'Cross $1'\n - regex: '; *(CROSS|Cross)[ _\\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Evercoss'\n model_replacement: 'Cross $2'", " #########\n # Explay\n # @ref: http://explay.ru/\n #########\n - regex: '; *Explay[_ ](.+?)(?:[\\)]| Build)'\n device_replacement: '$1'\n brand_replacement: 'Explay'\n model_replacement: '$1'", " #########\n # Fly\n # @ref: http://www.fly-phone.com/\n #########\n - regex: '; *(IQ.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Fly'\n model_replacement: '$1'\n - regex: '; *(Fly|FLY)[ _](IQ[^;]+?|F[34]\\d+[^;]*?);?(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Fly'\n model_replacement: '$2'", " #########\n # Fujitsu\n # @ref: http://www.fujitsu.com/global/\n #########\n - regex: '; *(M532|Q572|FJL21)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Fujitsu'\n model_replacement: '$1'", " #########\n # Galapad\n # @ref: http://www.galapad.net/product.html\n #########\n - regex: '; *(G1)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Galapad'\n model_replacement: '$1'", " #########\n # Geeksphone\n # @ref: http://www.geeksphone.com/\n #########\n - regex: '; *(Geeksphone) ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " #########\n # Gfive\n # @ref: http://www.gfivemobile.com/en\n #########\n #- regex: '; *(G\\'?FIVE) ([^;/]+) Build' # there is a problem with python yaml parser here\n - regex: '; *(G[^F]?FIVE) ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Gfive'\n model_replacement: '$2'", " #########\n # Gionee\n # @ref: http://www.gionee.com/\n #########\n - regex: '; *(Gionee)[ _\\-]([^;/]+?)(?:/[^;/]+|)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'Gionee'\n model_replacement: '$2'\n - regex: '; *(GN\\d+[A-Z]?|INFINITY_PASSION|Ctrl_V1)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Gionee $1'\n brand_replacement: 'Gionee'\n model_replacement: '$1'\n - regex: '; *(E3) Build/JOP40D'\n device_replacement: 'Gionee $1'\n brand_replacement: 'Gionee'\n model_replacement: '$1'\n - regex: '\\sGIONEE[-\\s_](\\w*)'\n regex_flag: 'i'\n device_replacement: 'Gionee $1'\n brand_replacement: 'Gionee'\n model_replacement: '$1'", " #########\n # GoClever\n # @ref: http://www.goclever.com\n #########\n - regex: '; *((?:FONE|QUANTUM|INSIGNIA) \\d+[^;/]*|PLAYTAB)(?: Build|\\) AppleWebKit)'\n device_replacement: 'GoClever $1'\n brand_replacement: 'GoClever'\n model_replacement: '$1'\n - regex: '; *GOCLEVER ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'GoClever $1'\n brand_replacement: 'GoClever'\n model_replacement: '$1'", " #########\n # Google\n # @ref: http://www.google.de/glass/start/\n #########\n - regex: '; *(Glass \\d+)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Google'\n model_replacement: '$1'\n - regex: '; *(Pixel.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Google'\n model_replacement: '$1'", " #########\n # Gigabyte\n # @ref: http://gsmart.gigabytecm.com/en/\n #########\n - regex: '; *(GSmart)[ -]([^/]+)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Gigabyte'\n model_replacement: '$1 $2'", " #########\n # Freescale development boards\n # @ref: http://www.freescale.com/webapp/sps/site/prod_summary.jsp?code=IMX53QSB\n #########\n - regex: '; *(imx5[13]_[^/]+)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Freescale $1'\n brand_replacement: 'Freescale'\n model_replacement: '$1'", " #########\n # Haier\n # @ref: http://www.haier.com/\n # @ref: http://www.haier.com/de/produkte/tablet/\n #########\n - regex: '; *Haier[ _\\-]([^/]+)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Haier $1'\n brand_replacement: 'Haier'\n model_replacement: '$1'\n - regex: '; *(PAD1016)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Haipad $1'\n brand_replacement: 'Haipad'\n model_replacement: '$1'", " #########\n # Haipad\n # @ref: http://www.haipad.net/\n # @models: V7P|M7SM7S|M9XM9X|M7XM7X|M9|M8|M7-M|M1002|M7|M701\n #########\n - regex: '; *(M701|M7|M8|M9)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Haipad $1'\n brand_replacement: 'Haipad'\n model_replacement: '$1'", " #########\n # Hannspree\n # @ref: http://www.hannspree.eu/\n # @models: SN10T1|SN10T2|SN70T31B|SN70T32W\n #########\n - regex: '; *(SN\\d+T[^;\\)/]*)(?: Build|[;\\)])'\n device_replacement: 'Hannspree $1'\n brand_replacement: 'Hannspree'\n model_replacement: '$1'", " #########\n # HCLme\n # @ref: http://www.hclmetablet.com/india/\n #########\n - regex: 'Build/HCL ME Tablet ([^;\\)]+)[\\);]'\n device_replacement: 'HCLme $1'\n brand_replacement: 'HCLme'\n model_replacement: '$1'\n - regex: '; *([^;\\/]+) Build/HCL'\n device_replacement: 'HCLme $1'\n brand_replacement: 'HCLme'\n model_replacement: '$1'", " #########\n # Hena\n # @ref: http://www.henadigital.com/en/product/index.asp?id=6\n #########\n - regex: '; *(MID-?\\d{4}C[EM])(?: Build|\\) AppleWebKit)'\n device_replacement: 'Hena $1'\n brand_replacement: 'Hena'\n model_replacement: '$1'", " #########\n # Hisense\n # @ref: http://www.hisense.com/\n #########\n - regex: '; *(EG\\d{2,}|HS-[^;/]+|MIRA[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Hisense $1'\n brand_replacement: 'Hisense'\n model_replacement: '$1'\n - regex: '; *(andromax[^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Hisense $1'\n brand_replacement: 'Hisense'\n model_replacement: '$1'", " #########\n # hitech\n # @ref: http://www.hitech-mobiles.com/\n #########\n - regex: '; *(?:AMAZE[ _](S\\d+)|(S\\d+)[ _]AMAZE)(?: Build|\\) AppleWebKit)'\n device_replacement: 'AMAZE $1$2'\n brand_replacement: 'hitech'\n model_replacement: 'AMAZE $1$2'", " #########\n # HP\n # @ref: http://www.hp.com/\n #########\n - regex: '; *(PlayBook)(?: Build|\\) AppleWebKit)'\n device_replacement: 'HP $1'\n brand_replacement: 'HP'\n model_replacement: '$1'\n - regex: '; *HP ([^/]+)(?: Build|\\) AppleWebKit)'\n device_replacement: 'HP $1'\n brand_replacement: 'HP'\n model_replacement: '$1'\n - regex: '; *([^/]+_tenderloin)(?: Build|\\) AppleWebKit)'\n device_replacement: 'HP TouchPad'\n brand_replacement: 'HP'\n model_replacement: 'TouchPad'", " #########\n # Huawei\n # @ref: http://www.huaweidevice.com\n # @note: Needs to be before HTC due to Desire HD Build on U8815\n #########\n - regex: '; *(HUAWEI |Huawei-|)([UY][^;/]+) Build/(?:Huawei|HUAWEI)([UY][^\\);]+)\\)'\n device_replacement: '$1$2'\n brand_replacement: 'Huawei'\n model_replacement: '$2'", " - regex: '; *([^;/]+) Build[/ ]Huawei(MT1-U06|[A-Z]+\\d+[^\\);]+)[^\\);]*\\)'", " device_replacement: '$1'\n brand_replacement: 'Huawei'\n model_replacement: '$2'\n - regex: '; *(S7|M860) Build'\n device_replacement: '$1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'\n - regex: '; *((?:HUAWEI|Huawei)[ \\-]?)(MediaPad) Build'\n device_replacement: '$1$2'\n brand_replacement: 'Huawei'\n model_replacement: '$2'\n - regex: '; *((?:HUAWEI[ _]?|Huawei[ _]|)Ascend[ _])([^;/]+) Build'\n device_replacement: '$1$2'\n brand_replacement: 'Huawei'\n model_replacement: '$2'\n - regex: '; *((?:HUAWEI|Huawei)[ _\\-]?)((?:G700-|MT-)[^;/]+) Build'\n device_replacement: '$1$2'\n brand_replacement: 'Huawei'\n model_replacement: '$2'\n - regex: '; *((?:HUAWEI|Huawei)[ _\\-]?)([^;/]+) Build'\n device_replacement: '$1$2'\n brand_replacement: 'Huawei'\n model_replacement: '$2'\n - regex: '; *(MediaPad[^;]+|SpringBoard) Build/Huawei'\n device_replacement: '$1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'\n - regex: '; *([^;]+) Build/(?:Huawei|HUAWEI)'\n device_replacement: '$1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'\n - regex: '; *([Uu])([89]\\d{3}) Build'\n device_replacement: '$1$2'\n brand_replacement: 'Huawei'\n model_replacement: 'U$2'\n - regex: '; *(?:Ideos |IDEOS )(S7) Build'\n device_replacement: 'Huawei Ideos$1'\n brand_replacement: 'Huawei'\n model_replacement: 'Ideos$1'\n - regex: '; *(?:Ideos |IDEOS )([^;/]+\\s*|\\s*)Build'\n device_replacement: 'Huawei Ideos$1'\n brand_replacement: 'Huawei'\n model_replacement: 'Ideos$1'\n - regex: '; *(Orange Daytona|Pulse|Pulse Mini|Vodafone 858|C8500|C8600|C8650|C8660|Nexus 6P|ATH-.+?) Build[/ ]'\n device_replacement: 'Huawei $1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'\n - regex: '; *((?:[A-Z]{3})\\-L[A-Za0-9]{2})[\\)]'\n device_replacement: 'Huawei $1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'", " #########\n # HTC\n # @ref: http://www.htc.com/www/products/\n # @ref: http://en.wikipedia.org/wiki/List_of_HTC_phones\n #########", " - regex: '; *HTC[ _]([^;]+); Windows Phone'\n device_replacement: 'HTC $1'\n brand_replacement: 'HTC'\n model_replacement: '$1'", " # Android HTC with Version Number matcher\n # ; HTC_0P3Z11/1.12.161.3 Build\n # ;HTC_A3335 V2.38.841.1 Build\n - regex: '; *(?:HTC[ _/])+([^ _/]+)(?:[/\\\\]1\\.0 | V|/| +)\\d+\\.\\d[\\d\\.]*(?: *Build|\\))'\n device_replacement: 'HTC $1'\n brand_replacement: 'HTC'\n model_replacement: '$1'\n - regex: '; *(?:HTC[ _/])+([^ _/]+)(?:[ _/]([^ _/]+)|)(?:[/\\\\]1\\.0 | V|/| +)\\d+\\.\\d[\\d\\.]*(?: *Build|\\))'\n device_replacement: 'HTC $1 $2'\n brand_replacement: 'HTC'\n model_replacement: '$1 $2'\n - regex: '; *(?:HTC[ _/])+([^ _/]+)(?:[ _/]([^ _/]+)(?:[ _/]([^ _/]+)|)|)(?:[/\\\\]1\\.0 | V|/| +)\\d+\\.\\d[\\d\\.]*(?: *Build|\\))'\n device_replacement: 'HTC $1 $2 $3'\n brand_replacement: 'HTC'\n model_replacement: '$1 $2 $3'\n - regex: '; *(?:HTC[ _/])+([^ _/]+)(?:[ _/]([^ _/]+)(?:[ _/]([^ _/]+)(?:[ _/]([^ _/]+)|)|)|)(?:[/\\\\]1\\.0 | V|/| +)\\d+\\.\\d[\\d\\.]*(?: *Build|\\))'\n device_replacement: 'HTC $1 $2 $3 $4'\n brand_replacement: 'HTC'\n model_replacement: '$1 $2 $3 $4'", " # Android HTC without Version Number matcher\n - regex: '; *(?:(?:HTC|htc)(?:_blocked|)[ _/])+([^ _/;]+)(?: *Build|[;\\)]| - )'\n device_replacement: 'HTC $1'\n brand_replacement: 'HTC'\n model_replacement: '$1'\n - regex: '; *(?:(?:HTC|htc)(?:_blocked|)[ _/])+([^ _/]+)(?:[ _/]([^ _/;\\)]+)|)(?: *Build|[;\\)]| - )'\n device_replacement: 'HTC $1 $2'\n brand_replacement: 'HTC'\n model_replacement: '$1 $2'\n - regex: '; *(?:(?:HTC|htc)(?:_blocked|)[ _/])+([^ _/]+)(?:[ _/]([^ _/]+)(?:[ _/]([^ _/;\\)]+)|)|)(?: *Build|[;\\)]| - )'\n device_replacement: 'HTC $1 $2 $3'\n brand_replacement: 'HTC'\n model_replacement: '$1 $2 $3'\n - regex: '; *(?:(?:HTC|htc)(?:_blocked|)[ _/])+([^ _/]+)(?:[ _/]([^ _/]+)(?:[ _/]([^ _/]+)(?:[ _/]([^ /;]+)|)|)|)(?: *Build|[;\\)]| - )'\n device_replacement: 'HTC $1 $2 $3 $4'\n brand_replacement: 'HTC'\n model_replacement: '$1 $2 $3 $4'", " # HTC Streaming Player\n - regex: 'HTC Streaming Player [^\\/]*/[^\\/]*/ htc_([^/]+) /'\n device_replacement: 'HTC $1'\n brand_replacement: 'HTC'\n model_replacement: '$1'\n # general matcher for anything else\n - regex: '(?:[;,] *|^)(?:htccn_chs-|)HTC[ _-]?([^;]+?)(?: *Build|clay|Android|-?Mozilla| Opera| Profile| UNTRUSTED|[;/\\(\\)]|$)'\n regex_flag: 'i'\n device_replacement: 'HTC $1'\n brand_replacement: 'HTC'\n model_replacement: '$1'\n # Android matchers without HTC\n - regex: '; *(A6277|ADR6200|ADR6300|ADR6350|ADR6400[A-Z]*|ADR6425[A-Z]*|APX515CKT|ARIA|Desire[^_ ]*|Dream|EndeavorU|Eris|Evo|Flyer|HD2|Hero|HERO200|Hero CDMA|HTL21|Incredible|Inspire[A-Z0-9]*|Legend|Liberty|Nexus ?(?:One|HD2)|One|One S C2|One[ _]?(?:S|V|X\\+?)\\w*|PC36100|PG06100|PG86100|S31HT|Sensation|Wildfire)(?: Build|[/;\\(\\)])'\n regex_flag: 'i'\n device_replacement: 'HTC $1'\n brand_replacement: 'HTC'\n model_replacement: '$1'\n - regex: '; *(ADR6200|ADR6400L|ADR6425LVW|Amaze|DesireS?|EndeavorU|Eris|EVO|Evo\\d[A-Z]+|HD2|IncredibleS?|Inspire[A-Z0-9]*|Inspire[A-Z0-9]*|Sensation[A-Z0-9]*|Wildfire)[ _-](.+?)(?:[/;\\)]|Build|MIUI|1\\.0)'\n regex_flag: 'i'\n device_replacement: 'HTC $1 $2'\n brand_replacement: 'HTC'\n model_replacement: '$1 $2'", " #########\n # Hyundai\n # @ref: http://www.hyundaitechnologies.com\n #########\n - regex: '; *HYUNDAI (T\\d[^/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Hyundai $1'\n brand_replacement: 'Hyundai'\n model_replacement: '$1'\n - regex: '; *HYUNDAI ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Hyundai $1'\n brand_replacement: 'Hyundai'\n model_replacement: '$1'\n # X900? http://www.amazon.com/Hyundai-X900-Retina-Android-Bluetooth/dp/B00AO07H3O\n - regex: '; *(X700|Hold X|MB-6900)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Hyundai $1'\n brand_replacement: 'Hyundai'\n model_replacement: '$1'", " #########\n # iBall\n # @ref: http://www.iball.co.in/Category/Mobiles/22\n #########\n - regex: '; *(?:iBall[ _\\-]|)(Andi)[ _]?(\\d[^;/]*)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'iBall'\n model_replacement: '$1 $2'\n - regex: '; *(IBall)(?:[ _]([^;/]+?)|)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'iBall'\n model_replacement: '$2'", " #########\n # IconBIT\n # @ref: http://www.iconbit.com/catalog/tablets/\n #########\n - regex: '; *(NT-\\d+[^ ;/]*|Net[Tt]AB [^;/]+|Mercury [A-Z]+|iconBIT)(?: S/N:[^;/]+|)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'IconBIT'\n model_replacement: '$1'", " #########\n # IMO\n # @ref: http://www.ponselimo.com/\n #########\n - regex: '; *(IMO)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'IMO'\n model_replacement: '$2'", " #########\n # i-mobile\n # @ref: http://www.i-mobilephone.com/\n #########\n - regex: '; *i-?mobile[ _]([^/]+)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'i-mobile $1'\n brand_replacement: 'imobile'\n model_replacement: '$1'\n - regex: '; *(i-(?:style|note)[^/]*)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'i-mobile $1'\n brand_replacement: 'imobile'\n model_replacement: '$1'", " #########\n # Impression\n # @ref: http://impression.ua/planshetnye-kompyutery\n #########\n - regex: '; *(ImPAD) ?(\\d+(?:.)*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Impression'\n model_replacement: '$1 $2'", " #########\n # Infinix\n # @ref: http://www.infinixmobility.com/index.html\n #########\n - regex: '; *(Infinix)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Infinix'\n model_replacement: '$2'", " #########\n # Informer\n # @ref: ??\n #########\n - regex: '; *(Informer)[ \\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Informer'\n model_replacement: '$2'", " #########\n # Intenso\n # @ref: http://www.intenso.de\n # @models: 7\":TAB 714,TAB 724;8\":TAB 814,TAB 824;10\":TAB 1004\n #########\n - regex: '; *(TAB) ?([78][12]4)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Intenso $1'\n brand_replacement: 'Intenso'\n model_replacement: '$1 $2'", " #########\n # Intex\n # @ref: http://intexmobile.in/index.aspx\n # @note: Zync also offers a \"Cloud Z5\" device\n #########\n # smartphones\n - regex: '; *(?:Intex[ _]|)(AQUA|Aqua)([ _\\.\\-])([^;/]+?) *(?:Build|;)'\n device_replacement: '$1$2$3'\n brand_replacement: 'Intex'\n model_replacement: '$1 $3'\n # matches \"INTEX CLOUD X1\"\n - regex: '; *(?:INTEX|Intex)(?:[_ ]([^\\ _;/]+))(?:[_ ]([^\\ _;/]+)|) *(?:Build|;)'\n device_replacement: '$1 $2'\n brand_replacement: 'Intex'\n model_replacement: '$1 $2'\n # tablets\n - regex: '; *([iI]Buddy)[ _]?(Connect)(?:_|\\?_| |)([^;/]*) *(?:Build|;)'\n device_replacement: '$1 $2 $3'\n brand_replacement: 'Intex'\n model_replacement: 'iBuddy $2 $3'\n - regex: '; *(I-Buddy)[ _]([^;/]+?) *(?:Build|;)'\n device_replacement: '$1 $2'\n brand_replacement: 'Intex'\n model_replacement: 'iBuddy $2'", " #########\n # iOCEAN\n # @ref: http://www.iocean.cc/\n #########\n - regex: '; *(iOCEAN) ([^/]+)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'iOCEAN'\n model_replacement: '$2'", " #########\n # i.onik\n # @ref: http://www.i-onik.de/\n #########\n - regex: '; *(TP\\d+(?:\\.\\d+|)\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'ionik $1'\n brand_replacement: 'ionik'\n model_replacement: '$1'", " #########\n # IRU.ru\n # @ref: http://www.iru.ru/catalog/soho/planetable/\n #########\n - regex: '; *(M702pro)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Iru'\n model_replacement: '$1'", " #########\n # Ivio\n # @ref: http://www.ivio.com/mobile.php\n # @models: DG80,DG20,DE38,DE88,MD70\n #########\n - regex: '; *(DE88Plus|MD70)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Ivio'\n model_replacement: '$1'\n - regex: '; *IVIO[_\\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Ivio'\n model_replacement: '$1'", " #########\n # Jaytech\n # @ref: http://www.jay-tech.de/jaytech/servlet/frontend/\n #########\n - regex: '; *(TPC-\\d+|JAY-TECH)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Jaytech'\n model_replacement: '$1'", " #########\n # Jiayu\n # @ref: http://www.ejiayu.com/en/Product.html\n #########\n - regex: '; *(JY-[^;/]+|G[234]S?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Jiayu'\n model_replacement: '$1'", " #########\n # JXD\n # @ref: http://www.jxd.hk/\n #########\n - regex: '; *(JXD)[ _\\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'JXD'\n model_replacement: '$2'", " #########\n # Karbonn\n # @ref: http://www.karbonnmobiles.com/products_tablet.php\n #########\n - regex: '; *Karbonn[ _]?([^;/]+) *(?:Build|;)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Karbonn'\n model_replacement: '$1'\n - regex: '; *([^;]+) Build/Karbonn'\n device_replacement: '$1'\n brand_replacement: 'Karbonn'\n model_replacement: '$1'\n - regex: '; *(A11|A39|A37|A34|ST8|ST10|ST7|Smart Tab3|Smart Tab2|Titanium S\\d) +Build'\n device_replacement: '$1'\n brand_replacement: 'Karbonn'\n model_replacement: '$1'", " #########\n # KDDI (Operator Branded Device)\n # @ref: http://www.ipentec.com/document/document.aspx?page=android-useragent\n #########\n - regex: '; *(IS01|IS03|IS05|IS\\d{2}SH)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Sharp'\n model_replacement: '$1'\n - regex: '; *(IS04)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Regza'\n model_replacement: '$1'\n - regex: '; *(IS06|IS\\d{2}PT)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Pantech'\n model_replacement: '$1'\n - regex: '; *(IS11S)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'SonyEricsson'\n model_replacement: 'Xperia Acro'\n - regex: '; *(IS11CA)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Casio'\n model_replacement: 'GzOne $1'\n - regex: '; *(IS11LG)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'LG'\n model_replacement: 'Optimus X'\n - regex: '; *(IS11N)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Medias'\n model_replacement: '$1'\n - regex: '; *(IS11PT)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Pantech'\n model_replacement: 'MIRACH'\n - regex: '; *(IS12F)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Fujitsu'\n model_replacement: 'Arrows ES'\n # @ref: https://ja.wikipedia.org/wiki/IS12M\n - regex: '; *(IS12M)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Motorola'\n model_replacement: 'XT909'\n - regex: '; *(IS12S)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'SonyEricsson'\n model_replacement: 'Xperia Acro HD'\n - regex: '; *(ISW11F)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Fujitsu'\n model_replacement: 'Arrowz Z'\n - regex: '; *(ISW11HT)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: 'EVO'\n - regex: '; *(ISW11K)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Kyocera'\n model_replacement: 'DIGNO'\n - regex: '; *(ISW11M)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Motorola'\n model_replacement: 'Photon'\n - regex: '; *(ISW11SC)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Samsung'\n model_replacement: 'GALAXY S II WiMAX'\n - regex: '; *(ISW12HT)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: 'EVO 3D'\n - regex: '; *(ISW13HT)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: 'J'\n - regex: '; *(ISW?[0-9]{2}[A-Z]{0,2})(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'KDDI'\n model_replacement: '$1'\n - regex: '; *(INFOBAR [^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'KDDI'\n model_replacement: '$1'", " #########\n # Kingcom\n # @ref: http://www.e-kingcom.com\n #########\n - regex: '; *(JOYPAD|Joypad)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Kingcom'\n model_replacement: '$1 $2'", " #########\n # Kobo\n # @ref: https://en.wikipedia.org/wiki/Kobo_Inc.\n # @ref: http://www.kobo.com/devices#tablets\n #########\n - regex: '; *(Vox|VOX|Arc|K080)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Kobo'\n model_replacement: '$1'\n - regex: '\\b(Kobo Touch)\\b'\n device_replacement: '$1'\n brand_replacement: 'Kobo'\n model_replacement: '$1'", " #########\n # K-Touch\n # @ref: ??\n #########\n - regex: '; *(K-Touch)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'Ktouch'\n model_replacement: '$2'", " #########\n # KT Tech\n # @ref: http://www.kttech.co.kr\n #########\n - regex: '; *((?:EV|KM)-S\\d+[A-Z]?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'KTtech'\n model_replacement: '$1'", " #########\n # Kyocera\n # @ref: http://www.android.com/devices/?country=all&m=kyocera\n #########\n - regex: '; *(Zio|Hydro|Torque|Event|EVENT|Echo|Milano|Rise|URBANO PROGRESSO|WX04K|WX06K|WX10K|KYL21|101K|C5[12]\\d{2})(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Kyocera'\n model_replacement: '$1'", " #########\n # Lava\n # @ref: http://www.lavamobiles.com/\n #########\n - regex: '; *(?:LAVA[ _]|)IRIS[ _\\-]?([^/;\\)]+) *(?:;|\\)|Build)'\n regex_flag: 'i'\n device_replacement: 'Iris $1'\n brand_replacement: 'Lava'\n model_replacement: 'Iris $1'\n - regex: '; *LAVA[ _]([^;/]+) Build'\n device_replacement: '$1'\n brand_replacement: 'Lava'\n model_replacement: '$1'", " #########\n # Lemon\n # @ref: http://www.lemonmobiles.com/products.php?type=1\n #########\n - regex: '; *(?:(Aspire A1)|(?:LEMON|Lemon)[ _]([^;/]+))_?(?: Build|\\) AppleWebKit)'\n device_replacement: 'Lemon $1$2'\n brand_replacement: 'Lemon'\n model_replacement: '$1$2'", " #########\n # Lenco\n # @ref: http://www.lenco.com/c/tablets/\n #########\n - regex: '; *(TAB-1012)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Lenco $1'\n brand_replacement: 'Lenco'\n model_replacement: '$1'\n - regex: '; Lenco ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Lenco $1'\n brand_replacement: 'Lenco'\n model_replacement: '$1'", " #########\n # Lenovo\n # @ref: http://support.lenovo.com/en_GB/downloads/default.page?#\n #########\n - regex: '; *(A1_07|A2107A-H|S2005A-H|S1-37AH0) Build'\n device_replacement: '$1'\n brand_replacement: 'Lenovo'\n model_replacement: '$1'\n - regex: '; *(Idea[Tp]ab)[ _]([^;/]+);? Build'\n device_replacement: 'Lenovo $1 $2'\n brand_replacement: 'Lenovo'\n model_replacement: '$1 $2'\n - regex: '; *(Idea(?:Tab|pad)) ?([^;/]+) Build'\n device_replacement: 'Lenovo $1 $2'\n brand_replacement: 'Lenovo'\n model_replacement: '$1 $2'\n - regex: '; *(ThinkPad) ?(Tablet) Build/'\n device_replacement: 'Lenovo $1 $2'\n brand_replacement: 'Lenovo'\n model_replacement: '$1 $2'\n - regex: '; *(?:LNV-|)(?:=?[Ll]enovo[ _\\-]?|LENOVO[ _])(.+?)(?:Build|[;/\\)])'\n device_replacement: 'Lenovo $1'\n brand_replacement: 'Lenovo'\n model_replacement: '$1'\n - regex: '[;,] (?:Vodafone |)(SmartTab) ?(II) ?(\\d+) Build/'\n device_replacement: 'Lenovo $1 $2 $3'\n brand_replacement: 'Lenovo'\n model_replacement: '$1 $2 $3'\n - regex: '; *(?:Ideapad |)K1 Build/'\n device_replacement: 'Lenovo Ideapad K1'\n brand_replacement: 'Lenovo'\n model_replacement: 'Ideapad K1'\n - regex: '; *(3GC101|3GW10[01]|A390) Build/'\n device_replacement: '$1'\n brand_replacement: 'Lenovo'\n model_replacement: '$1'\n - regex: '\\b(?:Lenovo|LENOVO)+[ _\\-]?([^,;:/ ]+)'\n device_replacement: 'Lenovo $1'\n brand_replacement: 'Lenovo'\n model_replacement: '$1'", " #########\n # Lexibook\n # @ref: http://www.lexibook.com/fr\n #########\n - regex: '; *(MFC\\d+)[A-Z]{2}([^;,/]*),?(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Lexibook'\n model_replacement: '$1$2'", " #########\n # LG\n # @ref: http://www.lg.com/uk/mobile\n #########\n - regex: '; *(E[34][0-9]{2}|LS[6-8][0-9]{2}|VS[6-9][0-9]+[^;/]+|Nexus 4|Nexus 5X?|GT540f?|Optimus (?:2X|G|4X HD)|OptimusX4HD) *(?:Build|;)'\n device_replacement: '$1'\n brand_replacement: 'LG'\n model_replacement: '$1'\n - regex: '[;:] *(L-\\d+[A-Z]|LGL\\d+[A-Z]?)(?:/V\\d+|) *(?:Build|[;\\)])'\n device_replacement: '$1'\n brand_replacement: 'LG'\n model_replacement: '$1'\n - regex: '; *(LG-)([A-Z]{1,2}\\d{2,}[^,;/\\)\\(]*?)(?:Build| V\\d+|[,;/\\)\\(]|$)'\n device_replacement: '$1$2'\n brand_replacement: 'LG'\n model_replacement: '$2'\n - regex: '; *(LG[ \\-]|LG)([^;/]+)[;/]? Build'\n device_replacement: '$1$2'\n brand_replacement: 'LG'\n model_replacement: '$2'\n - regex: '^(LG)-([^;/]+)/ Mozilla/.*; Android'\n device_replacement: '$1 $2'\n brand_replacement: 'LG'\n model_replacement: '$2'\n - regex: '(Web0S); Linux/(SmartTV)'\n device_replacement: 'LG $1 $2'\n brand_replacement: 'LG'\n model_replacement: '$1 $2'", " #########\n # Malata\n # @ref: http://www.malata.com/en/products.aspx?classid=680\n #########\n - regex: '; *((?:SMB|smb)[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Malata'\n model_replacement: '$1'\n - regex: '; *(?:Malata|MALATA) ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Malata'\n model_replacement: '$1'", " #########\n # Manta\n # @ref: http://www.manta.com.pl/en\n #########\n - regex: '; *(MS[45][0-9]{3}|MID0[568][NS]?|MID[1-9]|MID[78]0[1-9]|MID970[1-9]|MID100[1-9])(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Manta'\n model_replacement: '$1'", " #########\n # Match\n # @ref: http://www.match.net.cn/products.asp\n #########\n - regex: '; *(M1052|M806|M9000|M9100|M9701|MID100|MID120|MID125|MID130|MID135|MID140|MID701|MID710|MID713|MID727|MID728|MID731|MID732|MID733|MID735|MID736|MID737|MID760|MID800|MID810|MID820|MID830|MID833|MID835|MID860|MID900|MID930|MID933|MID960|MID980)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Match'\n model_replacement: '$1'", " #########\n # Maxx\n # @ref: http://www.maxxmobile.in/\n # @models: Maxx MSD7-Play, Maxx MX245+ Trance, Maxx AX8 Race, Maxx MSD7 3G- AX50, Maxx Genx Droid 7 - AX40, Maxx AX5 Duo,\n # Maxx AX3 Duo, Maxx AX3, Maxx AX8 Note II (Note 2), Maxx AX8 Note I, Maxx AX8, Maxx AX5 Plus, Maxx MSD7 Smarty,\n # Maxx AX9Z Race,\n # Maxx MT150, Maxx MQ601, Maxx M2020, Maxx Sleek MX463neo, Maxx MX525, Maxx MX192-Tune, Maxx Genx Droid 7 AX353,\n # @note: Need more User-Agents!!!\n #########\n - regex: '; *(GenxDroid7|MSD7.*?|AX\\d.*?|Tab 701|Tab 722)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Maxx $1'\n brand_replacement: 'Maxx'\n model_replacement: '$1'", " #########\n # Mediacom\n # @ref: http://www.mediacomeurope.it/\n #########\n - regex: '; *(M-PP[^;/]+|PhonePad ?\\d{2,}[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Mediacom $1'\n brand_replacement: 'Mediacom'\n model_replacement: '$1'\n - regex: '; *(M-MP[^;/]+|SmartPad ?\\d{2,}[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Mediacom $1'\n brand_replacement: 'Mediacom'\n model_replacement: '$1'", " #########\n # Medion\n # @ref: http://www.medion.com/en/\n #########\n - regex: '; *(?:MD_|)LIFETAB[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Medion Lifetab $1'\n brand_replacement: 'Medion'\n model_replacement: 'Lifetab $1'\n - regex: '; *MEDION ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Medion $1'\n brand_replacement: 'Medion'\n model_replacement: '$1'", " #########\n # Meizu\n # @ref: http://www.meizu.com\n #########\n - regex: '; *(M030|M031|M035|M040|M065|m9)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Meizu $1'\n brand_replacement: 'Meizu'\n model_replacement: '$1'\n - regex: '; *(?:meizu_|MEIZU )(.+?) *(?:Build|[;\\)])'\n device_replacement: 'Meizu $1'\n brand_replacement: 'Meizu'\n model_replacement: '$1'", " #########\n # Micromax\n # @ref: http://www.micromaxinfo.com\n #########\n - regex: '; *(?:Micromax[ _](A111|A240)|(A111|A240)) Build'\n regex_flag: 'i'\n device_replacement: 'Micromax $1$2'\n brand_replacement: 'Micromax'\n model_replacement: '$1$2'\n - regex: '; *Micromax[ _](A\\d{2,3}[^;/]*) Build'\n regex_flag: 'i'\n device_replacement: 'Micromax $1'\n brand_replacement: 'Micromax'\n model_replacement: '$1'\n # be carefull here with Acer e.g. A500\n - regex: '; *(A\\d{2}|A[12]\\d{2}|A90S|A110Q) Build'\n regex_flag: 'i'\n device_replacement: 'Micromax $1'\n brand_replacement: 'Micromax'\n model_replacement: '$1'\n - regex: '; *Micromax[ _](P\\d{3}[^;/]*) Build'\n regex_flag: 'i'\n device_replacement: 'Micromax $1'\n brand_replacement: 'Micromax'\n model_replacement: '$1'\n - regex: '; *(P\\d{3}|P\\d{3}\\(Funbook\\)) Build'\n regex_flag: 'i'\n device_replacement: 'Micromax $1'\n brand_replacement: 'Micromax'\n model_replacement: '$1'", " #########\n # Mito\n # @ref: http://new.mitomobile.com/\n #########\n - regex: '; *(MITO)[ _\\-]?([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'Mito'\n model_replacement: '$2'", " #########\n # Mobistel\n # @ref: http://www.mobistel.com/\n #########\n - regex: '; *(Cynus)[ _](F5|T\\d|.+?) *(?:Build|[;/\\)])'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'Mobistel'\n model_replacement: '$1 $2'", " #########\n # Modecom\n # @ref: http://www.modecom.eu/tablets/portal/\n #########\n - regex: '; *(MODECOM |)(FreeTab) ?([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1$2 $3'\n brand_replacement: 'Modecom'\n model_replacement: '$2 $3'\n - regex: '; *(MODECOM )([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'Modecom'\n model_replacement: '$2'", " #########\n # Motorola\n # @ref: http://www.motorola.com/us/shop-all-mobile-phones/\n #########\n - regex: '; *(MZ\\d{3}\\+?|MZ\\d{3} 4G|Xoom|XOOM[^;/]*) Build'\n device_replacement: 'Motorola $1'\n brand_replacement: 'Motorola'\n model_replacement: '$1'\n - regex: '; *(Milestone )(XT[^;/]*) Build'\n device_replacement: 'Motorola $1$2'\n brand_replacement: 'Motorola'\n model_replacement: '$2'\n - regex: '; *(Motoroi ?x|Droid X|DROIDX) Build'\n regex_flag: 'i'\n device_replacement: 'Motorola $1'\n brand_replacement: 'Motorola'\n model_replacement: 'DROID X'\n - regex: '; *(Droid[^;/]*|DROID[^;/]*|Milestone[^;/]*|Photon|Triumph|Devour|Titanium) Build'\n device_replacement: 'Motorola $1'\n brand_replacement: 'Motorola'\n model_replacement: '$1'\n - regex: '; *(A555|A85[34][^;/]*|A95[356]|ME[58]\\d{2}\\+?|ME600|ME632|ME722|MB\\d{3}\\+?|MT680|MT710|MT870|MT887|MT917|WX435|WX453|WX44[25]|XT\\d{3,4}[A-Z\\+]*|CL[iI]Q|CL[iI]Q XT) Build'\n device_replacement: '$1'\n brand_replacement: 'Motorola'\n model_replacement: '$1'\n - regex: '; *(Motorola MOT-|Motorola[ _\\-]|MOT\\-?)([^;/]+) Build'\n device_replacement: '$1$2'\n brand_replacement: 'Motorola'\n model_replacement: '$2'\n - regex: '; *(Moto[_ ]?|MOT\\-)([^;/]+) Build'\n device_replacement: '$1$2'\n brand_replacement: 'Motorola'\n model_replacement: '$2'", " #########\n # MpMan\n # @ref: http://www.mpmaneurope.com\n #########\n - regex: '; *((?:MP[DQ]C|MPG\\d{1,4}|MP\\d{3,4}|MID(?:(?:10[234]|114|43|7[247]|8[24]|7)C|8[01]1))[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Mpman'\n model_replacement: '$1'", " #########\n # MSI\n # @ref: http://www.msi.com/product/windpad/\n #########\n - regex: '; *(?:MSI[ _]|)(Primo\\d+|Enjoy[ _\\-][^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Msi'\n model_replacement: '$1'", " #########\n # Multilaser\n # http://www.multilaser.com.br/listagem_produtos.php?cat=5\n #########\n - regex: '; *Multilaser[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Multilaser'\n model_replacement: '$1'", " #########\n # MyPhone\n # @ref: http://myphone.com.ph/\n #########\n - regex: '; *(My)[_]?(Pad)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2 $3'\n brand_replacement: 'MyPhone'\n model_replacement: '$1$2 $3'\n - regex: '; *(My)\\|?(Phone)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2 $3'\n brand_replacement: 'MyPhone'\n model_replacement: '$3'\n - regex: '; *(A\\d+)[ _](Duo|)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'MyPhone'\n model_replacement: '$1 $2'", " #########\n # Mytab\n # @ref: http://www.mytab.eu/en/category/mytab-products/\n #########\n - regex: '; *(myTab[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Mytab'\n model_replacement: '$1'", " #########\n # Nabi\n # @ref: https://www.nabitablet.com\n #########\n - regex: '; *(NABI2?-)([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Nabi'\n model_replacement: '$2'", " #########\n # Nec Medias\n # @ref: http://www.n-keitai.com/\n #########\n - regex: '; *(N-\\d+[CDE])(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Nec'\n model_replacement: '$1'\n - regex: '; ?(NEC-)(.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Nec'\n model_replacement: '$2'\n - regex: '; *(LT-NA7)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Nec'\n model_replacement: 'Lifetouch Note'", " #########\n # Nextbook\n # @ref: http://nextbookusa.com\n #########\n - regex: '; *(NXM\\d+[A-Za-z0-9_]*|Next\\d[A-Za-z0-9_ \\-]*|NEXT\\d[A-Za-z0-9_ \\-]*|Nextbook [A-Za-z0-9_ ]*|DATAM803HC|M805)(?: Build|[\\);])'\n device_replacement: '$1'\n brand_replacement: 'Nextbook'\n model_replacement: '$1'", " #########\n # Nokia\n # @ref: http://www.nokia.com\n #########\n - regex: '; *(Nokia)([ _\\-]*)([^;/]*) Build'\n regex_flag: 'i'\n device_replacement: '$1$2$3'\n brand_replacement: 'Nokia'\n model_replacement: '$3'", " #########\n # Nook\n # @ref:\n # TODO nook browser/1.0\n #########\n - regex: '; *(Nook ?|Barnes & Noble Nook |BN )([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Nook'\n model_replacement: '$2'\n - regex: '; *(NOOK |)(BNRV200|BNRV200A|BNTV250|BNTV250A|BNTV400|BNTV600|LogicPD Zoom2)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Nook'\n model_replacement: '$2'\n - regex: '; Build/(Nook)'\n device_replacement: '$1'\n brand_replacement: 'Nook'\n model_replacement: 'Tablet'", " #########\n # Olivetti\n # @ref: http://www.olivetti.de/EN/Page/t02/view_html?idp=348\n #########\n - regex: '; *(OP110|OliPad[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Olivetti $1'\n brand_replacement: 'Olivetti'\n model_replacement: '$1'", " #########\n # Omega\n # @ref: http://omega-technology.eu/en/produkty/346/tablets\n # @note: MID tablets might get matched by CobyKyros first\n # @models: (T107|MID(?:700[2-5]|7031|7108|7132|750[02]|8001|8500|9001|971[12])\n #########\n - regex: '; *OMEGA[ _\\-](MID[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Omega $1'\n brand_replacement: 'Omega'\n model_replacement: '$1'\n - regex: '^(MID7500|MID\\d+) Mozilla/5\\.0 \\(iPad;'\n device_replacement: 'Omega $1'\n brand_replacement: 'Omega'\n model_replacement: '$1'", " #########\n # OpenPeak\n # @ref: https://support.google.com/googleplay/answer/1727131?hl=en\n #########\n - regex: '; *((?:CIUS|cius)[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Openpeak $1'\n brand_replacement: 'Openpeak'\n model_replacement: '$1'", " #########\n # Oppo\n # @ref: http://en.oppo.com/products/\n #########\n - regex: '; *(Find ?(?:5|7a)|R8[012]\\d{1,2}|T703\\d{0,1}|U70\\d{1,2}T?|X90\\d{1,2})(?: Build|\\) AppleWebKit)'\n device_replacement: 'Oppo $1'\n brand_replacement: 'Oppo'\n model_replacement: '$1'\n - regex: '; *OPPO ?([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Oppo $1'\n brand_replacement: 'Oppo'\n model_replacement: '$1'", " #########\n # Odys\n # @ref: http://odys.de\n #########\n - regex: '; *(?:Odys\\-|ODYS\\-|ODYS )([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Odys $1'\n brand_replacement: 'Odys'\n model_replacement: '$1'\n - regex: '; *(SELECT) ?(7)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Odys $1 $2'\n brand_replacement: 'Odys'\n model_replacement: '$1 $2'\n - regex: '; *(PEDI)_(PLUS)_(W)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Odys $1 $2 $3'\n brand_replacement: 'Odys'\n model_replacement: '$1 $2 $3'\n # Weltbild - Tablet PC 4 = Cat Phoenix = Odys Tablet PC 4?\n - regex: '; *(AEON|BRAVIO|FUSION|FUSION2IN1|Genio|EOS10|IEOS[^;/]*|IRON|Loox|LOOX|LOOX Plus|Motion|NOON|NOON_PRO|NEXT|OPOS|PEDI[^;/]*|PRIME[^;/]*|STUDYTAB|TABLO|Tablet-PC-4|UNO_X8|XELIO[^;/]*|Xelio ?\\d+ ?[Pp]ro|XENO10|XPRESS PRO)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Odys $1'\n brand_replacement: 'Odys'\n model_replacement: '$1'", " #########\n # OnePlus\n # @ref https://oneplus.net/\n #########\n - regex: '; (ONE [a-zA-Z]\\d+)(?: Build|\\) AppleWebKit)'\n device_replacement: 'OnePlus $1'\n brand_replacement: 'OnePlus'\n model_replacement: '$1'\n - regex: '; (ONEPLUS [a-zA-Z]\\d+)(?: Build|\\) AppleWebKit)'\n device_replacement: 'OnePlus $1'\n brand_replacement: 'OnePlus'\n model_replacement: '$1'", " #########\n # Orion\n # @ref: http://www.orion.ua/en/products/computer-products/tablet-pcs.html\n #########\n - regex: '; *(TP-\\d+)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Orion $1'\n brand_replacement: 'Orion'\n model_replacement: '$1'", " #########\n # PackardBell\n # @ref: http://www.packardbell.com/pb/en/AE/content/productgroup/tablets\n #########\n - regex: '; *(G100W?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'PackardBell $1'\n brand_replacement: 'PackardBell'\n model_replacement: '$1'", " #########\n # Panasonic\n # @ref: http://panasonic.jp/mobile/\n # @models: T11, T21, T31, P11, P51, Eluga Power, Eluga DL1\n # @models: (tab) Toughpad FZ-A1, Toughpad JT-B1\n #########\n - regex: '; *(Panasonic)[_ ]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'\n # Toughpad\n - regex: '; *(FZ-A1B|JT-B1)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Panasonic $1'\n brand_replacement: 'Panasonic'\n model_replacement: '$1'\n # Eluga Power\n - regex: '; *(dL1|DL1)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Panasonic $1'\n brand_replacement: 'Panasonic'\n model_replacement: '$1'", " #########\n # Pantech\n # @href: http://www.pantech.co.kr/en/prod/prodList.do?gbrand=PANTECH\n # @href: http://www.pantech.co.kr/en/prod/prodList.do?gbrand=VEGA\n # @models: ADR8995, ADR910L, ADR930VW, C790, CDM8992, CDM8999, IS06, IS11PT, P2000, P2020, P2030, P4100, P5000, P6010, P6020, P6030, P7000, P7040, P8000, P8010, P9020, P9050, P9060, P9070, P9090, PT001, PT002, PT003, TXT8040, TXT8045, VEGA PTL21\n #########\n - regex: '; *(SKY[ _]|)(IM\\-[AT]\\d{3}[^;/]+).* Build/'\n device_replacement: 'Pantech $1$2'\n brand_replacement: 'Pantech'\n model_replacement: '$1$2'\n - regex: '; *((?:ADR8995|ADR910L|ADR930L|ADR930VW|PTL21|P8000)(?: 4G|)) Build/'\n device_replacement: '$1'\n brand_replacement: 'Pantech'\n model_replacement: '$1'\n - regex: '; *Pantech([^;/]+).* Build/'\n device_replacement: 'Pantech $1'\n brand_replacement: 'Pantech'\n model_replacement: '$1'", " #########\n # Papayre\n # @ref: http://grammata.es/\n #########\n - regex: '; *(papyre)[ _\\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'Papyre'\n model_replacement: '$2'", " #########\n # Pearl\n # @ref: http://www.pearl.de/c-1540.shtml\n #########\n - regex: '; *(?:Touchlet )?(X10\\.[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Pearl $1'\n brand_replacement: 'Pearl'\n model_replacement: '$1'", " #########\n # Phicomm\n # @ref: http://www.phicomm.com.cn/\n #########\n - regex: '; PHICOMM (i800)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Phicomm $1'\n brand_replacement: 'Phicomm'\n model_replacement: '$1'\n - regex: '; PHICOMM ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Phicomm $1'\n brand_replacement: 'Phicomm'\n model_replacement: '$1'\n - regex: '; *(FWS\\d{3}[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Phicomm $1'\n brand_replacement: 'Phicomm'\n model_replacement: '$1'", " #########\n # Philips\n # @ref: http://www.support.philips.com/support/catalog/products.jsp?_dyncharset=UTF-8&country=&categoryid=MOBILE_PHONES_SMART_SU_CN_CARE&userLanguage=en&navCount=2&groupId=PC_PRODUCTS_AND_PHONES_GR_CN_CARE&catalogType=&navAction=push&userCountry=cn&title=Smartphones&cateId=MOBILE_PHONES_CA_CN_CARE\n # @TODO: Philips Tablets User-Agents missing!\n # @ref: http://www.support.philips.com/support/catalog/products.jsp?_dyncharset=UTF-8&country=&categoryid=ENTERTAINMENT_TABLETS_SU_CN_CARE&userLanguage=en&navCount=0&groupId=&catalogType=&navAction=push&userCountry=cn&title=Entertainment+Tablets&cateId=TABLETS_CA_CN_CARE\n #########\n # @note: this a best guess according to available philips models. Need more User-Agents\n - regex: '; *(D633|D822|D833|T539|T939|V726|W335|W336|W337|W3568|W536|W5510|W626|W632|W6350|W6360|W6500|W732|W736|W737|W7376|W820|W832|W8355|W8500|W8510|W930)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Philips'\n model_replacement: '$1'\n - regex: '; *(?:Philips|PHILIPS)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Philips $1'\n brand_replacement: 'Philips'\n model_replacement: '$1'", " #########\n # Pipo\n # @ref: http://www.pipo.cn/En/\n #########\n - regex: 'Android 4\\..*; *(M[12356789]|U[12368]|S[123])\\ ?(pro)?(?: Build|\\) AppleWebKit)'\n device_replacement: 'Pipo $1$2'\n brand_replacement: 'Pipo'\n model_replacement: '$1$2'", " #########\n # Ployer\n # @ref: http://en.ployer.cn/\n #########\n - regex: '; *(MOMO[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Ployer'\n model_replacement: '$1'", " #########\n # Polaroid/ Acho\n # @ref: http://polaroidstore.com/store/start.asp?category_id=382&category_id2=0&order=title&filter1=&filter2=&filter3=&view=all\n #########\n - regex: '; *(?:Polaroid[ _]|)((?:MIDC\\d{3,}|PMID\\d{2,}|PTAB\\d{3,})[^;/]*?)(\\/[^;/]*|)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Polaroid'\n model_replacement: '$1'\n - regex: '; *(?:Polaroid )(Tablet)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Polaroid'\n model_replacement: '$1'", " #########\n # Pomp\n # @ref: http://pompmobileshop.com/\n #########\n #~ TODO\n - regex: '; *(POMP)[ _\\-](.+?) *(?:Build|[;/\\)])'\n device_replacement: '$1 $2'\n brand_replacement: 'Pomp'\n model_replacement: '$2'", " #########\n # Positivo\n # @ref: http://www.positivoinformatica.com.br/www/pessoal/tablet-ypy/\n #########\n - regex: '; *(TB07STA|TB10STA|TB07FTA|TB10FTA)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Positivo'\n model_replacement: '$1'\n - regex: '; *(?:Positivo |)((?:YPY|Ypy)[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Positivo'\n model_replacement: '$1'", " #########\n # POV\n # @ref: http://www.pointofview-online.com/default2.php\n # @TODO: Smartphone Models MOB-3515, MOB-5045-B missing\n #########\n - regex: '; *(MOB-[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'POV'\n model_replacement: '$1'\n - regex: '; *POV[ _\\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'POV $1'\n brand_replacement: 'POV'\n model_replacement: '$1'\n - regex: '; *((?:TAB-PLAYTAB|TAB-PROTAB|PROTAB|PlayTabPro|Mobii[ _\\-]|TAB-P)[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: 'POV $1'\n brand_replacement: 'POV'\n model_replacement: '$1'", " #########\n # Prestigio\n # @ref: http://www.prestigio.com/catalogue/MultiPhones\n # @ref: http://www.prestigio.com/catalogue/MultiPads\n #########\n - regex: '; *(?:Prestigio |)((?:PAP|PMP)\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Prestigio $1'\n brand_replacement: 'Prestigio'\n model_replacement: '$1'", " #########\n # Proscan\n # @ref: http://www.proscanvideo.com/products-search.asp?itemClass=TABLET&itemnmbr=\n #########\n - regex: '; *(PLT[0-9]{4}.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Proscan'\n model_replacement: '$1'", " #########\n # QMobile\n # @ref: http://www.qmobile.com.pk/\n #########\n - regex: '; *(A2|A5|A8|A900)_?(Classic|)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Qmobile'\n model_replacement: '$1 $2'\n - regex: '; *(Q[Mm]obile)_([^_]+)_([^_]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Qmobile $2 $3'\n brand_replacement: 'Qmobile'\n model_replacement: '$2 $3'\n - regex: '; *(Q\\-?[Mm]obile)[_ ](A[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Qmobile $2'\n brand_replacement: 'Qmobile'\n model_replacement: '$2'", " #########\n # Qmobilevn\n # @ref: http://qmobile.vn/san-pham.html\n #########\n - regex: '; *(Q\\-Smart)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Qmobilevn'\n model_replacement: '$2'\n - regex: '; *(Q\\-?[Mm]obile)[ _\\-](S[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Qmobilevn'\n model_replacement: '$2'", " #########\n # Quanta\n # @ref: ?\n #########\n - regex: '; *(TA1013)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Quanta'\n model_replacement: '$1'", " #########\n # RCA\n # @ref: http://rcamobilephone.com/\n #########\n - regex: '; (RCT\\w+)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'RCA'\n model_replacement: '$1'\n - regex: '; RCA (\\w+)(?: Build|\\) AppleWebKit)'\n device_replacement: 'RCA $1'\n brand_replacement: 'RCA'\n model_replacement: '$1'", " #########\n # Rockchip\n # @ref: http://www.rock-chips.com/a/cn/product/index.html\n # @note: manufacturer sells chipsets - I assume that these UAs are dev-boards\n #########\n - regex: '; *(RK\\d+),?(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Rockchip'\n model_replacement: '$1'\n - regex: ' Build/(RK\\d+)'\n device_replacement: '$1'\n brand_replacement: 'Rockchip'\n model_replacement: '$1'", " #########\n # Samsung Android Devices\n # @ref: http://www.samsung.com/us/mobile/cell-phones/all-products\n #########\n - regex: '; *(SAMSUNG |Samsung |)((?:Galaxy (?:Note II|S\\d)|GT-I9082|GT-I9205|GT-N7\\d{3}|SM-N9005)[^;/]*)\\/?[^;/]* Build/'\n device_replacement: 'Samsung $1$2'\n brand_replacement: 'Samsung'\n model_replacement: '$2'\n - regex: '; *(Google |)(Nexus [Ss](?: 4G|)) Build/'\n device_replacement: 'Samsung $1$2'\n brand_replacement: 'Samsung'\n model_replacement: '$2'\n - regex: '; *(SAMSUNG |Samsung )([^\\/]*)\\/[^ ]* Build/'\n device_replacement: 'Samsung $2'\n brand_replacement: 'Samsung'\n model_replacement: '$2'\n - regex: '; *(Galaxy(?: Ace| Nexus| S ?II+|Nexus S| with MCR 1.2| Mini Plus 4G|)) Build/'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n - regex: '; *(SAMSUNG[ _\\-]|)(?:SAMSUNG[ _\\-])([^;/]+) Build'\n device_replacement: 'Samsung $2'\n brand_replacement: 'Samsung'\n model_replacement: '$2'\n - regex: '; *(SAMSUNG-|)(GT\\-[BINPS]\\d{4}[^\\/]*)(\\/[^ ]*) Build'\n device_replacement: 'Samsung $1$2$3'\n brand_replacement: 'Samsung'\n model_replacement: '$2'\n - regex: '(?:; *|^)((?:GT\\-[BIiNPS]\\d{4}|I9\\d{2}0[A-Za-z\\+]?\\b)[^;/\\)]*?)(?:Build|Linux|MIUI|[;/\\)])'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n - regex: '; (SAMSUNG-)([A-Za-z0-9\\-]+).* Build/'\n device_replacement: 'Samsung $1$2'\n brand_replacement: 'Samsung'\n model_replacement: '$2'\n - regex: '; *((?:SCH|SGH|SHV|SHW|SPH|SC|SM)\\-[A-Za-z0-9 ]+)(/?[^ ]*|) Build'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n - regex: '; *((?:SC)\\-[A-Za-z0-9 ]+)(/?[^ ]*|)\\)'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n - regex: ' ((?:SCH)\\-[A-Za-z0-9 ]+)(/?[^ ]*|) Build'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n - regex: '; *(Behold ?(?:2|II)|YP\\-G[^;/]+|EK-GC100|SCL21|I9300) Build'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n - regex: '; *((?:SCH|SGH|SHV|SHW|SPH|SC|SM)\\-[A-Za-z0-9]{5,6})[\\)]'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'", " #########\n # Sharp\n # @ref: http://www.sharp-phone.com/en/index.html\n # @ref: http://www.android.com/devices/?country=all&m=sharp\n #########\n - regex: '; *(SH\\-?\\d\\d[^;/]+|SBM\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Sharp'\n model_replacement: '$1'\n - regex: '; *(SHARP[ -])([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Sharp'\n model_replacement: '$2'", " #########\n # Simvalley\n # @ref: http://www.simvalley-mobile.de/\n #########\n - regex: '; *(SPX[_\\-]\\d[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Simvalley'\n model_replacement: '$1'\n - regex: '; *(SX7\\-PEARL\\.GmbH)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Simvalley'\n model_replacement: '$1'\n - regex: '; *(SP[T]?\\-\\d{2}[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Simvalley'\n model_replacement: '$1'", " #########\n # SK Telesys\n # @ref: http://www.sk-w.com/phone/phone_list.jsp\n # @ref: http://www.android.com/devices/?country=all&m=sk-telesys\n #########\n - regex: '; *(SK\\-.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'SKtelesys'\n model_replacement: '$1'", " #########\n # Skytex\n # @ref: http://skytex.com/android\n #########\n - regex: '; *(?:SKYTEX|SX)-([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Skytex'\n model_replacement: '$1'\n - regex: '; *(IMAGINE [^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Skytex'\n model_replacement: '$1'", " #########\n # SmartQ\n # @ref: http://en.smartdevices.com.cn/Products/\n # @models: Z8, X7, U7H, U7, T30, T20, Ten3, V5-II, T7-3G, SmartQ5, K7, S7, Q8, T19, Ten2, Ten, R10, T7, R7, V5, V7, SmartQ7\n #########\n - regex: '; *(SmartQ) ?([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " #########\n # Smartbitt\n # @ref: http://www.smartbitt.com/\n # @missing: SBT Useragents\n #########\n - regex: '; *(WF7C|WF10C|SBT[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Smartbitt'\n model_replacement: '$1'", " #########\n # Softbank (Operator Branded Devices)\n # @ref: http://www.ipentec.com/document/document.aspx?page=android-useragent\n #########\n - regex: '; *(SBM(?:003SH|005SH|006SH|007SH|102SH)) Build'\n device_replacement: '$1'\n brand_replacement: 'Sharp'\n model_replacement: '$1'\n - regex: '; *(003P|101P|101P11C|102P) Build'\n device_replacement: '$1'\n brand_replacement: 'Panasonic'\n model_replacement: '$1'\n - regex: '; *(00\\dZ) Build/'\n device_replacement: '$1'\n brand_replacement: 'ZTE'\n model_replacement: '$1'\n - regex: '; HTC(X06HT) Build'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: '$1'\n - regex: '; *(001HT|X06HT) Build'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: '$1'\n - regex: '; *(201M) Build'\n device_replacement: '$1'\n brand_replacement: 'Motorola'\n model_replacement: 'XT902'", " #########\n # Trekstor\n # @ref: http://www.trekstor.co.uk/surftabs-en.html\n # @note: Must come before SonyEricsson\n #########\n - regex: '; *(ST\\d{4}.*)Build/ST'\n device_replacement: 'Trekstor $1'\n brand_replacement: 'Trekstor'\n model_replacement: '$1'\n - regex: '; *(ST\\d{4}.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Trekstor $1'\n brand_replacement: 'Trekstor'\n model_replacement: '$1'", " #########\n # SonyEricsson\n # @note: Must come before nokia since they also use symbian\n # @ref: http://www.android.com/devices/?country=all&m=sony-ericssons\n # @TODO: type!\n #########\n # android matchers\n - regex: '; *(Sony ?Ericsson ?)([^;/]+) Build'\n device_replacement: '$1$2'\n brand_replacement: 'SonyEricsson'\n model_replacement: '$2'\n - regex: '; *((?:SK|ST|E|X|LT|MK|MT|WT)\\d{2}[a-z0-9]*(?:-o|)|R800i|U20i) Build'\n device_replacement: '$1'\n brand_replacement: 'SonyEricsson'\n model_replacement: '$1'\n # TODO X\\d+ is wrong\n - regex: '; *(Xperia (?:A8|Arc|Acro|Active|Live with Walkman|Mini|Neo|Play|Pro|Ray|X\\d+)[^;/]*) Build'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'SonyEricsson'\n model_replacement: '$1'", " #########\n # Sony\n # @ref: http://www.sonymobile.co.jp/index.html\n # @ref: http://www.sonymobile.com/global-en/products/phones/\n # @ref: http://www.sony.jp/tablet/\n #########\n - regex: '; Sony (Tablet[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Sony $1'\n brand_replacement: 'Sony'\n model_replacement: '$1'\n - regex: '; Sony ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Sony $1'\n brand_replacement: 'Sony'\n model_replacement: '$1'\n - regex: '; *(Sony)([A-Za-z0-9\\-]+)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'\n - regex: '; *(Xperia [^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Sony'\n model_replacement: '$1'\n - regex: '; *(C(?:1[0-9]|2[0-9]|53|55|6[0-9])[0-9]{2}|D[25]\\d{3}|D6[56]\\d{2})(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Sony'\n model_replacement: '$1'\n - regex: '; *(SGP\\d{3}|SGPT\\d{2})(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Sony'\n model_replacement: '$1'\n - regex: '; *(NW-Z1000Series)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Sony'\n model_replacement: '$1'", " ##########\n # Sony PlayStation\n # @ref: http://playstation.com\n # The Vita spoofs the Kindle\n ##########\n - regex: 'PLAYSTATION 3'\n device_replacement: 'PlayStation 3'\n brand_replacement: 'Sony'\n model_replacement: 'PlayStation 3'\n - regex: '(PlayStation (?:Portable|Vita|\\d+))'\n device_replacement: '$1'\n brand_replacement: 'Sony'\n model_replacement: '$1'", " #########\n # Spice\n # @ref: http://www.spicemobilephones.co.in/\n #########\n - regex: '; *((?:CSL_Spice|Spice|SPICE|CSL)[ _\\-]?|)([Mm][Ii])([ _\\-]|)(\\d{3}[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2$3$4'\n brand_replacement: 'Spice'\n model_replacement: 'Mi$4'", " #########\n # Sprint (Operator Branded Devices)\n # @ref:\n #########\n - regex: '; *(Sprint )(.+?) *(?:Build|[;/])'\n device_replacement: '$1$2'\n brand_replacement: 'Sprint'\n model_replacement: '$2'\n - regex: '\\b(Sprint)[: ]([^;,/ ]+)'\n device_replacement: '$1$2'\n brand_replacement: 'Sprint'\n model_replacement: '$2'", " #########\n # Tagi\n # @ref: ??\n #########\n - regex: '; *(TAGI[ ]?)(MID) ?([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2$3'\n brand_replacement: 'Tagi'\n model_replacement: '$2$3'", " #########\n # Tecmobile\n # @ref: http://www.tecmobile.com/\n #########\n - regex: '; *(Oyster500|Opal 800)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Tecmobile $1'\n brand_replacement: 'Tecmobile'\n model_replacement: '$1'", " #########\n # Tecno\n # @ref: www.tecno-mobile.com/‎\n #########\n - regex: '; *(TECNO[ _])([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Tecno'\n model_replacement: '$2'", " #########\n # Telechips, Techvision evaluation boards\n # @ref:\n #########\n - regex: '; *Android for (Telechips|Techvision) ([^ ]+) '\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " #########\n # Telstra\n # @ref: http://www.telstra.com.au/home-phone/thub-2/\n # @ref: https://support.google.com/googleplay/answer/1727131?hl=en\n #########\n - regex: '; *(T-Hub2)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Telstra'\n model_replacement: '$1'", " #########\n # Terra\n # @ref: http://www.wortmann.de/\n #########\n - regex: '; *(PAD) ?(100[12])(?: Build|\\) AppleWebKit)'\n device_replacement: 'Terra $1$2'\n brand_replacement: 'Terra'\n model_replacement: '$1$2'", " #########\n # Texet\n # @ref: http://www.texet.ru/tablet/\n #########\n - regex: '; *(T[BM]-\\d{3}[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Texet'\n model_replacement: '$1'", " #########\n # Thalia\n # @ref: http://www.thalia.de/shop/tolino-shine-ereader/show/\n #########\n - regex: '; *(tolino [^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Thalia'\n model_replacement: '$1'\n - regex: '; *Build/.* (TOLINO_BROWSER)'\n device_replacement: '$1'\n brand_replacement: 'Thalia'\n model_replacement: 'Tolino Shine'", " #########\n # Thl\n # @ref: http://en.thl.com.cn/Mobile\n # @ref: http://thlmobilestore.com\n #########\n - regex: '; *(?:CJ[ -])?(ThL|THL)[ -]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Thl'\n model_replacement: '$2'\n - regex: '; *(T100|T200|T5|W100|W200|W8s)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Thl'\n model_replacement: '$1'", " #########\n # T-Mobile (Operator Branded Devices)\n #########\n # @ref: https://en.wikipedia.org/wiki/HTC_Hero\n - regex: '; *(T-Mobile[ _]G2[ _]Touch) Build'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: 'Hero'\n # @ref: https://en.wikipedia.org/wiki/HTC_Desire_Z\n - regex: '; *(T-Mobile[ _]G2) Build'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: 'Desire Z'\n - regex: '; *(T-Mobile myTouch Q) Build'\n device_replacement: '$1'\n brand_replacement: 'Huawei'\n model_replacement: 'U8730'\n - regex: '; *(T-Mobile myTouch) Build'\n device_replacement: '$1'\n brand_replacement: 'Huawei'\n model_replacement: 'U8680'\n - regex: '; *(T-Mobile_Espresso) Build'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: 'Espresso'\n - regex: '; *(T-Mobile G1) Build'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: 'Dream'\n - regex: '\\b(T-Mobile ?|)(myTouch)[ _]?([34]G)[ _]?([^\\/]*) (?:Mozilla|Build)'\n device_replacement: '$1$2 $3 $4'\n brand_replacement: 'HTC'\n model_replacement: '$2 $3 $4'\n - regex: '\\b(T-Mobile)_([^_]+)_(.*) Build'\n device_replacement: '$1 $2 $3'\n brand_replacement: 'Tmobile'\n model_replacement: '$2 $3'\n - regex: '\\b(T-Mobile)[_ ]?(.*?)Build'\n device_replacement: '$1 $2'\n brand_replacement: 'Tmobile'\n model_replacement: '$2'", " #########\n # Tomtec\n # @ref: http://www.tom-tec.eu/pages/tablets.php\n #########\n - regex: ' (ATP[0-9]{4})(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Tomtec'\n model_replacement: '$1'", " #########\n # Tooky\n # @ref: http://www.tookymobile.com/\n #########\n - regex: ' *(TOOKY)[ _\\-]([^;/]+?) ?(?:Build|;)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'Tooky'\n model_replacement: '$2'", " #########\n # Toshiba\n # @ref: http://www.toshiba.co.jp/\n # @missing: LT170, Thrive 7, TOSHIBA STB10\n #########\n - regex: '\\b(TOSHIBA_AC_AND_AZ|TOSHIBA_FOLIO_AND_A|FOLIO_AND_A)'\n device_replacement: '$1'\n brand_replacement: 'Toshiba'\n model_replacement: 'Folio 100'\n - regex: '; *([Ff]olio ?100)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Toshiba'\n model_replacement: 'Folio 100'\n - regex: '; *(AT[0-9]{2,3}(?:\\-A|LE\\-A|PE\\-A|SE|a|)|AT7-A|AT1S0|Hikari-iFrame/WDPF-[^;/]+|THRiVE|Thrive)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Toshiba $1'\n brand_replacement: 'Toshiba'\n model_replacement: '$1'", " #########\n # Touchmate\n # @ref: http://touchmatepc.com/new/\n #########\n - regex: '; *(TM-MID\\d+[^;/]+|TOUCHMATE|MID-750)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Touchmate'\n model_replacement: '$1'\n # @todo: needs verification user-agents missing\n - regex: '; *(TM-SM\\d+[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Touchmate'\n model_replacement: '$1'", " #########\n # Treq\n # @ref: http://www.treq.co.id/product\n #########\n - regex: '; *(A10 [Bb]asic2?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Treq'\n model_replacement: '$1'\n - regex: '; *(TREQ[ _\\-])([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1$2'\n brand_replacement: 'Treq'\n model_replacement: '$2'", " #########\n # Umeox\n # @ref: http://umeox.com/\n # @models: A936|A603|X-5|X-3\n #########\n # @todo: guessed markers\n - regex: '; *(X-?5|X-?3)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Umeox'\n model_replacement: '$1'\n # @todo: guessed markers\n - regex: '; *(A502\\+?|A936|A603|X1|X2)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Umeox'\n model_replacement: '$1'", " #########\n # Versus\n # @ref: http://versusuk.com/support.html\n #########\n - regex: '(TOUCH(?:TAB|PAD).+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Versus $1'\n brand_replacement: 'Versus'\n model_replacement: '$1'", " #########\n # Vertu\n # @ref: http://www.vertu.com/\n #########\n - regex: '(VERTU) ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Vertu'\n model_replacement: '$2'", " #########\n # Videocon\n # @ref: http://www.videoconmobiles.com\n #########\n - regex: '; *(Videocon)[ _\\-]([^;/]+?) *(?:Build|;)'\n device_replacement: '$1 $2'\n brand_replacement: 'Videocon'\n model_replacement: '$2'\n - regex: ' (VT\\d{2}[A-Za-z]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Videocon'\n model_replacement: '$1'", " #########\n # Viewsonic\n # @ref: http://viewsonic.com\n #########\n - regex: '; *((?:ViewPad|ViewPhone|VSD)[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Viewsonic'\n model_replacement: '$1'\n - regex: '; *(ViewSonic-)([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Viewsonic'\n model_replacement: '$2'\n - regex: '; *(GTablet.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Viewsonic'\n model_replacement: '$1'", " #########\n # vivo\n # @ref: http://vivo.cn/\n #########\n - regex: '; *([Vv]ivo)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'vivo'\n model_replacement: '$2'", " #########\n # Vodafone (Operator Branded Devices)\n # @ref: ??\n #########\n - regex: '(Vodafone) (.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " #########\n # Walton\n # @ref: http://www.waltonbd.com/\n #########\n - regex: '; *(?:Walton[ _\\-]|)(Primo[ _\\-][^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Walton $1'\n brand_replacement: 'Walton'\n model_replacement: '$1'", " #########\n # Wiko\n # @ref: http://fr.wikomobile.com/collection.php?s=Smartphones\n #########\n - regex: '; *(?:WIKO[ \\-]|)(CINK\\+?|BARRY|BLOOM|DARKFULL|DARKMOON|DARKNIGHT|DARKSIDE|FIZZ|HIGHWAY|IGGY|OZZY|RAINBOW|STAIRWAY|SUBLIM|WAX|CINK [^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Wiko $1'\n brand_replacement: 'Wiko'\n model_replacement: '$1'", " #########\n # WellcoM\n # @ref: ??\n #########\n - regex: '; *WellcoM-([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Wellcom $1'\n brand_replacement: 'Wellcom'\n model_replacement: '$1'", " ##########\n # WeTab\n # @ref: http://wetab.mobi/\n ##########\n - regex: '(?:(WeTab)-Browser|; (wetab) Build)'\n device_replacement: '$1'\n brand_replacement: 'WeTab'\n model_replacement: 'WeTab'", " #########\n # Wolfgang\n # @ref: http://wolfgangmobile.com/\n #########\n - regex: '; *(AT-AS[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Wolfgang $1'\n brand_replacement: 'Wolfgang'\n model_replacement: '$1'", " #########\n # Woxter\n # @ref: http://www.woxter.es/es-es/categories/index\n #########\n - regex: '; *(?:Woxter|Wxt) ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Woxter $1'\n brand_replacement: 'Woxter'\n model_replacement: '$1'", " #########\n # Yarvik Zania\n # @ref: http://yarvik.com\n #########\n - regex: '; *(?:Xenta |Luna |)(TAB[234][0-9]{2}|TAB0[78]-\\d{3}|TAB0?9-\\d{3}|TAB1[03]-\\d{3}|SMP\\d{2}-\\d{3})(?: Build|\\) AppleWebKit)'\n device_replacement: 'Yarvik $1'\n brand_replacement: 'Yarvik'\n model_replacement: '$1'", " #########\n # Yifang\n # @note: Needs to be at the very last as manufacturer builds for other brands.\n # @ref: http://www.yifangdigital.com/\n # @models: M1010, M1011, M1007, M1008, M1005, M899, M899LP, M909, M8000,\n # M8001, M8002, M8003, M849, M815, M816, M819, M805, M878, M780LPW,\n # M778, M7000, M7000AD, M7000NBD, M7001, M7002, M7002KBD, M777, M767,\n # M789, M799, M769, M757, M755, M753, M752, M739, M729, M723, M712, M727\n #########\n - regex: '; *([A-Z]{2,4})(M\\d{3,}[A-Z]{2})([^;\\)\\/]*)(?: Build|[;\\)])'\n device_replacement: 'Yifang $1$2$3'\n brand_replacement: 'Yifang'\n model_replacement: '$2'", " #########\n # XiaoMi\n # @ref: http://www.xiaomi.com/event/buyphone\n #########\n - regex: '; *((Mi|MI|HM|MI-ONE|Redmi)[ -](NOTE |Note |)[^;/]*) (Build|MIUI)/'\n device_replacement: 'XiaoMi $1'\n brand_replacement: 'XiaoMi'\n model_replacement: '$1'\n - regex: '; *((Mi|MI|HM|MI-ONE|Redmi)[ -](NOTE |Note |)[^;/\\)]*)'\n device_replacement: 'XiaoMi $1'\n brand_replacement: 'XiaoMi'\n model_replacement: '$1'\n - regex: '; *(MIX) (Build|MIUI)/'\n device_replacement: 'XiaoMi $1'\n brand_replacement: 'XiaoMi'\n model_replacement: '$1'\n - regex: '; *((MIX) ([^;/]*)) (Build|MIUI)/'\n device_replacement: 'XiaoMi $1'\n brand_replacement: 'XiaoMi'\n model_replacement: '$1'", " #########\n # Xolo\n # @ref: http://www.xolo.in/\n #########\n - regex: '; *XOLO[ _]([^;/]*tab.*)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Xolo $1'\n brand_replacement: 'Xolo'\n model_replacement: '$1'\n - regex: '; *XOLO[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Xolo $1'\n brand_replacement: 'Xolo'\n model_replacement: '$1'\n - regex: '; *(q\\d0{2,3}[a-z]?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Xolo $1'\n brand_replacement: 'Xolo'\n model_replacement: '$1'", " #########\n # Xoro\n # @ref: http://www.xoro.de/produkte/\n #########\n - regex: '; *(PAD ?[79]\\d+[^;/]*|TelePAD\\d+[^;/])(?: Build|\\) AppleWebKit)'\n device_replacement: 'Xoro $1'\n brand_replacement: 'Xoro'\n model_replacement: '$1'", " #########\n # Zopo\n # @ref: http://www.zopomobiles.com/products.html\n #########\n - regex: '; *(?:(?:ZOPO|Zopo)[ _]([^;/]+?)|(ZP ?(?:\\d{2}[^;/]+|C2))|(C[2379]))(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2$3'\n brand_replacement: 'Zopo'\n model_replacement: '$1$2$3'", " #########\n # ZiiLabs\n # @ref: http://www.ziilabs.com/products/platforms/androidreferencetablets.php\n #########\n - regex: '; *(ZiiLABS) (Zii[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'ZiiLabs'\n model_replacement: '$2'\n - regex: '; *(Zii)_([^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'ZiiLabs'\n model_replacement: '$2'", " #########\n # ZTE\n # @ref: http://www.ztedevices.com/\n #########\n - regex: '; *(ARIZONA|(?:ATLAS|Atlas) W|D930|Grand (?:[SX][^;]*?|Era|Memo[^;]*?)|JOE|(?:Kis|KIS)\\b[^;]*?|Libra|Light [^;]*?|N8[056][01]|N850L|N8000|N9[15]\\d{2}|N9810|NX501|Optik|(?:Vip )Racer[^;]*?|RacerII|RACERII|San Francisco[^;]*?|V9[AC]|V55|V881|Z[679][0-9]{2}[A-z]?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'ZTE'\n model_replacement: '$1'\n - regex: '; *([A-Z]\\d+)_USA_[^;]*(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'ZTE'\n model_replacement: '$1'\n - regex: '; *(SmartTab\\d+)[^;]*(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'ZTE'\n model_replacement: '$1'\n - regex: '; *(?:Blade|BLADE|ZTE-BLADE)([^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: 'ZTE Blade$1'\n brand_replacement: 'ZTE'\n model_replacement: 'Blade$1'\n - regex: '; *(?:Skate|SKATE|ZTE-SKATE)([^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: 'ZTE Skate$1'\n brand_replacement: 'ZTE'\n model_replacement: 'Skate$1'\n - regex: '; *(Orange |Optimus )(Monte Carlo|San Francisco)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'ZTE'\n model_replacement: '$1$2'\n - regex: '; *(?:ZXY-ZTE_|ZTE\\-U |ZTE[\\- _]|ZTE-C[_ ])([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'ZTE $1'\n brand_replacement: 'ZTE'\n model_replacement: '$1'\n # operator specific\n - regex: '; (BASE) (lutea|Lutea 2|Tab[^;]*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'ZTE'\n model_replacement: '$1 $2'\n - regex: '; (Avea inTouch 2|soft stone|tmn smart a7|Movistar[ _]Link)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'ZTE'\n model_replacement: '$1'\n - regex: '; *(vp9plus)\\)'\n device_replacement: '$1'\n brand_replacement: 'ZTE'\n model_replacement: '$1'", " ##########\n # Zync\n # @ref: http://www.zync.in/index.php/our-products/tablet-phablets\n ##########\n - regex: '; ?(Cloud[ _]Z5|z1000|Z99 2G|z99|z930|z999|z990|z909|Z919|z900)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Zync'\n model_replacement: '$1'", " ##########\n # Kindle\n # @note: Needs to be after Sony Playstation Vita as this UA contains Silk/3.2\n # @ref: https://developer.amazon.com/sdk/fire/specifications.html\n # @ref: http://amazonsilk.wordpress.com/useful-bits/silk-user-agent/\n ##########\n - regex: '; ?(KFOT|Kindle Fire) Build\\b'\n device_replacement: 'Kindle Fire'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire'\n - regex: '; ?(KFOTE|Amazon Kindle Fire2) Build\\b'\n device_replacement: 'Kindle Fire 2'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire 2'\n - regex: '; ?(KFTT) Build\\b'\n device_replacement: 'Kindle Fire HD'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire HD 7\"'\n - regex: '; ?(KFJWI) Build\\b'\n device_replacement: 'Kindle Fire HD 8.9\" WiFi'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire HD 8.9\" WiFi'\n - regex: '; ?(KFJWA) Build\\b'\n device_replacement: 'Kindle Fire HD 8.9\" 4G'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire HD 8.9\" 4G'\n - regex: '; ?(KFSOWI) Build\\b'\n device_replacement: 'Kindle Fire HD 7\" WiFi'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire HD 7\" WiFi'\n - regex: '; ?(KFTHWI) Build\\b'\n device_replacement: 'Kindle Fire HDX 7\" WiFi'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire HDX 7\" WiFi'\n - regex: '; ?(KFTHWA) Build\\b'\n device_replacement: 'Kindle Fire HDX 7\" 4G'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire HDX 7\" 4G'\n - regex: '; ?(KFAPWI) Build\\b'\n device_replacement: 'Kindle Fire HDX 8.9\" WiFi'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire HDX 8.9\" WiFi'\n - regex: '; ?(KFAPWA) Build\\b'\n device_replacement: 'Kindle Fire HDX 8.9\" 4G'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire HDX 8.9\" 4G'\n - regex: '; ?Amazon ([^;/]+) Build\\b'\n device_replacement: '$1'\n brand_replacement: 'Amazon'\n model_replacement: '$1'\n - regex: '; ?(Kindle) Build\\b'\n device_replacement: 'Kindle'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle'\n - regex: '; ?(Silk)/(\\d+)\\.(\\d+)(?:\\.([0-9\\-]+)|) Build\\b'\n device_replacement: 'Kindle Fire'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire$2'\n - regex: ' (Kindle)/(\\d+\\.\\d+)'\n device_replacement: 'Kindle'\n brand_replacement: 'Amazon'\n model_replacement: '$1 $2'\n - regex: ' (Silk|Kindle)/(\\d+)\\.'\n device_replacement: 'Kindle'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle'", " #########\n # Devices from chinese manufacturer(s)\n # @note: identified by x-wap-profile http://218.249.47.94/Xianghe/.*\n #########\n - regex: '(sprd)\\-([^/]+)/'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'\n # @ref: http://eshinechina.en.alibaba.com/\n - regex: '; *(H\\d{2}00\\+?) Build'\n device_replacement: '$1'\n brand_replacement: 'Hero'\n model_replacement: '$1'\n - regex: '; *(iphone|iPhone5) Build/'\n device_replacement: 'Xianghe $1'\n brand_replacement: 'Xianghe'\n model_replacement: '$1'\n - regex: '; *(e\\d{4}[a-z]?_?v\\d+|v89_[^;/]+)[^;/]+ Build/'\n device_replacement: 'Xianghe $1'\n brand_replacement: 'Xianghe'\n model_replacement: '$1'", " #########\n # Cellular\n # @ref:\n # @note: Operator branded devices\n #########\n - regex: '\\bUSCC[_\\-]?([^ ;/\\)]+)'\n device_replacement: '$1'\n brand_replacement: 'Cellular'\n model_replacement: '$1'", " ######################################################################\n # Windows Phone Parsers\n ######################################################################", " #########\n # Alcatel Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|)(?:ALCATEL)[^;]*; *([^;,\\)]+)'\n device_replacement: 'Alcatel $1'\n brand_replacement: 'Alcatel'\n model_replacement: '$1'", " #########\n # Asus Windows Phones\n #########\n #~ - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|WpsLondonTest; ?|)(?:ASUS|Asus)[^;]*; *([^;,\\)]+)'\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|WpsLondonTest; ?|)(?:ASUS|Asus)[^;]*; *([^;,\\)]+)'\n device_replacement: 'Asus $1'\n brand_replacement: 'Asus'\n model_replacement: '$1'", " #########\n # Dell Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|)(?:DELL|Dell)[^;]*; *([^;,\\)]+)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: '$1'", " #########\n # HTC Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|WpsLondonTest; ?|)(?:HTC|Htc|HTC_blocked[^;]*)[^;]*; *(?:HTC|)([^;,\\)]+)'\n device_replacement: 'HTC $1'\n brand_replacement: 'HTC'\n model_replacement: '$1'", " #########\n # Huawei Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|)(?:HUAWEI)[^;]*; *(?:HUAWEI |)([^;,\\)]+)'\n device_replacement: 'Huawei $1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'", " #########\n # LG Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|)(?:LG|Lg)[^;]*; *(?:LG[ \\-]|)([^;,\\)]+)'\n device_replacement: 'LG $1'\n brand_replacement: 'LG'\n model_replacement: '$1'", " #########\n # Noka Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|)(?:rv:11; |)(?:NOKIA|Nokia)[^;]*; *(?:NOKIA ?|Nokia ?|LUMIA ?|[Ll]umia ?|)(\\d{3,10}[^;\\)]*)'\n device_replacement: 'Lumia $1'\n brand_replacement: 'Nokia'\n model_replacement: 'Lumia $1'\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|)(?:NOKIA|Nokia)[^;]*; *(RM-\\d{3,})'\n device_replacement: 'Nokia $1'\n brand_replacement: 'Nokia'\n model_replacement: '$1'\n - regex: '(?:Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)]|WPDesktop;) ?(?:ARM; ?Touch; ?|Touch; ?|)(?:NOKIA|Nokia)[^;]*; *(?:NOKIA ?|Nokia ?|LUMIA ?|[Ll]umia ?|)([^;\\)]+)'\n device_replacement: 'Nokia $1'\n brand_replacement: 'Nokia'\n model_replacement: '$1'", " #########\n # Microsoft Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|)(?:Microsoft(?: Corporation|))[^;]*; *([^;,\\)]+)'\n device_replacement: 'Microsoft $1'\n brand_replacement: 'Microsoft'\n model_replacement: '$1'", " #########\n # Samsung Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|WpsLondonTest; ?|)(?:SAMSUNG)[^;]*; *(?:SAMSUNG |)([^;,\\.\\)]+)'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'", " #########\n # Toshiba Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|WpsLondonTest; ?|)(?:TOSHIBA|FujitsuToshibaMobileCommun)[^;]*; *([^;,\\)]+)'\n device_replacement: 'Toshiba $1'\n brand_replacement: 'Toshiba'\n model_replacement: '$1'", " #########\n # Generic Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|WpsLondonTest; ?|)([^;]+); *([^;,\\)]+)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " ######################################################################\n # Other Devices Parser\n ######################################################################", " #########\n # Samsung Bada Phones\n #########\n - regex: '(?:^|; )SAMSUNG\\-([A-Za-z0-9\\-]+).* Bada/'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'", " #########\n # Firefox OS\n #########\n - regex: '\\(Mobile; ALCATEL ?(One|ONE) ?(Touch|TOUCH) ?([^;/]+?)(?:/[^;]+|); rv:[^\\)]+\\) Gecko/[^\\/]+ Firefox/'\n device_replacement: 'Alcatel $1 $2 $3'\n brand_replacement: 'Alcatel'\n model_replacement: 'One Touch $3'\n - regex: '\\(Mobile; (?:ZTE([^;]+)|(OpenC)); rv:[^\\)]+\\) Gecko/[^\\/]+ Firefox/'\n device_replacement: 'ZTE $1$2'\n brand_replacement: 'ZTE'\n model_replacement: '$1$2'", " #########\n # KaiOS\n #########\n - regex: '\\(Mobile; ALCATEL([A-Za-z0-9\\-]+); rv:[^\\)]+\\) Gecko/[^\\/]+ Firefox/[^\\/]+ KaiOS/'\n device_replacement: 'Alcatel $1'\n brand_replacement: 'Alcatel'\n model_replacement: '$1'\n - regex: '\\(Mobile; LYF\\/([A-Za-z0-9\\-]+)\\/.+;.+rv:[^\\)]+\\) Gecko/[^\\/]+ Firefox/[^\\/]+ KAIOS/'\n device_replacement: 'LYF $1'\n brand_replacement: 'LYF'\n model_replacement: '$1'\n - regex: '\\(Mobile; Nokia_([A-Za-z0-9\\-]+)_.+; rv:[^\\)]+\\) Gecko/[^\\/]+ Firefox/[^\\/]+ KAIOS/'\n device_replacement: 'Nokia $1'\n brand_replacement: 'Nokia'\n model_replacement: '$1'", " ##########\n # NOKIA\n # @note: NokiaN8-00 comes before iphone. Sometimes spoofs iphone\n ##########\n - regex: 'Nokia(N[0-9]+)([A-Za-z_\\-][A-Za-z0-9_\\-]*)'\n device_replacement: 'Nokia $1'\n brand_replacement: 'Nokia'\n model_replacement: '$1$2'\n - regex: '(?:NOKIA|Nokia)(?:\\-| *)(?:([A-Za-z0-9]+)\\-[0-9a-f]{32}|([A-Za-z0-9\\-]+)(?:UCBrowser)|([A-Za-z0-9\\-]+))'\n device_replacement: 'Nokia $1$2$3'\n brand_replacement: 'Nokia'\n model_replacement: '$1$2$3'\n - regex: 'Lumia ([A-Za-z0-9\\-]+)'\n device_replacement: 'Lumia $1'\n brand_replacement: 'Nokia'\n model_replacement: 'Lumia $1'\n # UCWEB Browser on Symbian\n - regex: '\\(Symbian; U; S60 V5; [A-z]{2}\\-[A-z]{2}; (SonyEricsson|Samsung|Nokia|LG)([^;/]+?)\\)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'\n # Nokia Symbian\n - regex: '\\(Symbian(?:/3|); U; ([^;]+);'\n device_replacement: 'Nokia $1'\n brand_replacement: 'Nokia'\n model_replacement: '$1'", " ##########\n # BlackBerry\n # @ref: http://www.useragentstring.com/pages/BlackBerry/\n ##########\n - regex: 'BB10; ([A-Za-z0-9\\- ]+)\\)'\n device_replacement: 'BlackBerry $1'\n brand_replacement: 'BlackBerry'\n model_replacement: '$1'\n - regex: 'Play[Bb]ook.+RIM Tablet OS'\n device_replacement: 'BlackBerry Playbook'\n brand_replacement: 'BlackBerry'\n model_replacement: 'Playbook'\n - regex: 'Black[Bb]erry ([0-9]+);'\n device_replacement: 'BlackBerry $1'\n brand_replacement: 'BlackBerry'\n model_replacement: '$1'\n - regex: 'Black[Bb]erry([0-9]+)'\n device_replacement: 'BlackBerry $1'\n brand_replacement: 'BlackBerry'\n model_replacement: '$1'\n - regex: 'Black[Bb]erry;'\n device_replacement: 'BlackBerry'\n brand_replacement: 'BlackBerry'", " ##########\n # PALM / HP\n # @note: some palm devices must come before iphone. sometimes spoofs iphone in ua\n ##########\n - regex: '(Pre|Pixi)/\\d+\\.\\d+'\n device_replacement: 'Palm $1'\n brand_replacement: 'Palm'\n model_replacement: '$1'\n - regex: 'Palm([0-9]+)'\n device_replacement: 'Palm $1'\n brand_replacement: 'Palm'\n model_replacement: '$1'\n - regex: 'Treo([A-Za-z0-9]+)'\n device_replacement: 'Palm Treo $1'\n brand_replacement: 'Palm'\n model_replacement: 'Treo $1'\n - regex: 'webOS.*(P160U(?:NA|))/(\\d+).(\\d+)'\n device_replacement: 'HP Veer'\n brand_replacement: 'HP'\n model_replacement: 'Veer'\n - regex: '(Touch[Pp]ad)/\\d+\\.\\d+'\n device_replacement: 'HP TouchPad'\n brand_replacement: 'HP'\n model_replacement: 'TouchPad'\n - regex: 'HPiPAQ([A-Za-z0-9]+)/\\d+.\\d+'\n device_replacement: 'HP iPAQ $1'\n brand_replacement: 'HP'\n model_replacement: 'iPAQ $1'\n - regex: 'PDA; (PalmOS)/sony/model ([a-z]+)/Revision'\n device_replacement: '$1'\n brand_replacement: 'Sony'\n model_replacement: '$1 $2'", " ##########\n # AppleTV\n # No built in browser that I can tell\n # Stack Overflow indicated iTunes-AppleTV/4.1 as a known UA for app available and I'm seeing it in live traffic\n ##########\n - regex: '(Apple\\s?TV)'\n device_replacement: 'AppleTV'\n brand_replacement: 'Apple'\n model_replacement: 'AppleTV'", " #########\n # Tesla Model S\n #########\n - regex: '(QtCarBrowser)'\n device_replacement: 'Tesla Model S'\n brand_replacement: 'Tesla'\n model_replacement: 'Model S'", " ##########\n # iSTUFF\n # @note: complete but probably catches spoofs\n # ipad and ipod must be parsed before iphone\n # cannot determine specific device type from ua string. (3g, 3gs, 4, etc)\n ##########\n # @note: on some ua the device can be identified e.g. iPhone5,1\n - regex: '(iPhone|iPad|iPod)(\\d+,\\d+)'\n device_replacement: '$1'\n brand_replacement: 'Apple'\n model_replacement: '$1$2'\n # @note: iPad needs to be before iPhone\n - regex: '(iPad)(?:;| Simulator;)'\n device_replacement: '$1'\n brand_replacement: 'Apple'\n model_replacement: '$1'\n - regex: '(iPod)(?:;| touch;| Simulator;)'\n device_replacement: '$1'\n brand_replacement: 'Apple'\n model_replacement: '$1'\n - regex: '(iPhone)(?:;| Simulator;)'\n device_replacement: '$1'\n brand_replacement: 'Apple'\n model_replacement: '$1'\n - regex: '(Watch)(\\d+,\\d+)'\n device_replacement: 'Apple $1'\n brand_replacement: 'Apple'\n model_replacement: '$1$2'\n - regex: '(Apple Watch)(?:;| Simulator;)'\n device_replacement: '$1'\n brand_replacement: 'Apple'\n model_replacement: '$1'\n - regex: '(HomePod)(?:;| Simulator;)'\n device_replacement: '$1'\n brand_replacement: 'Apple'\n model_replacement: '$1'\n - regex: 'iPhone'\n device_replacement: 'iPhone'\n brand_replacement: 'Apple'\n model_replacement: 'iPhone'\n # @note: desktop applications show device info\n - regex: 'CFNetwork/.* Darwin/\\d.*\\(((?:Mac|iMac|PowerMac|PowerBook)[^\\d]*)(\\d+)(?:,|%2C)(\\d+)'\n device_replacement: '$1$2,$3'\n brand_replacement: 'Apple'\n model_replacement: '$1$2,$3'\n # @note: newer desktop applications don't show device info\n # This is here so as to not have them recorded as iOS-Device\n - regex: 'CFNetwork/.* Darwin/\\d+\\.\\d+\\.\\d+ \\(x86_64\\)'\n device_replacement: 'Mac'\n brand_replacement: 'Apple'\n model_replacement: 'Mac'\n # @note: iOS applications do not show device info\n - regex: 'CFNetwork/.* Darwin/\\d'\n device_replacement: 'iOS-Device'\n brand_replacement: 'Apple'\n model_replacement: 'iOS-Device'", " ##########################\n # Outlook on iOS >= 2.62.0\n ##########################\n - regex: 'Outlook-(iOS)/\\d+\\.\\d+\\.prod\\.iphone'\n brand_replacement: 'Apple'\n device_replacement: 'iPhone'\n model_replacement: 'iPhone'", " ##########\n # Acer\n ##########\n - regex: 'acer_([A-Za-z0-9]+)_'\n device_replacement: 'Acer $1'\n brand_replacement: 'Acer'\n model_replacement: '$1'", " ##########\n # Alcatel\n ##########\n - regex: '(?:ALCATEL|Alcatel)-([A-Za-z0-9\\-]+)'\n device_replacement: 'Alcatel $1'\n brand_replacement: 'Alcatel'\n model_replacement: '$1'", " ##########\n # Amoi\n ##########\n - regex: '(?:Amoi|AMOI)\\-([A-Za-z0-9]+)'\n device_replacement: 'Amoi $1'\n brand_replacement: 'Amoi'\n model_replacement: '$1'", " ##########\n # Asus\n ##########\n - regex: '(?:; |\\/|^)((?:Transformer (?:Pad|Prime) |Transformer |PadFone[ _]?)[A-Za-z0-9]*)'\n device_replacement: 'Asus $1'\n brand_replacement: 'Asus'\n model_replacement: '$1'\n - regex: '(?:asus.*?ASUS|Asus|ASUS|asus)[\\- ;]*((?:Transformer (?:Pad|Prime) |Transformer |Padfone |Nexus[ _]|)[A-Za-z0-9]+)'\n device_replacement: 'Asus $1'\n brand_replacement: 'Asus'\n model_replacement: '$1'\n - regex: '(?:ASUS)_([A-Za-z0-9\\-]+)'\n device_replacement: 'Asus $1'\n brand_replacement: 'Asus'\n model_replacement: '$1'", "\n ##########\n # Bird\n ##########\n - regex: '\\bBIRD[ \\-\\.]([A-Za-z0-9]+)'\n device_replacement: 'Bird $1'\n brand_replacement: 'Bird'\n model_replacement: '$1'", " ##########\n # Dell\n ##########\n - regex: '\\bDell ([A-Za-z0-9]+)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: '$1'", " ##########\n # DoCoMo\n ##########\n - regex: 'DoCoMo/2\\.0 ([A-Za-z0-9]+)'\n device_replacement: 'DoCoMo $1'\n brand_replacement: 'DoCoMo'\n model_replacement: '$1'\n - regex: '([A-Za-z0-9]+)_W;FOMA'\n device_replacement: 'DoCoMo $1'\n brand_replacement: 'DoCoMo'\n model_replacement: '$1'\n - regex: '([A-Za-z0-9]+);FOMA'\n device_replacement: 'DoCoMo $1'\n brand_replacement: 'DoCoMo'\n model_replacement: '$1'", " ##########\n # htc\n ##########\n - regex: '\\b(?:HTC/|HTC/[a-z0-9]+/|)HTC[ _\\-;]? *(.*?)(?:-?Mozilla|fingerPrint|[;/\\(\\)]|$)'\n device_replacement: 'HTC $1'\n brand_replacement: 'HTC'\n model_replacement: '$1'", " ##########\n # Huawei\n ##########\n - regex: 'Huawei([A-Za-z0-9]+)'\n device_replacement: 'Huawei $1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'\n - regex: 'HUAWEI-([A-Za-z0-9]+)'\n device_replacement: 'Huawei $1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'\n - regex: 'HUAWEI ([A-Za-z0-9\\-]+)'\n device_replacement: 'Huawei $1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'\n - regex: 'vodafone([A-Za-z0-9]+)'\n device_replacement: 'Huawei Vodafone $1'\n brand_replacement: 'Huawei'\n model_replacement: 'Vodafone $1'", " ##########\n # i-mate\n ##########\n - regex: 'i\\-mate ([A-Za-z0-9]+)'\n device_replacement: 'i-mate $1'\n brand_replacement: 'i-mate'\n model_replacement: '$1'", " ##########\n # kyocera\n ##########\n - regex: 'Kyocera\\-([A-Za-z0-9]+)'\n device_replacement: 'Kyocera $1'\n brand_replacement: 'Kyocera'\n model_replacement: '$1'\n - regex: 'KWC\\-([A-Za-z0-9]+)'\n device_replacement: 'Kyocera $1'\n brand_replacement: 'Kyocera'\n model_replacement: '$1'", " ##########\n # lenovo\n ##########\n - regex: 'Lenovo[_\\-]([A-Za-z0-9]+)'\n device_replacement: 'Lenovo $1'\n brand_replacement: 'Lenovo'\n model_replacement: '$1'", " ##########\n # HbbTV (European and Australian standard)\n # written before the LG regexes, as LG is making HbbTV too\n ##########", " - regex: '(HbbTV)/[0-9]+\\.[0-9]+\\.[0-9]+ \\([^;]*; *(LG)E *; *([^;]*) *;[^;]*;[^;]*;\\)'", " device_replacement: '$1'\n brand_replacement: '$2'\n model_replacement: '$3'\n - regex: '(HbbTV)/1\\.1\\.1.*CE-HTML/1\\.\\d;(Vendor/|)(THOM[^;]*?)[;\\s].{0,30}(LF[^;]+);?'\n device_replacement: '$1'\n brand_replacement: 'Thomson'\n model_replacement: '$4'\n - regex: '(HbbTV)(?:/1\\.1\\.1|) ?(?: \\(;;;;;\\)|); *CE-HTML(?:/1\\.\\d|); *([^ ]+) ([^;]+);'\n device_replacement: '$1'\n brand_replacement: '$2'\n model_replacement: '$3'\n - regex: '(HbbTV)/1\\.1\\.1 \\(;;;;;\\) Maple_2011'\n device_replacement: '$1'\n brand_replacement: 'Samsung'", " - regex: '(HbbTV)/[0-9]+\\.[0-9]+\\.[0-9]+ \\([^;]*; *(?:CUS:([^;]*)|([^;]+)) *; *([^;]*) *;.*;'", " device_replacement: '$1'\n brand_replacement: '$2$3'\n model_replacement: '$4'\n - regex: '(HbbTV)/[0-9]+\\.[0-9]+\\.[0-9]+'\n device_replacement: '$1'", " ##########\n # LGE NetCast TV\n ##########\n - regex: 'LGE; (?:Media\\/|)([^;]*);[^;]*;[^;]*;?\\); \"?LG NetCast(\\.TV|\\.Media|)-\\d+'\n device_replacement: 'NetCast$2'\n brand_replacement: 'LG'\n model_replacement: '$1'", " ##########\n # InettvBrowser\n ##########\n - regex: 'InettvBrowser/[0-9]+\\.[0-9A-Z]+ \\([^;]*;(Sony)([^;]*);[^;]*;[^\\)]*\\)'\n device_replacement: 'Inettv'\n brand_replacement: '$1'\n model_replacement: '$2'\n - regex: 'InettvBrowser/[0-9]+\\.[0-9A-Z]+ \\([^;]*;([^;]*);[^;]*;[^\\)]*\\)'\n device_replacement: 'Inettv'\n brand_replacement: 'Generic_Inettv'\n model_replacement: '$1'\n - regex: '(?:InettvBrowser|TSBNetTV|NETTV|HBBTV)'\n device_replacement: 'Inettv'\n brand_replacement: 'Generic_Inettv'", " ##########\n # lg\n ##########\n # LG Symbian Phones\n - regex: 'Series60/\\d\\.\\d (LG)[\\-]?([A-Za-z0-9 \\-]+)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'\n # other LG phones\n - regex: '\\b(?:LGE[ \\-]LG\\-(?:AX|)|LGE |LGE?-LG|LGE?[ \\-]|LG[ /\\-]|lg[\\-])([A-Za-z0-9]+)\\b'\n device_replacement: 'LG $1'\n brand_replacement: 'LG'\n model_replacement: '$1'\n - regex: '(?:^LG[\\-]?|^LGE[\\-/]?)([A-Za-z]+[0-9]+[A-Za-z]*)'\n device_replacement: 'LG $1'\n brand_replacement: 'LG'\n model_replacement: '$1'\n - regex: '^LG([0-9]+[A-Za-z]*)'\n device_replacement: 'LG $1'\n brand_replacement: 'LG'\n model_replacement: '$1'", " ##########\n # microsoft\n ##########\n - regex: '(KIN\\.[^ ]+) (\\d+)\\.(\\d+)'\n device_replacement: 'Microsoft $1'\n brand_replacement: 'Microsoft'\n model_replacement: '$1'\n - regex: '(?:MSIE|XBMC).*\\b(Xbox)\\b'\n device_replacement: '$1'\n brand_replacement: 'Microsoft'\n model_replacement: '$1'\n - regex: '; ARM; Trident/6\\.0; Touch[\\);]'\n device_replacement: 'Microsoft Surface RT'\n brand_replacement: 'Microsoft'\n model_replacement: 'Surface RT'", " ##########\n # motorola\n ##########\n - regex: 'Motorola\\-([A-Za-z0-9]+)'\n device_replacement: 'Motorola $1'\n brand_replacement: 'Motorola'\n model_replacement: '$1'\n - regex: 'MOTO\\-([A-Za-z0-9]+)'\n device_replacement: 'Motorola $1'\n brand_replacement: 'Motorola'\n model_replacement: '$1'\n - regex: 'MOT\\-([A-z0-9][A-z0-9\\-]*)'\n device_replacement: 'Motorola $1'\n brand_replacement: 'Motorola'\n model_replacement: '$1'", " ##########\n # nintendo\n ##########\n - regex: 'Nintendo WiiU'\n device_replacement: 'Nintendo Wii U'\n brand_replacement: 'Nintendo'\n model_replacement: 'Wii U'\n - regex: 'Nintendo (DS|3DS|DSi|Wii);'\n device_replacement: 'Nintendo $1'\n brand_replacement: 'Nintendo'\n model_replacement: '$1'", " ##########\n # pantech\n ##########\n - regex: '(?:Pantech|PANTECH)[ _-]?([A-Za-z0-9\\-]+)'\n device_replacement: 'Pantech $1'\n brand_replacement: 'Pantech'\n model_replacement: '$1'", " ##########\n # philips\n ##########\n - regex: 'Philips([A-Za-z0-9]+)'\n device_replacement: 'Philips $1'\n brand_replacement: 'Philips'\n model_replacement: '$1'\n - regex: 'Philips ([A-Za-z0-9]+)'\n device_replacement: 'Philips $1'\n brand_replacement: 'Philips'\n model_replacement: '$1'", " ##########\n # Samsung\n ##########\n # Samsung Smart-TV\n - regex: '(SMART-TV); .* Tizen '\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n # Samsung Symbian Devices\n - regex: 'SymbianOS/9\\.\\d.* Samsung[/\\-]([A-Za-z0-9 \\-]+)'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n - regex: '(Samsung)(SGH)(i[0-9]+)'\n device_replacement: '$1 $2$3'\n brand_replacement: '$1'\n model_replacement: '$2-$3'\n - regex: 'SAMSUNG-ANDROID-MMS/([^;/]+)'\n device_replacement: '$1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n # Other Samsung\n #- regex: 'SAMSUNG(?:; |-)([A-Za-z0-9\\-]+)'\n - regex: 'SAMSUNG(?:; |[ -/])([A-Za-z0-9\\-]+)'\n regex_flag: 'i'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'", " ##########\n # Sega\n ##########\n - regex: '(Dreamcast)'\n device_replacement: 'Sega $1'\n brand_replacement: 'Sega'\n model_replacement: '$1'", " ##########\n # Siemens mobile\n ##########\n - regex: '^SIE-([A-Za-z0-9]+)'\n device_replacement: 'Siemens $1'\n brand_replacement: 'Siemens'\n model_replacement: '$1'", " ##########\n # Softbank\n ##########\n - regex: 'Softbank/[12]\\.0/([A-Za-z0-9]+)'\n device_replacement: 'Softbank $1'\n brand_replacement: 'Softbank'\n model_replacement: '$1'", " ##########\n # SonyEricsson\n ##########\n - regex: 'SonyEricsson ?([A-Za-z0-9\\-]+)'\n device_replacement: 'Ericsson $1'\n brand_replacement: 'SonyEricsson'\n model_replacement: '$1'", " ##########\n # Sony\n ##########\n - regex: 'Android [^;]+; ([^ ]+) (Sony)/'\n device_replacement: '$2 $1'\n brand_replacement: '$2'\n model_replacement: '$1'\n - regex: '(Sony)(?:BDP\\/|\\/|)([^ /;\\)]+)[ /;\\)]'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " #########\n # Puffin Browser Device detect\n # A=Android, I=iOS, P=Phone, T=Tablet\n # AT=Android+Tablet\n #########\n - regex: 'Puffin/[\\d\\.]+IT'\n device_replacement: 'iPad'\n brand_replacement: 'Apple'\n model_replacement: 'iPad'\n - regex: 'Puffin/[\\d\\.]+IP'\n device_replacement: 'iPhone'\n brand_replacement: 'Apple'\n model_replacement: 'iPhone'\n - regex: 'Puffin/[\\d\\.]+AT'\n device_replacement: 'Generic Tablet'\n brand_replacement: 'Generic'\n model_replacement: 'Tablet'\n - regex: 'Puffin/[\\d\\.]+AP'\n device_replacement: 'Generic Smartphone'\n brand_replacement: 'Generic'\n model_replacement: 'Smartphone'", " #########\n # Android General Device Matching (far from perfect)\n #########\n - regex: 'Android[\\- ][\\d]+\\.[\\d]+; [A-Za-z]{2}\\-[A-Za-z]{0,2}; WOWMobile (.+)( Build[/ ]|\\))'\n brand_replacement: 'Generic_Android'\n model_replacement: '$1'\n - regex: 'Android[\\- ][\\d]+\\.[\\d]+\\-update1; [A-Za-z]{2}\\-[A-Za-z]{0,2} *; *(.+?)( Build[/ ]|\\))'\n brand_replacement: 'Generic_Android'\n model_replacement: '$1'\n - regex: 'Android[\\- ][\\d]+(?:\\.[\\d]+)(?:\\.[\\d]+|); *[A-Za-z]{2}[_\\-][A-Za-z]{0,2}\\-? *; *(.+?)( Build[/ ]|\\))'\n brand_replacement: 'Generic_Android'\n model_replacement: '$1'\n - regex: 'Android[\\- ][\\d]+(?:\\.[\\d]+)(?:\\.[\\d]+|); *[A-Za-z]{0,2}\\- *; *(.+?)( Build[/ ]|\\))'\n brand_replacement: 'Generic_Android'\n model_replacement: '$1'\n # No build info at all - \"Build\" follows locale immediately\n - regex: 'Android[\\- ][\\d]+(?:\\.[\\d]+)(?:\\.[\\d]+|); *[a-z]{0,2}[_\\-]?[A-Za-z]{0,2};?( Build[/ ]|\\))'\n device_replacement: 'Generic Smartphone'\n brand_replacement: 'Generic'\n model_replacement: 'Smartphone'\n - regex: 'Android[\\- ][\\d]+(?:\\.[\\d]+)(?:\\.[\\d]+|); *\\-?[A-Za-z]{2}; *(.+?)( Build[/ ]|\\))'\n brand_replacement: 'Generic_Android'\n model_replacement: '$1'\n - regex: 'Android \\d+?(?:\\.\\d+|)(?:\\.\\d+|); ([^;]+?)(?: Build|\\) AppleWebKit).+? Mobile Safari'\n brand_replacement: 'Generic_Android'\n model_replacement: '$1'\n - regex: 'Android \\d+?(?:\\.\\d+|)(?:\\.\\d+|); ([^;]+?)(?: Build|\\) AppleWebKit).+? Safari'\n brand_replacement: 'Generic_Android_Tablet'\n model_replacement: '$1'\n - regex: 'Android \\d+?(?:\\.\\d+|)(?:\\.\\d+|); ([^;]+?)(?: Build|\\))'\n brand_replacement: 'Generic_Android'\n model_replacement: '$1'", " ##########\n # Google TV\n ##########\n - regex: '(GoogleTV)'\n brand_replacement: 'Generic_Inettv'\n model_replacement: '$1'", " ##########\n # WebTV\n ##########\n - regex: '(WebTV)/\\d+.\\d+'\n brand_replacement: 'Generic_Inettv'\n model_replacement: '$1'\n # Roku Digital-Video-Players https://www.roku.com/\n - regex: '^(Roku)/DVP-\\d+\\.\\d+'\n brand_replacement: 'Generic_Inettv'\n model_replacement: '$1'", " ##########\n # Generic Tablet\n ##########\n - regex: '(Android 3\\.\\d|Opera Tablet|Tablet; .+Firefox/|Android.*(?:Tab|Pad))'\n regex_flag: 'i'\n device_replacement: 'Generic Tablet'\n brand_replacement: 'Generic'\n model_replacement: 'Tablet'", " ##########\n # Generic Smart Phone\n ##########\n - regex: '(Symbian|\\bS60(Version|V\\d)|\\bS60\\b|\\((Series 60|Windows Mobile|Palm OS|Bada); Opera Mini|Windows CE|Opera Mobi|BREW|Brew|Mobile; .+Firefox/|iPhone OS|Android|MobileSafari|Windows *Phone|\\(webOS/|PalmOS)'\n device_replacement: 'Generic Smartphone'\n brand_replacement: 'Generic'\n model_replacement: 'Smartphone'\n - regex: '(hiptop|avantgo|plucker|xiino|blazer|elaine)'\n regex_flag: 'i'\n device_replacement: 'Generic Smartphone'\n brand_replacement: 'Generic'\n model_replacement: 'Smartphone'", " ##########\n # Spiders (this is a hack...)\n ##########\n - regex: '(bot|BUbiNG|zao|borg|DBot|oegp|silk|Xenu|zeal|^NING|CCBot|crawl|htdig|lycos|slurp|teoma|voila|yahoo|Sogou|CiBra|Nutch|^Java/|^JNLP/|Daumoa|Daum|Genieo|ichiro|larbin|pompos|Scrapy|snappy|speedy|spider|msnbot|msrbot|vortex|^vortex|crawler|favicon|indexer|Riddler|scooter|scraper|scrubby|WhatWeb|WinHTTP|bingbot|BingPreview|openbot|gigabot|furlbot|polybot|seekbot|^voyager|archiver|Icarus6j|mogimogi|Netvibes|blitzbot|altavista|charlotte|findlinks|Retreiver|TLSProber|WordPress|SeznamBot|ProoXiBot|wsr\\-agent|Squrl Java|EtaoSpider|PaperLiBot|SputnikBot|A6\\-Indexer|netresearch|searchsight|baiduspider|YisouSpider|ICC\\-Crawler|http%20client|Python-urllib|dataparksearch|converacrawler|Screaming Frog|AppEngine-Google|YahooCacheSystem|fast\\-webcrawler|Sogou Pic Spider|semanticdiscovery|Innovazion Crawler|facebookexternalhit|Google.*/\\+/web/snippet|Google-HTTP-Java-Client|BlogBridge|IlTrovatore-Setaccio|InternetArchive|GomezAgent|WebThumbnail|heritrix|NewsGator|PagePeeker|Reaper|ZooShot|holmes|NL-Crawler|Pingdom|StatusCake|WhatsApp|masscan|Google Web Preview|Qwantify|Yeti|OgScrper)'\n regex_flag: 'i'\n device_replacement: 'Spider'\n brand_replacement: 'Spider'\n model_replacement: 'Desktop'", " ##########\n # Generic Feature Phone\n # take care to do case insensitive matching\n ##########\n - regex: '^(1207|3gso|4thp|501i|502i|503i|504i|505i|506i|6310|6590|770s|802s|a wa|acer|acs\\-|airn|alav|asus|attw|au\\-m|aur |aus |abac|acoo|aiko|alco|alca|amoi|anex|anny|anyw|aptu|arch|argo|bmobile|bell|bird|bw\\-n|bw\\-u|beck|benq|bilb|blac|c55/|cdm\\-|chtm|capi|comp|cond|dall|dbte|dc\\-s|dica|ds\\-d|ds12|dait|devi|dmob|doco|dopo|dorado|el(?:38|39|48|49|50|55|58|68)|el[3456]\\d{2}dual|erk0|esl8|ex300|ez40|ez60|ez70|ezos|ezze|elai|emul|eric|ezwa|fake|fly\\-|fly_|g\\-mo|g1 u|g560|gf\\-5|grun|gene|go.w|good|grad|hcit|hd\\-m|hd\\-p|hd\\-t|hei\\-|hp i|hpip|hs\\-c|htc |htc\\-|htca|htcg)'\n regex_flag: 'i'\n device_replacement: 'Generic Feature Phone'\n brand_replacement: 'Generic'\n model_replacement: 'Feature Phone'\n - regex: '^(htcp|htcs|htct|htc_|haie|hita|huaw|hutc|i\\-20|i\\-go|i\\-ma|i\\-mobile|i230|iac|iac\\-|iac/|ig01|im1k|inno|iris|jata|kddi|kgt|kgt/|kpt |kwc\\-|klon|lexi|lg g|lg\\-a|lg\\-b|lg\\-c|lg\\-d|lg\\-f|lg\\-g|lg\\-k|lg\\-l|lg\\-m|lg\\-o|lg\\-p|lg\\-s|lg\\-t|lg\\-u|lg\\-w|lg/k|lg/l|lg/u|lg50|lg54|lge\\-|lge/|leno|m1\\-w|m3ga|m50/|maui|mc01|mc21|mcca|medi|meri|mio8|mioa|mo01|mo02|mode|modo|mot |mot\\-|mt50|mtp1|mtv |mate|maxo|merc|mits|mobi|motv|mozz|n100|n101|n102|n202|n203|n300|n302|n500|n502|n505|n700|n701|n710|nec\\-|nem\\-|newg|neon)'\n regex_flag: 'i'\n device_replacement: 'Generic Feature Phone'\n brand_replacement: 'Generic'\n model_replacement: 'Feature Phone'\n - regex: '^(netf|noki|nzph|o2 x|o2\\-x|opwv|owg1|opti|oran|ot\\-s|p800|pand|pg\\-1|pg\\-2|pg\\-3|pg\\-6|pg\\-8|pg\\-c|pg13|phil|pn\\-2|pt\\-g|palm|pana|pire|pock|pose|psio|qa\\-a|qc\\-2|qc\\-3|qc\\-5|qc\\-7|qc07|qc12|qc21|qc32|qc60|qci\\-|qwap|qtek|r380|r600|raks|rim9|rove|s55/|sage|sams|sc01|sch\\-|scp\\-|sdk/|se47|sec\\-|sec0|sec1|semc|sgh\\-|shar|sie\\-|sk\\-0|sl45|slid|smb3|smt5|sp01|sph\\-|spv |spv\\-|sy01|samm|sany|sava|scoo|send|siem|smar|smit|soft|sony|t\\-mo|t218|t250|t600|t610|t618|tcl\\-|tdg\\-|telm|tim\\-|ts70|tsm\\-|tsm3|tsm5|tx\\-9|tagt)'\n regex_flag: 'i'\n device_replacement: 'Generic Feature Phone'\n brand_replacement: 'Generic'\n model_replacement: 'Feature Phone'\n - regex: '^(talk|teli|topl|tosh|up.b|upg1|utst|v400|v750|veri|vk\\-v|vk40|vk50|vk52|vk53|vm40|vx98|virg|vertu|vite|voda|vulc|w3c |w3c\\-|wapj|wapp|wapu|wapm|wig |wapi|wapr|wapv|wapy|wapa|waps|wapt|winc|winw|wonu|x700|xda2|xdag|yas\\-|your|zte\\-|zeto|aste|audi|avan|blaz|brew|brvw|bumb|ccwa|cell|cldc|cmd\\-|dang|eml2|fetc|hipt|http|ibro|idea|ikom|ipaq|jbro|jemu|jigs|keji|kyoc|kyok|libw|m\\-cr|midp|mmef|moto|mwbp|mywa|newt|nok6|o2im|pant|pdxg|play|pluc|port|prox|rozo|sama|seri|smal|symb|treo|upsi|vx52|vx53|vx60|vx61|vx70|vx80|vx81|vx83|vx85|wap\\-|webc|whit|wmlb|xda\\-|xda_)'\n regex_flag: 'i'\n device_replacement: 'Generic Feature Phone'\n brand_replacement: 'Generic'\n model_replacement: 'Feature Phone'\n - regex: '^(Ice)$'\n device_replacement: 'Generic Feature Phone'\n brand_replacement: 'Generic'\n model_replacement: 'Feature Phone'\n - regex: '(wap[\\-\\ ]browser|maui|netfront|obigo|teleca|up\\.browser|midp|Opera Mini)'\n regex_flag: 'i'\n device_replacement: 'Generic Feature Phone'\n brand_replacement: 'Generic'\n model_replacement: 'Feature Phone'" ]
[ 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5145, 50], "buggy_code_start_loc": [1575, 43], "filenames": ["regexes.yaml", "tests/regexes.js"], "fixing_code_end_loc": [5145, 88], "fixing_code_start_loc": [1575, 43], "message": "uap-core before 0.7.3 is vulnerable to a denial of service attack when processing crafted User-Agent strings. Some regexes are vulnerable to regular expression denial of service (REDoS) due to overlapping capture groups. This allows remote attackers to overload a server by setting the User-Agent header in an HTTP(S) request to maliciously crafted long strings. This has been patched in uap-core 0.7.3.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:uap-core_project:uap-core:*:*:*:*:*:*:*:*", "matchCriteriaId": "E93CB3F6-D527-456D-ADDB-C3D911A1815D", "versionEndExcluding": "0.7.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "uap-core before 0.7.3 is vulnerable to a denial of service attack when processing crafted User-Agent strings. Some regexes are vulnerable to regular expression denial of service (REDoS) due to overlapping capture groups. This allows remote attackers to overload a server by setting the User-Agent header in an HTTP(S) request to maliciously crafted long strings. This has been patched in uap-core 0.7.3."}, {"lang": "es", "value": "uap-core versiones anteriores a 0.7.3, es vulnerable a un ataque de denegaci\u00f3n de servicio cuando se procesan cadenas de User-Agent dise\u00f1adas. Algunas expresiones regulares son vulnerables a una denegaci\u00f3n de servicio de expresi\u00f3n regular (REDoS) debido a una superposici\u00f3n de grupos de captura. Esto permite a atacantes remotos sobrecargar un servidor mediante la configuraci\u00f3n del encabezado User-Agent en una petici\u00f3n HTTP(S) para cadenas largas dise\u00f1adas maliciosamente. Esto ha sido parcheado en uap-core versi\u00f3n 0.7.3."}], "evaluatorComment": null, "id": "CVE-2020-5243", "lastModified": "2020-02-25T19:44:54.697", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-02-21T00:15:10.960", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ua-parser/uap-core/commit/0afd61ed85396a3b5316f18bfd1edfaadf8e88e1"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/ua-parser/uap-core/security/advisories/GHSA-cmcx-xhr8-3w9p"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-400"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-20"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/ua-parser/uap-core/commit/0afd61ed85396a3b5316f18bfd1edfaadf8e88e1"}, "type": "CWE-400"}
194
Determine whether the {function_name} code is vulnerable or not.
[ "user_agent_parsers:\n #### SPECIAL CASES TOP ####", " # CFNetwork Podcast catcher Applications\n - regex: '^(Luminary)[Stage]+/(\\d+) CFNetwork'\n - regex: '(ESPN)[%20| ]+Radio/(\\d+)\\.(\\d+)\\.(\\d+) CFNetwork'\n - regex: '(Antenna)/(\\d+) CFNetwork'\n family_replacement: 'AntennaPod'\n - regex: '(TopPodcasts)Pro/(\\d+) CFNetwork'\n - regex: '(MusicDownloader)Lite/(\\d+)\\.(\\d+)\\.(\\d+) CFNetwork'\n - regex: '^(.*)-iPad\\/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)(?:\\.(\\d+)|) CFNetwork'\n - regex: '^(.*)-iPhone/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)(?:\\.(\\d+)|) CFNetwork'\n - regex: '^(.*)/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)(?:\\.(\\d+)|) CFNetwork'", " # Podcast catchers\n - regex: '^(Luminary)/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'\n - regex: '(espn\\.go)'\n family_replacement: 'ESPN'\n - regex: '(espnradio\\.com)'\n family_replacement: 'ESPN'\n - regex: 'ESPN APP$'\n family_replacement: 'ESPN'\n - regex: '(audioboom\\.com)'\n family_replacement: 'AudioBoom'\n - regex: ' (Rivo) RHYTHM'", " # @note: iOS / OSX Applications\n - regex: '(CFNetwork)(?:/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)|)'\n family_replacement: 'CFNetwork'", " # Pingdom\n - regex: '(Pingdom\\.com_bot_version_)(\\d+)\\.(\\d+)'\n family_replacement: 'PingdomBot'\n # 'Mozilla/5.0 (Unknown; Linux x86_64) AppleWebKit/534.34 (KHTML, like Gecko) PingdomTMS/0.8.5 Safari/534.34'\n - regex: '(PingdomTMS)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'PingdomBot'", " # PTST / WebPageTest.org crawlers\n - regex: ' (PTST)/(\\d+)(?:\\.(\\d+)|)$'\n family_replacement: 'WebPageTest.org bot'", " # Datanyze.com spider\n - regex: 'X11; (Datanyze); Linux'", " # New Relic Pinger\n - regex: '(NewRelicPinger)/(\\d+)\\.(\\d+)'\n family_replacement: 'NewRelicPingerBot'", " # Tableau\n - regex: '(Tableau)/(\\d+)\\.(\\d+)'\n family_replacement: 'Tableau'", " # Adobe CreativeCloud\n - regex: 'AppleWebKit/\\d+\\.\\d+.* Safari.* (CreativeCloud)/(\\d+)\\.(\\d+).(\\d+)'\n family_replacement: 'Adobe CreativeCloud'", " # Salesforce\n - regex: '(Salesforce)(?:.)\\/(\\d+)\\.(\\d?)'", " #StatusCake\n - regex: '(\\(StatusCake\\))'\n family_replacement: 'StatusCakeBot'", " # Facebook\n - regex: '(facebookexternalhit)/(\\d+)\\.(\\d+)'\n family_replacement: 'FacebookBot'", " # Google Plus\n - regex: 'Google.*/\\+/web/snippet'\n family_replacement: 'GooglePlusBot'", " # Gmail\n - regex: 'via ggpht\\.com GoogleImageProxy'\n family_replacement: 'GmailImageProxy'", " # Yahoo\n - regex: 'YahooMailProxy; https://help\\.yahoo\\.com/kb/yahoo-mail-proxy-SLN28749\\.html'\n family_replacement: 'YahooMailProxy'", " # Twitter\n - regex: '(Twitterbot)/(\\d+)\\.(\\d+)'\n family_replacement: 'Twitterbot'", " # Bots Pattern 'name/0.0.0'\n - regex: '/((?:Ant-|)Nutch|[A-z]+[Bb]ot|[A-z]+[Ss]pider|Axtaris|fetchurl|Isara|ShopSalad|Tailsweep)[ \\-](\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'\n # Bots Pattern 'name/0.0.0'\n - regex: '\\b(008|Altresium|Argus|BaiduMobaider|BoardReader|DNSGroup|DataparkSearch|EDI|Goodzer|Grub|INGRID|Infohelfer|LinkedInBot|LOOQ|Nutch|OgScrper|PathDefender|Peew|PostPost|Steeler|Twitterbot|VSE|WebCrunch|WebZIP|Y!J-BR[A-Z]|YahooSeeker|envolk|sproose|wminer)/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'", " # MSIECrawler\n - regex: '(MSIE) (\\d+)\\.(\\d+)([a-z]\\d|[a-z]|);.* MSIECrawler'\n family_replacement: 'MSIECrawler'", " # DAVdroid\n - regex: '(DAVdroid)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'", " # Downloader ...\n - regex: '(Google-HTTP-Java-Client|Apache-HttpClient|Go-http-client|scalaj-http|http%20client|Python-urllib|HttpMonitor|TLSProber|WinHTTP|JNLP|okhttp|aihttp|reqwest|axios|unirest-(?:java|python|ruby|nodejs|php|net))(?:[ /](\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)|)'", " # Pinterestbot\n - regex: '(Pinterest(?:bot|))/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)[;\\s(]+\\+https://www.pinterest.com/bot.html'\n family_replacement: 'Pinterestbot'", " # Bots\n - regex: '(CSimpleSpider|Cityreview Robot|CrawlDaddy|CrawlFire|Finderbots|Index crawler|Job Roboter|KiwiStatus Spider|Lijit Crawler|QuerySeekerSpider|ScollSpider|Trends Crawler|USyd-NLP-Spider|SiteCat Webbot|BotName\\/\\$BotVersion|123metaspider-Bot|1470\\.net crawler|50\\.nu|8bo Crawler Bot|Aboundex|Accoona-[A-z]{1,30}-Agent|AdsBot-Google(?:-[a-z]{1,30}|)|altavista|AppEngine-Google|archive.{0,30}\\.org_bot|archiver|Ask Jeeves|[Bb]ai[Dd]u[Ss]pider(?:-[A-Za-z]{1,30})(?:-[A-Za-z]{1,30}|)|bingbot|BingPreview|blitzbot|BlogBridge|Bloglovin|BoardReader Blog Indexer|BoardReader Favicon Fetcher|boitho.com-dc|BotSeer|BUbiNG|\\b\\w{0,30}favicon\\w{0,30}\\b|\\bYeti(?:-[a-z]{1,30}|)|Catchpoint(?: bot|)|[Cc]harlotte|Checklinks|clumboot|Comodo HTTP\\(S\\) Crawler|Comodo-Webinspector-Crawler|ConveraCrawler|CRAWL-E|CrawlConvera|Daumoa(?:-feedfetcher|)|Feed Seeker Bot|Feedbin|findlinks|Flamingo_SearchEngine|FollowSite Bot|furlbot|Genieo|gigabot|GomezAgent|gonzo1|(?:[a-zA-Z]{1,30}-|)Googlebot(?:-[a-zA-Z]{1,30}|)|Google SketchUp|grub-client|gsa-crawler|heritrix|HiddenMarket|holmes|HooWWWer|htdig|ia_archiver|ICC-Crawler|Icarus6j|ichiro(?:/mobile|)|IconSurf|IlTrovatore(?:-Setaccio|)|InfuzApp|Innovazion Crawler|InternetArchive|IP2[a-z]{1,30}Bot|jbot\\b|KaloogaBot|Kraken|Kurzor|larbin|LEIA|LesnikBot|Linguee Bot|LinkAider|LinkedInBot|Lite Bot|Llaut|lycos|Mail\\.RU_Bot|masscan|masidani_bot|Mediapartners-Google|Microsoft .{0,30} Bot|mogimogi|mozDex|MJ12bot|msnbot(?:-media {0,2}|)|msrbot|Mtps Feed Aggregation System|netresearch|Netvibes|NewsGator[^/]{0,30}|^NING|Nutch[^/]{0,30}|Nymesis|ObjectsSearch|OgScrper|Orbiter|OOZBOT|PagePeeker|PagesInventory|PaxleFramework|Peeplo Screenshot Bot|PlantyNet_WebRobot|Pompos|Qwantify|Read%20Later|Reaper|RedCarpet|Retreiver|Riddler|Rival IQ|scooter|Scrapy|Scrubby|searchsight|seekbot|semanticdiscovery|SemrushBot|Simpy|SimplePie|SEOstats|SimpleRSS|SiteCon|Slackbot-LinkExpanding|Slack-ImgProxy|Slurp|snappy|Speedy Spider|Squrl Java|Stringer|TheUsefulbot|ThumbShotsBot|Thumbshots\\.ru|Tiny Tiny RSS|Twitterbot|WhatsApp|URL2PNG|Vagabondo|VoilaBot|^vortex|Votay bot|^voyager|WASALive.Bot|Web-sniffer|WebThumb|WeSEE:[A-z]{1,30}|WhatWeb|WIRE|WordPress|Wotbox|www\\.almaden\\.ibm\\.com|Xenu(?:.s|) Link Sleuth|Xerka [A-z]{1,30}Bot|yacy(?:bot|)|YahooSeeker|Yahoo! Slurp|Yandex\\w{1,30}|YodaoBot(?:-[A-z]{1,30}|)|YottaaMonitor|Yowedo|^Zao|^Zao-Crawler|ZeBot_www\\.ze\\.bz|ZooShot|ZyBorg)(?:[ /]v?(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)|)|)|)'", " # AWS S3 Clients\n # must come before \"Bots General matcher\" to catch \"boto\"/\"boto3\" before \"bot\"\n - regex: '\\b(Boto3?|JetS3t|aws-(?:cli|sdk-(?:cpp|go|java|nodejs|ruby2?|dotnet-(?:\\d{1,2}|core)))|s3fs)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'", " # Facebook\n # Must come before \"Bots General matcher\" to catch OrangeBotswana\n # Facebook Messenger must go before Facebook\n - regex: '\\[(FBAN/MessengerForiOS|FB_IAB/MESSENGER);FBAV/(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)|)|)'\n family_replacement: 'Facebook Messenger'\n # Facebook\n - regex: '\\[FB.*;(FBAV)/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'\n family_replacement: 'Facebook'\n # Sometimes Facebook does not specify a version (FBAV)\n - regex: '\\[FB.*;'\n family_replacement: 'Facebook'", " # Bots General matcher 'name/0.0'\n - regex: '(?:\\/[A-Za-z0-9\\.]+|) {0,5}([A-Za-z0-9 \\-_\\!\\[\\]:]{0,50}(?:[Aa]rchiver|[Ii]ndexer|[Ss]craper|[Bb]ot|[Ss]pider|[Cc]rawl[a-z]{0,50}))[/ ](\\d+)(?:\\.(\\d+)(?:\\.(\\d+)|)|)'\n # Bots containing bot(but not CUBOT)\n - regex: '((?:[A-Za-z][A-Za-z0-9 -]{0,50}|)[^C][^Uu][Bb]ot)\\b(?:(?:[ /]| v)(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)|)'\n # Bots containing spider|scrape|Crawl\n - regex: '((?:[A-z0-9]{1,50}|[A-z\\-]{1,50} ?|)(?: the |)(?:[Ss][Pp][Ii][Dd][Ee][Rr]|[Ss]crape|[Cc][Rr][Aa][Ww][Ll])[A-z0-9]{0,50})(?:(?:[ /]| v)(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)|)'", " # HbbTV standard defines what features the browser should understand.\n # but it's like targeting \"HTML5 browsers\", effective browser support depends on the model\n # See os_parsers if you want to target a specific TV\n - regex: '(HbbTV)/(\\d+)\\.(\\d+)\\.(\\d+) \\('", " # must go before Firefox to catch Chimera/SeaMonkey/Camino/Waterfox\n - regex: '(Chimera|SeaMonkey|Camino|Waterfox)/(\\d+)\\.(\\d+)\\.?([ab]?\\d+[a-z]*|)'", " # must be before Firefox / Gecko to catch SailfishBrowser properly\n - regex: '(SailfishBrowser)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Sailfish Browser'", " # Social Networks (non-Facebook)\n # Pinterest\n - regex: '\\[(Pinterest)/[^\\]]+\\]'\n - regex: '(Pinterest)(?: for Android(?: Tablet|)|)/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'\n # Instagram app\n - regex: 'Mozilla.*Mobile.*(Instagram).(\\d+)\\.(\\d+)\\.(\\d+)'\n # Flipboard app\n - regex: 'Mozilla.*Mobile.*(Flipboard).(\\d+)\\.(\\d+)\\.(\\d+)'\n # Flipboard-briefing app\n - regex: 'Mozilla.*Mobile.*(Flipboard-Briefing).(\\d+)\\.(\\d+)\\.(\\d+)'\n # Onefootball app\n - regex: 'Mozilla.*Mobile.*(Onefootball)\\/Android.(\\d+)\\.(\\d+)\\.(\\d+)'\n # Snapchat\n - regex: '(Snapchat)\\/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n # Twitter\n - regex: '(Twitter for (?:iPhone|iPad)|TwitterAndroid)(?:\\/(\\d+)\\.(\\d+)|)'\n family_replacement: 'Twitter'", " # Basilisk\n - regex: '(Firefox)/(\\d+)\\.(\\d+) Basilisk/(\\d+)'\n family_replacement: 'Basilisk'", " # Pale Moon\n - regex: '(PaleMoon)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Pale Moon'", " # Firefox\n - regex: '(Fennec)/(\\d+)\\.(\\d+)\\.?([ab]?\\d+[a-z]*)'\n family_replacement: 'Firefox Mobile'\n - regex: '(Fennec)/(\\d+)\\.(\\d+)(pre)'\n family_replacement: 'Firefox Mobile'\n - regex: '(Fennec)/(\\d+)\\.(\\d+)'\n family_replacement: 'Firefox Mobile'\n - regex: '(?:Mobile|Tablet);.*(Firefox)/(\\d+)\\.(\\d+)'\n family_replacement: 'Firefox Mobile'\n - regex: '(Namoroka|Shiretoko|Minefield)/(\\d+)\\.(\\d+)\\.(\\d+(?:pre|))'\n family_replacement: 'Firefox ($1)'\n - regex: '(Firefox)/(\\d+)\\.(\\d+)(a\\d+[a-z]*)'\n family_replacement: 'Firefox Alpha'\n - regex: '(Firefox)/(\\d+)\\.(\\d+)(b\\d+[a-z]*)'\n family_replacement: 'Firefox Beta'\n - regex: '(Firefox)-(?:\\d+\\.\\d+|)/(\\d+)\\.(\\d+)(a\\d+[a-z]*)'\n family_replacement: 'Firefox Alpha'\n - regex: '(Firefox)-(?:\\d+\\.\\d+|)/(\\d+)\\.(\\d+)(b\\d+[a-z]*)'\n family_replacement: 'Firefox Beta'\n - regex: '(Namoroka|Shiretoko|Minefield)/(\\d+)\\.(\\d+)([ab]\\d+[a-z]*|)'\n family_replacement: 'Firefox ($1)'\n - regex: '(Firefox).*Tablet browser (\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'MicroB'\n - regex: '(MozillaDeveloperPreview)/(\\d+)\\.(\\d+)([ab]\\d+[a-z]*|)'\n - regex: '(FxiOS)/(\\d+)\\.(\\d+)(\\.(\\d+)|)(\\.(\\d+)|)'\n family_replacement: 'Firefox iOS'", " # e.g.: Flock/2.0b2\n - regex: '(Flock)/(\\d+)\\.(\\d+)(b\\d+?)'", " # RockMelt\n - regex: '(RockMelt)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # e.g.: Fennec/0.9pre\n - regex: '(Navigator)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Netscape'", " - regex: '(Navigator)/(\\d+)\\.(\\d+)([ab]\\d+)'\n family_replacement: 'Netscape'", " - regex: '(Netscape6)/(\\d+)\\.(\\d+)\\.?([ab]?\\d+|)'\n family_replacement: 'Netscape'", " - regex: '(MyIBrow)/(\\d+)\\.(\\d+)'\n family_replacement: 'My Internet Browser'", " # UC Browser\n # we need check it before opera. In other case case UC Browser detected look like Opera Mini\n - regex: '(UC? ?Browser|UCWEB|U3)[ /]?(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'UC Browser'", " # Opera will stop at 9.80 and hide the real version in the Version string.\n # see: http://dev.opera.com/articles/view/opera-ua-string-changes/\n - regex: '(Opera Tablet).*Version/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n - regex: '(Opera Mini)(?:/att|)/?(\\d+|)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'\n - regex: '(Opera)/.+Opera Mobi.+Version/(\\d+)\\.(\\d+)'\n family_replacement: 'Opera Mobile'\n - regex: '(Opera)/(\\d+)\\.(\\d+).+Opera Mobi'\n family_replacement: 'Opera Mobile'\n - regex: 'Opera Mobi.+(Opera)(?:/|\\s+)(\\d+)\\.(\\d+)'\n family_replacement: 'Opera Mobile'\n - regex: 'Opera Mobi'\n family_replacement: 'Opera Mobile'\n - regex: '(Opera)/9.80.*Version/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'", " # Opera 14 for Android uses a WebKit render engine.\n - regex: '(?:Mobile Safari).*(OPR)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Opera Mobile'", " # Opera >=15 for Desktop is similar to Chrome but includes an \"OPR\" Version string.\n - regex: '(?:Chrome).*(OPR)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Opera'", " # Opera Coast\n - regex: '(Coast)/(\\d+).(\\d+).(\\d+)'\n family_replacement: 'Opera Coast'", " # Opera Mini for iOS (from version 8.0.0)\n - regex: '(OPiOS)/(\\d+).(\\d+).(\\d+)'\n family_replacement: 'Opera Mini'", " # Opera Neon\n - regex: 'Chrome/.+( MMS)/(\\d+).(\\d+).(\\d+)'\n family_replacement: 'Opera Neon'", " # Palm WebOS looks a lot like Safari.\n - regex: '(hpw|web)OS/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'webOS Browser'", " # LuaKit has no version info.\n # http://luakit.org/projects/luakit/\n - regex: '(luakit)'\n family_replacement: 'LuaKit'", " # Snowshoe\n - regex: '(Snowshoe)/(\\d+)\\.(\\d+).(\\d+)'", " # Lightning (for Thunderbird)\n # http://www.mozilla.org/projects/calendar/lightning/\n - regex: 'Gecko/\\d+ (Lightning)/(\\d+)\\.(\\d+)\\.?((?:[ab]?\\d+[a-z]*)|(?:\\d*))'", " # Swiftfox\n - regex: '(Firefox)/(\\d+)\\.(\\d+)\\.(\\d+(?:pre|)) \\(Swiftfox\\)'\n family_replacement: 'Swiftfox'\n - regex: '(Firefox)/(\\d+)\\.(\\d+)([ab]\\d+[a-z]*|) \\(Swiftfox\\)'\n family_replacement: 'Swiftfox'", " # Rekonq\n - regex: '(rekonq)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|) Safari'\n family_replacement: 'Rekonq'\n - regex: 'rekonq'\n family_replacement: 'Rekonq'", " # Conkeror lowercase/uppercase\n # http://conkeror.org/\n - regex: '(conkeror|Conkeror)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Conkeror'", " # catches lower case konqueror\n - regex: '(konqueror)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Konqueror'", " - regex: '(WeTab)-Browser'", " - regex: '(Comodo_Dragon)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Comodo Dragon'", " - regex: '(Symphony) (\\d+).(\\d+)'", " - regex: 'PLAYSTATION 3.+WebKit'\n family_replacement: 'NetFront NX'\n - regex: 'PLAYSTATION 3'\n family_replacement: 'NetFront'\n - regex: '(PlayStation Portable)'\n family_replacement: 'NetFront'\n - regex: '(PlayStation Vita)'\n family_replacement: 'NetFront NX'", " - regex: 'AppleWebKit.+ (NX)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'NetFront NX'\n - regex: '(Nintendo 3DS)'\n family_replacement: 'NetFront NX'", " # Amazon Silk, should go before Safari and Chrome Mobile\n - regex: '(Silk)/(\\d+)\\.(\\d+)(?:\\.([0-9\\-]+)|)'\n family_replacement: 'Amazon Silk'", " # @ref: http://www.puffinbrowser.com\n - regex: '(Puffin)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'", " # Edge Mobile\n - regex: 'Windows Phone .*(Edge)/(\\d+)\\.(\\d+)'\n family_replacement: 'Edge Mobile'\n - regex: '(EdgA)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Edge Mobile'\n - regex: '(EdgiOS)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Edge Mobile'", " # Samsung Internet (based on Chrome, but lacking some features)\n - regex: '(SamsungBrowser)/(\\d+)\\.(\\d+)'\n family_replacement: 'Samsung Internet'", " # Seznam.cz browser (based on WebKit)\n - regex: '(SznProhlizec)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Seznam prohlížeč'", " # Coc Coc browser, based on Chrome (used in Vietnam)\n - regex: '(coc_coc_browser)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Coc Coc'", " # Baidu Browsers (desktop spoofs chrome & IE, explorer is mobile)\n - regex: '(baidubrowser)[/\\s](\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'\n family_replacement: 'Baidu Browser'\n - regex: '(FlyFlow)/(\\d+)\\.(\\d+)'\n family_replacement: 'Baidu Explorer'", " # MxBrowser is Maxthon. Must go before Mobile Chrome for Android\n - regex: '(MxBrowser)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Maxthon'", " # Crosswalk must go before Mobile Chrome for Android\n - regex: '(Crosswalk)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'", " # LINE https://line.me/en/\n # Must go before Mobile Chrome for Android\n - regex: '(Line)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'LINE'", " # MiuiBrowser should got before Mobile Chrome for Android\n - regex: '(MiuiBrowser)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'MiuiBrowser'", " # Mint Browser should got before Mobile Chrome for Android\n - regex: '(Mint Browser)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Mint Browser'", " # TopBuzz Android must go before Chrome Mobile WebView\n - regex: '(TopBuzz)/(\\d+).(\\d+).(\\d+)'\n family_replacement: 'TopBuzz'", " # Google Search App on Android, eg:\n - regex: 'Mozilla.+Android.+(GSA)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Google'", " # QQ Browsers\n - regex: '(MQQBrowser/Mini)(?:(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)|)'\n family_replacement: 'QQ Browser Mini'\n - regex: '(MQQBrowser)(?:/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)|)'\n family_replacement: 'QQ Browser Mobile'\n - regex: '(QQBrowser)(?:/(\\d+)(?:\\.(\\d+)\\.(\\d+)(?:\\.(\\d+)|)|)|)'\n family_replacement: 'QQ Browser'", " # Chrome Mobile\n - regex: 'Version/.+(Chrome)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Chrome Mobile WebView'\n - regex: '; wv\\).+(Chrome)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Chrome Mobile WebView'\n - regex: '(CrMo)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Chrome Mobile'\n - regex: '(CriOS)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Chrome Mobile iOS'\n - regex: '(Chrome)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+) Mobile(?:[ /]|$)'\n family_replacement: 'Chrome Mobile'\n - regex: ' Mobile .*(Chrome)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Chrome Mobile'", " # Chrome Frame must come before MSIE.\n - regex: '(chromeframe)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Chrome Frame'", " # Tizen Browser (second case included in browser/major.minor regex)\n - regex: '(SLP Browser)/(\\d+)\\.(\\d+)'\n family_replacement: 'Tizen Browser'", " # Sogou Explorer 2.X\n - regex: '(SE 2\\.X) MetaSr (\\d+)\\.(\\d+)'\n family_replacement: 'Sogou Explorer'", " # Rackspace Monitoring\n - regex: '(Rackspace Monitoring)/(\\d+)\\.(\\d+)'\n family_replacement: 'RackspaceBot'", " # PyAMF\n - regex: '(PyAMF)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # Yandex Browser\n - regex: '(YaBrowser)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Yandex Browser'", " # Mail.ru Amigo/Internet Browser (Chromium-based)\n - regex: '(Chrome)/(\\d+)\\.(\\d+)\\.(\\d+).* MRCHROME'\n family_replacement: 'Mail.ru Chromium Browser'", " # AOL Browser (IE-based)\n - regex: '(AOL) (\\d+)\\.(\\d+); AOLBuild (\\d+)'", " # Podcast catcher Applications using iTunes\n - regex: '(PodCruncher|Downcast)[ /]?(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'", " # Box Notes https://www.box.com/resources/downloads\n # Must be before Electron\n - regex: ' (BoxNotes)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # Whale\n - regex: '(Whale)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+) Mobile(?:[ /]|$)'\n family_replacement: 'Whale'", " - regex: '(Whale)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Whale'", " # 1Password\n - regex: '(1Password)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # Ghost\n # @ref: http://www.ghost.org\n - regex: '(Ghost)/(\\d+)\\.(\\d+)\\.(\\d+)'", " #### END SPECIAL CASES TOP ####", " #### MAIN CASES - this catches > 50% of all browsers ####", "\n # Slack desktop client (needs to be before Apple Mail, Electron, and Chrome as it gets wrongly detected on Mac OS otherwise)\n - regex: '(Slack_SSB)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Slack Desktop Client'", " # HipChat provides a version on Mac, but not on Windows.\n # Needs to be before Chrome on Windows, and AppleMail on Mac.\n - regex: '(HipChat)/?(\\d+|)'\n family_replacement: 'HipChat Desktop Client'", " # Browser/major_version.minor_version.beta_version\n - regex: '\\b(MobileIron|FireWeb|Jasmine|ANTGalio|Midori|Fresco|Lobo|PaleMoon|Maxthon|Lynx|OmniWeb|Dillo|Camino|Demeter|Fluid|Fennec|Epiphany|Shiira|Sunrise|Spotify|Flock|Netscape|Lunascape|WebPilot|NetFront|Netfront|Konqueror|SeaMonkey|Kazehakase|Vienna|Iceape|Iceweasel|IceWeasel|Iron|K-Meleon|Sleipnir|Galeon|GranParadiso|Opera Mini|iCab|NetNewsWire|ThunderBrowse|Iris|UP\\.Browser|Bunjalloo|Google Earth|Raven for Mac|Openwave|MacOutlook|Electron|OktaMobile)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # Outlook 2007\n - regex: 'Microsoft Office Outlook 12\\.\\d+\\.\\d+|MSOffice 12'\n family_replacement: 'Outlook'\n v1_replacement: '2007'", " # Outlook 2010\n - regex: 'Microsoft Outlook 14\\.\\d+\\.\\d+|MSOffice 14'\n family_replacement: 'Outlook'\n v1_replacement: '2010'", " # Outlook 2013\n - regex: 'Microsoft Outlook 15\\.\\d+\\.\\d+'\n family_replacement: 'Outlook'\n v1_replacement: '2013'", " # Outlook 2016\n - regex: 'Microsoft Outlook (?:Mail )?16\\.\\d+\\.\\d+|MSOffice 16'\n family_replacement: 'Outlook'\n v1_replacement: '2016'", " # Word 2014\n - regex: 'Microsoft Office (Word) 2014'", " # Windows Live Mail\n - regex: 'Outlook-Express\\/7\\.0.*'\n family_replacement: 'Windows Live Mail'", " # Apple Air Mail\n - regex: '(Airmail) (\\d+)\\.(\\d+)(?:\\.(\\d+)|)'", " # Thunderbird\n - regex: '(Thunderbird)/(\\d+)\\.(\\d+)(?:\\.(\\d+(?:pre|))|)'\n family_replacement: 'Thunderbird'", " # Postbox\n - regex: '(Postbox)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Postbox'", " # Barca\n - regex: '(Barca(?:Pro)?)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Barca'", " # Lotus Notes\n - regex: '(Lotus-Notes)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Lotus Notes'", " # Superhuman Mail Client\n # @ref: https://www.superhuman.com\n - regex: 'Superhuman'\n family_replacement: 'Superhuman'", " # Vivaldi uses \"Vivaldi\"\n - regex: '(Vivaldi)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # Edge/major_version.minor_version\n # Edge with chromium Edg/major_version.minor_version.patch.minor_patch\n - regex: '(Edge?)/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'\n family_replacement: 'Edge'", " # Brave Browser https://brave.com/\n - regex: '(brave)/(\\d+)\\.(\\d+)\\.(\\d+) Chrome'\n family_replacement: 'Brave'", " # Iron Browser ~since version 50\n - regex: '(Chrome)/(\\d+)\\.(\\d+)\\.(\\d+)[\\d.]* Iron[^/]'\n family_replacement: 'Iron'", " # Dolphin Browser\n # @ref: http://www.dolphin.com\n - regex: '\\b(Dolphin)(?: |HDCN/|/INT\\-)(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'", " # Headless Chrome\n # https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md\n - regex: '(HeadlessChrome)(?:/(\\d+)\\.(\\d+)\\.(\\d+)|)'", " # Evolution Mail CardDav/CalDav integration\n - regex: '(Evolution)/(\\d+)\\.(\\d+)\\.(\\d+\\.\\d+)'", " # Roundcube Mail CardDav plugin\n - regex: '(RCM CardDAV plugin)/(\\d+)\\.(\\d+)\\.(\\d+(?:-dev|))'", " # Browser/major_version.minor_version\n - regex: '(bingbot|Bolt|AdobeAIR|Jasmine|IceCat|Skyfire|Midori|Maxthon|Lynx|Arora|IBrowse|Dillo|Camino|Shiira|Fennec|Phoenix|Flock|Netscape|Lunascape|Epiphany|WebPilot|Opera Mini|Opera|NetFront|Netfront|Konqueror|Googlebot|SeaMonkey|Kazehakase|Vienna|Iceape|Iceweasel|IceWeasel|Iron|K-Meleon|Sleipnir|Galeon|GranParadiso|iCab|iTunes|MacAppStore|NetNewsWire|Space Bison|Stainless|Orca|Dolfin|BOLT|Minimo|Tizen Browser|Polaris|Abrowser|Planetweb|ICE Browser|mDolphin|qutebrowser|Otter|QupZilla|MailBar|kmail2|YahooMobileMail|ExchangeWebServices|ExchangeServicesClient|Dragon|Outlook-iOS-Android)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'", " # Chrome/Chromium/major_version.minor_version\n - regex: '(Chromium|Chrome)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'", " ##########\n # IE Mobile needs to happen before Android to catch cases such as:\n # Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920)...\n # Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920; ANZ821)...\n # Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920; Orange)...\n # Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920; Vodafone)...\n ##########", " # IE Mobile\n - regex: '(IEMobile)[ /](\\d+)\\.(\\d+)'\n family_replacement: 'IE Mobile'", " # Baca Berita App News Reader\n - regex: '(BacaBerita App)\\/(\\d+)\\.(\\d+)\\.(\\d+)'", " # Podcast catchers\n - regex: '^(bPod|Pocket Casts|Player FM)$'\n - regex: '^(AlexaMediaPlayer|VLC)/(\\d+)\\.(\\d+)\\.([^.\\s]+)'\n - regex: '^(AntennaPod|WMPlayer|Zune|Podkicker|Radio|ExoPlayerDemo|Overcast|PocketTunes|NSPlayer|okhttp|DoggCatcher|QuickNews|QuickTime|Peapod|Podcasts|GoldenPod|VLC|Spotify|Miro|MediaGo|Juice|iPodder|gPodder|Banshee)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'\n - regex: '^(Peapod|Liferea)/([^.\\s]+)\\.([^.\\s]+|)\\.?([^.\\s]+|)'\n - regex: '^(bPod|Player FM) BMID/(\\S+)'\n - regex: '^(Podcast ?Addict)/v(\\d+) '\n - regex: '^(Podcast ?Addict) '\n family_replacement: 'PodcastAddict'\n - regex: '(Replay) AV'\n - regex: '(VOX) Music Player'\n - regex: '(CITA) RSS Aggregator/(\\d+)\\.(\\d+)'\n - regex: '(Pocket Casts)$'\n - regex: '(Player FM)$'\n - regex: '(LG Player|Doppler|FancyMusic|MediaMonkey|Clementine) (\\d+)\\.(\\d+)\\.?([^.\\s]+|)\\.?([^.\\s]+|)'\n - regex: '(philpodder)/(\\d+)\\.(\\d+)\\.?([^.\\s]+|)\\.?([^.\\s]+|)'\n - regex: '(Player FM|Pocket Casts|DoggCatcher|Spotify|MediaMonkey|MediaGo|BashPodder)'\n - regex: '(QuickTime)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n - regex: '(Kinoma)(\\d+)'\n - regex: '(Fancy) Cloud Music (\\d+)\\.(\\d+)'\n family_replacement: 'FancyMusic'\n - regex: 'EspnDownloadManager'\n family_replacement: 'ESPN'\n - regex: '(ESPN) Radio (\\d+)\\.(\\d+)(?:\\.(\\d+)|) ?(?:rv:(\\d+)|) '\n - regex: '(podracer|jPodder) v ?(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n - regex: '(ZDM)/(\\d+)\\.(\\d+)[; ]?'\n - regex: '(Zune|BeyondPod) (\\d+)(?:\\.(\\d+)|)[\\);]'\n - regex: '(WMPlayer)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n - regex: '^(Lavf)'\n family_replacement: 'WMPlayer'\n - regex: '^(RSSRadio)[ /]?(\\d+|)'\n - regex: '(RSS_Radio) (\\d+)\\.(\\d+)'\n family_replacement: 'RSSRadio'\n - regex: '(Podkicker) \\S+/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Podkicker'\n - regex: '^(HTC) Streaming Player \\S+ / \\S+ / \\S+ / (\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n - regex: '^(Stitcher)/iOS'\n - regex: '^(Stitcher)/Android'\n - regex: '^(VLC) .*version (\\d+)\\.(\\d+)\\.(\\d+)'\n - regex: ' (VLC) for'\n - regex: '(vlc)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'VLC'\n - regex: '^(foobar)\\S+/([^.\\s]+)\\.([^.\\s]+|)\\.?([^.\\s]+|)'\n - regex: '^(Clementine)\\S+ ([^.\\s]+)\\.([^.\\s]+|)\\.?([^.\\s]+|)'\n - regex: '(amarok)/([^.\\s]+)\\.([^.\\s]+|)\\.?([^.\\s]+|)'\n family_replacement: 'Amarok'\n - regex: '(Custom)-Feed Reader'", " # Browser major_version.minor_version.beta_version (space instead of slash)\n - regex: '(iRider|Crazy Browser|SkipStone|iCab|Lunascape|Sleipnir|Maemo Browser) (\\d+)\\.(\\d+)\\.(\\d+)'\n # Browser major_version.minor_version (space instead of slash)\n - regex: '(iCab|Lunascape|Opera|Android|Jasmine|Polaris|Microsoft SkyDriveSync|The Bat!) (\\d+)\\.(\\d+)(?:\\.(\\d+)|)'", " # Kindle WebKit\n - regex: '(Kindle)/(\\d+)\\.(\\d+)'", " # weird android UAs\n - regex: '(Android) Donut'\n v1_replacement: '1'\n v2_replacement: '2'", " - regex: '(Android) Eclair'\n v1_replacement: '2'\n v2_replacement: '1'", " - regex: '(Android) Froyo'\n v1_replacement: '2'\n v2_replacement: '2'", " - regex: '(Android) Gingerbread'\n v1_replacement: '2'\n v2_replacement: '3'", " - regex: '(Android) Honeycomb'\n v1_replacement: '3'", " # desktop mode\n # http://www.anandtech.com/show/3982/windows-phone-7-review\n - regex: '(MSIE) (\\d+)\\.(\\d+).*XBLWP7'\n family_replacement: 'IE Large Screen'", " # Nextcloud desktop sync client\n - regex: '(Nextcloud)'", " # Generic mirall client\n - regex: '(mirall)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # Nextcloud/Owncloud android client\n - regex: '(ownCloud-android)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Owncloud'", " # Skype for Business\n - regex: '(OC)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+) \\(Skype for Business\\)'\n family_replacement: 'Skype'", " #### END MAIN CASES ####", " #### SPECIAL CASES ####\n - regex: '(Obigo)InternetBrowser'\n - regex: '(Obigo)\\-Browser'\n - regex: '(Obigo|OBIGO)[^\\d]*(\\d+)(?:.(\\d+)|)'\n family_replacement: 'Obigo'", " - regex: '(MAXTHON|Maxthon) (\\d+)\\.(\\d+)'\n family_replacement: 'Maxthon'\n - regex: '(Maxthon|MyIE2|Uzbl|Shiira)'\n v1_replacement: '0'", " - regex: '(BrowseX) \\((\\d+)\\.(\\d+)\\.(\\d+)'", " - regex: '(NCSA_Mosaic)/(\\d+)\\.(\\d+)'\n family_replacement: 'NCSA Mosaic'", " # Polaris/d.d is above\n - regex: '(POLARIS)/(\\d+)\\.(\\d+)'\n family_replacement: 'Polaris'\n - regex: '(Embider)/(\\d+)\\.(\\d+)'\n family_replacement: 'Polaris'", " - regex: '(BonEcho)/(\\d+)\\.(\\d+)\\.?([ab]?\\d+|)'\n family_replacement: 'Bon Echo'", " # topbuzz on IOS\n - regex: '(TopBuzz) com.alex.NewsMaster/(\\d+).(\\d+).(\\d+)'\n family_replacement: 'TopBuzz'\n - regex: '(TopBuzz) com.mobilesrepublic.newsrepublic/(\\d+).(\\d+).(\\d+)'\n family_replacement: 'TopBuzz'\n - regex: '(TopBuzz) com.topbuzz.videoen/(\\d+).(\\d+).(\\d+)'\n family_replacement: 'TopBuzz'", " # @note: iOS / OSX Applications\n - regex: '(iPod|iPhone|iPad).+GSA/(\\d+)\\.(\\d+)\\.(\\d+) Mobile'\n family_replacement: 'Google'\n - regex: '(iPod|iPhone|iPad).+Version/(\\d+)\\.(\\d+)(?:\\.(\\d+)|).*[ +]Safari'\n family_replacement: 'Mobile Safari'\n - regex: '(iPod|iPod touch|iPhone|iPad);.*CPU.*OS[ +](\\d+)_(\\d+)(?:_(\\d+)|).* AppleNews\\/\\d+\\.\\d+\\.\\d+?'\n family_replacement: 'Mobile Safari UI/WKWebView'\n - regex: '(iPod|iPhone|iPad).+Version/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n family_replacement: 'Mobile Safari UI/WKWebView'\n - regex: '(iPod|iPod touch|iPhone|iPad).* Safari'\n family_replacement: 'Mobile Safari'\n - regex: '(iPod|iPod touch|iPhone|iPad)'\n family_replacement: 'Mobile Safari UI/WKWebView'\n - regex: '(Watch)(\\d+),(\\d+)'\n family_replacement: 'Apple $1 App'", " ##########################\n # Outlook on iOS >= 2.62.0\n ##########################\n - regex: '(Outlook-iOS)/\\d+\\.\\d+\\.prod\\.iphone \\((\\d+)\\.(\\d+)\\.(\\d+)\\)'", " - regex: '(AvantGo) (\\d+).(\\d+)'", " - regex: '(OneBrowser)/(\\d+).(\\d+)'\n family_replacement: 'ONE Browser'", " - regex: '(Avant)'\n v1_replacement: '1'", " # This is the Tesla Model S (see similar entry in device parsers)\n - regex: '(QtCarBrowser)'\n v1_replacement: '1'", " - regex: '^(iBrowser/Mini)(\\d+).(\\d+)'\n family_replacement: 'iBrowser Mini'\n - regex: '^(iBrowser|iRAPP)/(\\d+).(\\d+)'", " # nokia browsers\n # based on: http://www.developer.nokia.com/Community/Wiki/User-Agent_headers_for_Nokia_devices\n - regex: '^(Nokia)'\n family_replacement: 'Nokia Services (WAP) Browser'\n - regex: '(NokiaBrowser)/(\\d+)\\.(\\d+).(\\d+)\\.(\\d+)'\n family_replacement: 'Nokia Browser'\n - regex: '(NokiaBrowser)/(\\d+)\\.(\\d+).(\\d+)'\n family_replacement: 'Nokia Browser'\n - regex: '(NokiaBrowser)/(\\d+)\\.(\\d+)'\n family_replacement: 'Nokia Browser'\n - regex: '(BrowserNG)/(\\d+)\\.(\\d+).(\\d+)'\n family_replacement: 'Nokia Browser'\n - regex: '(Series60)/5\\.0'\n family_replacement: 'Nokia Browser'\n v1_replacement: '7'\n v2_replacement: '0'\n - regex: '(Series60)/(\\d+)\\.(\\d+)'\n family_replacement: 'Nokia OSS Browser'\n - regex: '(S40OviBrowser)/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Ovi Browser'\n - regex: '(Nokia)[EN]?(\\d+)'", " # BlackBerry devices\n - regex: '(PlayBook).+RIM Tablet OS (\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'BlackBerry WebKit'\n - regex: '(Black[bB]erry|BB10).+Version/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'BlackBerry WebKit'\n - regex: '(Black[bB]erry)\\s?(\\d+)'\n family_replacement: 'BlackBerry'", " - regex: '(OmniWeb)/v(\\d+)\\.(\\d+)'", " - regex: '(Blazer)/(\\d+)\\.(\\d+)'\n family_replacement: 'Palm Blazer'", " - regex: '(Pre)/(\\d+)\\.(\\d+)'\n family_replacement: 'Palm Pre'", " # fork of Links\n - regex: '(ELinks)/(\\d+)\\.(\\d+)'\n - regex: '(ELinks) \\((\\d+)\\.(\\d+)'\n - regex: '(Links) \\((\\d+)\\.(\\d+)'", " - regex: '(QtWeb) Internet Browser/(\\d+)\\.(\\d+)'", " #- regex: '\\(iPad;.+(Version)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|).*Safari/'\n # family_replacement: 'iPad'", " # Phantomjs, should go before Safari\n - regex: '(PhantomJS)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # WebKit Nightly\n - regex: '(AppleWebKit)/(\\d+)(?:\\.(\\d+)|)\\+ .* Safari'\n family_replacement: 'WebKit Nightly'", " # Safari\n - regex: '(Version)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|).*Safari/'\n family_replacement: 'Safari'\n # Safari didn't provide \"Version/d.d.d\" prior to 3.0\n - regex: '(Safari)/\\d+'", " - regex: '(OLPC)/Update(\\d+)\\.(\\d+)'", " - regex: '(OLPC)/Update()\\.(\\d+)'\n v1_replacement: '0'", " - regex: '(SEMC\\-Browser)/(\\d+)\\.(\\d+)'", " - regex: '(Teleca)'\n family_replacement: 'Teleca Browser'", " - regex: '(Phantom)/V(\\d+)\\.(\\d+)'\n family_replacement: 'Phantom Browser'", " - regex: '(Trident)/(7|8)\\.(0)'\n family_replacement: 'IE'\n v1_replacement: '11'", " - regex: '(Trident)/(6)\\.(0)'\n family_replacement: 'IE'\n v1_replacement: '10'", " - regex: '(Trident)/(5)\\.(0)'\n family_replacement: 'IE'\n v1_replacement: '9'", " - regex: '(Trident)/(4)\\.(0)'\n family_replacement: 'IE'\n v1_replacement: '8'", " # Espial\n - regex: '(Espial)/(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'", " # Apple Mail", " # apple mail - not directly detectable, have it after Safari stuff\n - regex: '(AppleWebKit)/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Apple Mail'", " # AFTER THE EDGE CASES ABOVE!\n # AFTER IE11\n # BEFORE all other IE\n - regex: '(Firefox)/(\\d+)\\.(\\d+)\\.(\\d+)'\n - regex: '(Firefox)/(\\d+)\\.(\\d+)(pre|[ab]\\d+[a-z]*|)'", " - regex: '([MS]?IE) (\\d+)\\.(\\d+)'\n family_replacement: 'IE'", " - regex: '(python-requests)/(\\d+)\\.(\\d+)'\n family_replacement: 'Python Requests'", " # headless user-agents\n - regex: '\\b(Windows-Update-Agent|Microsoft-CryptoAPI|SophosUpdateManager|SophosAgent|Debian APT-HTTP|Ubuntu APT-HTTP|libcurl-agent|libwww-perl|urlgrabber|curl|PycURL|Wget|aria2|Axel|OpenBSD ftp|lftp|jupdate|insomnia|fetch libfetch|akka-http|got)(?:[ /](\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)|)'", " # Asynchronous HTTP Client/Server for asyncio and Python (https://aiohttp.readthedocs.io/)\n - regex: '(Python/3\\.\\d{1,3} aiohttp)/(\\d+)\\.(\\d+)\\.(\\d+)'\n # Asynchronous HTTP Client/Server for asyncio and Python (https://aiohttp.readthedocs.io/)\n - regex: '(Python/3\\.\\d{1,3} aiohttp)/(\\d+)\\.(\\d+)\\.(\\d+)'", " - regex: '(Java)[/ ]{0,1}\\d+\\.(\\d+)\\.(\\d+)[_-]*([a-zA-Z0-9]+|)'", " # Cloud Storage Clients\n - regex: '^(Cyberduck)/(\\d+)\\.(\\d+)\\.(\\d+)(?:\\.\\d+|)'\n - regex: '^(S3 Browser) (\\d+)-(\\d+)-(\\d+)(?:\\s*http://s3browser\\.com|)'\n - regex: '(S3Gof3r)'\n # IBM COS (Cloud Object Storage) API\n - regex: '\\b(ibm-cos-sdk-(?:core|java|js|python))/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n # rusoto - Rusoto - AWS SDK for Rust - https://github.com/rusoto/rusoto\n - regex: '^(rusoto)/(\\d+)\\.(\\d+)\\.(\\d+)'\n # rclone - rsync for cloud storage - https://rclone.org/\n - regex: '^(rclone)/v(\\d+)\\.(\\d+)'", " # Roku Digital-Video-Players https://www.roku.com/\n - regex: '^(Roku)/DVP-(\\d+)\\.(\\d+)'", " # Kurio App News Reader https://kurio.co.id/\n - regex: '(Kurio)\\/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'Kurio App'", " # Box Drive and Box Sync https://www.box.com/resources/downloads\n - regex: '^(Box(?: Sync)?)/(\\d+)\\.(\\d+)\\.(\\d+)'", " # ViaFree streaming app https://www.viafree.{dk|se|no}\n - regex: '^(ViaFree|Viafree)-(?:tvOS-)?[A-Z]{2}/(\\d+)\\.(\\d+)\\.(\\d+)'\n family_replacement: 'ViaFree'", "os_parsers:\n ##########\n # HbbTV vendors\n ##########", " # starts with the easy one : Panasonic seems consistent across years, hope it will continue\n #HbbTV/1.1.1 (;Panasonic;VIERA 2011;f.532;0071-0802 2000-0000;)\n #HbbTV/1.1.1 (;Panasonic;VIERA 2012;1.261;0071-3103 2000-0000;)\n #HbbTV/1.2.1 (;Panasonic;VIERA 2013;3.672;4101-0003 0002-0000;)\n #- regex: 'HbbTV/\\d+\\.\\d+\\.\\d+ \\(;(Panasonic);VIERA ([0-9]{4});'", " # Sony is consistent too but do not place year like the other\n # Opera/9.80 (Linux armv7l; HbbTV/1.1.1 (; Sony; KDL32W650A; PKG3.211EUA; 2013;); ) Presto/2.12.362 Version/12.11\n # Opera/9.80 (Linux mips; U; HbbTV/1.1.1 (; Sony; KDL40HX751; PKG1.902EUA; 2012;);; en) Presto/2.10.250 Version/11.60\n # Opera/9.80 (Linux mips; U; HbbTV/1.1.1 (; Sony; KDL22EX320; PKG4.017EUA; 2011;);; en) Presto/2.7.61 Version/11.00\n #- regex: 'HbbTV/\\d+\\.\\d+\\.\\d+ \\(; (Sony);.*;.*; ([0-9]{4});\\)'", "\n # LG is consistent too, but we need to add manually the year model\n #Mozilla/5.0 (Unknown; Linux armv7l) AppleWebKit/537.1+ (KHTML, like Gecko) Safari/537.1+ HbbTV/1.1.1 ( ;LGE ;NetCast 4.0 ;03.20.30 ;1.0M ;)\n #Mozilla/5.0 (DirectFB; Linux armv7l) AppleWebKit/534.26+ (KHTML, like Gecko) Version/5.0 Safari/534.26+ HbbTV/1.1.1 ( ;LGE ;NetCast 3.0 ;1.0 ;1.0M ;)\n - regex: 'HbbTV/\\d+\\.\\d+\\.\\d+ \\( ;(LG)E ;NetCast 4.0'\n os_v1_replacement: '2013'\n - regex: 'HbbTV/\\d+\\.\\d+\\.\\d+ \\( ;(LG)E ;NetCast 3.0'\n os_v1_replacement: '2012'", " # Samsung is on its way of normalizing their user-agent\n # HbbTV/1.1.1 (;Samsung;SmartTV2013;T-FXPDEUC-1102.2;;) WebKit\n # HbbTV/1.1.1 (;Samsung;SmartTV2013;T-MST12DEUC-1102.1;;) WebKit\n # HbbTV/1.1.1 (;Samsung;SmartTV2012;;;) WebKit\n # HbbTV/1.1.1 (;;;;;) Maple_2011\n - regex: 'HbbTV/1.1.1 \\(;;;;;\\) Maple_2011'\n os_replacement: 'Samsung'\n os_v1_replacement: '2011'\n # manage the two models of 2013\n - regex: 'HbbTV/\\d+\\.\\d+\\.\\d+ \\(;(Samsung);SmartTV([0-9]{4});.*FXPDEUC'\n os_v2_replacement: 'UE40F7000'\n - regex: 'HbbTV/\\d+\\.\\d+\\.\\d+ \\(;(Samsung);SmartTV([0-9]{4});.*MST12DEUC'\n os_v2_replacement: 'UE32F4500'\n # generic Samsung (works starting in 2012)\n #- regex: 'HbbTV/\\d+\\.\\d+\\.\\d+ \\(;(Samsung);SmartTV([0-9]{4});'", " # Philips : not found any other way than a manual mapping\n # Opera/9.80 (Linux mips; U; HbbTV/1.1.1 (; Philips; ; ; ; ) CE-HTML/1.0 NETTV/4.1.3 PHILIPSTV/1.1.1; en) Presto/2.10.250 Version/11.60\n # Opera/9.80 (Linux mips ; U; HbbTV/1.1.1 (; Philips; ; ; ; ) CE-HTML/1.0 NETTV/3.2.1; en) Presto/2.6.33 Version/10.70\n - regex: 'HbbTV/1\\.1\\.1 \\(; (Philips);.*NETTV/4'\n os_v1_replacement: '2013'\n - regex: 'HbbTV/1\\.1\\.1 \\(; (Philips);.*NETTV/3'\n os_v1_replacement: '2012'\n - regex: 'HbbTV/1\\.1\\.1 \\(; (Philips);.*NETTV/2'\n os_v1_replacement: '2011'", " # the HbbTV emulator developers use HbbTV/1.1.1 (;;;;;) firetv-firefox-plugin 1.1.20\n - regex: 'HbbTV/\\d+\\.\\d+\\.\\d+.*(firetv)-firefox-plugin (\\d+).(\\d+).(\\d+)'\n os_replacement: 'FireHbbTV'", " # generic HbbTV, hoping to catch manufacturer name (always after 2nd comma) and the first string that looks like a 2011-2019 year\n - regex: 'HbbTV/\\d+\\.\\d+\\.\\d+ \\(.*; ?([a-zA-Z]+) ?;.*(201[1-9]).*\\)'", " ##########\n # @note: Windows Phone needs to come before Windows NT 6.1 *and* before Android to catch cases such as:\n # Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920)...\n # Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920; ANZ821)...\n # Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920; Orange)...\n # Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920; Vodafone)...\n ##########", " - regex: '(Windows Phone) (?:OS[ /])?(\\d+)\\.(\\d+)'", " # Again a MS-special one: iPhone.*Outlook-iOS-Android/x.x is erroneously detected as Android\n - regex: '(CPU[ +]OS|iPhone[ +]OS|CPU[ +]iPhone)[ +]+(\\d+)[_\\.](\\d+)(?:[_\\.](\\d+)|).*Outlook-iOS-Android'\n os_replacement: 'iOS'", " ##########\n # Android\n # can actually detect rooted android os. do we care?\n ##########\n - regex: '(Android)[ \\-/](\\d+)(?:\\.(\\d+)|)(?:[.\\-]([a-z0-9]+)|)'", " - regex: '(Android) Donut'\n os_v1_replacement: '1'\n os_v2_replacement: '2'", " - regex: '(Android) Eclair'\n os_v1_replacement: '2'\n os_v2_replacement: '1'", " - regex: '(Android) Froyo'\n os_v1_replacement: '2'\n os_v2_replacement: '2'", " - regex: '(Android) Gingerbread'\n os_v1_replacement: '2'\n os_v2_replacement: '3'", " - regex: '(Android) Honeycomb'\n os_v1_replacement: '3'", " # Android 9; Android 10;\n - regex: '(Android) (\\d+);'", " # UCWEB\n - regex: '^UCWEB.*; (Adr) (\\d+)\\.(\\d+)(?:[.\\-]([a-z0-9]+)|);'\n os_replacement: 'Android'\n - regex: '^UCWEB.*; (iPad|iPh|iPd) OS (\\d+)_(\\d+)(?:_(\\d+)|);'\n os_replacement: 'iOS'\n - regex: '^UCWEB.*; (wds) (\\d+)\\.(\\d+)(?:\\.(\\d+)|);'\n os_replacement: 'Windows Phone'\n # JUC\n - regex: '^(JUC).*; ?U; ?(?:Android|)(\\d+)\\.(\\d+)(?:[\\.\\-]([a-z0-9]+)|)'\n os_replacement: 'Android'", " # Salesforce\n - regex: '(android)\\s(?:mobile\\/)(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)|)|)'\n os_replacement: 'Android'", " ##########\n # Kindle Android\n ##########\n - regex: '(Silk-Accelerated=[a-z]{4,5})'\n os_replacement: 'Android'", " # Citrix Chrome App on Chrome OS\n # Note, this needs to come before the windows parsers as the app doesn't\n # properly identify as Chrome OS\n #\n # ex: Mozilla/5.0 (X11; Windows aarch64 10718.88.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.118 Safari/537.36 CitrixChromeApp\n - regex: '(x86_64|aarch64)\\ (\\d+)\\.(\\d+)\\.(\\d+).*Chrome.*(?:CitrixChromeApp)$'\n os_replacement: 'Chrome OS'", " ##########\n # Windows\n # http://en.wikipedia.org/wiki/Windows_NT#Releases\n # possibility of false positive when different marketing names share same NT kernel\n # e.g. windows server 2003 and windows xp\n # lots of ua strings have Windows NT 4.1 !?!?!?!? !?!? !? !????!?! !!! ??? !?!?! ?\n # (very) roughly ordered in terms of frequency of occurence of regex (win xp currently most frequent, etc)\n ##########", " # ie mobile desktop mode\n # spoofs nt 6.1. must come before windows 7\n - regex: '(XBLWP7)'\n os_replacement: 'Windows Phone'", " # @note: This needs to come before Windows NT 6.1\n - regex: '(Windows ?Mobile)'\n os_replacement: 'Windows Mobile'", " - regex: '(Windows 10)'\n os_replacement: 'Windows'\n os_v1_replacement: '10'", " - regex: '(Windows (?:NT 5\\.2|NT 5\\.1))'\n os_replacement: 'Windows'\n os_v1_replacement: 'XP'", " - regex: '(Windows NT 6\\.1)'\n os_replacement: 'Windows'\n os_v1_replacement: '7'", " - regex: '(Windows NT 6\\.0)'\n os_replacement: 'Windows'\n os_v1_replacement: 'Vista'", " - regex: '(Win 9x 4\\.90)'\n os_replacement: 'Windows'\n os_v1_replacement: 'ME'", " - regex: '(Windows NT 6\\.2; ARM;)'\n os_replacement: 'Windows'\n os_v1_replacement: 'RT'", " - regex: '(Windows NT 6\\.2)'\n os_replacement: 'Windows'\n os_v1_replacement: '8'", " - regex: '(Windows NT 6\\.3; ARM;)'\n os_replacement: 'Windows'\n os_v1_replacement: 'RT 8'\n os_v2_replacement: '1'", " - regex: '(Windows NT 6\\.3)'\n os_replacement: 'Windows'\n os_v1_replacement: '8'\n os_v2_replacement: '1'", " - regex: '(Windows NT 6\\.4)'\n os_replacement: 'Windows'\n os_v1_replacement: '10'", " - regex: '(Windows NT 10\\.0)'\n os_replacement: 'Windows'\n os_v1_replacement: '10'", " - regex: '(Windows NT 5\\.0)'\n os_replacement: 'Windows'\n os_v1_replacement: '2000'", " - regex: '(WinNT4.0)'\n os_replacement: 'Windows'\n os_v1_replacement: 'NT 4.0'", " - regex: '(Windows ?CE)'\n os_replacement: 'Windows'\n os_v1_replacement: 'CE'", " - regex: 'Win(?:dows)? ?(95|98|3.1|NT|ME|2000|XP|Vista|7|CE)'\n os_replacement: 'Windows'\n os_v1_replacement: '$1'", " - regex: 'Win16'\n os_replacement: 'Windows'\n os_v1_replacement: '3.1'", " - regex: 'Win32'\n os_replacement: 'Windows'\n os_v1_replacement: '95'", " # Box apps (Drive, Sync, Notes) on Windows https://www.box.com/resources/downloads\n - regex: '^Box.*Windows/([\\d.]+);'\n os_replacement: 'Windows'\n os_v1_replacement: '$1'", " ##########\n # Tizen OS from Samsung\n # spoofs Android so pushing it above\n ##########\n - regex: '(Tizen)[/ ](\\d+)\\.(\\d+)'", " ##########\n # Mac OS\n # @ref: http://en.wikipedia.org/wiki/Mac_OS_X#Versions\n # @ref: http://www.puredarwin.org/curious/versions\n ##########\n - regex: '((?:Mac[ +]?|; )OS[ +]X)[\\s+/](?:(\\d+)[_.](\\d+)(?:[_.](\\d+)|)|Mach-O)'\n os_replacement: 'Mac OS X'\n - regex: '\\w+\\s+Mac OS X\\s+\\w+\\s+(\\d+).(\\d+).(\\d+).*'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '$1'\n os_v2_replacement: '$2'\n os_v3_replacement: '$3'\n # Leopard\n - regex: ' (Dar)(win)/(9).(\\d+).*\\((?:i386|x86_64|Power Macintosh)\\)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '5'\n # Snow Leopard\n - regex: ' (Dar)(win)/(10).(\\d+).*\\((?:i386|x86_64)\\)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '6'\n # Lion\n - regex: ' (Dar)(win)/(11).(\\d+).*\\((?:i386|x86_64)\\)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '7'\n # Mountain Lion\n - regex: ' (Dar)(win)/(12).(\\d+).*\\((?:i386|x86_64)\\)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '8'\n # Mavericks\n - regex: ' (Dar)(win)/(13).(\\d+).*\\((?:i386|x86_64)\\)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '9'\n # Yosemite is Darwin/14.x but patch versions are inconsistent in the Darwin string;\n # more accurately covered by CFNetwork regexes downstream", " # IE on Mac doesn't specify version number\n - regex: 'Mac_PowerPC'\n os_replacement: 'Mac OS'", " # builds before tiger don't seem to specify version?", " # ios devices spoof (mac os x), so including intel/ppc prefixes\n - regex: '(?:PPC|Intel) (Mac OS X)'", " # Box Drive and Box Sync on Mac OS X use OSX version numbers, not Darwin\n - regex: '^Box.*;(Darwin)/(10)\\.(1\\d)(?:\\.(\\d+)|)'\n os_replacement: 'Mac OS X'", " ##########\n # iOS\n # http://en.wikipedia.org/wiki/IOS_version_history\n ##########\n # keep this above generic iOS, since AppleTV UAs contain 'CPU OS'\n - regex: '(Apple\\s?TV)(?:/(\\d+)\\.(\\d+)|)'\n os_replacement: 'ATV OS X'", " - regex: '(CPU[ +]OS|iPhone[ +]OS|CPU[ +]iPhone|CPU IPhone OS)[ +]+(\\d+)[_\\.](\\d+)(?:[_\\.](\\d+)|)'\n os_replacement: 'iOS'", " # remaining cases are mostly only opera uas, so catch opera as to not catch iphone spoofs\n - regex: '(iPhone|iPad|iPod); Opera'\n os_replacement: 'iOS'", " # few more stragglers\n - regex: '(iPhone|iPad|iPod).*Mac OS X.*Version/(\\d+)\\.(\\d+)'\n os_replacement: 'iOS'", " # CFNetwork/Darwin - The specific CFNetwork or Darwin version determines\n # whether the os maps to Mac OS, or iOS, or just Darwin.\n # See: http://user-agents.me/cfnetwork-version-list\n - regex: '(CFNetwork)/(5)48\\.0\\.3.* Darwin/11\\.0\\.0'\n os_replacement: 'iOS'\n - regex: '(CFNetwork)/(5)48\\.(0)\\.4.* Darwin/(1)1\\.0\\.0'\n os_replacement: 'iOS'\n - regex: '(CFNetwork)/(5)48\\.(1)\\.4'\n os_replacement: 'iOS'\n - regex: '(CFNetwork)/(4)85\\.1(3)\\.9'\n os_replacement: 'iOS'\n - regex: '(CFNetwork)/(6)09\\.(1)\\.4'\n os_replacement: 'iOS'\n - regex: '(CFNetwork)/(6)(0)9'\n os_replacement: 'iOS'\n - regex: '(CFNetwork)/6(7)2\\.(1)\\.13'\n os_replacement: 'iOS'\n - regex: '(CFNetwork)/6(7)2\\.(1)\\.(1)4'\n os_replacement: 'iOS'\n - regex: '(CF)(Network)/6(7)(2)\\.1\\.15'\n os_replacement: 'iOS'\n os_v1_replacement: '7'\n os_v2_replacement: '1'\n - regex: '(CFNetwork)/6(7)2\\.(0)\\.(?:2|8)'\n os_replacement: 'iOS'\n - regex: '(CFNetwork)/709\\.1'\n os_replacement: 'iOS'\n os_v1_replacement: '8'\n os_v2_replacement: '0.b5'\n - regex: '(CF)(Network)/711\\.(\\d)'\n os_replacement: 'iOS'\n os_v1_replacement: '8'\n - regex: '(CF)(Network)/(720)\\.(\\d)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '10'\n - regex: '(CF)(Network)/(760)\\.(\\d)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '11'\n - regex: 'CFNetwork/7.* Darwin/15\\.4\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '9'\n os_v2_replacement: '3'\n os_v3_replacement: '1'\n - regex: 'CFNetwork/7.* Darwin/15\\.5\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '9'\n os_v2_replacement: '3'\n os_v3_replacement: '2'\n - regex: 'CFNetwork/7.* Darwin/15\\.6\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '9'\n os_v2_replacement: '3'\n os_v3_replacement: '5'\n - regex: '(CF)(Network)/758\\.(\\d)'\n os_replacement: 'iOS'\n os_v1_replacement: '9'\n - regex: 'CFNetwork/808\\.3 Darwin/16\\.3\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '10'\n os_v2_replacement: '2'\n os_v3_replacement: '1'\n - regex: '(CF)(Network)/808\\.(\\d)'\n os_replacement: 'iOS'\n os_v1_replacement: '10'", " ##########\n # CFNetwork macOS Apps (must be before CFNetwork iOS Apps\n # @ref: https://en.wikipedia.org/wiki/Darwin_(operating_system)#Release_history\n ##########\n - regex: 'CFNetwork/.* Darwin/17\\.\\d+.*\\(x86_64\\)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '13'\n - regex: 'CFNetwork/.* Darwin/16\\.\\d+.*\\(x86_64\\)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '12'\n - regex: 'CFNetwork/8.* Darwin/15\\.\\d+.*\\(x86_64\\)'\n os_replacement: 'Mac OS X'\n os_v1_replacement: '10'\n os_v2_replacement: '11'\n ##########\n # CFNetwork iOS Apps\n # @ref: https://en.wikipedia.org/wiki/Darwin_(operating_system)#Release_history\n ##########\n - regex: 'CFNetwork/.* Darwin/(9)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '1'\n - regex: 'CFNetwork/.* Darwin/(10)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '4'\n - regex: 'CFNetwork/.* Darwin/(11)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '5'\n - regex: 'CFNetwork/.* Darwin/(13)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '6'\n - regex: 'CFNetwork/6.* Darwin/(14)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '7'\n - regex: 'CFNetwork/7.* Darwin/(14)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '8'\n os_v2_replacement: '0'\n - regex: 'CFNetwork/7.* Darwin/(15)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '9'\n os_v2_replacement: '0'\n - regex: 'CFNetwork/8.* Darwin/16\\.5\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '10'\n os_v2_replacement: '3'\n - regex: 'CFNetwork/8.* Darwin/16\\.6\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '10'\n os_v2_replacement: '3'\n os_v3_replacement: '2'\n - regex: 'CFNetwork/8.* Darwin/16\\.7\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '10'\n os_v2_replacement: '3'\n os_v3_replacement: '3'\n - regex: 'CFNetwork/8.* Darwin/(16)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '10'\n - regex: 'CFNetwork/8.* Darwin/17\\.0\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '11'\n os_v2_replacement: '0'\n - regex: 'CFNetwork/8.* Darwin/17\\.2\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '11'\n os_v2_replacement: '1'\n - regex: 'CFNetwork/8.* Darwin/17\\.3\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '11'\n os_v2_replacement: '2'\n - regex: 'CFNetwork/8.* Darwin/17\\.4\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '11'\n os_v2_replacement: '2'\n os_v3_replacement: '6'\n - regex: 'CFNetwork/8.* Darwin/17\\.5\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '11'\n os_v2_replacement: '3'\n - regex: 'CFNetwork/9.* Darwin/17\\.6\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '11'\n os_v2_replacement: '4'\n - regex: 'CFNetwork/9.* Darwin/17\\.7\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '11'\n os_v2_replacement: '4'\n os_v3_replacement: '1'\n - regex: 'CFNetwork/8.* Darwin/(17)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '11'\n - regex: 'CFNetwork/9.* Darwin/18\\.0\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '12'\n os_v2_replacement: '0'\n - regex: 'CFNetwork/9.* Darwin/(18)\\.\\d+'\n os_replacement: 'iOS'\n os_v1_replacement: '12'\n - regex: 'CFNetwork/.* Darwin/'\n os_replacement: 'iOS'", " # iOS Apps\n - regex: '\\b(iOS[ /]|iOS; |iPhone(?:/| v|[ _]OS[/,]|; | OS : |\\d,\\d/|\\d,\\d; )|iPad/)(\\d{1,2})[_\\.](\\d{1,2})(?:[_\\.](\\d+)|)'\n os_replacement: 'iOS'\n - regex: '\\((iOS);'", " ##########\n # Apple Watch\n ##########\n - regex: '(watchOS)/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n os_replacement: 'WatchOS'", " ##########################\n # Outlook on iOS >= 2.62.0\n ##########################\n - regex: 'Outlook-(iOS)/\\d+\\.\\d+\\.prod\\.iphone'", " ##########################\n # iOS devices, the same regex matches mobile safari webviews\n ##########################\n - regex: '(iPod|iPhone|iPad)'\n os_replacement: 'iOS'", " ##########\n # Apple TV\n ##########\n - regex: '(tvOS)[/ ](\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n os_replacement: 'tvOS'", " ##########\n # Chrome OS\n # if version 0.0.0, probably this stuff:\n # http://code.google.com/p/chromium-os/issues/detail?id=11573\n # http://code.google.com/p/chromium-os/issues/detail?id=13790\n ##########\n - regex: '(CrOS) [a-z0-9_]+ (\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n os_replacement: 'Chrome OS'", " ##########\n # Linux distros\n ##########\n - regex: '([Dd]ebian)'\n os_replacement: 'Debian'\n - regex: '(Linux Mint)(?:/(\\d+)|)'\n - regex: '(Mandriva)(?: Linux|)/(?:[\\d.-]+m[a-z]{2}(\\d+).(\\d)|)'", " ##########\n # Symbian + Symbian OS\n # http://en.wikipedia.org/wiki/History_of_Symbian\n ##########\n - regex: '(Symbian[Oo][Ss])[/ ](\\d+)\\.(\\d+)'\n os_replacement: 'Symbian OS'\n - regex: '(Symbian/3).+NokiaBrowser/7\\.3'\n os_replacement: 'Symbian^3 Anna'\n - regex: '(Symbian/3).+NokiaBrowser/7\\.4'\n os_replacement: 'Symbian^3 Belle'\n - regex: '(Symbian/3)'\n os_replacement: 'Symbian^3'\n - regex: '\\b(Series 60|SymbOS|S60Version|S60V\\d|S60\\b)'\n os_replacement: 'Symbian OS'\n - regex: '(MeeGo)'\n - regex: 'Symbian [Oo][Ss]'\n os_replacement: 'Symbian OS'\n - regex: 'Series40;'\n os_replacement: 'Nokia Series 40'\n - regex: 'Series30Plus;'\n os_replacement: 'Nokia Series 30 Plus'", " ##########\n # BlackBerry devices\n ##########\n - regex: '(BB10);.+Version/(\\d+)\\.(\\d+)\\.(\\d+)'\n os_replacement: 'BlackBerry OS'\n - regex: '(Black[Bb]erry)[0-9a-z]+/(\\d+)\\.(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n os_replacement: 'BlackBerry OS'\n - regex: '(Black[Bb]erry).+Version/(\\d+)\\.(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n os_replacement: 'BlackBerry OS'\n - regex: '(RIM Tablet OS) (\\d+)\\.(\\d+)\\.(\\d+)'\n os_replacement: 'BlackBerry Tablet OS'\n - regex: '(Play[Bb]ook)'\n os_replacement: 'BlackBerry Tablet OS'\n - regex: '(Black[Bb]erry)'\n os_replacement: 'BlackBerry OS'", " ##########\n # KaiOS\n ##########\n - regex: '(K[Aa][Ii]OS)\\/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n os_replacement: 'KaiOS'", " ##########\n # Firefox OS\n ##########\n - regex: '\\((?:Mobile|Tablet);.+Gecko/18.0 Firefox/\\d+\\.\\d+'\n os_replacement: 'Firefox OS'\n os_v1_replacement: '1'\n os_v2_replacement: '0'\n os_v3_replacement: '1'", " - regex: '\\((?:Mobile|Tablet);.+Gecko/18.1 Firefox/\\d+\\.\\d+'\n os_replacement: 'Firefox OS'\n os_v1_replacement: '1'\n os_v2_replacement: '1'", " - regex: '\\((?:Mobile|Tablet);.+Gecko/26.0 Firefox/\\d+\\.\\d+'\n os_replacement: 'Firefox OS'\n os_v1_replacement: '1'\n os_v2_replacement: '2'", " - regex: '\\((?:Mobile|Tablet);.+Gecko/28.0 Firefox/\\d+\\.\\d+'\n os_replacement: 'Firefox OS'\n os_v1_replacement: '1'\n os_v2_replacement: '3'", " - regex: '\\((?:Mobile|Tablet);.+Gecko/30.0 Firefox/\\d+\\.\\d+'\n os_replacement: 'Firefox OS'\n os_v1_replacement: '1'\n os_v2_replacement: '4'", " - regex: '\\((?:Mobile|Tablet);.+Gecko/32.0 Firefox/\\d+\\.\\d+'\n os_replacement: 'Firefox OS'\n os_v1_replacement: '2'\n os_v2_replacement: '0'", " - regex: '\\((?:Mobile|Tablet);.+Gecko/34.0 Firefox/\\d+\\.\\d+'\n os_replacement: 'Firefox OS'\n os_v1_replacement: '2'\n os_v2_replacement: '1'", " # Firefox OS Generic\n - regex: '\\((?:Mobile|Tablet);.+Firefox/\\d+\\.\\d+'\n os_replacement: 'Firefox OS'", "\n ##########\n # BREW\n # yes, Brew is lower-cased for Brew MP\n ##########\n - regex: '(BREW)[ /](\\d+)\\.(\\d+)\\.(\\d+)'\n - regex: '(BREW);'\n - regex: '(Brew MP|BMP)[ /](\\d+)\\.(\\d+)\\.(\\d+)'\n os_replacement: 'Brew MP'\n - regex: 'BMP;'\n os_replacement: 'Brew MP'", " ##########\n # Google TV\n ##########\n - regex: '(GoogleTV)(?: (\\d+)\\.(\\d+)(?:\\.(\\d+)|)|/[\\da-z]+)'", " - regex: '(WebTV)/(\\d+).(\\d+)'", " ##########\n # Chromecast\n ##########\n - regex: '(CrKey)(?:[/](\\d+)\\.(\\d+)(?:\\.(\\d+)|)|)'\n os_replacement: 'Chromecast'", " ##########\n # Misc mobile\n ##########\n - regex: '(hpw|web)OS/(\\d+)\\.(\\d+)(?:\\.(\\d+)|)'\n os_replacement: 'webOS'\n - regex: '(VRE);'", " ##########\n # Generic patterns\n # since the majority of os cases are very specific, these go last\n ##########\n - regex: '(Fedora|Red Hat|PCLinuxOS|Puppy|Ubuntu|Kindle|Bada|Sailfish|Lubuntu|BackTrack|Slackware|(?:Free|Open|Net|\\b)BSD)[/ ](\\d+)\\.(\\d+)(?:\\.(\\d+)|)(?:\\.(\\d+)|)'", " # Gentoo Linux + Kernel Version\n - regex: '(Linux)[ /](\\d+)\\.(\\d+)(?:\\.(\\d+)|).*gentoo'\n os_replacement: 'Gentoo'", " # Opera Mini Bada\n - regex: '\\((Bada);'", " # just os\n - regex: '(Windows|Android|WeTab|Maemo|Web0S)'\n - regex: '(Ubuntu|Kubuntu|Arch Linux|CentOS|Slackware|Gentoo|openSUSE|SUSE|Red Hat|Fedora|PCLinuxOS|Mageia|(?:Free|Open|Net|\\b)BSD)'\n # Linux + Kernel Version\n - regex: '(Linux)(?:[ /](\\d+)\\.(\\d+)(?:\\.(\\d+)|)|)'\n - regex: 'SunOS'\n os_replacement: 'Solaris'\n # Wget/x.x.x (linux-gnu)\n - regex: '\\(linux-gnu\\)'\n os_replacement: 'Linux'\n - regex: '\\(x86_64-redhat-linux-gnu\\)'\n os_replacement: 'Red Hat'\n - regex: '\\((freebsd)(\\d+)\\.(\\d+)\\)'\n os_replacement: 'FreeBSD'\n - regex: 'linux'\n os_replacement: 'Linux'", " # Roku Digital-Video-Players https://www.roku.com/\n - regex: '^(Roku)/DVP-(\\d+)\\.(\\d+)'", "device_parsers:", " #########\n # Mobile Spiders\n # Catch the mobile crawler before checking for iPhones / Androids.\n #########\n - regex: '(?:(?:iPhone|Windows CE|Windows Phone|Android).*(?:(?:Bot|Yeti)-Mobile|YRSpider|BingPreview|bots?/\\d|(?:bot|spider)\\.html)|AdsBot-Google-Mobile.*iPhone)'\n regex_flag: 'i'\n device_replacement: 'Spider'\n brand_replacement: 'Spider'\n model_replacement: 'Smartphone'\n - regex: '(?:DoCoMo|\\bMOT\\b|\\bLG\\b|Nokia|Samsung|SonyEricsson).*(?:(?:Bot|Yeti)-Mobile|bots?/\\d|(?:bot|crawler)\\.html|(?:jump|google|Wukong)bot|ichiro/mobile|/spider|YahooSeeker)'\n regex_flag: 'i'\n device_replacement: 'Spider'\n brand_replacement: 'Spider'\n model_replacement: 'Feature Phone'", " # PTST / WebPageTest.org crawlers\n - regex: ' PTST/\\d+(?:\\.)?\\d+$'\n device_replacement: 'Spider'\n brand_replacement: 'Spider'", " # Datanyze.com spider\n - regex: 'X11; Datanyze; Linux'\n device_replacement: 'Spider'\n brand_replacement: 'Spider'", " #########\n # WebBrowser for SmartWatch\n # @ref: https://play.google.com/store/apps/details?id=se.vaggan.webbrowser&hl=en\n #########", " - regex: '\\bSmartWatch {0,2}\\( {0,2}([^;]+) {0,2}; {0,2}([^;]+) {0,2};'", " device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " ######################################################################\n # Android parsers\n #\n # @ref: https://support.google.com/googleplay/answer/1727131?hl=en\n ######################################################################", " # Android Application\n - regex: 'Android Application[^\\-]+ - (Sony) ?(Ericsson|) (.+) \\w+ - '\n device_replacement: '$1 $2'\n brand_replacement: '$1$2'\n model_replacement: '$3'\n - regex: 'Android Application[^\\-]+ - (?:HTC|HUAWEI|LGE|LENOVO|MEDION|TCT) (HTC|HUAWEI|LG|LENOVO|MEDION|ALCATEL)[ _\\-](.+) \\w+ - '\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'\n - regex: 'Android Application[^\\-]+ - ([^ ]+) (.+) \\w+ - '\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " #########\n # 3Q\n # @ref: http://www.3q-int.com/\n #########\n - regex: '; *([BLRQ]C\\d{4}[A-Z]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '3Q $1'\n brand_replacement: '3Q'\n model_replacement: '$1'\n - regex: '; *(?:3Q_)([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '3Q $1'\n brand_replacement: '3Q'\n model_replacement: '$1'", " #########\n # Acer\n # @ref: http://us.acer.com/ac/en/US/content/group/tablets\n #########\n - regex: 'Android [34].*; *(A100|A101|A110|A200|A210|A211|A500|A501|A510|A511|A700(?: Lite| 3G|)|A701|B1-A71|A1-\\d{3}|B1-\\d{3}|V360|V370|W500|W500P|W501|W501P|W510|W511|W700|Slider SL101|DA22[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Acer'\n model_replacement: '$1'\n - regex: '; *Acer Iconia Tab ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Acer'\n model_replacement: '$1'\n - regex: '; *(Z1[1235]0|E320[^/]*|S500|S510|Liquid[^;/]*|Iconia A\\d+)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Acer'\n model_replacement: '$1'\n - regex: '; *(Acer |ACER )([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Acer'\n model_replacement: '$2'", " #########\n # Advent\n # @ref: https://en.wikipedia.org/wiki/Advent_Vega\n # @note: VegaBean and VegaComb (names derived from jellybean, honeycomb) are\n # custom ROM builds for Vega\n #########\n - regex: '; *(Advent |)(Vega(?:Bean|Comb|)).*?(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Advent'\n model_replacement: '$2'", " #########\n # Ainol\n # @ref: http://www.ainol.com/plugin.php?identifier=ainol&module=product\n #########\n - regex: '; *(Ainol |)((?:NOVO|[Nn]ovo)[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Ainol'\n model_replacement: '$2'", " #########\n # Airis\n # @ref: http://airis.es/Tienda/Default.aspx?idG=001\n #########\n - regex: '; *AIRIS[ _\\-]?([^/;\\)]+) *(?:;|\\)|Build)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Airis'\n model_replacement: '$1'\n - regex: '; *(OnePAD[^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Airis'\n model_replacement: '$1'", " #########\n # Airpad\n # @ref: ??\n #########\n - regex: '; *Airpad[ \\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Airpad $1'\n brand_replacement: 'Airpad'\n model_replacement: '$1'", " #########\n # Alcatel - TCT\n # @ref: http://www.alcatelonetouch.com/global-en/products/smartphones.html\n #########\n - regex: '; *(one ?touch) (EVO7|T10|T20)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Alcatel One Touch $2'\n brand_replacement: 'Alcatel'\n model_replacement: 'One Touch $2'\n - regex: '; *(?:alcatel[ _]|)(?:(?:one[ _]?touch[ _])|ot[ \\-])([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Alcatel One Touch $1'\n brand_replacement: 'Alcatel'\n model_replacement: 'One Touch $1'\n - regex: '; *(TCL)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'\n # operator specific models\n - regex: '; *(Vodafone Smart II|Optimus_Madrid)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Alcatel $1'\n brand_replacement: 'Alcatel'\n model_replacement: '$1'\n - regex: '; *BASE_Lutea_3(?: Build|\\) AppleWebKit)'\n device_replacement: 'Alcatel One Touch 998'\n brand_replacement: 'Alcatel'\n model_replacement: 'One Touch 998'\n - regex: '; *BASE_Varia(?: Build|\\) AppleWebKit)'\n device_replacement: 'Alcatel One Touch 918D'\n brand_replacement: 'Alcatel'\n model_replacement: 'One Touch 918D'", " #########\n # Allfine\n # @ref: http://www.myallfine.com/Products.asp\n #########\n - regex: '; *((?:FINE|Fine)\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Allfine'\n model_replacement: '$1'", " #########\n # Allview\n # @ref: http://www.allview.ro/produse/droseries/lista-tablete-pc/\n #########\n - regex: '; *(ALLVIEW[ _]?|Allview[ _]?)((?:Speed|SPEED).*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Allview'\n model_replacement: '$2'\n - regex: '; *(ALLVIEW[ _]?|Allview[ _]?|)(AX1_Shine|AX2_Frenzy)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Allview'\n model_replacement: '$2'\n - regex: '; *(ALLVIEW[ _]?|Allview[ _]?)([^;/]*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Allview'\n model_replacement: '$2'", " #########\n # Allwinner\n # @ref: http://www.allwinner.com/\n # @models: A31 (13.3\"),A20,A10,\n #########\n - regex: '; *(A13-MID)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Allwinner'\n model_replacement: '$1'\n - regex: '; *(Allwinner)[ _\\-]?([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Allwinner'\n model_replacement: '$1'", " #########\n # Amaway\n # @ref: http://www.amaway.cn/\n #########\n - regex: '; *(A651|A701B?|A702|A703|A705|A706|A707|A711|A712|A713|A717|A722|A785|A801|A802|A803|A901|A902|A1002|A1003|A1006|A1007|A9701|A9703|Q710|Q80)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Amaway'\n model_replacement: '$1'", " #########\n # Amoi\n # @ref: http://www.amoi.com/en/prd/prd_index.jspx\n #########\n - regex: '; *(?:AMOI|Amoi)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Amoi $1'\n brand_replacement: 'Amoi'\n model_replacement: '$1'\n - regex: '^(?:AMOI|Amoi)[ _]([^;/]+?) Linux'\n device_replacement: 'Amoi $1'\n brand_replacement: 'Amoi'\n model_replacement: '$1'", " #########\n # Aoc\n # @ref: http://latin.aoc.com/media_tablet\n #########\n - regex: '; *(MW(?:0[789]|10)[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Aoc'\n model_replacement: '$1'", " #########\n # Aoson\n # @ref: http://www.luckystar.com.cn/en/mid.aspx?page=1\n # @ref: http://www.luckystar.com.cn/en/mobiletel.aspx?page=1\n # @note: brand owned by luckystar\n #########\n - regex: '; *(G7|M1013|M1015G|M11[CG]?|M-?12[B]?|M15|M19[G]?|M30[ACQ]?|M31[GQ]|M32|M33[GQ]|M36|M37|M38|M701T|M710|M712B|M713|M715G|M716G|M71(?:G|GS|T|)|M72[T]?|M73[T]?|M75[GT]?|M77G|M79T|M7L|M7LN|M81|M810|M81T|M82|M92|M92KS|M92S|M717G|M721|M722G|M723|M725G|M739|M785|M791|M92SK|M93D)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Aoson $1'\n brand_replacement: 'Aoson'\n model_replacement: '$1'\n - regex: '; *Aoson ([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Aoson $1'\n brand_replacement: 'Aoson'\n model_replacement: '$1'", " #########\n # Apanda\n # @ref: http://www.apanda.com.cn/\n #########\n - regex: '; *[Aa]panda[ _\\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Apanda $1'\n brand_replacement: 'Apanda'\n model_replacement: '$1'", " #########\n # Archos\n # @ref: http://www.archos.com/de/products/tablets.html\n # @ref: http://www.archos.com/de/products/smartphones/index.html\n #########\n - regex: '; *(?:ARCHOS|Archos) ?(GAMEPAD.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Archos $1'\n brand_replacement: 'Archos'\n model_replacement: '$1'\n - regex: 'ARCHOS; GOGI; ([^;]+);'\n device_replacement: 'Archos $1'\n brand_replacement: 'Archos'\n model_replacement: '$1'\n - regex: '(?:ARCHOS|Archos)[ _]?(.*?)(?: Build|[;/\\(\\)\\-]|$)'\n device_replacement: 'Archos $1'\n brand_replacement: 'Archos'\n model_replacement: '$1'\n - regex: '; *(AN(?:7|8|9|10|13)[A-Z0-9]{1,4})(?: Build|\\) AppleWebKit)'\n device_replacement: 'Archos $1'\n brand_replacement: 'Archos'\n model_replacement: '$1'\n - regex: '; *(A28|A32|A43|A70(?:BHT|CHT|HB|S|X)|A101(?:B|C|IT)|A7EB|A7EB-WK|101G9|80G9)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Archos $1'\n brand_replacement: 'Archos'\n model_replacement: '$1'", " #########\n # A-rival\n # @ref: http://www.a-rival.de/de/\n #########\n - regex: '; *(PAD-FMD[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Arival'\n model_replacement: '$1'\n - regex: '; *(BioniQ) ?([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Arival'\n model_replacement: '$1 $2'", " #########\n # Arnova\n # @ref: http://arnovatech.com/\n #########\n - regex: '; *(AN\\d[^;/]+|ARCHM\\d+)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Arnova $1'\n brand_replacement: 'Arnova'\n model_replacement: '$1'\n - regex: '; *(?:ARNOVA|Arnova) ?([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Arnova $1'\n brand_replacement: 'Arnova'\n model_replacement: '$1'", " #########\n # Assistant\n # @ref: http://www.assistant.ua\n #########\n - regex: '; *(?:ASSISTANT |)(AP)-?([1789]\\d{2}[A-Z]{0,2}|80104)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Assistant $1-$2'\n brand_replacement: 'Assistant'\n model_replacement: '$1-$2'", " #########\n # Asus\n # @ref: http://www.asus.com/uk/Tablets_Mobile/\n #########\n - regex: '; *(ME17\\d[^;/]*|ME3\\d{2}[^;/]+|K00[A-Z]|Nexus 10|Nexus 7(?: 2013|)|PadFone[^;/]*|Transformer[^;/]*|TF\\d{3}[^;/]*|eeepc)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Asus $1'\n brand_replacement: 'Asus'\n model_replacement: '$1'\n - regex: '; *ASUS[ _]*([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Asus $1'\n brand_replacement: 'Asus'\n model_replacement: '$1'", " #########\n # Garmin-Asus\n #########\n - regex: '; *Garmin-Asus ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Garmin-Asus $1'\n brand_replacement: 'Garmin-Asus'\n model_replacement: '$1'\n - regex: '; *(Garminfone)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Garmin $1'\n brand_replacement: 'Garmin-Asus'\n model_replacement: '$1'", " #########\n # Attab\n # @ref: http://www.theattab.com/\n #########\n - regex: '; (@TAB-[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Attab'\n model_replacement: '$1'", " #########\n # Audiosonic\n # @ref: ??\n # @note: Take care with Docomo T-01 Toshiba\n #########\n - regex: '; *(T-(?:07|[^0]\\d)[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Audiosonic'\n model_replacement: '$1'", " #########\n # Axioo\n # @ref: http://www.axiooworld.com/ww/index.php\n #########\n - regex: '; *(?:Axioo[ _\\-]([^;/]+?)|(picopad)[ _\\-]([^;/]+?))(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Axioo $1$2 $3'\n brand_replacement: 'Axioo'\n model_replacement: '$1$2 $3'", " #########\n # Azend\n # @ref: http://azendcorp.com/index.php/products/portable-electronics\n #########\n - regex: '; *(V(?:100|700|800)[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Azend'\n model_replacement: '$1'", " #########\n # Bak\n # @ref: http://www.bakinternational.com/produtos.php?cat=80\n #########\n - regex: '; *(IBAK\\-[^;/]*)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Bak'\n model_replacement: '$1'", " #########\n # Bedove\n # @ref: http://www.bedove.com/product.html\n # @models: HY6501|HY5001|X12|X21|I5\n #########\n - regex: '; *(HY5001|HY6501|X12|X21|I5)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Bedove $1'\n brand_replacement: 'Bedove'\n model_replacement: '$1'", " #########\n # Benss\n # @ref: http://www.benss.net/\n #########\n - regex: '; *(JC-[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Benss $1'\n brand_replacement: 'Benss'\n model_replacement: '$1'", " #########\n # Blackberry\n # @ref: http://uk.blackberry.com/\n # @note: Android Apps seams to be used here\n #########\n - regex: '; *(BB) ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Blackberry'\n model_replacement: '$2'", " #########\n # Blackbird\n # @ref: http://iblackbird.co.kr\n #########\n - regex: '; *(BlackBird)[ _](I8.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'\n - regex: '; *(BlackBird)[ _](.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " #########\n # Blaupunkt\n # @ref: http://www.blaupunkt.com\n #########\n # Endeavour\n - regex: '; *([0-9]+BP[EM][^;/]*|Endeavour[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Blaupunkt $1'\n brand_replacement: 'Blaupunkt'\n model_replacement: '$1'", " #########\n # Blu\n # @ref: http://bluproducts.com\n #########\n - regex: '; *((?:BLU|Blu)[ _\\-])([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Blu'\n model_replacement: '$2'\n # BMOBILE = operator branded device\n - regex: '; *(?:BMOBILE )?(Blu|BLU|DASH [^;/]+|VIVO 4\\.3|TANK 4\\.5)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Blu'\n model_replacement: '$1'", " #########\n # Blusens\n # @ref: http://www.blusens.com/es/?sg=1&sv=al&roc=1\n #########\n # tablet\n - regex: '; *(TOUCH\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Blusens'\n model_replacement: '$1'", " #########\n # Bmobile\n # @ref: http://bmobile.eu.com/?categoria=smartphones-2\n # @note: Might collide with Maxx as AX is used also there.\n #########\n # smartphone\n - regex: '; *(AX5\\d+)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Bmobile'\n model_replacement: '$1'", " #########\n # bq\n # @ref: http://bqreaders.com\n #########\n - regex: '; *([Bb]q) ([^;/]+?);?(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'bq'\n model_replacement: '$2'\n - regex: '; *(Maxwell [^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'bq'\n model_replacement: '$1'", " #########\n # Braun Phototechnik\n # @ref: http://www.braun-phototechnik.de/en/products/list/~pcat.250/Tablet-PC.html\n #########\n - regex: '; *((?:B-Tab|B-TAB) ?\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Braun'\n model_replacement: '$1'", " #########\n # Broncho\n # @ref: http://www.broncho.cn/\n #########\n - regex: '; *(Broncho) ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " #########\n # Captiva\n # @ref: http://www.captiva-power.de\n #########\n - regex: '; *CAPTIVA ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Captiva $1'\n brand_replacement: 'Captiva'\n model_replacement: '$1'", " #########\n # Casio\n # @ref: http://www.casiogzone.com/\n #########\n - regex: '; *(C771|CAL21|IS11CA)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Casio'\n model_replacement: '$1'", " #########\n # Cat\n # @ref: http://www.cat-sound.com\n #########\n - regex: '; *(?:Cat|CAT) ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Cat $1'\n brand_replacement: 'Cat'\n model_replacement: '$1'\n - regex: '; *(?:Cat)(Nova.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Cat $1'\n brand_replacement: 'Cat'\n model_replacement: '$1'\n - regex: '; *(INM8002KP|ADM8000KP_[AB])(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Cat'\n model_replacement: 'Tablet PHOENIX 8.1J0'", " #########\n # Celkon\n # @ref: http://www.celkonmobiles.com/?_a=products\n # @models: A10, A19Q, A101, A105, A107, A107\\+, A112, A118, A119, A119Q, A15, A19, A20, A200, A220, A225, A22 Race, A27, A58, A59, A60, A62, A63, A64, A66, A67, A69, A75, A77, A79, A8\\+, A83, A85, A86, A87, A89 Ultima, A9\\+, A90, A900, A95, A97i, A98, AR 40, AR 45, AR 50, ML5\n #########\n - regex: '; *(?:[Cc]elkon[ _\\*]|CELKON[ _\\*])([^;/\\)]+) ?(?:Build|;|\\))'\n device_replacement: '$1'\n brand_replacement: 'Celkon'\n model_replacement: '$1'\n - regex: 'Build/(?:[Cc]elkon)+_?([^;/_\\)]+)'\n device_replacement: '$1'\n brand_replacement: 'Celkon'\n model_replacement: '$1'\n - regex: '; *(CT)-?(\\d+)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Celkon'\n model_replacement: '$1$2'\n # smartphones\n - regex: '; *(A19|A19Q|A105|A107[^;/\\)]*) ?(?:Build|;|\\))'\n device_replacement: '$1'\n brand_replacement: 'Celkon'\n model_replacement: '$1'", " #########\n # ChangJia\n # @ref: http://www.cjshowroom.com/eproducts.aspx?classcode=004001001\n # @brief: China manufacturer makes tablets for different small brands\n # (eg. http://www.zeepad.net/index.html)\n #########\n - regex: '; *(TPC[0-9]{4,5})(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'ChangJia'\n model_replacement: '$1'", " #########\n # Cloudfone\n # @ref: http://www.cloudfonemobile.com/\n #########\n - regex: '; *(Cloudfone)[ _](Excite)([^ ][^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2 $3'\n brand_replacement: 'Cloudfone'\n model_replacement: '$1 $2 $3'\n - regex: '; *(Excite|ICE)[ _](\\d+[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Cloudfone $1 $2'\n brand_replacement: 'Cloudfone'\n model_replacement: 'Cloudfone $1 $2'\n - regex: '; *(Cloudfone|CloudPad)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Cloudfone'\n model_replacement: '$1 $2'", " #########\n # Cmx\n # @ref: http://cmx.at/de/\n #########\n - regex: '; *((?:Aquila|Clanga|Rapax)[^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Cmx'\n model_replacement: '$1'", " #########\n # CobyKyros\n # @ref: http://cobykyros.com\n # @note: Be careful with MID\\d{3} from MpMan or Manta\n #########\n - regex: '; *(?:CFW-|Kyros )?(MID[0-9]{4}(?:[ABC]|SR|TV)?)(\\(3G\\)-4G| GB 8K| 3G| 8K| GB)? *(?:Build|[;\\)])'\n device_replacement: 'CobyKyros $1$2'\n brand_replacement: 'CobyKyros'\n model_replacement: '$1$2'", " #########\n # Coolpad\n # @ref: ??\n #########\n - regex: '; *([^;/]*)Coolpad[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Coolpad'\n model_replacement: '$1$2'", " #########\n # Cube\n # @ref: http://www.cube-tablet.com/buy-products.html\n #########\n - regex: '; *(CUBE[ _])?([KU][0-9]+ ?GT.*?|A5300)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1$2'\n brand_replacement: 'Cube'\n model_replacement: '$2'", " #########\n # Cubot\n # @ref: http://www.cubotmall.com/\n #########\n - regex: '; *CUBOT ([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Cubot'\n model_replacement: '$1'\n - regex: '; *(BOBBY)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Cubot'\n model_replacement: '$1'", " #########\n # Danew\n # @ref: http://www.danew.com/produits-tablette.php\n #########\n - regex: '; *(Dslide [^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Danew'\n model_replacement: '$1'", " #########\n # Dell\n # @ref: http://www.dell.com\n # @ref: http://www.softbank.jp/mobile/support/product/101dl/\n # @ref: http://www.softbank.jp/mobile/support/product/001dl/\n # @ref: http://developer.emnet.ne.jp/android.html\n # @ref: http://www.dell.com/in/p/mobile-xcd28/pd\n # @ref: http://www.dell.com/in/p/mobile-xcd35/pd\n #########\n - regex: '; *(XCD)[ _]?(28|35)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1$2'\n brand_replacement: 'Dell'\n model_replacement: '$1$2'\n - regex: '; *(001DL)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: 'Streak'\n - regex: '; *(?:Dell|DELL) (Streak)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: 'Streak'\n - regex: '; *(101DL|GS01|Streak Pro[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: 'Streak Pro'\n - regex: '; *([Ss]treak ?7)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: 'Streak 7'\n - regex: '; *(Mini-3iX)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: '$1'\n - regex: '; *(?:Dell|DELL)[ _](Aero|Venue|Thunder|Mini.*?|Streak[ _]Pro)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: '$1'\n - regex: '; *Dell[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: '$1'\n - regex: '; *Dell ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: '$1'", " #########\n # Denver\n # @ref: http://www.denver-electronics.com/tablets1/\n #########\n - regex: '; *(TA[CD]-\\d+[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Denver'\n model_replacement: '$1'", " #########\n # Dex\n # @ref: http://dex.ua/\n #########\n - regex: '; *(iP[789]\\d{2}(?:-3G)?|IP10\\d{2}(?:-8GB)?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Dex'\n model_replacement: '$1'", " #########\n # DNS AirTab\n # @ref: http://www.dns-shop.ru/\n #########\n - regex: '; *(AirTab)[ _\\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'DNS'\n model_replacement: '$1 $2'", " #########\n # Docomo (Operator Branded Device)\n # @ref: http://www.ipentec.com/document/document.aspx?page=android-useragent\n #########\n - regex: '; *(F\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Fujitsu'\n model_replacement: '$1'\n - regex: '; *(HT-03A)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: 'Magic'\n - regex: '; *(HT\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: '$1'\n - regex: '; *(L\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'LG'\n model_replacement: '$1'\n - regex: '; *(N\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Nec'\n model_replacement: '$1'\n - regex: '; *(P\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Panasonic'\n model_replacement: '$1'\n - regex: '; *(SC\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n - regex: '; *(SH\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Sharp'\n model_replacement: '$1'\n - regex: '; *(SO\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'SonyEricsson'\n model_replacement: '$1'\n - regex: '; *(T\\-0[12][^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Toshiba'\n model_replacement: '$1'", " #########\n # DOOV\n # @ref: http://www.doov.com.cn/\n #########\n - regex: '; *(DOOV)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'DOOV'\n model_replacement: '$2'", " #########\n # Enot\n # @ref: http://www.enot.ua/\n #########\n - regex: '; *(Enot|ENOT)[ -]?([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Enot'\n model_replacement: '$2'", " #########\n # Evercoss\n # @ref: http://evercoss.com/android/\n #########\n - regex: '; *[^;/]+ Build/(?:CROSS|Cross)+[ _\\-]([^\\)]+)'\n device_replacement: 'CROSS $1'\n brand_replacement: 'Evercoss'\n model_replacement: 'Cross $1'\n - regex: '; *(CROSS|Cross)[ _\\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Evercoss'\n model_replacement: 'Cross $2'", " #########\n # Explay\n # @ref: http://explay.ru/\n #########\n - regex: '; *Explay[_ ](.+?)(?:[\\)]| Build)'\n device_replacement: '$1'\n brand_replacement: 'Explay'\n model_replacement: '$1'", " #########\n # Fly\n # @ref: http://www.fly-phone.com/\n #########\n - regex: '; *(IQ.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Fly'\n model_replacement: '$1'\n - regex: '; *(Fly|FLY)[ _](IQ[^;]+?|F[34]\\d+[^;]*?);?(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Fly'\n model_replacement: '$2'", " #########\n # Fujitsu\n # @ref: http://www.fujitsu.com/global/\n #########\n - regex: '; *(M532|Q572|FJL21)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Fujitsu'\n model_replacement: '$1'", " #########\n # Galapad\n # @ref: http://www.galapad.net/product.html\n #########\n - regex: '; *(G1)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Galapad'\n model_replacement: '$1'", " #########\n # Geeksphone\n # @ref: http://www.geeksphone.com/\n #########\n - regex: '; *(Geeksphone) ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " #########\n # Gfive\n # @ref: http://www.gfivemobile.com/en\n #########\n #- regex: '; *(G\\'?FIVE) ([^;/]+) Build' # there is a problem with python yaml parser here\n - regex: '; *(G[^F]?FIVE) ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Gfive'\n model_replacement: '$2'", " #########\n # Gionee\n # @ref: http://www.gionee.com/\n #########\n - regex: '; *(Gionee)[ _\\-]([^;/]+?)(?:/[^;/]+|)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'Gionee'\n model_replacement: '$2'\n - regex: '; *(GN\\d+[A-Z]?|INFINITY_PASSION|Ctrl_V1)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Gionee $1'\n brand_replacement: 'Gionee'\n model_replacement: '$1'\n - regex: '; *(E3) Build/JOP40D'\n device_replacement: 'Gionee $1'\n brand_replacement: 'Gionee'\n model_replacement: '$1'\n - regex: '\\sGIONEE[-\\s_](\\w*)'\n regex_flag: 'i'\n device_replacement: 'Gionee $1'\n brand_replacement: 'Gionee'\n model_replacement: '$1'", " #########\n # GoClever\n # @ref: http://www.goclever.com\n #########\n - regex: '; *((?:FONE|QUANTUM|INSIGNIA) \\d+[^;/]*|PLAYTAB)(?: Build|\\) AppleWebKit)'\n device_replacement: 'GoClever $1'\n brand_replacement: 'GoClever'\n model_replacement: '$1'\n - regex: '; *GOCLEVER ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'GoClever $1'\n brand_replacement: 'GoClever'\n model_replacement: '$1'", " #########\n # Google\n # @ref: http://www.google.de/glass/start/\n #########\n - regex: '; *(Glass \\d+)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Google'\n model_replacement: '$1'\n - regex: '; *(Pixel.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Google'\n model_replacement: '$1'", " #########\n # Gigabyte\n # @ref: http://gsmart.gigabytecm.com/en/\n #########\n - regex: '; *(GSmart)[ -]([^/]+)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Gigabyte'\n model_replacement: '$1 $2'", " #########\n # Freescale development boards\n # @ref: http://www.freescale.com/webapp/sps/site/prod_summary.jsp?code=IMX53QSB\n #########\n - regex: '; *(imx5[13]_[^/]+)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Freescale $1'\n brand_replacement: 'Freescale'\n model_replacement: '$1'", " #########\n # Haier\n # @ref: http://www.haier.com/\n # @ref: http://www.haier.com/de/produkte/tablet/\n #########\n - regex: '; *Haier[ _\\-]([^/]+)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Haier $1'\n brand_replacement: 'Haier'\n model_replacement: '$1'\n - regex: '; *(PAD1016)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Haipad $1'\n brand_replacement: 'Haipad'\n model_replacement: '$1'", " #########\n # Haipad\n # @ref: http://www.haipad.net/\n # @models: V7P|M7SM7S|M9XM9X|M7XM7X|M9|M8|M7-M|M1002|M7|M701\n #########\n - regex: '; *(M701|M7|M8|M9)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Haipad $1'\n brand_replacement: 'Haipad'\n model_replacement: '$1'", " #########\n # Hannspree\n # @ref: http://www.hannspree.eu/\n # @models: SN10T1|SN10T2|SN70T31B|SN70T32W\n #########\n - regex: '; *(SN\\d+T[^;\\)/]*)(?: Build|[;\\)])'\n device_replacement: 'Hannspree $1'\n brand_replacement: 'Hannspree'\n model_replacement: '$1'", " #########\n # HCLme\n # @ref: http://www.hclmetablet.com/india/\n #########\n - regex: 'Build/HCL ME Tablet ([^;\\)]+)[\\);]'\n device_replacement: 'HCLme $1'\n brand_replacement: 'HCLme'\n model_replacement: '$1'\n - regex: '; *([^;\\/]+) Build/HCL'\n device_replacement: 'HCLme $1'\n brand_replacement: 'HCLme'\n model_replacement: '$1'", " #########\n # Hena\n # @ref: http://www.henadigital.com/en/product/index.asp?id=6\n #########\n - regex: '; *(MID-?\\d{4}C[EM])(?: Build|\\) AppleWebKit)'\n device_replacement: 'Hena $1'\n brand_replacement: 'Hena'\n model_replacement: '$1'", " #########\n # Hisense\n # @ref: http://www.hisense.com/\n #########\n - regex: '; *(EG\\d{2,}|HS-[^;/]+|MIRA[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Hisense $1'\n brand_replacement: 'Hisense'\n model_replacement: '$1'\n - regex: '; *(andromax[^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Hisense $1'\n brand_replacement: 'Hisense'\n model_replacement: '$1'", " #########\n # hitech\n # @ref: http://www.hitech-mobiles.com/\n #########\n - regex: '; *(?:AMAZE[ _](S\\d+)|(S\\d+)[ _]AMAZE)(?: Build|\\) AppleWebKit)'\n device_replacement: 'AMAZE $1$2'\n brand_replacement: 'hitech'\n model_replacement: 'AMAZE $1$2'", " #########\n # HP\n # @ref: http://www.hp.com/\n #########\n - regex: '; *(PlayBook)(?: Build|\\) AppleWebKit)'\n device_replacement: 'HP $1'\n brand_replacement: 'HP'\n model_replacement: '$1'\n - regex: '; *HP ([^/]+)(?: Build|\\) AppleWebKit)'\n device_replacement: 'HP $1'\n brand_replacement: 'HP'\n model_replacement: '$1'\n - regex: '; *([^/]+_tenderloin)(?: Build|\\) AppleWebKit)'\n device_replacement: 'HP TouchPad'\n brand_replacement: 'HP'\n model_replacement: 'TouchPad'", " #########\n # Huawei\n # @ref: http://www.huaweidevice.com\n # @note: Needs to be before HTC due to Desire HD Build on U8815\n #########\n - regex: '; *(HUAWEI |Huawei-|)([UY][^;/]+) Build/(?:Huawei|HUAWEI)([UY][^\\);]+)\\)'\n device_replacement: '$1$2'\n brand_replacement: 'Huawei'\n model_replacement: '$2'", " - regex: '; *([^;/]+) Build[/ ]Huawei(MT1-U06|[A-Z]+\\d+[^\\);]+)\\)'", " device_replacement: '$1'\n brand_replacement: 'Huawei'\n model_replacement: '$2'\n - regex: '; *(S7|M860) Build'\n device_replacement: '$1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'\n - regex: '; *((?:HUAWEI|Huawei)[ \\-]?)(MediaPad) Build'\n device_replacement: '$1$2'\n brand_replacement: 'Huawei'\n model_replacement: '$2'\n - regex: '; *((?:HUAWEI[ _]?|Huawei[ _]|)Ascend[ _])([^;/]+) Build'\n device_replacement: '$1$2'\n brand_replacement: 'Huawei'\n model_replacement: '$2'\n - regex: '; *((?:HUAWEI|Huawei)[ _\\-]?)((?:G700-|MT-)[^;/]+) Build'\n device_replacement: '$1$2'\n brand_replacement: 'Huawei'\n model_replacement: '$2'\n - regex: '; *((?:HUAWEI|Huawei)[ _\\-]?)([^;/]+) Build'\n device_replacement: '$1$2'\n brand_replacement: 'Huawei'\n model_replacement: '$2'\n - regex: '; *(MediaPad[^;]+|SpringBoard) Build/Huawei'\n device_replacement: '$1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'\n - regex: '; *([^;]+) Build/(?:Huawei|HUAWEI)'\n device_replacement: '$1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'\n - regex: '; *([Uu])([89]\\d{3}) Build'\n device_replacement: '$1$2'\n brand_replacement: 'Huawei'\n model_replacement: 'U$2'\n - regex: '; *(?:Ideos |IDEOS )(S7) Build'\n device_replacement: 'Huawei Ideos$1'\n brand_replacement: 'Huawei'\n model_replacement: 'Ideos$1'\n - regex: '; *(?:Ideos |IDEOS )([^;/]+\\s*|\\s*)Build'\n device_replacement: 'Huawei Ideos$1'\n brand_replacement: 'Huawei'\n model_replacement: 'Ideos$1'\n - regex: '; *(Orange Daytona|Pulse|Pulse Mini|Vodafone 858|C8500|C8600|C8650|C8660|Nexus 6P|ATH-.+?) Build[/ ]'\n device_replacement: 'Huawei $1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'\n - regex: '; *((?:[A-Z]{3})\\-L[A-Za0-9]{2})[\\)]'\n device_replacement: 'Huawei $1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'", " #########\n # HTC\n # @ref: http://www.htc.com/www/products/\n # @ref: http://en.wikipedia.org/wiki/List_of_HTC_phones\n #########", " - regex: '; *HTC[ _]([^;]+); Windows Phone'\n device_replacement: 'HTC $1'\n brand_replacement: 'HTC'\n model_replacement: '$1'", " # Android HTC with Version Number matcher\n # ; HTC_0P3Z11/1.12.161.3 Build\n # ;HTC_A3335 V2.38.841.1 Build\n - regex: '; *(?:HTC[ _/])+([^ _/]+)(?:[/\\\\]1\\.0 | V|/| +)\\d+\\.\\d[\\d\\.]*(?: *Build|\\))'\n device_replacement: 'HTC $1'\n brand_replacement: 'HTC'\n model_replacement: '$1'\n - regex: '; *(?:HTC[ _/])+([^ _/]+)(?:[ _/]([^ _/]+)|)(?:[/\\\\]1\\.0 | V|/| +)\\d+\\.\\d[\\d\\.]*(?: *Build|\\))'\n device_replacement: 'HTC $1 $2'\n brand_replacement: 'HTC'\n model_replacement: '$1 $2'\n - regex: '; *(?:HTC[ _/])+([^ _/]+)(?:[ _/]([^ _/]+)(?:[ _/]([^ _/]+)|)|)(?:[/\\\\]1\\.0 | V|/| +)\\d+\\.\\d[\\d\\.]*(?: *Build|\\))'\n device_replacement: 'HTC $1 $2 $3'\n brand_replacement: 'HTC'\n model_replacement: '$1 $2 $3'\n - regex: '; *(?:HTC[ _/])+([^ _/]+)(?:[ _/]([^ _/]+)(?:[ _/]([^ _/]+)(?:[ _/]([^ _/]+)|)|)|)(?:[/\\\\]1\\.0 | V|/| +)\\d+\\.\\d[\\d\\.]*(?: *Build|\\))'\n device_replacement: 'HTC $1 $2 $3 $4'\n brand_replacement: 'HTC'\n model_replacement: '$1 $2 $3 $4'", " # Android HTC without Version Number matcher\n - regex: '; *(?:(?:HTC|htc)(?:_blocked|)[ _/])+([^ _/;]+)(?: *Build|[;\\)]| - )'\n device_replacement: 'HTC $1'\n brand_replacement: 'HTC'\n model_replacement: '$1'\n - regex: '; *(?:(?:HTC|htc)(?:_blocked|)[ _/])+([^ _/]+)(?:[ _/]([^ _/;\\)]+)|)(?: *Build|[;\\)]| - )'\n device_replacement: 'HTC $1 $2'\n brand_replacement: 'HTC'\n model_replacement: '$1 $2'\n - regex: '; *(?:(?:HTC|htc)(?:_blocked|)[ _/])+([^ _/]+)(?:[ _/]([^ _/]+)(?:[ _/]([^ _/;\\)]+)|)|)(?: *Build|[;\\)]| - )'\n device_replacement: 'HTC $1 $2 $3'\n brand_replacement: 'HTC'\n model_replacement: '$1 $2 $3'\n - regex: '; *(?:(?:HTC|htc)(?:_blocked|)[ _/])+([^ _/]+)(?:[ _/]([^ _/]+)(?:[ _/]([^ _/]+)(?:[ _/]([^ /;]+)|)|)|)(?: *Build|[;\\)]| - )'\n device_replacement: 'HTC $1 $2 $3 $4'\n brand_replacement: 'HTC'\n model_replacement: '$1 $2 $3 $4'", " # HTC Streaming Player\n - regex: 'HTC Streaming Player [^\\/]*/[^\\/]*/ htc_([^/]+) /'\n device_replacement: 'HTC $1'\n brand_replacement: 'HTC'\n model_replacement: '$1'\n # general matcher for anything else\n - regex: '(?:[;,] *|^)(?:htccn_chs-|)HTC[ _-]?([^;]+?)(?: *Build|clay|Android|-?Mozilla| Opera| Profile| UNTRUSTED|[;/\\(\\)]|$)'\n regex_flag: 'i'\n device_replacement: 'HTC $1'\n brand_replacement: 'HTC'\n model_replacement: '$1'\n # Android matchers without HTC\n - regex: '; *(A6277|ADR6200|ADR6300|ADR6350|ADR6400[A-Z]*|ADR6425[A-Z]*|APX515CKT|ARIA|Desire[^_ ]*|Dream|EndeavorU|Eris|Evo|Flyer|HD2|Hero|HERO200|Hero CDMA|HTL21|Incredible|Inspire[A-Z0-9]*|Legend|Liberty|Nexus ?(?:One|HD2)|One|One S C2|One[ _]?(?:S|V|X\\+?)\\w*|PC36100|PG06100|PG86100|S31HT|Sensation|Wildfire)(?: Build|[/;\\(\\)])'\n regex_flag: 'i'\n device_replacement: 'HTC $1'\n brand_replacement: 'HTC'\n model_replacement: '$1'\n - regex: '; *(ADR6200|ADR6400L|ADR6425LVW|Amaze|DesireS?|EndeavorU|Eris|EVO|Evo\\d[A-Z]+|HD2|IncredibleS?|Inspire[A-Z0-9]*|Inspire[A-Z0-9]*|Sensation[A-Z0-9]*|Wildfire)[ _-](.+?)(?:[/;\\)]|Build|MIUI|1\\.0)'\n regex_flag: 'i'\n device_replacement: 'HTC $1 $2'\n brand_replacement: 'HTC'\n model_replacement: '$1 $2'", " #########\n # Hyundai\n # @ref: http://www.hyundaitechnologies.com\n #########\n - regex: '; *HYUNDAI (T\\d[^/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Hyundai $1'\n brand_replacement: 'Hyundai'\n model_replacement: '$1'\n - regex: '; *HYUNDAI ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Hyundai $1'\n brand_replacement: 'Hyundai'\n model_replacement: '$1'\n # X900? http://www.amazon.com/Hyundai-X900-Retina-Android-Bluetooth/dp/B00AO07H3O\n - regex: '; *(X700|Hold X|MB-6900)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Hyundai $1'\n brand_replacement: 'Hyundai'\n model_replacement: '$1'", " #########\n # iBall\n # @ref: http://www.iball.co.in/Category/Mobiles/22\n #########\n - regex: '; *(?:iBall[ _\\-]|)(Andi)[ _]?(\\d[^;/]*)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'iBall'\n model_replacement: '$1 $2'\n - regex: '; *(IBall)(?:[ _]([^;/]+?)|)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'iBall'\n model_replacement: '$2'", " #########\n # IconBIT\n # @ref: http://www.iconbit.com/catalog/tablets/\n #########\n - regex: '; *(NT-\\d+[^ ;/]*|Net[Tt]AB [^;/]+|Mercury [A-Z]+|iconBIT)(?: S/N:[^;/]+|)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'IconBIT'\n model_replacement: '$1'", " #########\n # IMO\n # @ref: http://www.ponselimo.com/\n #########\n - regex: '; *(IMO)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'IMO'\n model_replacement: '$2'", " #########\n # i-mobile\n # @ref: http://www.i-mobilephone.com/\n #########\n - regex: '; *i-?mobile[ _]([^/]+)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'i-mobile $1'\n brand_replacement: 'imobile'\n model_replacement: '$1'\n - regex: '; *(i-(?:style|note)[^/]*)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'i-mobile $1'\n brand_replacement: 'imobile'\n model_replacement: '$1'", " #########\n # Impression\n # @ref: http://impression.ua/planshetnye-kompyutery\n #########\n - regex: '; *(ImPAD) ?(\\d+(?:.)*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Impression'\n model_replacement: '$1 $2'", " #########\n # Infinix\n # @ref: http://www.infinixmobility.com/index.html\n #########\n - regex: '; *(Infinix)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Infinix'\n model_replacement: '$2'", " #########\n # Informer\n # @ref: ??\n #########\n - regex: '; *(Informer)[ \\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Informer'\n model_replacement: '$2'", " #########\n # Intenso\n # @ref: http://www.intenso.de\n # @models: 7\":TAB 714,TAB 724;8\":TAB 814,TAB 824;10\":TAB 1004\n #########\n - regex: '; *(TAB) ?([78][12]4)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Intenso $1'\n brand_replacement: 'Intenso'\n model_replacement: '$1 $2'", " #########\n # Intex\n # @ref: http://intexmobile.in/index.aspx\n # @note: Zync also offers a \"Cloud Z5\" device\n #########\n # smartphones\n - regex: '; *(?:Intex[ _]|)(AQUA|Aqua)([ _\\.\\-])([^;/]+?) *(?:Build|;)'\n device_replacement: '$1$2$3'\n brand_replacement: 'Intex'\n model_replacement: '$1 $3'\n # matches \"INTEX CLOUD X1\"\n - regex: '; *(?:INTEX|Intex)(?:[_ ]([^\\ _;/]+))(?:[_ ]([^\\ _;/]+)|) *(?:Build|;)'\n device_replacement: '$1 $2'\n brand_replacement: 'Intex'\n model_replacement: '$1 $2'\n # tablets\n - regex: '; *([iI]Buddy)[ _]?(Connect)(?:_|\\?_| |)([^;/]*) *(?:Build|;)'\n device_replacement: '$1 $2 $3'\n brand_replacement: 'Intex'\n model_replacement: 'iBuddy $2 $3'\n - regex: '; *(I-Buddy)[ _]([^;/]+?) *(?:Build|;)'\n device_replacement: '$1 $2'\n brand_replacement: 'Intex'\n model_replacement: 'iBuddy $2'", " #########\n # iOCEAN\n # @ref: http://www.iocean.cc/\n #########\n - regex: '; *(iOCEAN) ([^/]+)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'iOCEAN'\n model_replacement: '$2'", " #########\n # i.onik\n # @ref: http://www.i-onik.de/\n #########\n - regex: '; *(TP\\d+(?:\\.\\d+|)\\-\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'ionik $1'\n brand_replacement: 'ionik'\n model_replacement: '$1'", " #########\n # IRU.ru\n # @ref: http://www.iru.ru/catalog/soho/planetable/\n #########\n - regex: '; *(M702pro)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Iru'\n model_replacement: '$1'", " #########\n # Ivio\n # @ref: http://www.ivio.com/mobile.php\n # @models: DG80,DG20,DE38,DE88,MD70\n #########\n - regex: '; *(DE88Plus|MD70)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Ivio'\n model_replacement: '$1'\n - regex: '; *IVIO[_\\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Ivio'\n model_replacement: '$1'", " #########\n # Jaytech\n # @ref: http://www.jay-tech.de/jaytech/servlet/frontend/\n #########\n - regex: '; *(TPC-\\d+|JAY-TECH)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Jaytech'\n model_replacement: '$1'", " #########\n # Jiayu\n # @ref: http://www.ejiayu.com/en/Product.html\n #########\n - regex: '; *(JY-[^;/]+|G[234]S?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Jiayu'\n model_replacement: '$1'", " #########\n # JXD\n # @ref: http://www.jxd.hk/\n #########\n - regex: '; *(JXD)[ _\\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'JXD'\n model_replacement: '$2'", " #########\n # Karbonn\n # @ref: http://www.karbonnmobiles.com/products_tablet.php\n #########\n - regex: '; *Karbonn[ _]?([^;/]+) *(?:Build|;)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Karbonn'\n model_replacement: '$1'\n - regex: '; *([^;]+) Build/Karbonn'\n device_replacement: '$1'\n brand_replacement: 'Karbonn'\n model_replacement: '$1'\n - regex: '; *(A11|A39|A37|A34|ST8|ST10|ST7|Smart Tab3|Smart Tab2|Titanium S\\d) +Build'\n device_replacement: '$1'\n brand_replacement: 'Karbonn'\n model_replacement: '$1'", " #########\n # KDDI (Operator Branded Device)\n # @ref: http://www.ipentec.com/document/document.aspx?page=android-useragent\n #########\n - regex: '; *(IS01|IS03|IS05|IS\\d{2}SH)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Sharp'\n model_replacement: '$1'\n - regex: '; *(IS04)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Regza'\n model_replacement: '$1'\n - regex: '; *(IS06|IS\\d{2}PT)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Pantech'\n model_replacement: '$1'\n - regex: '; *(IS11S)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'SonyEricsson'\n model_replacement: 'Xperia Acro'\n - regex: '; *(IS11CA)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Casio'\n model_replacement: 'GzOne $1'\n - regex: '; *(IS11LG)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'LG'\n model_replacement: 'Optimus X'\n - regex: '; *(IS11N)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Medias'\n model_replacement: '$1'\n - regex: '; *(IS11PT)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Pantech'\n model_replacement: 'MIRACH'\n - regex: '; *(IS12F)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Fujitsu'\n model_replacement: 'Arrows ES'\n # @ref: https://ja.wikipedia.org/wiki/IS12M\n - regex: '; *(IS12M)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Motorola'\n model_replacement: 'XT909'\n - regex: '; *(IS12S)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'SonyEricsson'\n model_replacement: 'Xperia Acro HD'\n - regex: '; *(ISW11F)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Fujitsu'\n model_replacement: 'Arrowz Z'\n - regex: '; *(ISW11HT)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: 'EVO'\n - regex: '; *(ISW11K)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Kyocera'\n model_replacement: 'DIGNO'\n - regex: '; *(ISW11M)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Motorola'\n model_replacement: 'Photon'\n - regex: '; *(ISW11SC)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Samsung'\n model_replacement: 'GALAXY S II WiMAX'\n - regex: '; *(ISW12HT)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: 'EVO 3D'\n - regex: '; *(ISW13HT)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: 'J'\n - regex: '; *(ISW?[0-9]{2}[A-Z]{0,2})(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'KDDI'\n model_replacement: '$1'\n - regex: '; *(INFOBAR [^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'KDDI'\n model_replacement: '$1'", " #########\n # Kingcom\n # @ref: http://www.e-kingcom.com\n #########\n - regex: '; *(JOYPAD|Joypad)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Kingcom'\n model_replacement: '$1 $2'", " #########\n # Kobo\n # @ref: https://en.wikipedia.org/wiki/Kobo_Inc.\n # @ref: http://www.kobo.com/devices#tablets\n #########\n - regex: '; *(Vox|VOX|Arc|K080)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Kobo'\n model_replacement: '$1'\n - regex: '\\b(Kobo Touch)\\b'\n device_replacement: '$1'\n brand_replacement: 'Kobo'\n model_replacement: '$1'", " #########\n # K-Touch\n # @ref: ??\n #########\n - regex: '; *(K-Touch)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'Ktouch'\n model_replacement: '$2'", " #########\n # KT Tech\n # @ref: http://www.kttech.co.kr\n #########\n - regex: '; *((?:EV|KM)-S\\d+[A-Z]?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'KTtech'\n model_replacement: '$1'", " #########\n # Kyocera\n # @ref: http://www.android.com/devices/?country=all&m=kyocera\n #########\n - regex: '; *(Zio|Hydro|Torque|Event|EVENT|Echo|Milano|Rise|URBANO PROGRESSO|WX04K|WX06K|WX10K|KYL21|101K|C5[12]\\d{2})(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Kyocera'\n model_replacement: '$1'", " #########\n # Lava\n # @ref: http://www.lavamobiles.com/\n #########\n - regex: '; *(?:LAVA[ _]|)IRIS[ _\\-]?([^/;\\)]+) *(?:;|\\)|Build)'\n regex_flag: 'i'\n device_replacement: 'Iris $1'\n brand_replacement: 'Lava'\n model_replacement: 'Iris $1'\n - regex: '; *LAVA[ _]([^;/]+) Build'\n device_replacement: '$1'\n brand_replacement: 'Lava'\n model_replacement: '$1'", " #########\n # Lemon\n # @ref: http://www.lemonmobiles.com/products.php?type=1\n #########\n - regex: '; *(?:(Aspire A1)|(?:LEMON|Lemon)[ _]([^;/]+))_?(?: Build|\\) AppleWebKit)'\n device_replacement: 'Lemon $1$2'\n brand_replacement: 'Lemon'\n model_replacement: '$1$2'", " #########\n # Lenco\n # @ref: http://www.lenco.com/c/tablets/\n #########\n - regex: '; *(TAB-1012)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Lenco $1'\n brand_replacement: 'Lenco'\n model_replacement: '$1'\n - regex: '; Lenco ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Lenco $1'\n brand_replacement: 'Lenco'\n model_replacement: '$1'", " #########\n # Lenovo\n # @ref: http://support.lenovo.com/en_GB/downloads/default.page?#\n #########\n - regex: '; *(A1_07|A2107A-H|S2005A-H|S1-37AH0) Build'\n device_replacement: '$1'\n brand_replacement: 'Lenovo'\n model_replacement: '$1'\n - regex: '; *(Idea[Tp]ab)[ _]([^;/]+);? Build'\n device_replacement: 'Lenovo $1 $2'\n brand_replacement: 'Lenovo'\n model_replacement: '$1 $2'\n - regex: '; *(Idea(?:Tab|pad)) ?([^;/]+) Build'\n device_replacement: 'Lenovo $1 $2'\n brand_replacement: 'Lenovo'\n model_replacement: '$1 $2'\n - regex: '; *(ThinkPad) ?(Tablet) Build/'\n device_replacement: 'Lenovo $1 $2'\n brand_replacement: 'Lenovo'\n model_replacement: '$1 $2'\n - regex: '; *(?:LNV-|)(?:=?[Ll]enovo[ _\\-]?|LENOVO[ _])(.+?)(?:Build|[;/\\)])'\n device_replacement: 'Lenovo $1'\n brand_replacement: 'Lenovo'\n model_replacement: '$1'\n - regex: '[;,] (?:Vodafone |)(SmartTab) ?(II) ?(\\d+) Build/'\n device_replacement: 'Lenovo $1 $2 $3'\n brand_replacement: 'Lenovo'\n model_replacement: '$1 $2 $3'\n - regex: '; *(?:Ideapad |)K1 Build/'\n device_replacement: 'Lenovo Ideapad K1'\n brand_replacement: 'Lenovo'\n model_replacement: 'Ideapad K1'\n - regex: '; *(3GC101|3GW10[01]|A390) Build/'\n device_replacement: '$1'\n brand_replacement: 'Lenovo'\n model_replacement: '$1'\n - regex: '\\b(?:Lenovo|LENOVO)+[ _\\-]?([^,;:/ ]+)'\n device_replacement: 'Lenovo $1'\n brand_replacement: 'Lenovo'\n model_replacement: '$1'", " #########\n # Lexibook\n # @ref: http://www.lexibook.com/fr\n #########\n - regex: '; *(MFC\\d+)[A-Z]{2}([^;,/]*),?(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Lexibook'\n model_replacement: '$1$2'", " #########\n # LG\n # @ref: http://www.lg.com/uk/mobile\n #########\n - regex: '; *(E[34][0-9]{2}|LS[6-8][0-9]{2}|VS[6-9][0-9]+[^;/]+|Nexus 4|Nexus 5X?|GT540f?|Optimus (?:2X|G|4X HD)|OptimusX4HD) *(?:Build|;)'\n device_replacement: '$1'\n brand_replacement: 'LG'\n model_replacement: '$1'\n - regex: '[;:] *(L-\\d+[A-Z]|LGL\\d+[A-Z]?)(?:/V\\d+|) *(?:Build|[;\\)])'\n device_replacement: '$1'\n brand_replacement: 'LG'\n model_replacement: '$1'\n - regex: '; *(LG-)([A-Z]{1,2}\\d{2,}[^,;/\\)\\(]*?)(?:Build| V\\d+|[,;/\\)\\(]|$)'\n device_replacement: '$1$2'\n brand_replacement: 'LG'\n model_replacement: '$2'\n - regex: '; *(LG[ \\-]|LG)([^;/]+)[;/]? Build'\n device_replacement: '$1$2'\n brand_replacement: 'LG'\n model_replacement: '$2'\n - regex: '^(LG)-([^;/]+)/ Mozilla/.*; Android'\n device_replacement: '$1 $2'\n brand_replacement: 'LG'\n model_replacement: '$2'\n - regex: '(Web0S); Linux/(SmartTV)'\n device_replacement: 'LG $1 $2'\n brand_replacement: 'LG'\n model_replacement: '$1 $2'", " #########\n # Malata\n # @ref: http://www.malata.com/en/products.aspx?classid=680\n #########\n - regex: '; *((?:SMB|smb)[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Malata'\n model_replacement: '$1'\n - regex: '; *(?:Malata|MALATA) ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Malata'\n model_replacement: '$1'", " #########\n # Manta\n # @ref: http://www.manta.com.pl/en\n #########\n - regex: '; *(MS[45][0-9]{3}|MID0[568][NS]?|MID[1-9]|MID[78]0[1-9]|MID970[1-9]|MID100[1-9])(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Manta'\n model_replacement: '$1'", " #########\n # Match\n # @ref: http://www.match.net.cn/products.asp\n #########\n - regex: '; *(M1052|M806|M9000|M9100|M9701|MID100|MID120|MID125|MID130|MID135|MID140|MID701|MID710|MID713|MID727|MID728|MID731|MID732|MID733|MID735|MID736|MID737|MID760|MID800|MID810|MID820|MID830|MID833|MID835|MID860|MID900|MID930|MID933|MID960|MID980)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Match'\n model_replacement: '$1'", " #########\n # Maxx\n # @ref: http://www.maxxmobile.in/\n # @models: Maxx MSD7-Play, Maxx MX245+ Trance, Maxx AX8 Race, Maxx MSD7 3G- AX50, Maxx Genx Droid 7 - AX40, Maxx AX5 Duo,\n # Maxx AX3 Duo, Maxx AX3, Maxx AX8 Note II (Note 2), Maxx AX8 Note I, Maxx AX8, Maxx AX5 Plus, Maxx MSD7 Smarty,\n # Maxx AX9Z Race,\n # Maxx MT150, Maxx MQ601, Maxx M2020, Maxx Sleek MX463neo, Maxx MX525, Maxx MX192-Tune, Maxx Genx Droid 7 AX353,\n # @note: Need more User-Agents!!!\n #########\n - regex: '; *(GenxDroid7|MSD7.*?|AX\\d.*?|Tab 701|Tab 722)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Maxx $1'\n brand_replacement: 'Maxx'\n model_replacement: '$1'", " #########\n # Mediacom\n # @ref: http://www.mediacomeurope.it/\n #########\n - regex: '; *(M-PP[^;/]+|PhonePad ?\\d{2,}[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Mediacom $1'\n brand_replacement: 'Mediacom'\n model_replacement: '$1'\n - regex: '; *(M-MP[^;/]+|SmartPad ?\\d{2,}[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Mediacom $1'\n brand_replacement: 'Mediacom'\n model_replacement: '$1'", " #########\n # Medion\n # @ref: http://www.medion.com/en/\n #########\n - regex: '; *(?:MD_|)LIFETAB[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Medion Lifetab $1'\n brand_replacement: 'Medion'\n model_replacement: 'Lifetab $1'\n - regex: '; *MEDION ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Medion $1'\n brand_replacement: 'Medion'\n model_replacement: '$1'", " #########\n # Meizu\n # @ref: http://www.meizu.com\n #########\n - regex: '; *(M030|M031|M035|M040|M065|m9)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Meizu $1'\n brand_replacement: 'Meizu'\n model_replacement: '$1'\n - regex: '; *(?:meizu_|MEIZU )(.+?) *(?:Build|[;\\)])'\n device_replacement: 'Meizu $1'\n brand_replacement: 'Meizu'\n model_replacement: '$1'", " #########\n # Micromax\n # @ref: http://www.micromaxinfo.com\n #########\n - regex: '; *(?:Micromax[ _](A111|A240)|(A111|A240)) Build'\n regex_flag: 'i'\n device_replacement: 'Micromax $1$2'\n brand_replacement: 'Micromax'\n model_replacement: '$1$2'\n - regex: '; *Micromax[ _](A\\d{2,3}[^;/]*) Build'\n regex_flag: 'i'\n device_replacement: 'Micromax $1'\n brand_replacement: 'Micromax'\n model_replacement: '$1'\n # be carefull here with Acer e.g. A500\n - regex: '; *(A\\d{2}|A[12]\\d{2}|A90S|A110Q) Build'\n regex_flag: 'i'\n device_replacement: 'Micromax $1'\n brand_replacement: 'Micromax'\n model_replacement: '$1'\n - regex: '; *Micromax[ _](P\\d{3}[^;/]*) Build'\n regex_flag: 'i'\n device_replacement: 'Micromax $1'\n brand_replacement: 'Micromax'\n model_replacement: '$1'\n - regex: '; *(P\\d{3}|P\\d{3}\\(Funbook\\)) Build'\n regex_flag: 'i'\n device_replacement: 'Micromax $1'\n brand_replacement: 'Micromax'\n model_replacement: '$1'", " #########\n # Mito\n # @ref: http://new.mitomobile.com/\n #########\n - regex: '; *(MITO)[ _\\-]?([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'Mito'\n model_replacement: '$2'", " #########\n # Mobistel\n # @ref: http://www.mobistel.com/\n #########\n - regex: '; *(Cynus)[ _](F5|T\\d|.+?) *(?:Build|[;/\\)])'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'Mobistel'\n model_replacement: '$1 $2'", " #########\n # Modecom\n # @ref: http://www.modecom.eu/tablets/portal/\n #########\n - regex: '; *(MODECOM |)(FreeTab) ?([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1$2 $3'\n brand_replacement: 'Modecom'\n model_replacement: '$2 $3'\n - regex: '; *(MODECOM )([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'Modecom'\n model_replacement: '$2'", " #########\n # Motorola\n # @ref: http://www.motorola.com/us/shop-all-mobile-phones/\n #########\n - regex: '; *(MZ\\d{3}\\+?|MZ\\d{3} 4G|Xoom|XOOM[^;/]*) Build'\n device_replacement: 'Motorola $1'\n brand_replacement: 'Motorola'\n model_replacement: '$1'\n - regex: '; *(Milestone )(XT[^;/]*) Build'\n device_replacement: 'Motorola $1$2'\n brand_replacement: 'Motorola'\n model_replacement: '$2'\n - regex: '; *(Motoroi ?x|Droid X|DROIDX) Build'\n regex_flag: 'i'\n device_replacement: 'Motorola $1'\n brand_replacement: 'Motorola'\n model_replacement: 'DROID X'\n - regex: '; *(Droid[^;/]*|DROID[^;/]*|Milestone[^;/]*|Photon|Triumph|Devour|Titanium) Build'\n device_replacement: 'Motorola $1'\n brand_replacement: 'Motorola'\n model_replacement: '$1'\n - regex: '; *(A555|A85[34][^;/]*|A95[356]|ME[58]\\d{2}\\+?|ME600|ME632|ME722|MB\\d{3}\\+?|MT680|MT710|MT870|MT887|MT917|WX435|WX453|WX44[25]|XT\\d{3,4}[A-Z\\+]*|CL[iI]Q|CL[iI]Q XT) Build'\n device_replacement: '$1'\n brand_replacement: 'Motorola'\n model_replacement: '$1'\n - regex: '; *(Motorola MOT-|Motorola[ _\\-]|MOT\\-?)([^;/]+) Build'\n device_replacement: '$1$2'\n brand_replacement: 'Motorola'\n model_replacement: '$2'\n - regex: '; *(Moto[_ ]?|MOT\\-)([^;/]+) Build'\n device_replacement: '$1$2'\n brand_replacement: 'Motorola'\n model_replacement: '$2'", " #########\n # MpMan\n # @ref: http://www.mpmaneurope.com\n #########\n - regex: '; *((?:MP[DQ]C|MPG\\d{1,4}|MP\\d{3,4}|MID(?:(?:10[234]|114|43|7[247]|8[24]|7)C|8[01]1))[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Mpman'\n model_replacement: '$1'", " #########\n # MSI\n # @ref: http://www.msi.com/product/windpad/\n #########\n - regex: '; *(?:MSI[ _]|)(Primo\\d+|Enjoy[ _\\-][^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'Msi'\n model_replacement: '$1'", " #########\n # Multilaser\n # http://www.multilaser.com.br/listagem_produtos.php?cat=5\n #########\n - regex: '; *Multilaser[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Multilaser'\n model_replacement: '$1'", " #########\n # MyPhone\n # @ref: http://myphone.com.ph/\n #########\n - regex: '; *(My)[_]?(Pad)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2 $3'\n brand_replacement: 'MyPhone'\n model_replacement: '$1$2 $3'\n - regex: '; *(My)\\|?(Phone)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2 $3'\n brand_replacement: 'MyPhone'\n model_replacement: '$3'\n - regex: '; *(A\\d+)[ _](Duo|)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'MyPhone'\n model_replacement: '$1 $2'", " #########\n # Mytab\n # @ref: http://www.mytab.eu/en/category/mytab-products/\n #########\n - regex: '; *(myTab[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Mytab'\n model_replacement: '$1'", " #########\n # Nabi\n # @ref: https://www.nabitablet.com\n #########\n - regex: '; *(NABI2?-)([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Nabi'\n model_replacement: '$2'", " #########\n # Nec Medias\n # @ref: http://www.n-keitai.com/\n #########\n - regex: '; *(N-\\d+[CDE])(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Nec'\n model_replacement: '$1'\n - regex: '; ?(NEC-)(.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Nec'\n model_replacement: '$2'\n - regex: '; *(LT-NA7)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Nec'\n model_replacement: 'Lifetouch Note'", " #########\n # Nextbook\n # @ref: http://nextbookusa.com\n #########\n - regex: '; *(NXM\\d+[A-Za-z0-9_]*|Next\\d[A-Za-z0-9_ \\-]*|NEXT\\d[A-Za-z0-9_ \\-]*|Nextbook [A-Za-z0-9_ ]*|DATAM803HC|M805)(?: Build|[\\);])'\n device_replacement: '$1'\n brand_replacement: 'Nextbook'\n model_replacement: '$1'", " #########\n # Nokia\n # @ref: http://www.nokia.com\n #########\n - regex: '; *(Nokia)([ _\\-]*)([^;/]*) Build'\n regex_flag: 'i'\n device_replacement: '$1$2$3'\n brand_replacement: 'Nokia'\n model_replacement: '$3'", " #########\n # Nook\n # @ref:\n # TODO nook browser/1.0\n #########\n - regex: '; *(Nook ?|Barnes & Noble Nook |BN )([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Nook'\n model_replacement: '$2'\n - regex: '; *(NOOK |)(BNRV200|BNRV200A|BNTV250|BNTV250A|BNTV400|BNTV600|LogicPD Zoom2)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Nook'\n model_replacement: '$2'\n - regex: '; Build/(Nook)'\n device_replacement: '$1'\n brand_replacement: 'Nook'\n model_replacement: 'Tablet'", " #########\n # Olivetti\n # @ref: http://www.olivetti.de/EN/Page/t02/view_html?idp=348\n #########\n - regex: '; *(OP110|OliPad[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Olivetti $1'\n brand_replacement: 'Olivetti'\n model_replacement: '$1'", " #########\n # Omega\n # @ref: http://omega-technology.eu/en/produkty/346/tablets\n # @note: MID tablets might get matched by CobyKyros first\n # @models: (T107|MID(?:700[2-5]|7031|7108|7132|750[02]|8001|8500|9001|971[12])\n #########\n - regex: '; *OMEGA[ _\\-](MID[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Omega $1'\n brand_replacement: 'Omega'\n model_replacement: '$1'\n - regex: '^(MID7500|MID\\d+) Mozilla/5\\.0 \\(iPad;'\n device_replacement: 'Omega $1'\n brand_replacement: 'Omega'\n model_replacement: '$1'", " #########\n # OpenPeak\n # @ref: https://support.google.com/googleplay/answer/1727131?hl=en\n #########\n - regex: '; *((?:CIUS|cius)[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Openpeak $1'\n brand_replacement: 'Openpeak'\n model_replacement: '$1'", " #########\n # Oppo\n # @ref: http://en.oppo.com/products/\n #########\n - regex: '; *(Find ?(?:5|7a)|R8[012]\\d{1,2}|T703\\d{0,1}|U70\\d{1,2}T?|X90\\d{1,2})(?: Build|\\) AppleWebKit)'\n device_replacement: 'Oppo $1'\n brand_replacement: 'Oppo'\n model_replacement: '$1'\n - regex: '; *OPPO ?([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Oppo $1'\n brand_replacement: 'Oppo'\n model_replacement: '$1'", " #########\n # Odys\n # @ref: http://odys.de\n #########\n - regex: '; *(?:Odys\\-|ODYS\\-|ODYS )([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Odys $1'\n brand_replacement: 'Odys'\n model_replacement: '$1'\n - regex: '; *(SELECT) ?(7)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Odys $1 $2'\n brand_replacement: 'Odys'\n model_replacement: '$1 $2'\n - regex: '; *(PEDI)_(PLUS)_(W)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Odys $1 $2 $3'\n brand_replacement: 'Odys'\n model_replacement: '$1 $2 $3'\n # Weltbild - Tablet PC 4 = Cat Phoenix = Odys Tablet PC 4?\n - regex: '; *(AEON|BRAVIO|FUSION|FUSION2IN1|Genio|EOS10|IEOS[^;/]*|IRON|Loox|LOOX|LOOX Plus|Motion|NOON|NOON_PRO|NEXT|OPOS|PEDI[^;/]*|PRIME[^;/]*|STUDYTAB|TABLO|Tablet-PC-4|UNO_X8|XELIO[^;/]*|Xelio ?\\d+ ?[Pp]ro|XENO10|XPRESS PRO)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Odys $1'\n brand_replacement: 'Odys'\n model_replacement: '$1'", " #########\n # OnePlus\n # @ref https://oneplus.net/\n #########\n - regex: '; (ONE [a-zA-Z]\\d+)(?: Build|\\) AppleWebKit)'\n device_replacement: 'OnePlus $1'\n brand_replacement: 'OnePlus'\n model_replacement: '$1'\n - regex: '; (ONEPLUS [a-zA-Z]\\d+)(?: Build|\\) AppleWebKit)'\n device_replacement: 'OnePlus $1'\n brand_replacement: 'OnePlus'\n model_replacement: '$1'", " #########\n # Orion\n # @ref: http://www.orion.ua/en/products/computer-products/tablet-pcs.html\n #########\n - regex: '; *(TP-\\d+)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Orion $1'\n brand_replacement: 'Orion'\n model_replacement: '$1'", " #########\n # PackardBell\n # @ref: http://www.packardbell.com/pb/en/AE/content/productgroup/tablets\n #########\n - regex: '; *(G100W?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'PackardBell $1'\n brand_replacement: 'PackardBell'\n model_replacement: '$1'", " #########\n # Panasonic\n # @ref: http://panasonic.jp/mobile/\n # @models: T11, T21, T31, P11, P51, Eluga Power, Eluga DL1\n # @models: (tab) Toughpad FZ-A1, Toughpad JT-B1\n #########\n - regex: '; *(Panasonic)[_ ]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'\n # Toughpad\n - regex: '; *(FZ-A1B|JT-B1)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Panasonic $1'\n brand_replacement: 'Panasonic'\n model_replacement: '$1'\n # Eluga Power\n - regex: '; *(dL1|DL1)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Panasonic $1'\n brand_replacement: 'Panasonic'\n model_replacement: '$1'", " #########\n # Pantech\n # @href: http://www.pantech.co.kr/en/prod/prodList.do?gbrand=PANTECH\n # @href: http://www.pantech.co.kr/en/prod/prodList.do?gbrand=VEGA\n # @models: ADR8995, ADR910L, ADR930VW, C790, CDM8992, CDM8999, IS06, IS11PT, P2000, P2020, P2030, P4100, P5000, P6010, P6020, P6030, P7000, P7040, P8000, P8010, P9020, P9050, P9060, P9070, P9090, PT001, PT002, PT003, TXT8040, TXT8045, VEGA PTL21\n #########\n - regex: '; *(SKY[ _]|)(IM\\-[AT]\\d{3}[^;/]+).* Build/'\n device_replacement: 'Pantech $1$2'\n brand_replacement: 'Pantech'\n model_replacement: '$1$2'\n - regex: '; *((?:ADR8995|ADR910L|ADR930L|ADR930VW|PTL21|P8000)(?: 4G|)) Build/'\n device_replacement: '$1'\n brand_replacement: 'Pantech'\n model_replacement: '$1'\n - regex: '; *Pantech([^;/]+).* Build/'\n device_replacement: 'Pantech $1'\n brand_replacement: 'Pantech'\n model_replacement: '$1'", " #########\n # Papayre\n # @ref: http://grammata.es/\n #########\n - regex: '; *(papyre)[ _\\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'Papyre'\n model_replacement: '$2'", " #########\n # Pearl\n # @ref: http://www.pearl.de/c-1540.shtml\n #########\n - regex: '; *(?:Touchlet )?(X10\\.[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Pearl $1'\n brand_replacement: 'Pearl'\n model_replacement: '$1'", " #########\n # Phicomm\n # @ref: http://www.phicomm.com.cn/\n #########\n - regex: '; PHICOMM (i800)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Phicomm $1'\n brand_replacement: 'Phicomm'\n model_replacement: '$1'\n - regex: '; PHICOMM ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Phicomm $1'\n brand_replacement: 'Phicomm'\n model_replacement: '$1'\n - regex: '; *(FWS\\d{3}[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Phicomm $1'\n brand_replacement: 'Phicomm'\n model_replacement: '$1'", " #########\n # Philips\n # @ref: http://www.support.philips.com/support/catalog/products.jsp?_dyncharset=UTF-8&country=&categoryid=MOBILE_PHONES_SMART_SU_CN_CARE&userLanguage=en&navCount=2&groupId=PC_PRODUCTS_AND_PHONES_GR_CN_CARE&catalogType=&navAction=push&userCountry=cn&title=Smartphones&cateId=MOBILE_PHONES_CA_CN_CARE\n # @TODO: Philips Tablets User-Agents missing!\n # @ref: http://www.support.philips.com/support/catalog/products.jsp?_dyncharset=UTF-8&country=&categoryid=ENTERTAINMENT_TABLETS_SU_CN_CARE&userLanguage=en&navCount=0&groupId=&catalogType=&navAction=push&userCountry=cn&title=Entertainment+Tablets&cateId=TABLETS_CA_CN_CARE\n #########\n # @note: this a best guess according to available philips models. Need more User-Agents\n - regex: '; *(D633|D822|D833|T539|T939|V726|W335|W336|W337|W3568|W536|W5510|W626|W632|W6350|W6360|W6500|W732|W736|W737|W7376|W820|W832|W8355|W8500|W8510|W930)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Philips'\n model_replacement: '$1'\n - regex: '; *(?:Philips|PHILIPS)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Philips $1'\n brand_replacement: 'Philips'\n model_replacement: '$1'", " #########\n # Pipo\n # @ref: http://www.pipo.cn/En/\n #########\n - regex: 'Android 4\\..*; *(M[12356789]|U[12368]|S[123])\\ ?(pro)?(?: Build|\\) AppleWebKit)'\n device_replacement: 'Pipo $1$2'\n brand_replacement: 'Pipo'\n model_replacement: '$1$2'", " #########\n # Ployer\n # @ref: http://en.ployer.cn/\n #########\n - regex: '; *(MOMO[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Ployer'\n model_replacement: '$1'", " #########\n # Polaroid/ Acho\n # @ref: http://polaroidstore.com/store/start.asp?category_id=382&category_id2=0&order=title&filter1=&filter2=&filter3=&view=all\n #########\n - regex: '; *(?:Polaroid[ _]|)((?:MIDC\\d{3,}|PMID\\d{2,}|PTAB\\d{3,})[^;/]*?)(\\/[^;/]*|)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Polaroid'\n model_replacement: '$1'\n - regex: '; *(?:Polaroid )(Tablet)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Polaroid'\n model_replacement: '$1'", " #########\n # Pomp\n # @ref: http://pompmobileshop.com/\n #########\n #~ TODO\n - regex: '; *(POMP)[ _\\-](.+?) *(?:Build|[;/\\)])'\n device_replacement: '$1 $2'\n brand_replacement: 'Pomp'\n model_replacement: '$2'", " #########\n # Positivo\n # @ref: http://www.positivoinformatica.com.br/www/pessoal/tablet-ypy/\n #########\n - regex: '; *(TB07STA|TB10STA|TB07FTA|TB10FTA)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Positivo'\n model_replacement: '$1'\n - regex: '; *(?:Positivo |)((?:YPY|Ypy)[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Positivo'\n model_replacement: '$1'", " #########\n # POV\n # @ref: http://www.pointofview-online.com/default2.php\n # @TODO: Smartphone Models MOB-3515, MOB-5045-B missing\n #########\n - regex: '; *(MOB-[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'POV'\n model_replacement: '$1'\n - regex: '; *POV[ _\\-]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'POV $1'\n brand_replacement: 'POV'\n model_replacement: '$1'\n - regex: '; *((?:TAB-PLAYTAB|TAB-PROTAB|PROTAB|PlayTabPro|Mobii[ _\\-]|TAB-P)[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: 'POV $1'\n brand_replacement: 'POV'\n model_replacement: '$1'", " #########\n # Prestigio\n # @ref: http://www.prestigio.com/catalogue/MultiPhones\n # @ref: http://www.prestigio.com/catalogue/MultiPads\n #########\n - regex: '; *(?:Prestigio |)((?:PAP|PMP)\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Prestigio $1'\n brand_replacement: 'Prestigio'\n model_replacement: '$1'", " #########\n # Proscan\n # @ref: http://www.proscanvideo.com/products-search.asp?itemClass=TABLET&itemnmbr=\n #########\n - regex: '; *(PLT[0-9]{4}.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Proscan'\n model_replacement: '$1'", " #########\n # QMobile\n # @ref: http://www.qmobile.com.pk/\n #########\n - regex: '; *(A2|A5|A8|A900)_?(Classic|)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Qmobile'\n model_replacement: '$1 $2'\n - regex: '; *(Q[Mm]obile)_([^_]+)_([^_]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Qmobile $2 $3'\n brand_replacement: 'Qmobile'\n model_replacement: '$2 $3'\n - regex: '; *(Q\\-?[Mm]obile)[_ ](A[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Qmobile $2'\n brand_replacement: 'Qmobile'\n model_replacement: '$2'", " #########\n # Qmobilevn\n # @ref: http://qmobile.vn/san-pham.html\n #########\n - regex: '; *(Q\\-Smart)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Qmobilevn'\n model_replacement: '$2'\n - regex: '; *(Q\\-?[Mm]obile)[ _\\-](S[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Qmobilevn'\n model_replacement: '$2'", " #########\n # Quanta\n # @ref: ?\n #########\n - regex: '; *(TA1013)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Quanta'\n model_replacement: '$1'", " #########\n # RCA\n # @ref: http://rcamobilephone.com/\n #########\n - regex: '; (RCT\\w+)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'RCA'\n model_replacement: '$1'\n - regex: '; RCA (\\w+)(?: Build|\\) AppleWebKit)'\n device_replacement: 'RCA $1'\n brand_replacement: 'RCA'\n model_replacement: '$1'", " #########\n # Rockchip\n # @ref: http://www.rock-chips.com/a/cn/product/index.html\n # @note: manufacturer sells chipsets - I assume that these UAs are dev-boards\n #########\n - regex: '; *(RK\\d+),?(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Rockchip'\n model_replacement: '$1'\n - regex: ' Build/(RK\\d+)'\n device_replacement: '$1'\n brand_replacement: 'Rockchip'\n model_replacement: '$1'", " #########\n # Samsung Android Devices\n # @ref: http://www.samsung.com/us/mobile/cell-phones/all-products\n #########\n - regex: '; *(SAMSUNG |Samsung |)((?:Galaxy (?:Note II|S\\d)|GT-I9082|GT-I9205|GT-N7\\d{3}|SM-N9005)[^;/]*)\\/?[^;/]* Build/'\n device_replacement: 'Samsung $1$2'\n brand_replacement: 'Samsung'\n model_replacement: '$2'\n - regex: '; *(Google |)(Nexus [Ss](?: 4G|)) Build/'\n device_replacement: 'Samsung $1$2'\n brand_replacement: 'Samsung'\n model_replacement: '$2'\n - regex: '; *(SAMSUNG |Samsung )([^\\/]*)\\/[^ ]* Build/'\n device_replacement: 'Samsung $2'\n brand_replacement: 'Samsung'\n model_replacement: '$2'\n - regex: '; *(Galaxy(?: Ace| Nexus| S ?II+|Nexus S| with MCR 1.2| Mini Plus 4G|)) Build/'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n - regex: '; *(SAMSUNG[ _\\-]|)(?:SAMSUNG[ _\\-])([^;/]+) Build'\n device_replacement: 'Samsung $2'\n brand_replacement: 'Samsung'\n model_replacement: '$2'\n - regex: '; *(SAMSUNG-|)(GT\\-[BINPS]\\d{4}[^\\/]*)(\\/[^ ]*) Build'\n device_replacement: 'Samsung $1$2$3'\n brand_replacement: 'Samsung'\n model_replacement: '$2'\n - regex: '(?:; *|^)((?:GT\\-[BIiNPS]\\d{4}|I9\\d{2}0[A-Za-z\\+]?\\b)[^;/\\)]*?)(?:Build|Linux|MIUI|[;/\\)])'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n - regex: '; (SAMSUNG-)([A-Za-z0-9\\-]+).* Build/'\n device_replacement: 'Samsung $1$2'\n brand_replacement: 'Samsung'\n model_replacement: '$2'\n - regex: '; *((?:SCH|SGH|SHV|SHW|SPH|SC|SM)\\-[A-Za-z0-9 ]+)(/?[^ ]*|) Build'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n - regex: '; *((?:SC)\\-[A-Za-z0-9 ]+)(/?[^ ]*|)\\)'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n - regex: ' ((?:SCH)\\-[A-Za-z0-9 ]+)(/?[^ ]*|) Build'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n - regex: '; *(Behold ?(?:2|II)|YP\\-G[^;/]+|EK-GC100|SCL21|I9300) Build'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n - regex: '; *((?:SCH|SGH|SHV|SHW|SPH|SC|SM)\\-[A-Za-z0-9]{5,6})[\\)]'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'", " #########\n # Sharp\n # @ref: http://www.sharp-phone.com/en/index.html\n # @ref: http://www.android.com/devices/?country=all&m=sharp\n #########\n - regex: '; *(SH\\-?\\d\\d[^;/]+|SBM\\d[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Sharp'\n model_replacement: '$1'\n - regex: '; *(SHARP[ -])([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Sharp'\n model_replacement: '$2'", " #########\n # Simvalley\n # @ref: http://www.simvalley-mobile.de/\n #########\n - regex: '; *(SPX[_\\-]\\d[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Simvalley'\n model_replacement: '$1'\n - regex: '; *(SX7\\-PEARL\\.GmbH)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Simvalley'\n model_replacement: '$1'\n - regex: '; *(SP[T]?\\-\\d{2}[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Simvalley'\n model_replacement: '$1'", " #########\n # SK Telesys\n # @ref: http://www.sk-w.com/phone/phone_list.jsp\n # @ref: http://www.android.com/devices/?country=all&m=sk-telesys\n #########\n - regex: '; *(SK\\-.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'SKtelesys'\n model_replacement: '$1'", " #########\n # Skytex\n # @ref: http://skytex.com/android\n #########\n - regex: '; *(?:SKYTEX|SX)-([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Skytex'\n model_replacement: '$1'\n - regex: '; *(IMAGINE [^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Skytex'\n model_replacement: '$1'", " #########\n # SmartQ\n # @ref: http://en.smartdevices.com.cn/Products/\n # @models: Z8, X7, U7H, U7, T30, T20, Ten3, V5-II, T7-3G, SmartQ5, K7, S7, Q8, T19, Ten2, Ten, R10, T7, R7, V5, V7, SmartQ7\n #########\n - regex: '; *(SmartQ) ?([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " #########\n # Smartbitt\n # @ref: http://www.smartbitt.com/\n # @missing: SBT Useragents\n #########\n - regex: '; *(WF7C|WF10C|SBT[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Smartbitt'\n model_replacement: '$1'", " #########\n # Softbank (Operator Branded Devices)\n # @ref: http://www.ipentec.com/document/document.aspx?page=android-useragent\n #########\n - regex: '; *(SBM(?:003SH|005SH|006SH|007SH|102SH)) Build'\n device_replacement: '$1'\n brand_replacement: 'Sharp'\n model_replacement: '$1'\n - regex: '; *(003P|101P|101P11C|102P) Build'\n device_replacement: '$1'\n brand_replacement: 'Panasonic'\n model_replacement: '$1'\n - regex: '; *(00\\dZ) Build/'\n device_replacement: '$1'\n brand_replacement: 'ZTE'\n model_replacement: '$1'\n - regex: '; HTC(X06HT) Build'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: '$1'\n - regex: '; *(001HT|X06HT) Build'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: '$1'\n - regex: '; *(201M) Build'\n device_replacement: '$1'\n brand_replacement: 'Motorola'\n model_replacement: 'XT902'", " #########\n # Trekstor\n # @ref: http://www.trekstor.co.uk/surftabs-en.html\n # @note: Must come before SonyEricsson\n #########\n - regex: '; *(ST\\d{4}.*)Build/ST'\n device_replacement: 'Trekstor $1'\n brand_replacement: 'Trekstor'\n model_replacement: '$1'\n - regex: '; *(ST\\d{4}.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Trekstor $1'\n brand_replacement: 'Trekstor'\n model_replacement: '$1'", " #########\n # SonyEricsson\n # @note: Must come before nokia since they also use symbian\n # @ref: http://www.android.com/devices/?country=all&m=sony-ericssons\n # @TODO: type!\n #########\n # android matchers\n - regex: '; *(Sony ?Ericsson ?)([^;/]+) Build'\n device_replacement: '$1$2'\n brand_replacement: 'SonyEricsson'\n model_replacement: '$2'\n - regex: '; *((?:SK|ST|E|X|LT|MK|MT|WT)\\d{2}[a-z0-9]*(?:-o|)|R800i|U20i) Build'\n device_replacement: '$1'\n brand_replacement: 'SonyEricsson'\n model_replacement: '$1'\n # TODO X\\d+ is wrong\n - regex: '; *(Xperia (?:A8|Arc|Acro|Active|Live with Walkman|Mini|Neo|Play|Pro|Ray|X\\d+)[^;/]*) Build'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'SonyEricsson'\n model_replacement: '$1'", " #########\n # Sony\n # @ref: http://www.sonymobile.co.jp/index.html\n # @ref: http://www.sonymobile.com/global-en/products/phones/\n # @ref: http://www.sony.jp/tablet/\n #########\n - regex: '; Sony (Tablet[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Sony $1'\n brand_replacement: 'Sony'\n model_replacement: '$1'\n - regex: '; Sony ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Sony $1'\n brand_replacement: 'Sony'\n model_replacement: '$1'\n - regex: '; *(Sony)([A-Za-z0-9\\-]+)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'\n - regex: '; *(Xperia [^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Sony'\n model_replacement: '$1'\n - regex: '; *(C(?:1[0-9]|2[0-9]|53|55|6[0-9])[0-9]{2}|D[25]\\d{3}|D6[56]\\d{2})(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Sony'\n model_replacement: '$1'\n - regex: '; *(SGP\\d{3}|SGPT\\d{2})(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Sony'\n model_replacement: '$1'\n - regex: '; *(NW-Z1000Series)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Sony'\n model_replacement: '$1'", " ##########\n # Sony PlayStation\n # @ref: http://playstation.com\n # The Vita spoofs the Kindle\n ##########\n - regex: 'PLAYSTATION 3'\n device_replacement: 'PlayStation 3'\n brand_replacement: 'Sony'\n model_replacement: 'PlayStation 3'\n - regex: '(PlayStation (?:Portable|Vita|\\d+))'\n device_replacement: '$1'\n brand_replacement: 'Sony'\n model_replacement: '$1'", " #########\n # Spice\n # @ref: http://www.spicemobilephones.co.in/\n #########\n - regex: '; *((?:CSL_Spice|Spice|SPICE|CSL)[ _\\-]?|)([Mm][Ii])([ _\\-]|)(\\d{3}[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2$3$4'\n brand_replacement: 'Spice'\n model_replacement: 'Mi$4'", " #########\n # Sprint (Operator Branded Devices)\n # @ref:\n #########\n - regex: '; *(Sprint )(.+?) *(?:Build|[;/])'\n device_replacement: '$1$2'\n brand_replacement: 'Sprint'\n model_replacement: '$2'\n - regex: '\\b(Sprint)[: ]([^;,/ ]+)'\n device_replacement: '$1$2'\n brand_replacement: 'Sprint'\n model_replacement: '$2'", " #########\n # Tagi\n # @ref: ??\n #########\n - regex: '; *(TAGI[ ]?)(MID) ?([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2$3'\n brand_replacement: 'Tagi'\n model_replacement: '$2$3'", " #########\n # Tecmobile\n # @ref: http://www.tecmobile.com/\n #########\n - regex: '; *(Oyster500|Opal 800)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Tecmobile $1'\n brand_replacement: 'Tecmobile'\n model_replacement: '$1'", " #########\n # Tecno\n # @ref: www.tecno-mobile.com/‎\n #########\n - regex: '; *(TECNO[ _])([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Tecno'\n model_replacement: '$2'", " #########\n # Telechips, Techvision evaluation boards\n # @ref:\n #########\n - regex: '; *Android for (Telechips|Techvision) ([^ ]+) '\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " #########\n # Telstra\n # @ref: http://www.telstra.com.au/home-phone/thub-2/\n # @ref: https://support.google.com/googleplay/answer/1727131?hl=en\n #########\n - regex: '; *(T-Hub2)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Telstra'\n model_replacement: '$1'", " #########\n # Terra\n # @ref: http://www.wortmann.de/\n #########\n - regex: '; *(PAD) ?(100[12])(?: Build|\\) AppleWebKit)'\n device_replacement: 'Terra $1$2'\n brand_replacement: 'Terra'\n model_replacement: '$1$2'", " #########\n # Texet\n # @ref: http://www.texet.ru/tablet/\n #########\n - regex: '; *(T[BM]-\\d{3}[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Texet'\n model_replacement: '$1'", " #########\n # Thalia\n # @ref: http://www.thalia.de/shop/tolino-shine-ereader/show/\n #########\n - regex: '; *(tolino [^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Thalia'\n model_replacement: '$1'\n - regex: '; *Build/.* (TOLINO_BROWSER)'\n device_replacement: '$1'\n brand_replacement: 'Thalia'\n model_replacement: 'Tolino Shine'", " #########\n # Thl\n # @ref: http://en.thl.com.cn/Mobile\n # @ref: http://thlmobilestore.com\n #########\n - regex: '; *(?:CJ[ -])?(ThL|THL)[ -]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Thl'\n model_replacement: '$2'\n - regex: '; *(T100|T200|T5|W100|W200|W8s)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Thl'\n model_replacement: '$1'", " #########\n # T-Mobile (Operator Branded Devices)\n #########\n # @ref: https://en.wikipedia.org/wiki/HTC_Hero\n - regex: '; *(T-Mobile[ _]G2[ _]Touch) Build'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: 'Hero'\n # @ref: https://en.wikipedia.org/wiki/HTC_Desire_Z\n - regex: '; *(T-Mobile[ _]G2) Build'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: 'Desire Z'\n - regex: '; *(T-Mobile myTouch Q) Build'\n device_replacement: '$1'\n brand_replacement: 'Huawei'\n model_replacement: 'U8730'\n - regex: '; *(T-Mobile myTouch) Build'\n device_replacement: '$1'\n brand_replacement: 'Huawei'\n model_replacement: 'U8680'\n - regex: '; *(T-Mobile_Espresso) Build'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: 'Espresso'\n - regex: '; *(T-Mobile G1) Build'\n device_replacement: '$1'\n brand_replacement: 'HTC'\n model_replacement: 'Dream'\n - regex: '\\b(T-Mobile ?|)(myTouch)[ _]?([34]G)[ _]?([^\\/]*) (?:Mozilla|Build)'\n device_replacement: '$1$2 $3 $4'\n brand_replacement: 'HTC'\n model_replacement: '$2 $3 $4'\n - regex: '\\b(T-Mobile)_([^_]+)_(.*) Build'\n device_replacement: '$1 $2 $3'\n brand_replacement: 'Tmobile'\n model_replacement: '$2 $3'\n - regex: '\\b(T-Mobile)[_ ]?(.*?)Build'\n device_replacement: '$1 $2'\n brand_replacement: 'Tmobile'\n model_replacement: '$2'", " #########\n # Tomtec\n # @ref: http://www.tom-tec.eu/pages/tablets.php\n #########\n - regex: ' (ATP[0-9]{4})(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Tomtec'\n model_replacement: '$1'", " #########\n # Tooky\n # @ref: http://www.tookymobile.com/\n #########\n - regex: ' *(TOOKY)[ _\\-]([^;/]+?) ?(?:Build|;)'\n regex_flag: 'i'\n device_replacement: '$1 $2'\n brand_replacement: 'Tooky'\n model_replacement: '$2'", " #########\n # Toshiba\n # @ref: http://www.toshiba.co.jp/\n # @missing: LT170, Thrive 7, TOSHIBA STB10\n #########\n - regex: '\\b(TOSHIBA_AC_AND_AZ|TOSHIBA_FOLIO_AND_A|FOLIO_AND_A)'\n device_replacement: '$1'\n brand_replacement: 'Toshiba'\n model_replacement: 'Folio 100'\n - regex: '; *([Ff]olio ?100)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Toshiba'\n model_replacement: 'Folio 100'\n - regex: '; *(AT[0-9]{2,3}(?:\\-A|LE\\-A|PE\\-A|SE|a|)|AT7-A|AT1S0|Hikari-iFrame/WDPF-[^;/]+|THRiVE|Thrive)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Toshiba $1'\n brand_replacement: 'Toshiba'\n model_replacement: '$1'", " #########\n # Touchmate\n # @ref: http://touchmatepc.com/new/\n #########\n - regex: '; *(TM-MID\\d+[^;/]+|TOUCHMATE|MID-750)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Touchmate'\n model_replacement: '$1'\n # @todo: needs verification user-agents missing\n - regex: '; *(TM-SM\\d+[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Touchmate'\n model_replacement: '$1'", " #########\n # Treq\n # @ref: http://www.treq.co.id/product\n #########\n - regex: '; *(A10 [Bb]asic2?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Treq'\n model_replacement: '$1'\n - regex: '; *(TREQ[ _\\-])([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1$2'\n brand_replacement: 'Treq'\n model_replacement: '$2'", " #########\n # Umeox\n # @ref: http://umeox.com/\n # @models: A936|A603|X-5|X-3\n #########\n # @todo: guessed markers\n - regex: '; *(X-?5|X-?3)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Umeox'\n model_replacement: '$1'\n # @todo: guessed markers\n - regex: '; *(A502\\+?|A936|A603|X1|X2)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Umeox'\n model_replacement: '$1'", " #########\n # Versus\n # @ref: http://versusuk.com/support.html\n #########\n - regex: '(TOUCH(?:TAB|PAD).+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Versus $1'\n brand_replacement: 'Versus'\n model_replacement: '$1'", " #########\n # Vertu\n # @ref: http://www.vertu.com/\n #########\n - regex: '(VERTU) ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'Vertu'\n model_replacement: '$2'", " #########\n # Videocon\n # @ref: http://www.videoconmobiles.com\n #########\n - regex: '; *(Videocon)[ _\\-]([^;/]+?) *(?:Build|;)'\n device_replacement: '$1 $2'\n brand_replacement: 'Videocon'\n model_replacement: '$2'\n - regex: ' (VT\\d{2}[A-Za-z]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Videocon'\n model_replacement: '$1'", " #########\n # Viewsonic\n # @ref: http://viewsonic.com\n #########\n - regex: '; *((?:ViewPad|ViewPhone|VSD)[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Viewsonic'\n model_replacement: '$1'\n - regex: '; *(ViewSonic-)([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'Viewsonic'\n model_replacement: '$2'\n - regex: '; *(GTablet.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Viewsonic'\n model_replacement: '$1'", " #########\n # vivo\n # @ref: http://vivo.cn/\n #########\n - regex: '; *([Vv]ivo)[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'vivo'\n model_replacement: '$2'", " #########\n # Vodafone (Operator Branded Devices)\n # @ref: ??\n #########\n - regex: '(Vodafone) (.*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " #########\n # Walton\n # @ref: http://www.waltonbd.com/\n #########\n - regex: '; *(?:Walton[ _\\-]|)(Primo[ _\\-][^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Walton $1'\n brand_replacement: 'Walton'\n model_replacement: '$1'", " #########\n # Wiko\n # @ref: http://fr.wikomobile.com/collection.php?s=Smartphones\n #########\n - regex: '; *(?:WIKO[ \\-]|)(CINK\\+?|BARRY|BLOOM|DARKFULL|DARKMOON|DARKNIGHT|DARKSIDE|FIZZ|HIGHWAY|IGGY|OZZY|RAINBOW|STAIRWAY|SUBLIM|WAX|CINK [^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Wiko $1'\n brand_replacement: 'Wiko'\n model_replacement: '$1'", " #########\n # WellcoM\n # @ref: ??\n #########\n - regex: '; *WellcoM-([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Wellcom $1'\n brand_replacement: 'Wellcom'\n model_replacement: '$1'", " ##########\n # WeTab\n # @ref: http://wetab.mobi/\n ##########\n - regex: '(?:(WeTab)-Browser|; (wetab) Build)'\n device_replacement: '$1'\n brand_replacement: 'WeTab'\n model_replacement: 'WeTab'", " #########\n # Wolfgang\n # @ref: http://wolfgangmobile.com/\n #########\n - regex: '; *(AT-AS[^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Wolfgang $1'\n brand_replacement: 'Wolfgang'\n model_replacement: '$1'", " #########\n # Woxter\n # @ref: http://www.woxter.es/es-es/categories/index\n #########\n - regex: '; *(?:Woxter|Wxt) ([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'Woxter $1'\n brand_replacement: 'Woxter'\n model_replacement: '$1'", " #########\n # Yarvik Zania\n # @ref: http://yarvik.com\n #########\n - regex: '; *(?:Xenta |Luna |)(TAB[234][0-9]{2}|TAB0[78]-\\d{3}|TAB0?9-\\d{3}|TAB1[03]-\\d{3}|SMP\\d{2}-\\d{3})(?: Build|\\) AppleWebKit)'\n device_replacement: 'Yarvik $1'\n brand_replacement: 'Yarvik'\n model_replacement: '$1'", " #########\n # Yifang\n # @note: Needs to be at the very last as manufacturer builds for other brands.\n # @ref: http://www.yifangdigital.com/\n # @models: M1010, M1011, M1007, M1008, M1005, M899, M899LP, M909, M8000,\n # M8001, M8002, M8003, M849, M815, M816, M819, M805, M878, M780LPW,\n # M778, M7000, M7000AD, M7000NBD, M7001, M7002, M7002KBD, M777, M767,\n # M789, M799, M769, M757, M755, M753, M752, M739, M729, M723, M712, M727\n #########\n - regex: '; *([A-Z]{2,4})(M\\d{3,}[A-Z]{2})([^;\\)\\/]*)(?: Build|[;\\)])'\n device_replacement: 'Yifang $1$2$3'\n brand_replacement: 'Yifang'\n model_replacement: '$2'", " #########\n # XiaoMi\n # @ref: http://www.xiaomi.com/event/buyphone\n #########\n - regex: '; *((Mi|MI|HM|MI-ONE|Redmi)[ -](NOTE |Note |)[^;/]*) (Build|MIUI)/'\n device_replacement: 'XiaoMi $1'\n brand_replacement: 'XiaoMi'\n model_replacement: '$1'\n - regex: '; *((Mi|MI|HM|MI-ONE|Redmi)[ -](NOTE |Note |)[^;/\\)]*)'\n device_replacement: 'XiaoMi $1'\n brand_replacement: 'XiaoMi'\n model_replacement: '$1'\n - regex: '; *(MIX) (Build|MIUI)/'\n device_replacement: 'XiaoMi $1'\n brand_replacement: 'XiaoMi'\n model_replacement: '$1'\n - regex: '; *((MIX) ([^;/]*)) (Build|MIUI)/'\n device_replacement: 'XiaoMi $1'\n brand_replacement: 'XiaoMi'\n model_replacement: '$1'", " #########\n # Xolo\n # @ref: http://www.xolo.in/\n #########\n - regex: '; *XOLO[ _]([^;/]*tab.*)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Xolo $1'\n brand_replacement: 'Xolo'\n model_replacement: '$1'\n - regex: '; *XOLO[ _]([^;/]+?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Xolo $1'\n brand_replacement: 'Xolo'\n model_replacement: '$1'\n - regex: '; *(q\\d0{2,3}[a-z]?)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: 'Xolo $1'\n brand_replacement: 'Xolo'\n model_replacement: '$1'", " #########\n # Xoro\n # @ref: http://www.xoro.de/produkte/\n #########\n - regex: '; *(PAD ?[79]\\d+[^;/]*|TelePAD\\d+[^;/])(?: Build|\\) AppleWebKit)'\n device_replacement: 'Xoro $1'\n brand_replacement: 'Xoro'\n model_replacement: '$1'", " #########\n # Zopo\n # @ref: http://www.zopomobiles.com/products.html\n #########\n - regex: '; *(?:(?:ZOPO|Zopo)[ _]([^;/]+?)|(ZP ?(?:\\d{2}[^;/]+|C2))|(C[2379]))(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2$3'\n brand_replacement: 'Zopo'\n model_replacement: '$1$2$3'", " #########\n # ZiiLabs\n # @ref: http://www.ziilabs.com/products/platforms/androidreferencetablets.php\n #########\n - regex: '; *(ZiiLABS) (Zii[^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'ZiiLabs'\n model_replacement: '$2'\n - regex: '; *(Zii)_([^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'ZiiLabs'\n model_replacement: '$2'", " #########\n # ZTE\n # @ref: http://www.ztedevices.com/\n #########\n - regex: '; *(ARIZONA|(?:ATLAS|Atlas) W|D930|Grand (?:[SX][^;]*?|Era|Memo[^;]*?)|JOE|(?:Kis|KIS)\\b[^;]*?|Libra|Light [^;]*?|N8[056][01]|N850L|N8000|N9[15]\\d{2}|N9810|NX501|Optik|(?:Vip )Racer[^;]*?|RacerII|RACERII|San Francisco[^;]*?|V9[AC]|V55|V881|Z[679][0-9]{2}[A-z]?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'ZTE'\n model_replacement: '$1'\n - regex: '; *([A-Z]\\d+)_USA_[^;]*(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'ZTE'\n model_replacement: '$1'\n - regex: '; *(SmartTab\\d+)[^;]*(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'ZTE'\n model_replacement: '$1'\n - regex: '; *(?:Blade|BLADE|ZTE-BLADE)([^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: 'ZTE Blade$1'\n brand_replacement: 'ZTE'\n model_replacement: 'Blade$1'\n - regex: '; *(?:Skate|SKATE|ZTE-SKATE)([^;/]*)(?: Build|\\) AppleWebKit)'\n device_replacement: 'ZTE Skate$1'\n brand_replacement: 'ZTE'\n model_replacement: 'Skate$1'\n - regex: '; *(Orange |Optimus )(Monte Carlo|San Francisco)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1$2'\n brand_replacement: 'ZTE'\n model_replacement: '$1$2'\n - regex: '; *(?:ZXY-ZTE_|ZTE\\-U |ZTE[\\- _]|ZTE-C[_ ])([^;/]+?)(?: Build|\\) AppleWebKit)'\n device_replacement: 'ZTE $1'\n brand_replacement: 'ZTE'\n model_replacement: '$1'\n # operator specific\n - regex: '; (BASE) (lutea|Lutea 2|Tab[^;]*?)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1 $2'\n brand_replacement: 'ZTE'\n model_replacement: '$1 $2'\n - regex: '; (Avea inTouch 2|soft stone|tmn smart a7|Movistar[ _]Link)(?: Build|\\) AppleWebKit)'\n regex_flag: 'i'\n device_replacement: '$1'\n brand_replacement: 'ZTE'\n model_replacement: '$1'\n - regex: '; *(vp9plus)\\)'\n device_replacement: '$1'\n brand_replacement: 'ZTE'\n model_replacement: '$1'", " ##########\n # Zync\n # @ref: http://www.zync.in/index.php/our-products/tablet-phablets\n ##########\n - regex: '; ?(Cloud[ _]Z5|z1000|Z99 2G|z99|z930|z999|z990|z909|Z919|z900)(?: Build|\\) AppleWebKit)'\n device_replacement: '$1'\n brand_replacement: 'Zync'\n model_replacement: '$1'", " ##########\n # Kindle\n # @note: Needs to be after Sony Playstation Vita as this UA contains Silk/3.2\n # @ref: https://developer.amazon.com/sdk/fire/specifications.html\n # @ref: http://amazonsilk.wordpress.com/useful-bits/silk-user-agent/\n ##########\n - regex: '; ?(KFOT|Kindle Fire) Build\\b'\n device_replacement: 'Kindle Fire'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire'\n - regex: '; ?(KFOTE|Amazon Kindle Fire2) Build\\b'\n device_replacement: 'Kindle Fire 2'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire 2'\n - regex: '; ?(KFTT) Build\\b'\n device_replacement: 'Kindle Fire HD'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire HD 7\"'\n - regex: '; ?(KFJWI) Build\\b'\n device_replacement: 'Kindle Fire HD 8.9\" WiFi'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire HD 8.9\" WiFi'\n - regex: '; ?(KFJWA) Build\\b'\n device_replacement: 'Kindle Fire HD 8.9\" 4G'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire HD 8.9\" 4G'\n - regex: '; ?(KFSOWI) Build\\b'\n device_replacement: 'Kindle Fire HD 7\" WiFi'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire HD 7\" WiFi'\n - regex: '; ?(KFTHWI) Build\\b'\n device_replacement: 'Kindle Fire HDX 7\" WiFi'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire HDX 7\" WiFi'\n - regex: '; ?(KFTHWA) Build\\b'\n device_replacement: 'Kindle Fire HDX 7\" 4G'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire HDX 7\" 4G'\n - regex: '; ?(KFAPWI) Build\\b'\n device_replacement: 'Kindle Fire HDX 8.9\" WiFi'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire HDX 8.9\" WiFi'\n - regex: '; ?(KFAPWA) Build\\b'\n device_replacement: 'Kindle Fire HDX 8.9\" 4G'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire HDX 8.9\" 4G'\n - regex: '; ?Amazon ([^;/]+) Build\\b'\n device_replacement: '$1'\n brand_replacement: 'Amazon'\n model_replacement: '$1'\n - regex: '; ?(Kindle) Build\\b'\n device_replacement: 'Kindle'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle'\n - regex: '; ?(Silk)/(\\d+)\\.(\\d+)(?:\\.([0-9\\-]+)|) Build\\b'\n device_replacement: 'Kindle Fire'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle Fire$2'\n - regex: ' (Kindle)/(\\d+\\.\\d+)'\n device_replacement: 'Kindle'\n brand_replacement: 'Amazon'\n model_replacement: '$1 $2'\n - regex: ' (Silk|Kindle)/(\\d+)\\.'\n device_replacement: 'Kindle'\n brand_replacement: 'Amazon'\n model_replacement: 'Kindle'", " #########\n # Devices from chinese manufacturer(s)\n # @note: identified by x-wap-profile http://218.249.47.94/Xianghe/.*\n #########\n - regex: '(sprd)\\-([^/]+)/'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'\n # @ref: http://eshinechina.en.alibaba.com/\n - regex: '; *(H\\d{2}00\\+?) Build'\n device_replacement: '$1'\n brand_replacement: 'Hero'\n model_replacement: '$1'\n - regex: '; *(iphone|iPhone5) Build/'\n device_replacement: 'Xianghe $1'\n brand_replacement: 'Xianghe'\n model_replacement: '$1'\n - regex: '; *(e\\d{4}[a-z]?_?v\\d+|v89_[^;/]+)[^;/]+ Build/'\n device_replacement: 'Xianghe $1'\n brand_replacement: 'Xianghe'\n model_replacement: '$1'", " #########\n # Cellular\n # @ref:\n # @note: Operator branded devices\n #########\n - regex: '\\bUSCC[_\\-]?([^ ;/\\)]+)'\n device_replacement: '$1'\n brand_replacement: 'Cellular'\n model_replacement: '$1'", " ######################################################################\n # Windows Phone Parsers\n ######################################################################", " #########\n # Alcatel Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|)(?:ALCATEL)[^;]*; *([^;,\\)]+)'\n device_replacement: 'Alcatel $1'\n brand_replacement: 'Alcatel'\n model_replacement: '$1'", " #########\n # Asus Windows Phones\n #########\n #~ - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|WpsLondonTest; ?|)(?:ASUS|Asus)[^;]*; *([^;,\\)]+)'\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|WpsLondonTest; ?|)(?:ASUS|Asus)[^;]*; *([^;,\\)]+)'\n device_replacement: 'Asus $1'\n brand_replacement: 'Asus'\n model_replacement: '$1'", " #########\n # Dell Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|)(?:DELL|Dell)[^;]*; *([^;,\\)]+)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: '$1'", " #########\n # HTC Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|WpsLondonTest; ?|)(?:HTC|Htc|HTC_blocked[^;]*)[^;]*; *(?:HTC|)([^;,\\)]+)'\n device_replacement: 'HTC $1'\n brand_replacement: 'HTC'\n model_replacement: '$1'", " #########\n # Huawei Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|)(?:HUAWEI)[^;]*; *(?:HUAWEI |)([^;,\\)]+)'\n device_replacement: 'Huawei $1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'", " #########\n # LG Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|)(?:LG|Lg)[^;]*; *(?:LG[ \\-]|)([^;,\\)]+)'\n device_replacement: 'LG $1'\n brand_replacement: 'LG'\n model_replacement: '$1'", " #########\n # Noka Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|)(?:rv:11; |)(?:NOKIA|Nokia)[^;]*; *(?:NOKIA ?|Nokia ?|LUMIA ?|[Ll]umia ?|)(\\d{3,10}[^;\\)]*)'\n device_replacement: 'Lumia $1'\n brand_replacement: 'Nokia'\n model_replacement: 'Lumia $1'\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|)(?:NOKIA|Nokia)[^;]*; *(RM-\\d{3,})'\n device_replacement: 'Nokia $1'\n brand_replacement: 'Nokia'\n model_replacement: '$1'\n - regex: '(?:Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)]|WPDesktop;) ?(?:ARM; ?Touch; ?|Touch; ?|)(?:NOKIA|Nokia)[^;]*; *(?:NOKIA ?|Nokia ?|LUMIA ?|[Ll]umia ?|)([^;\\)]+)'\n device_replacement: 'Nokia $1'\n brand_replacement: 'Nokia'\n model_replacement: '$1'", " #########\n # Microsoft Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|)(?:Microsoft(?: Corporation|))[^;]*; *([^;,\\)]+)'\n device_replacement: 'Microsoft $1'\n brand_replacement: 'Microsoft'\n model_replacement: '$1'", " #########\n # Samsung Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|WpsLondonTest; ?|)(?:SAMSUNG)[^;]*; *(?:SAMSUNG |)([^;,\\.\\)]+)'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'", " #########\n # Toshiba Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|WpsLondonTest; ?|)(?:TOSHIBA|FujitsuToshibaMobileCommun)[^;]*; *([^;,\\)]+)'\n device_replacement: 'Toshiba $1'\n brand_replacement: 'Toshiba'\n model_replacement: '$1'", " #########\n # Generic Windows Phones\n #########\n - regex: 'Windows Phone [^;]+; .*?IEMobile/[^;\\)]+[;\\)] ?(?:ARM; ?Touch; ?|Touch; ?|WpsLondonTest; ?|)([^;]+); *([^;,\\)]+)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " ######################################################################\n # Other Devices Parser\n ######################################################################", " #########\n # Samsung Bada Phones\n #########\n - regex: '(?:^|; )SAMSUNG\\-([A-Za-z0-9\\-]+).* Bada/'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'", " #########\n # Firefox OS\n #########\n - regex: '\\(Mobile; ALCATEL ?(One|ONE) ?(Touch|TOUCH) ?([^;/]+?)(?:/[^;]+|); rv:[^\\)]+\\) Gecko/[^\\/]+ Firefox/'\n device_replacement: 'Alcatel $1 $2 $3'\n brand_replacement: 'Alcatel'\n model_replacement: 'One Touch $3'\n - regex: '\\(Mobile; (?:ZTE([^;]+)|(OpenC)); rv:[^\\)]+\\) Gecko/[^\\/]+ Firefox/'\n device_replacement: 'ZTE $1$2'\n brand_replacement: 'ZTE'\n model_replacement: '$1$2'", " #########\n # KaiOS\n #########\n - regex: '\\(Mobile; ALCATEL([A-Za-z0-9\\-]+); rv:[^\\)]+\\) Gecko/[^\\/]+ Firefox/[^\\/]+ KaiOS/'\n device_replacement: 'Alcatel $1'\n brand_replacement: 'Alcatel'\n model_replacement: '$1'\n - regex: '\\(Mobile; LYF\\/([A-Za-z0-9\\-]+)\\/.+;.+rv:[^\\)]+\\) Gecko/[^\\/]+ Firefox/[^\\/]+ KAIOS/'\n device_replacement: 'LYF $1'\n brand_replacement: 'LYF'\n model_replacement: '$1'\n - regex: '\\(Mobile; Nokia_([A-Za-z0-9\\-]+)_.+; rv:[^\\)]+\\) Gecko/[^\\/]+ Firefox/[^\\/]+ KAIOS/'\n device_replacement: 'Nokia $1'\n brand_replacement: 'Nokia'\n model_replacement: '$1'", " ##########\n # NOKIA\n # @note: NokiaN8-00 comes before iphone. Sometimes spoofs iphone\n ##########\n - regex: 'Nokia(N[0-9]+)([A-Za-z_\\-][A-Za-z0-9_\\-]*)'\n device_replacement: 'Nokia $1'\n brand_replacement: 'Nokia'\n model_replacement: '$1$2'\n - regex: '(?:NOKIA|Nokia)(?:\\-| *)(?:([A-Za-z0-9]+)\\-[0-9a-f]{32}|([A-Za-z0-9\\-]+)(?:UCBrowser)|([A-Za-z0-9\\-]+))'\n device_replacement: 'Nokia $1$2$3'\n brand_replacement: 'Nokia'\n model_replacement: '$1$2$3'\n - regex: 'Lumia ([A-Za-z0-9\\-]+)'\n device_replacement: 'Lumia $1'\n brand_replacement: 'Nokia'\n model_replacement: 'Lumia $1'\n # UCWEB Browser on Symbian\n - regex: '\\(Symbian; U; S60 V5; [A-z]{2}\\-[A-z]{2}; (SonyEricsson|Samsung|Nokia|LG)([^;/]+?)\\)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'\n # Nokia Symbian\n - regex: '\\(Symbian(?:/3|); U; ([^;]+);'\n device_replacement: 'Nokia $1'\n brand_replacement: 'Nokia'\n model_replacement: '$1'", " ##########\n # BlackBerry\n # @ref: http://www.useragentstring.com/pages/BlackBerry/\n ##########\n - regex: 'BB10; ([A-Za-z0-9\\- ]+)\\)'\n device_replacement: 'BlackBerry $1'\n brand_replacement: 'BlackBerry'\n model_replacement: '$1'\n - regex: 'Play[Bb]ook.+RIM Tablet OS'\n device_replacement: 'BlackBerry Playbook'\n brand_replacement: 'BlackBerry'\n model_replacement: 'Playbook'\n - regex: 'Black[Bb]erry ([0-9]+);'\n device_replacement: 'BlackBerry $1'\n brand_replacement: 'BlackBerry'\n model_replacement: '$1'\n - regex: 'Black[Bb]erry([0-9]+)'\n device_replacement: 'BlackBerry $1'\n brand_replacement: 'BlackBerry'\n model_replacement: '$1'\n - regex: 'Black[Bb]erry;'\n device_replacement: 'BlackBerry'\n brand_replacement: 'BlackBerry'", " ##########\n # PALM / HP\n # @note: some palm devices must come before iphone. sometimes spoofs iphone in ua\n ##########\n - regex: '(Pre|Pixi)/\\d+\\.\\d+'\n device_replacement: 'Palm $1'\n brand_replacement: 'Palm'\n model_replacement: '$1'\n - regex: 'Palm([0-9]+)'\n device_replacement: 'Palm $1'\n brand_replacement: 'Palm'\n model_replacement: '$1'\n - regex: 'Treo([A-Za-z0-9]+)'\n device_replacement: 'Palm Treo $1'\n brand_replacement: 'Palm'\n model_replacement: 'Treo $1'\n - regex: 'webOS.*(P160U(?:NA|))/(\\d+).(\\d+)'\n device_replacement: 'HP Veer'\n brand_replacement: 'HP'\n model_replacement: 'Veer'\n - regex: '(Touch[Pp]ad)/\\d+\\.\\d+'\n device_replacement: 'HP TouchPad'\n brand_replacement: 'HP'\n model_replacement: 'TouchPad'\n - regex: 'HPiPAQ([A-Za-z0-9]+)/\\d+.\\d+'\n device_replacement: 'HP iPAQ $1'\n brand_replacement: 'HP'\n model_replacement: 'iPAQ $1'\n - regex: 'PDA; (PalmOS)/sony/model ([a-z]+)/Revision'\n device_replacement: '$1'\n brand_replacement: 'Sony'\n model_replacement: '$1 $2'", " ##########\n # AppleTV\n # No built in browser that I can tell\n # Stack Overflow indicated iTunes-AppleTV/4.1 as a known UA for app available and I'm seeing it in live traffic\n ##########\n - regex: '(Apple\\s?TV)'\n device_replacement: 'AppleTV'\n brand_replacement: 'Apple'\n model_replacement: 'AppleTV'", " #########\n # Tesla Model S\n #########\n - regex: '(QtCarBrowser)'\n device_replacement: 'Tesla Model S'\n brand_replacement: 'Tesla'\n model_replacement: 'Model S'", " ##########\n # iSTUFF\n # @note: complete but probably catches spoofs\n # ipad and ipod must be parsed before iphone\n # cannot determine specific device type from ua string. (3g, 3gs, 4, etc)\n ##########\n # @note: on some ua the device can be identified e.g. iPhone5,1\n - regex: '(iPhone|iPad|iPod)(\\d+,\\d+)'\n device_replacement: '$1'\n brand_replacement: 'Apple'\n model_replacement: '$1$2'\n # @note: iPad needs to be before iPhone\n - regex: '(iPad)(?:;| Simulator;)'\n device_replacement: '$1'\n brand_replacement: 'Apple'\n model_replacement: '$1'\n - regex: '(iPod)(?:;| touch;| Simulator;)'\n device_replacement: '$1'\n brand_replacement: 'Apple'\n model_replacement: '$1'\n - regex: '(iPhone)(?:;| Simulator;)'\n device_replacement: '$1'\n brand_replacement: 'Apple'\n model_replacement: '$1'\n - regex: '(Watch)(\\d+,\\d+)'\n device_replacement: 'Apple $1'\n brand_replacement: 'Apple'\n model_replacement: '$1$2'\n - regex: '(Apple Watch)(?:;| Simulator;)'\n device_replacement: '$1'\n brand_replacement: 'Apple'\n model_replacement: '$1'\n - regex: '(HomePod)(?:;| Simulator;)'\n device_replacement: '$1'\n brand_replacement: 'Apple'\n model_replacement: '$1'\n - regex: 'iPhone'\n device_replacement: 'iPhone'\n brand_replacement: 'Apple'\n model_replacement: 'iPhone'\n # @note: desktop applications show device info\n - regex: 'CFNetwork/.* Darwin/\\d.*\\(((?:Mac|iMac|PowerMac|PowerBook)[^\\d]*)(\\d+)(?:,|%2C)(\\d+)'\n device_replacement: '$1$2,$3'\n brand_replacement: 'Apple'\n model_replacement: '$1$2,$3'\n # @note: newer desktop applications don't show device info\n # This is here so as to not have them recorded as iOS-Device\n - regex: 'CFNetwork/.* Darwin/\\d+\\.\\d+\\.\\d+ \\(x86_64\\)'\n device_replacement: 'Mac'\n brand_replacement: 'Apple'\n model_replacement: 'Mac'\n # @note: iOS applications do not show device info\n - regex: 'CFNetwork/.* Darwin/\\d'\n device_replacement: 'iOS-Device'\n brand_replacement: 'Apple'\n model_replacement: 'iOS-Device'", " ##########################\n # Outlook on iOS >= 2.62.0\n ##########################\n - regex: 'Outlook-(iOS)/\\d+\\.\\d+\\.prod\\.iphone'\n brand_replacement: 'Apple'\n device_replacement: 'iPhone'\n model_replacement: 'iPhone'", " ##########\n # Acer\n ##########\n - regex: 'acer_([A-Za-z0-9]+)_'\n device_replacement: 'Acer $1'\n brand_replacement: 'Acer'\n model_replacement: '$1'", " ##########\n # Alcatel\n ##########\n - regex: '(?:ALCATEL|Alcatel)-([A-Za-z0-9\\-]+)'\n device_replacement: 'Alcatel $1'\n brand_replacement: 'Alcatel'\n model_replacement: '$1'", " ##########\n # Amoi\n ##########\n - regex: '(?:Amoi|AMOI)\\-([A-Za-z0-9]+)'\n device_replacement: 'Amoi $1'\n brand_replacement: 'Amoi'\n model_replacement: '$1'", " ##########\n # Asus\n ##########\n - regex: '(?:; |\\/|^)((?:Transformer (?:Pad|Prime) |Transformer |PadFone[ _]?)[A-Za-z0-9]*)'\n device_replacement: 'Asus $1'\n brand_replacement: 'Asus'\n model_replacement: '$1'\n - regex: '(?:asus.*?ASUS|Asus|ASUS|asus)[\\- ;]*((?:Transformer (?:Pad|Prime) |Transformer |Padfone |Nexus[ _]|)[A-Za-z0-9]+)'\n device_replacement: 'Asus $1'\n brand_replacement: 'Asus'\n model_replacement: '$1'\n - regex: '(?:ASUS)_([A-Za-z0-9\\-]+)'\n device_replacement: 'Asus $1'\n brand_replacement: 'Asus'\n model_replacement: '$1'", "\n ##########\n # Bird\n ##########\n - regex: '\\bBIRD[ \\-\\.]([A-Za-z0-9]+)'\n device_replacement: 'Bird $1'\n brand_replacement: 'Bird'\n model_replacement: '$1'", " ##########\n # Dell\n ##########\n - regex: '\\bDell ([A-Za-z0-9]+)'\n device_replacement: 'Dell $1'\n brand_replacement: 'Dell'\n model_replacement: '$1'", " ##########\n # DoCoMo\n ##########\n - regex: 'DoCoMo/2\\.0 ([A-Za-z0-9]+)'\n device_replacement: 'DoCoMo $1'\n brand_replacement: 'DoCoMo'\n model_replacement: '$1'\n - regex: '([A-Za-z0-9]+)_W;FOMA'\n device_replacement: 'DoCoMo $1'\n brand_replacement: 'DoCoMo'\n model_replacement: '$1'\n - regex: '([A-Za-z0-9]+);FOMA'\n device_replacement: 'DoCoMo $1'\n brand_replacement: 'DoCoMo'\n model_replacement: '$1'", " ##########\n # htc\n ##########\n - regex: '\\b(?:HTC/|HTC/[a-z0-9]+/|)HTC[ _\\-;]? *(.*?)(?:-?Mozilla|fingerPrint|[;/\\(\\)]|$)'\n device_replacement: 'HTC $1'\n brand_replacement: 'HTC'\n model_replacement: '$1'", " ##########\n # Huawei\n ##########\n - regex: 'Huawei([A-Za-z0-9]+)'\n device_replacement: 'Huawei $1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'\n - regex: 'HUAWEI-([A-Za-z0-9]+)'\n device_replacement: 'Huawei $1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'\n - regex: 'HUAWEI ([A-Za-z0-9\\-]+)'\n device_replacement: 'Huawei $1'\n brand_replacement: 'Huawei'\n model_replacement: '$1'\n - regex: 'vodafone([A-Za-z0-9]+)'\n device_replacement: 'Huawei Vodafone $1'\n brand_replacement: 'Huawei'\n model_replacement: 'Vodafone $1'", " ##########\n # i-mate\n ##########\n - regex: 'i\\-mate ([A-Za-z0-9]+)'\n device_replacement: 'i-mate $1'\n brand_replacement: 'i-mate'\n model_replacement: '$1'", " ##########\n # kyocera\n ##########\n - regex: 'Kyocera\\-([A-Za-z0-9]+)'\n device_replacement: 'Kyocera $1'\n brand_replacement: 'Kyocera'\n model_replacement: '$1'\n - regex: 'KWC\\-([A-Za-z0-9]+)'\n device_replacement: 'Kyocera $1'\n brand_replacement: 'Kyocera'\n model_replacement: '$1'", " ##########\n # lenovo\n ##########\n - regex: 'Lenovo[_\\-]([A-Za-z0-9]+)'\n device_replacement: 'Lenovo $1'\n brand_replacement: 'Lenovo'\n model_replacement: '$1'", " ##########\n # HbbTV (European and Australian standard)\n # written before the LG regexes, as LG is making HbbTV too\n ##########", " - regex: '(HbbTV)/[0-9]+\\.[0-9]+\\.[0-9]+ \\( {0,1};(LG)E {0,1};([^;]{0,30})'", " device_replacement: '$1'\n brand_replacement: '$2'\n model_replacement: '$3'\n - regex: '(HbbTV)/1\\.1\\.1.*CE-HTML/1\\.\\d;(Vendor/|)(THOM[^;]*?)[;\\s].{0,30}(LF[^;]+);?'\n device_replacement: '$1'\n brand_replacement: 'Thomson'\n model_replacement: '$4'\n - regex: '(HbbTV)(?:/1\\.1\\.1|) ?(?: \\(;;;;;\\)|); *CE-HTML(?:/1\\.\\d|); *([^ ]+) ([^;]+);'\n device_replacement: '$1'\n brand_replacement: '$2'\n model_replacement: '$3'\n - regex: '(HbbTV)/1\\.1\\.1 \\(;;;;;\\) Maple_2011'\n device_replacement: '$1'\n brand_replacement: 'Samsung'", " - regex: '(HbbTV)/[0-9]+\\.[0-9]+\\.[0-9]+ \\([^;]{0,30}; {0,1}(?:CUS:([^;]*)|([^;]+)) {0,1}; {0,1}([^;]{0,30})'", " device_replacement: '$1'\n brand_replacement: '$2$3'\n model_replacement: '$4'\n - regex: '(HbbTV)/[0-9]+\\.[0-9]+\\.[0-9]+'\n device_replacement: '$1'", " ##########\n # LGE NetCast TV\n ##########\n - regex: 'LGE; (?:Media\\/|)([^;]*);[^;]*;[^;]*;?\\); \"?LG NetCast(\\.TV|\\.Media|)-\\d+'\n device_replacement: 'NetCast$2'\n brand_replacement: 'LG'\n model_replacement: '$1'", " ##########\n # InettvBrowser\n ##########\n - regex: 'InettvBrowser/[0-9]+\\.[0-9A-Z]+ \\([^;]*;(Sony)([^;]*);[^;]*;[^\\)]*\\)'\n device_replacement: 'Inettv'\n brand_replacement: '$1'\n model_replacement: '$2'\n - regex: 'InettvBrowser/[0-9]+\\.[0-9A-Z]+ \\([^;]*;([^;]*);[^;]*;[^\\)]*\\)'\n device_replacement: 'Inettv'\n brand_replacement: 'Generic_Inettv'\n model_replacement: '$1'\n - regex: '(?:InettvBrowser|TSBNetTV|NETTV|HBBTV)'\n device_replacement: 'Inettv'\n brand_replacement: 'Generic_Inettv'", " ##########\n # lg\n ##########\n # LG Symbian Phones\n - regex: 'Series60/\\d\\.\\d (LG)[\\-]?([A-Za-z0-9 \\-]+)'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'\n # other LG phones\n - regex: '\\b(?:LGE[ \\-]LG\\-(?:AX|)|LGE |LGE?-LG|LGE?[ \\-]|LG[ /\\-]|lg[\\-])([A-Za-z0-9]+)\\b'\n device_replacement: 'LG $1'\n brand_replacement: 'LG'\n model_replacement: '$1'\n - regex: '(?:^LG[\\-]?|^LGE[\\-/]?)([A-Za-z]+[0-9]+[A-Za-z]*)'\n device_replacement: 'LG $1'\n brand_replacement: 'LG'\n model_replacement: '$1'\n - regex: '^LG([0-9]+[A-Za-z]*)'\n device_replacement: 'LG $1'\n brand_replacement: 'LG'\n model_replacement: '$1'", " ##########\n # microsoft\n ##########\n - regex: '(KIN\\.[^ ]+) (\\d+)\\.(\\d+)'\n device_replacement: 'Microsoft $1'\n brand_replacement: 'Microsoft'\n model_replacement: '$1'\n - regex: '(?:MSIE|XBMC).*\\b(Xbox)\\b'\n device_replacement: '$1'\n brand_replacement: 'Microsoft'\n model_replacement: '$1'\n - regex: '; ARM; Trident/6\\.0; Touch[\\);]'\n device_replacement: 'Microsoft Surface RT'\n brand_replacement: 'Microsoft'\n model_replacement: 'Surface RT'", " ##########\n # motorola\n ##########\n - regex: 'Motorola\\-([A-Za-z0-9]+)'\n device_replacement: 'Motorola $1'\n brand_replacement: 'Motorola'\n model_replacement: '$1'\n - regex: 'MOTO\\-([A-Za-z0-9]+)'\n device_replacement: 'Motorola $1'\n brand_replacement: 'Motorola'\n model_replacement: '$1'\n - regex: 'MOT\\-([A-z0-9][A-z0-9\\-]*)'\n device_replacement: 'Motorola $1'\n brand_replacement: 'Motorola'\n model_replacement: '$1'", " ##########\n # nintendo\n ##########\n - regex: 'Nintendo WiiU'\n device_replacement: 'Nintendo Wii U'\n brand_replacement: 'Nintendo'\n model_replacement: 'Wii U'\n - regex: 'Nintendo (DS|3DS|DSi|Wii);'\n device_replacement: 'Nintendo $1'\n brand_replacement: 'Nintendo'\n model_replacement: '$1'", " ##########\n # pantech\n ##########\n - regex: '(?:Pantech|PANTECH)[ _-]?([A-Za-z0-9\\-]+)'\n device_replacement: 'Pantech $1'\n brand_replacement: 'Pantech'\n model_replacement: '$1'", " ##########\n # philips\n ##########\n - regex: 'Philips([A-Za-z0-9]+)'\n device_replacement: 'Philips $1'\n brand_replacement: 'Philips'\n model_replacement: '$1'\n - regex: 'Philips ([A-Za-z0-9]+)'\n device_replacement: 'Philips $1'\n brand_replacement: 'Philips'\n model_replacement: '$1'", " ##########\n # Samsung\n ##########\n # Samsung Smart-TV\n - regex: '(SMART-TV); .* Tizen '\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n # Samsung Symbian Devices\n - regex: 'SymbianOS/9\\.\\d.* Samsung[/\\-]([A-Za-z0-9 \\-]+)'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n - regex: '(Samsung)(SGH)(i[0-9]+)'\n device_replacement: '$1 $2$3'\n brand_replacement: '$1'\n model_replacement: '$2-$3'\n - regex: 'SAMSUNG-ANDROID-MMS/([^;/]+)'\n device_replacement: '$1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'\n # Other Samsung\n #- regex: 'SAMSUNG(?:; |-)([A-Za-z0-9\\-]+)'\n - regex: 'SAMSUNG(?:; |[ -/])([A-Za-z0-9\\-]+)'\n regex_flag: 'i'\n device_replacement: 'Samsung $1'\n brand_replacement: 'Samsung'\n model_replacement: '$1'", " ##########\n # Sega\n ##########\n - regex: '(Dreamcast)'\n device_replacement: 'Sega $1'\n brand_replacement: 'Sega'\n model_replacement: '$1'", " ##########\n # Siemens mobile\n ##########\n - regex: '^SIE-([A-Za-z0-9]+)'\n device_replacement: 'Siemens $1'\n brand_replacement: 'Siemens'\n model_replacement: '$1'", " ##########\n # Softbank\n ##########\n - regex: 'Softbank/[12]\\.0/([A-Za-z0-9]+)'\n device_replacement: 'Softbank $1'\n brand_replacement: 'Softbank'\n model_replacement: '$1'", " ##########\n # SonyEricsson\n ##########\n - regex: 'SonyEricsson ?([A-Za-z0-9\\-]+)'\n device_replacement: 'Ericsson $1'\n brand_replacement: 'SonyEricsson'\n model_replacement: '$1'", " ##########\n # Sony\n ##########\n - regex: 'Android [^;]+; ([^ ]+) (Sony)/'\n device_replacement: '$2 $1'\n brand_replacement: '$2'\n model_replacement: '$1'\n - regex: '(Sony)(?:BDP\\/|\\/|)([^ /;\\)]+)[ /;\\)]'\n device_replacement: '$1 $2'\n brand_replacement: '$1'\n model_replacement: '$2'", " #########\n # Puffin Browser Device detect\n # A=Android, I=iOS, P=Phone, T=Tablet\n # AT=Android+Tablet\n #########\n - regex: 'Puffin/[\\d\\.]+IT'\n device_replacement: 'iPad'\n brand_replacement: 'Apple'\n model_replacement: 'iPad'\n - regex: 'Puffin/[\\d\\.]+IP'\n device_replacement: 'iPhone'\n brand_replacement: 'Apple'\n model_replacement: 'iPhone'\n - regex: 'Puffin/[\\d\\.]+AT'\n device_replacement: 'Generic Tablet'\n brand_replacement: 'Generic'\n model_replacement: 'Tablet'\n - regex: 'Puffin/[\\d\\.]+AP'\n device_replacement: 'Generic Smartphone'\n brand_replacement: 'Generic'\n model_replacement: 'Smartphone'", " #########\n # Android General Device Matching (far from perfect)\n #########\n - regex: 'Android[\\- ][\\d]+\\.[\\d]+; [A-Za-z]{2}\\-[A-Za-z]{0,2}; WOWMobile (.+)( Build[/ ]|\\))'\n brand_replacement: 'Generic_Android'\n model_replacement: '$1'\n - regex: 'Android[\\- ][\\d]+\\.[\\d]+\\-update1; [A-Za-z]{2}\\-[A-Za-z]{0,2} *; *(.+?)( Build[/ ]|\\))'\n brand_replacement: 'Generic_Android'\n model_replacement: '$1'\n - regex: 'Android[\\- ][\\d]+(?:\\.[\\d]+)(?:\\.[\\d]+|); *[A-Za-z]{2}[_\\-][A-Za-z]{0,2}\\-? *; *(.+?)( Build[/ ]|\\))'\n brand_replacement: 'Generic_Android'\n model_replacement: '$1'\n - regex: 'Android[\\- ][\\d]+(?:\\.[\\d]+)(?:\\.[\\d]+|); *[A-Za-z]{0,2}\\- *; *(.+?)( Build[/ ]|\\))'\n brand_replacement: 'Generic_Android'\n model_replacement: '$1'\n # No build info at all - \"Build\" follows locale immediately\n - regex: 'Android[\\- ][\\d]+(?:\\.[\\d]+)(?:\\.[\\d]+|); *[a-z]{0,2}[_\\-]?[A-Za-z]{0,2};?( Build[/ ]|\\))'\n device_replacement: 'Generic Smartphone'\n brand_replacement: 'Generic'\n model_replacement: 'Smartphone'\n - regex: 'Android[\\- ][\\d]+(?:\\.[\\d]+)(?:\\.[\\d]+|); *\\-?[A-Za-z]{2}; *(.+?)( Build[/ ]|\\))'\n brand_replacement: 'Generic_Android'\n model_replacement: '$1'\n - regex: 'Android \\d+?(?:\\.\\d+|)(?:\\.\\d+|); ([^;]+?)(?: Build|\\) AppleWebKit).+? Mobile Safari'\n brand_replacement: 'Generic_Android'\n model_replacement: '$1'\n - regex: 'Android \\d+?(?:\\.\\d+|)(?:\\.\\d+|); ([^;]+?)(?: Build|\\) AppleWebKit).+? Safari'\n brand_replacement: 'Generic_Android_Tablet'\n model_replacement: '$1'\n - regex: 'Android \\d+?(?:\\.\\d+|)(?:\\.\\d+|); ([^;]+?)(?: Build|\\))'\n brand_replacement: 'Generic_Android'\n model_replacement: '$1'", " ##########\n # Google TV\n ##########\n - regex: '(GoogleTV)'\n brand_replacement: 'Generic_Inettv'\n model_replacement: '$1'", " ##########\n # WebTV\n ##########\n - regex: '(WebTV)/\\d+.\\d+'\n brand_replacement: 'Generic_Inettv'\n model_replacement: '$1'\n # Roku Digital-Video-Players https://www.roku.com/\n - regex: '^(Roku)/DVP-\\d+\\.\\d+'\n brand_replacement: 'Generic_Inettv'\n model_replacement: '$1'", " ##########\n # Generic Tablet\n ##########\n - regex: '(Android 3\\.\\d|Opera Tablet|Tablet; .+Firefox/|Android.*(?:Tab|Pad))'\n regex_flag: 'i'\n device_replacement: 'Generic Tablet'\n brand_replacement: 'Generic'\n model_replacement: 'Tablet'", " ##########\n # Generic Smart Phone\n ##########\n - regex: '(Symbian|\\bS60(Version|V\\d)|\\bS60\\b|\\((Series 60|Windows Mobile|Palm OS|Bada); Opera Mini|Windows CE|Opera Mobi|BREW|Brew|Mobile; .+Firefox/|iPhone OS|Android|MobileSafari|Windows *Phone|\\(webOS/|PalmOS)'\n device_replacement: 'Generic Smartphone'\n brand_replacement: 'Generic'\n model_replacement: 'Smartphone'\n - regex: '(hiptop|avantgo|plucker|xiino|blazer|elaine)'\n regex_flag: 'i'\n device_replacement: 'Generic Smartphone'\n brand_replacement: 'Generic'\n model_replacement: 'Smartphone'", " ##########\n # Spiders (this is a hack...)\n ##########\n - regex: '(bot|BUbiNG|zao|borg|DBot|oegp|silk|Xenu|zeal|^NING|CCBot|crawl|htdig|lycos|slurp|teoma|voila|yahoo|Sogou|CiBra|Nutch|^Java/|^JNLP/|Daumoa|Daum|Genieo|ichiro|larbin|pompos|Scrapy|snappy|speedy|spider|msnbot|msrbot|vortex|^vortex|crawler|favicon|indexer|Riddler|scooter|scraper|scrubby|WhatWeb|WinHTTP|bingbot|BingPreview|openbot|gigabot|furlbot|polybot|seekbot|^voyager|archiver|Icarus6j|mogimogi|Netvibes|blitzbot|altavista|charlotte|findlinks|Retreiver|TLSProber|WordPress|SeznamBot|ProoXiBot|wsr\\-agent|Squrl Java|EtaoSpider|PaperLiBot|SputnikBot|A6\\-Indexer|netresearch|searchsight|baiduspider|YisouSpider|ICC\\-Crawler|http%20client|Python-urllib|dataparksearch|converacrawler|Screaming Frog|AppEngine-Google|YahooCacheSystem|fast\\-webcrawler|Sogou Pic Spider|semanticdiscovery|Innovazion Crawler|facebookexternalhit|Google.*/\\+/web/snippet|Google-HTTP-Java-Client|BlogBridge|IlTrovatore-Setaccio|InternetArchive|GomezAgent|WebThumbnail|heritrix|NewsGator|PagePeeker|Reaper|ZooShot|holmes|NL-Crawler|Pingdom|StatusCake|WhatsApp|masscan|Google Web Preview|Qwantify|Yeti|OgScrper)'\n regex_flag: 'i'\n device_replacement: 'Spider'\n brand_replacement: 'Spider'\n model_replacement: 'Desktop'", " ##########\n # Generic Feature Phone\n # take care to do case insensitive matching\n ##########\n - regex: '^(1207|3gso|4thp|501i|502i|503i|504i|505i|506i|6310|6590|770s|802s|a wa|acer|acs\\-|airn|alav|asus|attw|au\\-m|aur |aus |abac|acoo|aiko|alco|alca|amoi|anex|anny|anyw|aptu|arch|argo|bmobile|bell|bird|bw\\-n|bw\\-u|beck|benq|bilb|blac|c55/|cdm\\-|chtm|capi|comp|cond|dall|dbte|dc\\-s|dica|ds\\-d|ds12|dait|devi|dmob|doco|dopo|dorado|el(?:38|39|48|49|50|55|58|68)|el[3456]\\d{2}dual|erk0|esl8|ex300|ez40|ez60|ez70|ezos|ezze|elai|emul|eric|ezwa|fake|fly\\-|fly_|g\\-mo|g1 u|g560|gf\\-5|grun|gene|go.w|good|grad|hcit|hd\\-m|hd\\-p|hd\\-t|hei\\-|hp i|hpip|hs\\-c|htc |htc\\-|htca|htcg)'\n regex_flag: 'i'\n device_replacement: 'Generic Feature Phone'\n brand_replacement: 'Generic'\n model_replacement: 'Feature Phone'\n - regex: '^(htcp|htcs|htct|htc_|haie|hita|huaw|hutc|i\\-20|i\\-go|i\\-ma|i\\-mobile|i230|iac|iac\\-|iac/|ig01|im1k|inno|iris|jata|kddi|kgt|kgt/|kpt |kwc\\-|klon|lexi|lg g|lg\\-a|lg\\-b|lg\\-c|lg\\-d|lg\\-f|lg\\-g|lg\\-k|lg\\-l|lg\\-m|lg\\-o|lg\\-p|lg\\-s|lg\\-t|lg\\-u|lg\\-w|lg/k|lg/l|lg/u|lg50|lg54|lge\\-|lge/|leno|m1\\-w|m3ga|m50/|maui|mc01|mc21|mcca|medi|meri|mio8|mioa|mo01|mo02|mode|modo|mot |mot\\-|mt50|mtp1|mtv |mate|maxo|merc|mits|mobi|motv|mozz|n100|n101|n102|n202|n203|n300|n302|n500|n502|n505|n700|n701|n710|nec\\-|nem\\-|newg|neon)'\n regex_flag: 'i'\n device_replacement: 'Generic Feature Phone'\n brand_replacement: 'Generic'\n model_replacement: 'Feature Phone'\n - regex: '^(netf|noki|nzph|o2 x|o2\\-x|opwv|owg1|opti|oran|ot\\-s|p800|pand|pg\\-1|pg\\-2|pg\\-3|pg\\-6|pg\\-8|pg\\-c|pg13|phil|pn\\-2|pt\\-g|palm|pana|pire|pock|pose|psio|qa\\-a|qc\\-2|qc\\-3|qc\\-5|qc\\-7|qc07|qc12|qc21|qc32|qc60|qci\\-|qwap|qtek|r380|r600|raks|rim9|rove|s55/|sage|sams|sc01|sch\\-|scp\\-|sdk/|se47|sec\\-|sec0|sec1|semc|sgh\\-|shar|sie\\-|sk\\-0|sl45|slid|smb3|smt5|sp01|sph\\-|spv |spv\\-|sy01|samm|sany|sava|scoo|send|siem|smar|smit|soft|sony|t\\-mo|t218|t250|t600|t610|t618|tcl\\-|tdg\\-|telm|tim\\-|ts70|tsm\\-|tsm3|tsm5|tx\\-9|tagt)'\n regex_flag: 'i'\n device_replacement: 'Generic Feature Phone'\n brand_replacement: 'Generic'\n model_replacement: 'Feature Phone'\n - regex: '^(talk|teli|topl|tosh|up.b|upg1|utst|v400|v750|veri|vk\\-v|vk40|vk50|vk52|vk53|vm40|vx98|virg|vertu|vite|voda|vulc|w3c |w3c\\-|wapj|wapp|wapu|wapm|wig |wapi|wapr|wapv|wapy|wapa|waps|wapt|winc|winw|wonu|x700|xda2|xdag|yas\\-|your|zte\\-|zeto|aste|audi|avan|blaz|brew|brvw|bumb|ccwa|cell|cldc|cmd\\-|dang|eml2|fetc|hipt|http|ibro|idea|ikom|ipaq|jbro|jemu|jigs|keji|kyoc|kyok|libw|m\\-cr|midp|mmef|moto|mwbp|mywa|newt|nok6|o2im|pant|pdxg|play|pluc|port|prox|rozo|sama|seri|smal|symb|treo|upsi|vx52|vx53|vx60|vx61|vx70|vx80|vx81|vx83|vx85|wap\\-|webc|whit|wmlb|xda\\-|xda_)'\n regex_flag: 'i'\n device_replacement: 'Generic Feature Phone'\n brand_replacement: 'Generic'\n model_replacement: 'Feature Phone'\n - regex: '^(Ice)$'\n device_replacement: 'Generic Feature Phone'\n brand_replacement: 'Generic'\n model_replacement: 'Feature Phone'\n - regex: '(wap[\\-\\ ]browser|maui|netfront|obigo|teleca|up\\.browser|midp|Opera Mini)'\n regex_flag: 'i'\n device_replacement: 'Generic Feature Phone'\n brand_replacement: 'Generic'\n model_replacement: 'Feature Phone'" ]
[ 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5145, 50], "buggy_code_start_loc": [1575, 43], "filenames": ["regexes.yaml", "tests/regexes.js"], "fixing_code_end_loc": [5145, 88], "fixing_code_start_loc": [1575, 43], "message": "uap-core before 0.7.3 is vulnerable to a denial of service attack when processing crafted User-Agent strings. Some regexes are vulnerable to regular expression denial of service (REDoS) due to overlapping capture groups. This allows remote attackers to overload a server by setting the User-Agent header in an HTTP(S) request to maliciously crafted long strings. This has been patched in uap-core 0.7.3.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:uap-core_project:uap-core:*:*:*:*:*:*:*:*", "matchCriteriaId": "E93CB3F6-D527-456D-ADDB-C3D911A1815D", "versionEndExcluding": "0.7.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "uap-core before 0.7.3 is vulnerable to a denial of service attack when processing crafted User-Agent strings. Some regexes are vulnerable to regular expression denial of service (REDoS) due to overlapping capture groups. This allows remote attackers to overload a server by setting the User-Agent header in an HTTP(S) request to maliciously crafted long strings. This has been patched in uap-core 0.7.3."}, {"lang": "es", "value": "uap-core versiones anteriores a 0.7.3, es vulnerable a un ataque de denegaci\u00f3n de servicio cuando se procesan cadenas de User-Agent dise\u00f1adas. Algunas expresiones regulares son vulnerables a una denegaci\u00f3n de servicio de expresi\u00f3n regular (REDoS) debido a una superposici\u00f3n de grupos de captura. Esto permite a atacantes remotos sobrecargar un servidor mediante la configuraci\u00f3n del encabezado User-Agent en una petici\u00f3n HTTP(S) para cadenas largas dise\u00f1adas maliciosamente. Esto ha sido parcheado en uap-core versi\u00f3n 0.7.3."}], "evaluatorComment": null, "id": "CVE-2020-5243", "lastModified": "2020-02-25T19:44:54.697", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-02-21T00:15:10.960", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ua-parser/uap-core/commit/0afd61ed85396a3b5316f18bfd1edfaadf8e88e1"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/ua-parser/uap-core/security/advisories/GHSA-cmcx-xhr8-3w9p"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-400"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-20"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/ua-parser/uap-core/commit/0afd61ed85396a3b5316f18bfd1edfaadf8e88e1"}, "type": "CWE-400"}
194
Determine whether the {function_name} code is vulnerable or not.
[ "'use strict'", "var assert = require('assert')\nvar path = require('path')\nvar fs = require('fs')\nvar yaml = require('yamlparser')\nvar regexes = readYAML('../regexes.yaml')\nvar safe = require('safe-regex')\nvar refImpl = require('uap-ref-impl')", "function readYAML (fileName) {\n var file = path.join(__dirname, fileName)\n var data = fs.readFileSync(file, 'utf8')\n return yaml.eval(data)\n}", "suite('regexes', function () {\n Object.keys(regexes).forEach(function (parser) {\n suite(parser, function () {\n regexes[parser].forEach(function(item) {\n test(item.regex, function () {\n assert.ok(safe(item.regex))\n })\n })\n })\n })", " Object.keys(regexes).forEach(function (parser) {\n suite(`no reverse lookup in ${parser}`, function () {\n regexes[parser].forEach(function(item) {\n test(item.regex, function () {\n if (/\\(\\?<[!=]/.test(item.regex)) {\n assert.ok(false, 'go parser does not support regex lookbehind. See https://github.com/google/re2/wiki/Syntax')\n }\n if (/\\(\\?[!=]/.test(item.regex)) {\n assert.ok(false, 'go parser does not support regex lookahead. See https://github.com/google/re2/wiki/Syntax')\n }\n })\n })\n })\n })\n", " test('should not backtrack', function () {\n var parse = refImpl(regexes).parse\n var ua = Array(3200).fill('a').join('')", " var start = Date.now()", "", " parse(ua)", " var diff = Date.now() - start\n assert.ok(diff < 500, diff)", " })\n})" ]
[ 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5145, 50], "buggy_code_start_loc": [1575, 43], "filenames": ["regexes.yaml", "tests/regexes.js"], "fixing_code_end_loc": [5145, 88], "fixing_code_start_loc": [1575, 43], "message": "uap-core before 0.7.3 is vulnerable to a denial of service attack when processing crafted User-Agent strings. Some regexes are vulnerable to regular expression denial of service (REDoS) due to overlapping capture groups. This allows remote attackers to overload a server by setting the User-Agent header in an HTTP(S) request to maliciously crafted long strings. This has been patched in uap-core 0.7.3.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:uap-core_project:uap-core:*:*:*:*:*:*:*:*", "matchCriteriaId": "E93CB3F6-D527-456D-ADDB-C3D911A1815D", "versionEndExcluding": "0.7.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "uap-core before 0.7.3 is vulnerable to a denial of service attack when processing crafted User-Agent strings. Some regexes are vulnerable to regular expression denial of service (REDoS) due to overlapping capture groups. This allows remote attackers to overload a server by setting the User-Agent header in an HTTP(S) request to maliciously crafted long strings. This has been patched in uap-core 0.7.3."}, {"lang": "es", "value": "uap-core versiones anteriores a 0.7.3, es vulnerable a un ataque de denegaci\u00f3n de servicio cuando se procesan cadenas de User-Agent dise\u00f1adas. Algunas expresiones regulares son vulnerables a una denegaci\u00f3n de servicio de expresi\u00f3n regular (REDoS) debido a una superposici\u00f3n de grupos de captura. Esto permite a atacantes remotos sobrecargar un servidor mediante la configuraci\u00f3n del encabezado User-Agent en una petici\u00f3n HTTP(S) para cadenas largas dise\u00f1adas maliciosamente. Esto ha sido parcheado en uap-core versi\u00f3n 0.7.3."}], "evaluatorComment": null, "id": "CVE-2020-5243", "lastModified": "2020-02-25T19:44:54.697", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-02-21T00:15:10.960", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ua-parser/uap-core/commit/0afd61ed85396a3b5316f18bfd1edfaadf8e88e1"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/ua-parser/uap-core/security/advisories/GHSA-cmcx-xhr8-3w9p"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-400"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-20"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/ua-parser/uap-core/commit/0afd61ed85396a3b5316f18bfd1edfaadf8e88e1"}, "type": "CWE-400"}
194
Determine whether the {function_name} code is vulnerable or not.
[ "'use strict'", "var assert = require('assert')\nvar path = require('path')\nvar fs = require('fs')\nvar yaml = require('yamlparser')\nvar regexes = readYAML('../regexes.yaml')\nvar safe = require('safe-regex')\nvar refImpl = require('uap-ref-impl')", "function readYAML (fileName) {\n var file = path.join(__dirname, fileName)\n var data = fs.readFileSync(file, 'utf8')\n return yaml.eval(data)\n}", "suite('regexes', function () {\n Object.keys(regexes).forEach(function (parser) {\n suite(parser, function () {\n regexes[parser].forEach(function(item) {\n test(item.regex, function () {\n assert.ok(safe(item.regex))\n })\n })\n })\n })", " Object.keys(regexes).forEach(function (parser) {\n suite(`no reverse lookup in ${parser}`, function () {\n regexes[parser].forEach(function(item) {\n test(item.regex, function () {\n if (/\\(\\?<[!=]/.test(item.regex)) {\n assert.ok(false, 'go parser does not support regex lookbehind. See https://github.com/google/re2/wiki/Syntax')\n }\n if (/\\(\\?[!=]/.test(item.regex)) {\n assert.ok(false, 'go parser does not support regex lookahead. See https://github.com/google/re2/wiki/Syntax')\n }\n })\n })\n })\n })\n", "})", "suite('redos', function () {\n var parse = refImpl(regexes).parse", " function timer () {", " var start = Date.now()", " return function () {\n return Date.now() - start\n }\n }", " function testRedos (ua) {\n var time = timer()", " parse(ua)", " var diff = time()\n assert.ok(diff < 300, diff)\n }", " test('should not backtrack aaaa..', function () {\n testRedos(Array(3200).fill('a').join(''))\n })", " test('should not backtrack Smartwatch', function () {\n testRedos('SmartWatch(' + Array(3500).fill(' ').join('') + 'z')\n })", " test('should not backtrack HuaweiA', function () {\n testRedos(';A Build HuaweiA' + Array(3500).fill('4').join('') + 'z')\n })", " test('should not backtrack HbbTV LGE', function () {\n testRedos('HbbTV/0.0.0 (;LGE;' + Array(3500).fill(' ').join('') + 'z')\n })", " test('should not backtrack HbbTV CUS', function () {\n testRedos('HbbTV/0.0.0 (;CUS:;' + Array(3500).fill(' ').join('') + 'z')\n })", " test('should not backtrack HbbTV', function () {\n testRedos('HbbTV/0.0.0 (;' + Array(3500).fill(' ').join('') + 'z')\n })", " test('should not backtrack HbbTV z', function () {\n testRedos('HbbTV/0.0.0 (;z;' + Array(3500).fill(' ').join('') + 'z')", " })\n})" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5145, 50], "buggy_code_start_loc": [1575, 43], "filenames": ["regexes.yaml", "tests/regexes.js"], "fixing_code_end_loc": [5145, 88], "fixing_code_start_loc": [1575, 43], "message": "uap-core before 0.7.3 is vulnerable to a denial of service attack when processing crafted User-Agent strings. Some regexes are vulnerable to regular expression denial of service (REDoS) due to overlapping capture groups. This allows remote attackers to overload a server by setting the User-Agent header in an HTTP(S) request to maliciously crafted long strings. This has been patched in uap-core 0.7.3.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:uap-core_project:uap-core:*:*:*:*:*:*:*:*", "matchCriteriaId": "E93CB3F6-D527-456D-ADDB-C3D911A1815D", "versionEndExcluding": "0.7.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "uap-core before 0.7.3 is vulnerable to a denial of service attack when processing crafted User-Agent strings. Some regexes are vulnerable to regular expression denial of service (REDoS) due to overlapping capture groups. This allows remote attackers to overload a server by setting the User-Agent header in an HTTP(S) request to maliciously crafted long strings. This has been patched in uap-core 0.7.3."}, {"lang": "es", "value": "uap-core versiones anteriores a 0.7.3, es vulnerable a un ataque de denegaci\u00f3n de servicio cuando se procesan cadenas de User-Agent dise\u00f1adas. Algunas expresiones regulares son vulnerables a una denegaci\u00f3n de servicio de expresi\u00f3n regular (REDoS) debido a una superposici\u00f3n de grupos de captura. Esto permite a atacantes remotos sobrecargar un servidor mediante la configuraci\u00f3n del encabezado User-Agent en una petici\u00f3n HTTP(S) para cadenas largas dise\u00f1adas maliciosamente. Esto ha sido parcheado en uap-core versi\u00f3n 0.7.3."}], "evaluatorComment": null, "id": "CVE-2020-5243", "lastModified": "2020-02-25T19:44:54.697", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-02-21T00:15:10.960", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ua-parser/uap-core/commit/0afd61ed85396a3b5316f18bfd1edfaadf8e88e1"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/ua-parser/uap-core/security/advisories/GHSA-cmcx-xhr8-3w9p"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-400"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-20"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/ua-parser/uap-core/commit/0afd61ed85396a3b5316f18bfd1edfaadf8e88e1"}, "type": "CWE-400"}
194
Determine whether the {function_name} code is vulnerable or not.
[ "package account\n", "import \"github.com/kongchuanhujiao/server/internal/app/datahub/internal/memory\"", "", "func GetCode(id string) string {\n\treturn memory.Code[id]", "}\n", "func WriteCode(id string, code string) {\n\tmemory.Code[id] = code", "}\n", "func DeleteCode(id string) {\n\tdelete(memory.Code, id)\n}" ]
[ 1, 0, 1, 0, 1, 0, 1, 0 ]
PreciseBugs
{"buggy_code_end_loc": [16, 45, 47], "buggy_code_start_loc": [3, 44, 5], "filenames": ["internal/app/datahub/pkg/account/memory.go", "internal/app/kongchuanhujiao/account/apis.go", "internal/app/kongchuanhujiao/account/utils.go"], "fixing_code_end_loc": [40, 45, 29], "fixing_code_start_loc": [3, 44, 4], "message": "In github.com/kongchuanhujiao/server before version 1.3.21 there is an authentication Bypass by Primary Weakness vulnerability. All users are impacted. This is fixed in version 1.3.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kongchuanhujiao_project:kongchuanhujiao:*:*:*:*:*:*:*:*", "matchCriteriaId": "11A4F437-0527-4C8C-A4B3-DBAE999BAADA", "versionEndExcluding": "1.3.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In github.com/kongchuanhujiao/server before version 1.3.21 there is an authentication Bypass by Primary Weakness vulnerability. All users are impacted. This is fixed in version 1.3.21."}, {"lang": "es", "value": "En github.com/kongchuanhujiao/server versiones anteriores a 1.3.21, se presenta una Omisi\u00f3n de autenticaci\u00f3n por una vulnerabilidad de Debilidad Primaria.&#xa0;Todos los usuarios est\u00e1n afectados.&#xa0;Esto es corregido en la versi\u00f3n 1.3.21."}], "evaluatorComment": null, "id": "CVE-2021-21403", "lastModified": "2022-10-24T17:13:44.350", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-26T18:15:12.360", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kongchuanhujiao/server/commit/9a125624f219e496bdf4b07b404816d5a309bdc1"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/kongchuanhujiao/server/security/advisories/GHSA-8wrg-m8vm-5fvj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-305"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/kongchuanhujiao/server/commit/9a125624f219e496bdf4b07b404816d5a309bdc1"}, "type": "CWE-287"}
195
Determine whether the {function_name} code is vulnerable or not.
[ "package account\n", "import (\n\t\"math/rand\"\n\t\"strconv\"\n\t\"time\"", "", "\t\"github.com/kongchuanhujiao/server/internal/app/datahub/internal/memory\"\n)", "// GenerateCode 写入验证码返回一个验证码\nfunc GenerateCode(id string) (c string) {", "\trand.Seed(time.Now().UnixNano())\n\tc = strconv.FormatFloat(rand.Float64(), 'f', -1, 64)[2:6]", "\tmemory.Code[id] = c", "\tgo func() {\n\t\ttimer := time.NewTimer(5 * time.Minute)\n\t\tdefer timer.Stop()\n\t\t<-timer.C\n\t\tdeleteCode(id)\n\t}()", "\treturn", "}\n", "// VerifyCode 验证验证码\nfunc VerifyCode(id string, code string) (ok bool) {\n\tif code == memory.Code[id] {\n\t\tok = true\n\t\tdeleteCode(id)\n\t}\n\treturn", "}\n", "// deleteCode 删除验证码\nfunc deleteCode(id string) { delete(memory.Code, id) }" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [16, 45, 47], "buggy_code_start_loc": [3, 44, 5], "filenames": ["internal/app/datahub/pkg/account/memory.go", "internal/app/kongchuanhujiao/account/apis.go", "internal/app/kongchuanhujiao/account/utils.go"], "fixing_code_end_loc": [40, 45, 29], "fixing_code_start_loc": [3, 44, 4], "message": "In github.com/kongchuanhujiao/server before version 1.3.21 there is an authentication Bypass by Primary Weakness vulnerability. All users are impacted. This is fixed in version 1.3.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kongchuanhujiao_project:kongchuanhujiao:*:*:*:*:*:*:*:*", "matchCriteriaId": "11A4F437-0527-4C8C-A4B3-DBAE999BAADA", "versionEndExcluding": "1.3.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In github.com/kongchuanhujiao/server before version 1.3.21 there is an authentication Bypass by Primary Weakness vulnerability. All users are impacted. This is fixed in version 1.3.21."}, {"lang": "es", "value": "En github.com/kongchuanhujiao/server versiones anteriores a 1.3.21, se presenta una Omisi\u00f3n de autenticaci\u00f3n por una vulnerabilidad de Debilidad Primaria.&#xa0;Todos los usuarios est\u00e1n afectados.&#xa0;Esto es corregido en la versi\u00f3n 1.3.21."}], "evaluatorComment": null, "id": "CVE-2021-21403", "lastModified": "2022-10-24T17:13:44.350", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-26T18:15:12.360", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kongchuanhujiao/server/commit/9a125624f219e496bdf4b07b404816d5a309bdc1"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/kongchuanhujiao/server/security/advisories/GHSA-8wrg-m8vm-5fvj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-305"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/kongchuanhujiao/server/commit/9a125624f219e496bdf4b07b404816d5a309bdc1"}, "type": "CWE-287"}
195
Determine whether the {function_name} code is vulnerable or not.
[ "package account", "import (\n\t\"github.com/kongchuanhujiao/server/internal/app/datahub/pkg/account\"\n\t\"time\"", "\t\"github.com/kongchuanhujiao/server/internal/app/kongchuanhujiao\"\n\t\"github.com/kongchuanhujiao/server/internal/pkg/config\"\n\t\"github.com/kongchuanhujiao/server/internal/pkg/logger\"", "\t\"github.com/iris-contrib/middleware/jwt\"\n\t\"go.uber.org/zap\"\n)", "// APIs 账号 APIs\ntype APIs struct{}", "// PostCodeReq 发送验证码 请求结构\ntype PostCodeReq struct {\n\tID string // 标识号\n}", "// PostCode 发送验证码 APIs。\n// 调用方法:POST apis/accounts/code\nfunc (a *APIs) PostCode(v *PostCodeReq) *kongchuanhujiao.Response {\n\tif err := sendCode(v.ID); err != nil {\n\t\treturn kongchuanhujiao.GenerateErrResp(1, err.Error())\n\t}\n\treturn kongchuanhujiao.DefaultSuccResp\n}", "// ====================================================================================================================", "// PostLoginReq 登录验证 请求结构\ntype PostLoginReq struct {\n\tID string // 标识号\n\tCode string // 验证码\n}", "// PostLogin 登录验证 APIs。\n// 调用方法:POST apis/accounts/login\nfunc (a *APIs) PostLogin(v *PostLoginReq) *kongchuanhujiao.Response {\n", "\tif v.Code != account.GetCode(v.ID) || v.Code == \"\" { // FIXME datahub 鉴权", "\t\treturn kongchuanhujiao.GenerateErrResp(1, \"验证码有误\")\n\t}", "\tnow := time.Now()\n\tt, err := jwt.NewTokenWithClaims(jwt.SigningMethodES256, jwt.MapClaims{\n\t\t\"iss\": config.GetJWTConf().Iss,\n\t\t\"sub\": v.ID,\n\t\t\"exp\": now.AddDate(0, 1, 0).Unix(),\n\t\t\"nbf\": now.Unix(),\n\t\t\"iat\": now.Unix(),\n\t}).SignedString(config.GetJWTConf().Key)\n\tif err != nil {\n\t\tlogger.Error(\"生成 JWT Token 失败\", zap.Error(err))\n\t\treturn kongchuanhujiao.DefaultErrResp\n\t}", "\treturn &kongchuanhujiao.Response{Message: t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [16, 45, 47], "buggy_code_start_loc": [3, 44, 5], "filenames": ["internal/app/datahub/pkg/account/memory.go", "internal/app/kongchuanhujiao/account/apis.go", "internal/app/kongchuanhujiao/account/utils.go"], "fixing_code_end_loc": [40, 45, 29], "fixing_code_start_loc": [3, 44, 4], "message": "In github.com/kongchuanhujiao/server before version 1.3.21 there is an authentication Bypass by Primary Weakness vulnerability. All users are impacted. This is fixed in version 1.3.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kongchuanhujiao_project:kongchuanhujiao:*:*:*:*:*:*:*:*", "matchCriteriaId": "11A4F437-0527-4C8C-A4B3-DBAE999BAADA", "versionEndExcluding": "1.3.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In github.com/kongchuanhujiao/server before version 1.3.21 there is an authentication Bypass by Primary Weakness vulnerability. All users are impacted. This is fixed in version 1.3.21."}, {"lang": "es", "value": "En github.com/kongchuanhujiao/server versiones anteriores a 1.3.21, se presenta una Omisi\u00f3n de autenticaci\u00f3n por una vulnerabilidad de Debilidad Primaria.&#xa0;Todos los usuarios est\u00e1n afectados.&#xa0;Esto es corregido en la versi\u00f3n 1.3.21."}], "evaluatorComment": null, "id": "CVE-2021-21403", "lastModified": "2022-10-24T17:13:44.350", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-26T18:15:12.360", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kongchuanhujiao/server/commit/9a125624f219e496bdf4b07b404816d5a309bdc1"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/kongchuanhujiao/server/security/advisories/GHSA-8wrg-m8vm-5fvj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-305"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/kongchuanhujiao/server/commit/9a125624f219e496bdf4b07b404816d5a309bdc1"}, "type": "CWE-287"}
195
Determine whether the {function_name} code is vulnerable or not.
[ "package account", "import (\n\t\"github.com/kongchuanhujiao/server/internal/app/datahub/pkg/account\"\n\t\"time\"", "\t\"github.com/kongchuanhujiao/server/internal/app/kongchuanhujiao\"\n\t\"github.com/kongchuanhujiao/server/internal/pkg/config\"\n\t\"github.com/kongchuanhujiao/server/internal/pkg/logger\"", "\t\"github.com/iris-contrib/middleware/jwt\"\n\t\"go.uber.org/zap\"\n)", "// APIs 账号 APIs\ntype APIs struct{}", "// PostCodeReq 发送验证码 请求结构\ntype PostCodeReq struct {\n\tID string // 标识号\n}", "// PostCode 发送验证码 APIs。\n// 调用方法:POST apis/accounts/code\nfunc (a *APIs) PostCode(v *PostCodeReq) *kongchuanhujiao.Response {\n\tif err := sendCode(v.ID); err != nil {\n\t\treturn kongchuanhujiao.GenerateErrResp(1, err.Error())\n\t}\n\treturn kongchuanhujiao.DefaultSuccResp\n}", "// ====================================================================================================================", "// PostLoginReq 登录验证 请求结构\ntype PostLoginReq struct {\n\tID string // 标识号\n\tCode string // 验证码\n}", "// PostLogin 登录验证 APIs。\n// 调用方法:POST apis/accounts/login\nfunc (a *APIs) PostLogin(v *PostLoginReq) *kongchuanhujiao.Response {\n", "\tif account.VerifyCode(v.ID, v.Code) || v.Code == \"\" {", "\t\treturn kongchuanhujiao.GenerateErrResp(1, \"验证码有误\")\n\t}", "\tnow := time.Now()\n\tt, err := jwt.NewTokenWithClaims(jwt.SigningMethodES256, jwt.MapClaims{\n\t\t\"iss\": config.GetJWTConf().Iss,\n\t\t\"sub\": v.ID,\n\t\t\"exp\": now.AddDate(0, 1, 0).Unix(),\n\t\t\"nbf\": now.Unix(),\n\t\t\"iat\": now.Unix(),\n\t}).SignedString(config.GetJWTConf().Key)\n\tif err != nil {\n\t\tlogger.Error(\"生成 JWT Token 失败\", zap.Error(err))\n\t\treturn kongchuanhujiao.DefaultErrResp\n\t}", "\treturn &kongchuanhujiao.Response{Message: t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [16, 45, 47], "buggy_code_start_loc": [3, 44, 5], "filenames": ["internal/app/datahub/pkg/account/memory.go", "internal/app/kongchuanhujiao/account/apis.go", "internal/app/kongchuanhujiao/account/utils.go"], "fixing_code_end_loc": [40, 45, 29], "fixing_code_start_loc": [3, 44, 4], "message": "In github.com/kongchuanhujiao/server before version 1.3.21 there is an authentication Bypass by Primary Weakness vulnerability. All users are impacted. This is fixed in version 1.3.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kongchuanhujiao_project:kongchuanhujiao:*:*:*:*:*:*:*:*", "matchCriteriaId": "11A4F437-0527-4C8C-A4B3-DBAE999BAADA", "versionEndExcluding": "1.3.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In github.com/kongchuanhujiao/server before version 1.3.21 there is an authentication Bypass by Primary Weakness vulnerability. All users are impacted. This is fixed in version 1.3.21."}, {"lang": "es", "value": "En github.com/kongchuanhujiao/server versiones anteriores a 1.3.21, se presenta una Omisi\u00f3n de autenticaci\u00f3n por una vulnerabilidad de Debilidad Primaria.&#xa0;Todos los usuarios est\u00e1n afectados.&#xa0;Esto es corregido en la versi\u00f3n 1.3.21."}], "evaluatorComment": null, "id": "CVE-2021-21403", "lastModified": "2022-10-24T17:13:44.350", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-26T18:15:12.360", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kongchuanhujiao/server/commit/9a125624f219e496bdf4b07b404816d5a309bdc1"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/kongchuanhujiao/server/security/advisories/GHSA-8wrg-m8vm-5fvj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-305"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/kongchuanhujiao/server/commit/9a125624f219e496bdf4b07b404816d5a309bdc1"}, "type": "CWE-287"}
195
Determine whether the {function_name} code is vulnerable or not.
[ "package account", "import (\n\t\"errors\"", "\t\"math/rand\"\n\t\"strconv\"\n\t\"time\"\n", "\t\"github.com/kongchuanhujiao/server/internal/app/client\"\n\t\"github.com/kongchuanhujiao/server/internal/app/client/message\"\n\t\"github.com/kongchuanhujiao/server/internal/app/datahub/pkg/account\"\n\t\"github.com/kongchuanhujiao/server/internal/pkg/logger\"", "\t\"go.uber.org/zap\"\n)", "// sendCode 发送验证码\nfunc sendCode(id string) (err error) {", "\ta, err := account.SelectAccount(id, 0)\n\tif err != nil {\n\t\tlogger.Error(\"发送验证码失败\", zap.Error(err))\n\t\treturn\n\t}", "", "\tif len(a) == 0 {\n\t\treturn errors.New(\"账号不存在\")\n\t}\n", "\trand.Seed(time.Now().UnixNano())\n\tc := strconv.FormatFloat(rand.Float64(), 'f', -1, 64)[2:6]\n", "\tclient.GetClient().SendMessage(", "\t\tmessage.NewTextMessage(\"您的验证码是:\" + c + \",请勿泄露给他人。有效期5分钟\").", "\t\t\tSetTarget(&message.Target{ID: a[0].QQ}),\n\t)\n", "\taccount.WriteCode(id, c)", "\tgo func() {\n\t\ttimer := time.NewTimer(5 * time.Minute)\n\t\tdefer timer.Stop()\n\t\t<-timer.C\n\t\taccount.DeleteCode(id)\n\t}()\n", "\treturn\n}" ]
[ 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [16, 45, 47], "buggy_code_start_loc": [3, 44, 5], "filenames": ["internal/app/datahub/pkg/account/memory.go", "internal/app/kongchuanhujiao/account/apis.go", "internal/app/kongchuanhujiao/account/utils.go"], "fixing_code_end_loc": [40, 45, 29], "fixing_code_start_loc": [3, 44, 4], "message": "In github.com/kongchuanhujiao/server before version 1.3.21 there is an authentication Bypass by Primary Weakness vulnerability. All users are impacted. This is fixed in version 1.3.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kongchuanhujiao_project:kongchuanhujiao:*:*:*:*:*:*:*:*", "matchCriteriaId": "11A4F437-0527-4C8C-A4B3-DBAE999BAADA", "versionEndExcluding": "1.3.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In github.com/kongchuanhujiao/server before version 1.3.21 there is an authentication Bypass by Primary Weakness vulnerability. All users are impacted. This is fixed in version 1.3.21."}, {"lang": "es", "value": "En github.com/kongchuanhujiao/server versiones anteriores a 1.3.21, se presenta una Omisi\u00f3n de autenticaci\u00f3n por una vulnerabilidad de Debilidad Primaria.&#xa0;Todos los usuarios est\u00e1n afectados.&#xa0;Esto es corregido en la versi\u00f3n 1.3.21."}], "evaluatorComment": null, "id": "CVE-2021-21403", "lastModified": "2022-10-24T17:13:44.350", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-26T18:15:12.360", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kongchuanhujiao/server/commit/9a125624f219e496bdf4b07b404816d5a309bdc1"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/kongchuanhujiao/server/security/advisories/GHSA-8wrg-m8vm-5fvj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-305"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/kongchuanhujiao/server/commit/9a125624f219e496bdf4b07b404816d5a309bdc1"}, "type": "CWE-287"}
195
Determine whether the {function_name} code is vulnerable or not.
[ "package account", "import (\n\t\"errors\"", "", "\t\"github.com/kongchuanhujiao/server/internal/app/client\"\n\t\"github.com/kongchuanhujiao/server/internal/app/client/message\"\n\t\"github.com/kongchuanhujiao/server/internal/app/datahub/pkg/account\"\n\t\"github.com/kongchuanhujiao/server/internal/pkg/logger\"", "\t\"go.uber.org/zap\"\n)", "// sendCode 发送验证码\nfunc sendCode(id string) (err error) {", "\ta, err := account.SelectAccount(id, 0)\n\tif err != nil {\n\t\tlogger.Error(\"发送验证码失败\", zap.Error(err))\n\t\treturn\n\t}", "", "\tif len(a) == 0 {\n\t\treturn errors.New(\"账号不存在\")\n\t}\n", "", "\tclient.GetClient().SendMessage(", "\t\tmessage.NewTextMessage(\"您的验证码是:\" + account.GenerateCode(id) + \",请勿泄露给他人。有效期5分钟\").", "\t\t\tSetTarget(&message.Target{ID: a[0].QQ}),\n\t)\n", "", "\treturn\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [16, 45, 47], "buggy_code_start_loc": [3, 44, 5], "filenames": ["internal/app/datahub/pkg/account/memory.go", "internal/app/kongchuanhujiao/account/apis.go", "internal/app/kongchuanhujiao/account/utils.go"], "fixing_code_end_loc": [40, 45, 29], "fixing_code_start_loc": [3, 44, 4], "message": "In github.com/kongchuanhujiao/server before version 1.3.21 there is an authentication Bypass by Primary Weakness vulnerability. All users are impacted. This is fixed in version 1.3.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kongchuanhujiao_project:kongchuanhujiao:*:*:*:*:*:*:*:*", "matchCriteriaId": "11A4F437-0527-4C8C-A4B3-DBAE999BAADA", "versionEndExcluding": "1.3.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In github.com/kongchuanhujiao/server before version 1.3.21 there is an authentication Bypass by Primary Weakness vulnerability. All users are impacted. This is fixed in version 1.3.21."}, {"lang": "es", "value": "En github.com/kongchuanhujiao/server versiones anteriores a 1.3.21, se presenta una Omisi\u00f3n de autenticaci\u00f3n por una vulnerabilidad de Debilidad Primaria.&#xa0;Todos los usuarios est\u00e1n afectados.&#xa0;Esto es corregido en la versi\u00f3n 1.3.21."}], "evaluatorComment": null, "id": "CVE-2021-21403", "lastModified": "2022-10-24T17:13:44.350", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-26T18:15:12.360", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kongchuanhujiao/server/commit/9a125624f219e496bdf4b07b404816d5a309bdc1"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/kongchuanhujiao/server/security/advisories/GHSA-8wrg-m8vm-5fvj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-305"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/kongchuanhujiao/server/commit/9a125624f219e496bdf4b07b404816d5a309bdc1"}, "type": "CWE-287"}
195
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * linux/ipc/shm.c\n * Copyright (C) 1992, 1993 Krishna Balasubramanian\n *\t Many improvements/fixes by Bruno Haible.\n * Replaced `struct shm_desc' by `struct vm_area_struct', July 1994.\n * Fixed the shm swap deallocation (shm_unuse()), August 1998 Andrea Arcangeli.\n *\n * /proc/sysvipc/shm support (c) 1999 Dragos Acostachioaie <dragos@iname.com>\n * BIGMEM support, Andrea Arcangeli <andrea@suse.de>\n * SMP thread shm, Jean-Luc Boyard <jean-luc.boyard@siemens.fr>\n * HIGHMEM support, Ingo Molnar <mingo@redhat.com>\n * Make shmmax, shmall, shmmni sysctl'able, Christoph Rohland <cr@sap.com>\n * Shared /dev/zero support, Kanoj Sarcar <kanoj@sgi.com>\n * Move the mm functionality over to mm/shmem.c, Christoph Rohland <cr@sap.com>\n *\n * support for audit of ipc object properties and permission changes\n * Dustin Kirkland <dustin.kirkland@us.ibm.com>\n *\n * namespaces support\n * OpenVZ, SWsoft Inc.\n * Pavel Emelianov <xemul@openvz.org>\n *\n * Better ipc lock (kern_ipc_perm.lock) handling\n * Davidlohr Bueso <davidlohr.bueso@hp.com>, June 2013.\n */", "#include <linux/slab.h>\n#include <linux/mm.h>\n#include <linux/hugetlb.h>\n#include <linux/shm.h>\n#include <linux/init.h>\n#include <linux/file.h>\n#include <linux/mman.h>\n#include <linux/shmem_fs.h>\n#include <linux/security.h>\n#include <linux/syscalls.h>\n#include <linux/audit.h>\n#include <linux/capability.h>\n#include <linux/ptrace.h>\n#include <linux/seq_file.h>\n#include <linux/rwsem.h>\n#include <linux/nsproxy.h>\n#include <linux/mount.h>\n#include <linux/ipc_namespace.h>", "#include <linux/uaccess.h>", "#include \"util.h\"", "struct shm_file_data {\n\tint id;\n\tstruct ipc_namespace *ns;\n\tstruct file *file;\n\tconst struct vm_operations_struct *vm_ops;\n};", "#define shm_file_data(file) (*((struct shm_file_data **)&(file)->private_data))", "static const struct file_operations shm_file_operations;\nstatic const struct vm_operations_struct shm_vm_ops;", "#define shm_ids(ns)\t((ns)->ids[IPC_SHM_IDS])", "#define shm_unlock(shp)\t\t\t\\\n\tipc_unlock(&(shp)->shm_perm)", "static int newseg(struct ipc_namespace *, struct ipc_params *);\nstatic void shm_open(struct vm_area_struct *vma);\nstatic void shm_close(struct vm_area_struct *vma);\nstatic void shm_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp);\n#ifdef CONFIG_PROC_FS\nstatic int sysvipc_shm_proc_show(struct seq_file *s, void *it);\n#endif", "void shm_init_ns(struct ipc_namespace *ns)\n{\n\tns->shm_ctlmax = SHMMAX;\n\tns->shm_ctlall = SHMALL;\n\tns->shm_ctlmni = SHMMNI;\n\tns->shm_rmid_forced = 0;\n\tns->shm_tot = 0;\n\tipc_init_ids(&shm_ids(ns));\n}", "/*\n * Called with shm_ids.rwsem (writer) and the shp structure locked.\n * Only shm_ids.rwsem remains locked on exit.\n */\nstatic void do_shm_rmid(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp)\n{\n\tstruct shmid_kernel *shp;", "\tshp = container_of(ipcp, struct shmid_kernel, shm_perm);", "\tif (shp->shm_nattch) {\n\t\tshp->shm_perm.mode |= SHM_DEST;\n\t\t/* Do not find it any more */\n\t\tshp->shm_perm.key = IPC_PRIVATE;\n\t\tshm_unlock(shp);\n\t} else\n\t\tshm_destroy(ns, shp);\n}", "#ifdef CONFIG_IPC_NS\nvoid shm_exit_ns(struct ipc_namespace *ns)\n{\n\tfree_ipcs(ns, &shm_ids(ns), do_shm_rmid);\n\tidr_destroy(&ns->ids[IPC_SHM_IDS].ipcs_idr);\n}\n#endif", "static int __init ipc_ns_init(void)\n{\n\tshm_init_ns(&init_ipc_ns);\n\treturn 0;\n}", "pure_initcall(ipc_ns_init);", "void __init shm_init(void)\n{\n\tipc_init_proc_interface(\"sysvipc/shm\",\n#if BITS_PER_LONG <= 32\n\t\t\t\t\" key shmid perms size cpid lpid nattch uid gid cuid cgid atime dtime ctime rss swap\\n\",\n#else\n\t\t\t\t\" key shmid perms size cpid lpid nattch uid gid cuid cgid atime dtime ctime rss swap\\n\",\n#endif\n\t\t\t\tIPC_SHM_IDS, sysvipc_shm_proc_show);\n}", "static inline struct shmid_kernel *shm_obtain_object(struct ipc_namespace *ns, int id)\n{\n\tstruct kern_ipc_perm *ipcp = ipc_obtain_object_idr(&shm_ids(ns), id);", "\tif (IS_ERR(ipcp))\n\t\treturn ERR_CAST(ipcp);", "\treturn container_of(ipcp, struct shmid_kernel, shm_perm);\n}", "static inline struct shmid_kernel *shm_obtain_object_check(struct ipc_namespace *ns, int id)\n{\n\tstruct kern_ipc_perm *ipcp = ipc_obtain_object_check(&shm_ids(ns), id);", "\tif (IS_ERR(ipcp))\n\t\treturn ERR_CAST(ipcp);", "\treturn container_of(ipcp, struct shmid_kernel, shm_perm);\n}", "/*\n * shm_lock_(check_) routines are called in the paths where the rwsem\n * is not necessarily held.\n */\nstatic inline struct shmid_kernel *shm_lock(struct ipc_namespace *ns, int id)\n{\n\tstruct kern_ipc_perm *ipcp = ipc_lock(&shm_ids(ns), id);", "\t/*\n\t * Callers of shm_lock() must validate the status of the returned ipc\n\t * object pointer (as returned by ipc_lock()), and error out as\n\t * appropriate.\n\t */\n\tif (IS_ERR(ipcp))\n\t\treturn (void *)ipcp;\n\treturn container_of(ipcp, struct shmid_kernel, shm_perm);\n}", "static inline void shm_lock_by_ptr(struct shmid_kernel *ipcp)\n{\n\trcu_read_lock();\n\tipc_lock_object(&ipcp->shm_perm);\n}", "static void shm_rcu_free(struct rcu_head *head)\n{\n\tstruct ipc_rcu *p = container_of(head, struct ipc_rcu, rcu);\n\tstruct shmid_kernel *shp = ipc_rcu_to_struct(p);", "\tsecurity_shm_free(shp);\n\tipc_rcu_free(head);\n}", "static inline void shm_rmid(struct ipc_namespace *ns, struct shmid_kernel *s)\n{\n\tlist_del(&s->shm_clist);\n\tipc_rmid(&shm_ids(ns), &s->shm_perm);\n}", "\nstatic int __shm_open(struct vm_area_struct *vma)\n{\n\tstruct file *file = vma->vm_file;\n\tstruct shm_file_data *sfd = shm_file_data(file);\n\tstruct shmid_kernel *shp;", "\tshp = shm_lock(sfd->ns, sfd->id);", "\tif (IS_ERR(shp))\n\t\treturn PTR_ERR(shp);", "\tshp->shm_atim = get_seconds();\n\tshp->shm_lprid = task_tgid_vnr(current);\n\tshp->shm_nattch++;\n\tshm_unlock(shp);\n\treturn 0;\n}", "/* This is called by fork, once for every shm attach. */\nstatic void shm_open(struct vm_area_struct *vma)\n{\n\tint err = __shm_open(vma);\n\t/*\n\t * We raced in the idr lookup or with shm_destroy().\n\t * Either way, the ID is busted.\n\t */\n\tWARN_ON_ONCE(err);\n}", "/*\n * shm_destroy - free the struct shmid_kernel\n *\n * @ns: namespace\n * @shp: struct to free\n *\n * It has to be called with shp and shm_ids.rwsem (writer) locked,\n * but returns with shp unlocked and freed.\n */\nstatic void shm_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp)\n{\n\tstruct file *shm_file;", "\tshm_file = shp->shm_file;\n\tshp->shm_file = NULL;\n\tns->shm_tot -= (shp->shm_segsz + PAGE_SIZE - 1) >> PAGE_SHIFT;\n\tshm_rmid(ns, shp);\n\tshm_unlock(shp);\n\tif (!is_file_hugepages(shm_file))\n\t\tshmem_lock(shm_file, 0, shp->mlock_user);\n\telse if (shp->mlock_user)\n\t\tuser_shm_unlock(i_size_read(file_inode(shm_file)),\n\t\t\t\tshp->mlock_user);\n\tfput(shm_file);\n\tipc_rcu_putref(shp, shm_rcu_free);\n}", "/*\n * shm_may_destroy - identifies whether shm segment should be destroyed now\n *\n * Returns true if and only if there are no active users of the segment and\n * one of the following is true:\n *\n * 1) shmctl(id, IPC_RMID, NULL) was called for this shp\n *\n * 2) sysctl kernel.shm_rmid_forced is set to 1.\n */\nstatic bool shm_may_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp)\n{\n\treturn (shp->shm_nattch == 0) &&\n\t (ns->shm_rmid_forced ||\n\t\t(shp->shm_perm.mode & SHM_DEST));\n}", "/*\n * remove the attach descriptor vma.\n * free memory for segment if it is marked destroyed.\n * The descriptor has already been removed from the current->mm->mmap list\n * and will later be kfree()d.\n */\nstatic void shm_close(struct vm_area_struct *vma)\n{\n\tstruct file *file = vma->vm_file;\n\tstruct shm_file_data *sfd = shm_file_data(file);\n\tstruct shmid_kernel *shp;\n\tstruct ipc_namespace *ns = sfd->ns;", "\tdown_write(&shm_ids(ns).rwsem);\n\t/* remove from the list of attaches of the shm segment */\n\tshp = shm_lock(ns, sfd->id);", "\t/*\n\t * We raced in the idr lookup or with shm_destroy().\n\t * Either way, the ID is busted.\n\t */\n\tif (WARN_ON_ONCE(IS_ERR(shp)))\n\t\tgoto done; /* no-op */", "\tshp->shm_lprid = task_tgid_vnr(current);\n\tshp->shm_dtim = get_seconds();\n\tshp->shm_nattch--;\n\tif (shm_may_destroy(ns, shp))\n\t\tshm_destroy(ns, shp);\n\telse\n\t\tshm_unlock(shp);\ndone:\n\tup_write(&shm_ids(ns).rwsem);\n}", "/* Called with ns->shm_ids(ns).rwsem locked */\nstatic int shm_try_destroy_orphaned(int id, void *p, void *data)\n{\n\tstruct ipc_namespace *ns = data;\n\tstruct kern_ipc_perm *ipcp = p;\n\tstruct shmid_kernel *shp = container_of(ipcp, struct shmid_kernel, shm_perm);", "\t/*\n\t * We want to destroy segments without users and with already\n\t * exit'ed originating process.\n\t *\n\t * As shp->* are changed under rwsem, it's safe to skip shp locking.\n\t */\n\tif (shp->shm_creator != NULL)\n\t\treturn 0;", "\tif (shm_may_destroy(ns, shp)) {\n\t\tshm_lock_by_ptr(shp);\n\t\tshm_destroy(ns, shp);\n\t}\n\treturn 0;\n}", "void shm_destroy_orphaned(struct ipc_namespace *ns)\n{\n\tdown_write(&shm_ids(ns).rwsem);\n\tif (shm_ids(ns).in_use)\n\t\tidr_for_each(&shm_ids(ns).ipcs_idr, &shm_try_destroy_orphaned, ns);\n\tup_write(&shm_ids(ns).rwsem);\n}", "/* Locking assumes this will only be called with task == current */\nvoid exit_shm(struct task_struct *task)\n{\n\tstruct ipc_namespace *ns = task->nsproxy->ipc_ns;\n\tstruct shmid_kernel *shp, *n;", "\tif (list_empty(&task->sysvshm.shm_clist))\n\t\treturn;", "\t/*\n\t * If kernel.shm_rmid_forced is not set then only keep track of\n\t * which shmids are orphaned, so that a later set of the sysctl\n\t * can clean them up.\n\t */\n\tif (!ns->shm_rmid_forced) {\n\t\tdown_read(&shm_ids(ns).rwsem);\n\t\tlist_for_each_entry(shp, &task->sysvshm.shm_clist, shm_clist)\n\t\t\tshp->shm_creator = NULL;\n\t\t/*\n\t\t * Only under read lock but we are only called on current\n\t\t * so no entry on the list will be shared.\n\t\t */\n\t\tlist_del(&task->sysvshm.shm_clist);\n\t\tup_read(&shm_ids(ns).rwsem);\n\t\treturn;\n\t}", "\t/*\n\t * Destroy all already created segments, that were not yet mapped,\n\t * and mark any mapped as orphan to cover the sysctl toggling.\n\t * Destroy is skipped if shm_may_destroy() returns false.\n\t */\n\tdown_write(&shm_ids(ns).rwsem);\n\tlist_for_each_entry_safe(shp, n, &task->sysvshm.shm_clist, shm_clist) {\n\t\tshp->shm_creator = NULL;", "\t\tif (shm_may_destroy(ns, shp)) {\n\t\t\tshm_lock_by_ptr(shp);\n\t\t\tshm_destroy(ns, shp);\n\t\t}\n\t}", "\t/* Remove the list head from any segments still attached. */\n\tlist_del(&task->sysvshm.shm_clist);\n\tup_write(&shm_ids(ns).rwsem);\n}", "static int shm_fault(struct vm_fault *vmf)\n{\n\tstruct file *file = vmf->vma->vm_file;\n\tstruct shm_file_data *sfd = shm_file_data(file);", "\treturn sfd->vm_ops->fault(vmf);\n}", "#ifdef CONFIG_NUMA\nstatic int shm_set_policy(struct vm_area_struct *vma, struct mempolicy *new)\n{\n\tstruct file *file = vma->vm_file;\n\tstruct shm_file_data *sfd = shm_file_data(file);\n\tint err = 0;", "\tif (sfd->vm_ops->set_policy)\n\t\terr = sfd->vm_ops->set_policy(vma, new);\n\treturn err;\n}", "static struct mempolicy *shm_get_policy(struct vm_area_struct *vma,\n\t\t\t\t\tunsigned long addr)\n{\n\tstruct file *file = vma->vm_file;\n\tstruct shm_file_data *sfd = shm_file_data(file);\n\tstruct mempolicy *pol = NULL;", "\tif (sfd->vm_ops->get_policy)\n\t\tpol = sfd->vm_ops->get_policy(vma, addr);\n\telse if (vma->vm_policy)\n\t\tpol = vma->vm_policy;", "\treturn pol;\n}\n#endif", "static int shm_mmap(struct file *file, struct vm_area_struct *vma)\n{\n\tstruct shm_file_data *sfd = shm_file_data(file);\n\tint ret;", "\t/*\n\t * In case of remap_file_pages() emulation, the file can represent\n\t * removed IPC ID: propogate shm_lock() error to caller.\n\t */\n\tret = __shm_open(vma);\n\tif (ret)\n\t\treturn ret;", "\tret = sfd->file->f_op->mmap(sfd->file, vma);\n\tif (ret) {\n\t\tshm_close(vma);\n\t\treturn ret;\n\t}\n\tsfd->vm_ops = vma->vm_ops;\n#ifdef CONFIG_MMU\n\tWARN_ON(!sfd->vm_ops->fault);\n#endif\n\tvma->vm_ops = &shm_vm_ops;\n\treturn 0;\n}", "static int shm_release(struct inode *ino, struct file *file)\n{\n\tstruct shm_file_data *sfd = shm_file_data(file);", "\tput_ipc_ns(sfd->ns);\n\tshm_file_data(file) = NULL;\n\tkfree(sfd);\n\treturn 0;\n}", "static int shm_fsync(struct file *file, loff_t start, loff_t end, int datasync)\n{\n\tstruct shm_file_data *sfd = shm_file_data(file);", "\tif (!sfd->file->f_op->fsync)\n\t\treturn -EINVAL;\n\treturn sfd->file->f_op->fsync(sfd->file, start, end, datasync);\n}", "static long shm_fallocate(struct file *file, int mode, loff_t offset,\n\t\t\t loff_t len)\n{\n\tstruct shm_file_data *sfd = shm_file_data(file);", "\tif (!sfd->file->f_op->fallocate)\n\t\treturn -EOPNOTSUPP;\n\treturn sfd->file->f_op->fallocate(file, mode, offset, len);\n}", "static unsigned long shm_get_unmapped_area(struct file *file,\n\tunsigned long addr, unsigned long len, unsigned long pgoff,\n\tunsigned long flags)\n{\n\tstruct shm_file_data *sfd = shm_file_data(file);", "\treturn sfd->file->f_op->get_unmapped_area(sfd->file, addr, len,\n\t\t\t\t\t\tpgoff, flags);\n}", "static const struct file_operations shm_file_operations = {\n\t.mmap\t\t= shm_mmap,\n\t.fsync\t\t= shm_fsync,\n\t.release\t= shm_release,\n\t.get_unmapped_area\t= shm_get_unmapped_area,\n\t.llseek\t\t= noop_llseek,\n\t.fallocate\t= shm_fallocate,\n};", "/*\n * shm_file_operations_huge is now identical to shm_file_operations,\n * but we keep it distinct for the sake of is_file_shm_hugepages().\n */\nstatic const struct file_operations shm_file_operations_huge = {\n\t.mmap\t\t= shm_mmap,\n\t.fsync\t\t= shm_fsync,\n\t.release\t= shm_release,\n\t.get_unmapped_area\t= shm_get_unmapped_area,\n\t.llseek\t\t= noop_llseek,\n\t.fallocate\t= shm_fallocate,\n};", "bool is_file_shm_hugepages(struct file *file)\n{\n\treturn file->f_op == &shm_file_operations_huge;\n}", "static const struct vm_operations_struct shm_vm_ops = {\n\t.open\t= shm_open,\t/* callback for a new vm-area open */\n\t.close\t= shm_close,\t/* callback for when the vm-area is released */\n\t.fault\t= shm_fault,\n#if defined(CONFIG_NUMA)\n\t.set_policy = shm_set_policy,\n\t.get_policy = shm_get_policy,\n#endif\n};", "/**\n * newseg - Create a new shared memory segment\n * @ns: namespace\n * @params: ptr to the structure that contains key, size and shmflg\n *\n * Called with shm_ids.rwsem held as a writer.\n */\nstatic int newseg(struct ipc_namespace *ns, struct ipc_params *params)\n{\n\tkey_t key = params->key;\n\tint shmflg = params->flg;\n\tsize_t size = params->u.size;\n\tint error;\n\tstruct shmid_kernel *shp;\n\tsize_t numpages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;\n\tstruct file *file;\n\tchar name[13];\n\tint id;\n\tvm_flags_t acctflag = 0;", "\tif (size < SHMMIN || size > ns->shm_ctlmax)\n\t\treturn -EINVAL;", "\tif (numpages << PAGE_SHIFT < size)\n\t\treturn -ENOSPC;", "\tif (ns->shm_tot + numpages < ns->shm_tot ||\n\t\t\tns->shm_tot + numpages > ns->shm_ctlall)\n\t\treturn -ENOSPC;", "\tshp = ipc_rcu_alloc(sizeof(*shp));\n\tif (!shp)\n\t\treturn -ENOMEM;", "\tshp->shm_perm.key = key;\n\tshp->shm_perm.mode = (shmflg & S_IRWXUGO);\n\tshp->mlock_user = NULL;", "\tshp->shm_perm.security = NULL;\n\terror = security_shm_alloc(shp);\n\tif (error) {\n\t\tipc_rcu_putref(shp, ipc_rcu_free);\n\t\treturn error;\n\t}", "\tsprintf(name, \"SYSV%08x\", key);\n\tif (shmflg & SHM_HUGETLB) {\n\t\tstruct hstate *hs;\n\t\tsize_t hugesize;", "\t\ths = hstate_sizelog((shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK);\n\t\tif (!hs) {\n\t\t\terror = -EINVAL;\n\t\t\tgoto no_file;\n\t\t}\n\t\thugesize = ALIGN(size, huge_page_size(hs));", "\t\t/* hugetlb_file_setup applies strict accounting */\n\t\tif (shmflg & SHM_NORESERVE)\n\t\t\tacctflag = VM_NORESERVE;\n\t\tfile = hugetlb_file_setup(name, hugesize, acctflag,\n\t\t\t\t &shp->mlock_user, HUGETLB_SHMFS_INODE,\n\t\t\t\t(shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK);\n\t} else {\n\t\t/*\n\t\t * Do not allow no accounting for OVERCOMMIT_NEVER, even\n\t\t * if it's asked for.\n\t\t */\n\t\tif ((shmflg & SHM_NORESERVE) &&\n\t\t\t\tsysctl_overcommit_memory != OVERCOMMIT_NEVER)\n\t\t\tacctflag = VM_NORESERVE;\n\t\tfile = shmem_kernel_file_setup(name, size, acctflag);\n\t}\n\terror = PTR_ERR(file);\n\tif (IS_ERR(file))\n\t\tgoto no_file;", "\tshp->shm_cprid = task_tgid_vnr(current);\n\tshp->shm_lprid = 0;\n\tshp->shm_atim = shp->shm_dtim = 0;\n\tshp->shm_ctim = get_seconds();\n\tshp->shm_segsz = size;\n\tshp->shm_nattch = 0;\n\tshp->shm_file = file;\n\tshp->shm_creator = current;", "\tid = ipc_addid(&shm_ids(ns), &shp->shm_perm, ns->shm_ctlmni);\n\tif (id < 0) {\n\t\terror = id;\n\t\tgoto no_id;\n\t}", "\tlist_add(&shp->shm_clist, &current->sysvshm.shm_clist);", "\t/*\n\t * shmid gets reported as \"inode#\" in /proc/pid/maps.\n\t * proc-ps tools use this. Changing this will break them.\n\t */\n\tfile_inode(file)->i_ino = shp->shm_perm.id;", "\tns->shm_tot += numpages;\n\terror = shp->shm_perm.id;", "\tipc_unlock_object(&shp->shm_perm);\n\trcu_read_unlock();\n\treturn error;", "no_id:\n\tif (is_file_hugepages(file) && shp->mlock_user)\n\t\tuser_shm_unlock(size, shp->mlock_user);\n\tfput(file);\nno_file:\n\tipc_rcu_putref(shp, shm_rcu_free);\n\treturn error;\n}", "/*\n * Called with shm_ids.rwsem and ipcp locked.\n */\nstatic inline int shm_security(struct kern_ipc_perm *ipcp, int shmflg)\n{\n\tstruct shmid_kernel *shp;", "\tshp = container_of(ipcp, struct shmid_kernel, shm_perm);\n\treturn security_shm_associate(shp, shmflg);\n}", "/*\n * Called with shm_ids.rwsem and ipcp locked.\n */\nstatic inline int shm_more_checks(struct kern_ipc_perm *ipcp,\n\t\t\t\tstruct ipc_params *params)\n{\n\tstruct shmid_kernel *shp;", "\tshp = container_of(ipcp, struct shmid_kernel, shm_perm);\n\tif (shp->shm_segsz < params->u.size)\n\t\treturn -EINVAL;", "\treturn 0;\n}", "SYSCALL_DEFINE3(shmget, key_t, key, size_t, size, int, shmflg)\n{\n\tstruct ipc_namespace *ns;\n\tstatic const struct ipc_ops shm_ops = {\n\t\t.getnew = newseg,\n\t\t.associate = shm_security,\n\t\t.more_checks = shm_more_checks,\n\t};\n\tstruct ipc_params shm_params;", "\tns = current->nsproxy->ipc_ns;", "\tshm_params.key = key;\n\tshm_params.flg = shmflg;\n\tshm_params.u.size = size;", "\treturn ipcget(ns, &shm_ids(ns), &shm_ops, &shm_params);\n}", "static inline unsigned long copy_shmid_to_user(void __user *buf, struct shmid64_ds *in, int version)\n{\n\tswitch (version) {\n\tcase IPC_64:\n\t\treturn copy_to_user(buf, in, sizeof(*in));\n\tcase IPC_OLD:\n\t {\n\t\tstruct shmid_ds out;", "\t\tmemset(&out, 0, sizeof(out));\n\t\tipc64_perm_to_ipc_perm(&in->shm_perm, &out.shm_perm);\n\t\tout.shm_segsz\t= in->shm_segsz;\n\t\tout.shm_atime\t= in->shm_atime;\n\t\tout.shm_dtime\t= in->shm_dtime;\n\t\tout.shm_ctime\t= in->shm_ctime;\n\t\tout.shm_cpid\t= in->shm_cpid;\n\t\tout.shm_lpid\t= in->shm_lpid;\n\t\tout.shm_nattch\t= in->shm_nattch;", "\t\treturn copy_to_user(buf, &out, sizeof(out));\n\t }\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n}", "static inline unsigned long\ncopy_shmid_from_user(struct shmid64_ds *out, void __user *buf, int version)\n{\n\tswitch (version) {\n\tcase IPC_64:\n\t\tif (copy_from_user(out, buf, sizeof(*out)))\n\t\t\treturn -EFAULT;\n\t\treturn 0;\n\tcase IPC_OLD:\n\t {\n\t\tstruct shmid_ds tbuf_old;", "\t\tif (copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))\n\t\t\treturn -EFAULT;", "\t\tout->shm_perm.uid\t= tbuf_old.shm_perm.uid;\n\t\tout->shm_perm.gid\t= tbuf_old.shm_perm.gid;\n\t\tout->shm_perm.mode\t= tbuf_old.shm_perm.mode;", "\t\treturn 0;\n\t }\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n}", "static inline unsigned long copy_shminfo_to_user(void __user *buf, struct shminfo64 *in, int version)\n{\n\tswitch (version) {\n\tcase IPC_64:\n\t\treturn copy_to_user(buf, in, sizeof(*in));\n\tcase IPC_OLD:\n\t {\n\t\tstruct shminfo out;", "\t\tif (in->shmmax > INT_MAX)\n\t\t\tout.shmmax = INT_MAX;\n\t\telse\n\t\t\tout.shmmax = (int)in->shmmax;", "\t\tout.shmmin\t= in->shmmin;\n\t\tout.shmmni\t= in->shmmni;\n\t\tout.shmseg\t= in->shmseg;\n\t\tout.shmall\t= in->shmall;", "\t\treturn copy_to_user(buf, &out, sizeof(out));\n\t }\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n}", "/*\n * Calculate and add used RSS and swap pages of a shm.\n * Called with shm_ids.rwsem held as a reader\n */\nstatic void shm_add_rss_swap(struct shmid_kernel *shp,\n\tunsigned long *rss_add, unsigned long *swp_add)\n{\n\tstruct inode *inode;", "\tinode = file_inode(shp->shm_file);", "\tif (is_file_hugepages(shp->shm_file)) {\n\t\tstruct address_space *mapping = inode->i_mapping;\n\t\tstruct hstate *h = hstate_file(shp->shm_file);\n\t\t*rss_add += pages_per_huge_page(h) * mapping->nrpages;\n\t} else {\n#ifdef CONFIG_SHMEM\n\t\tstruct shmem_inode_info *info = SHMEM_I(inode);", "\t\tspin_lock_irq(&info->lock);\n\t\t*rss_add += inode->i_mapping->nrpages;\n\t\t*swp_add += info->swapped;\n\t\tspin_unlock_irq(&info->lock);\n#else\n\t\t*rss_add += inode->i_mapping->nrpages;\n#endif\n\t}\n}", "/*\n * Called with shm_ids.rwsem held as a reader\n */\nstatic void shm_get_stat(struct ipc_namespace *ns, unsigned long *rss,\n\t\tunsigned long *swp)\n{\n\tint next_id;\n\tint total, in_use;", "\t*rss = 0;\n\t*swp = 0;", "\tin_use = shm_ids(ns).in_use;", "\tfor (total = 0, next_id = 0; total < in_use; next_id++) {\n\t\tstruct kern_ipc_perm *ipc;\n\t\tstruct shmid_kernel *shp;", "\t\tipc = idr_find(&shm_ids(ns).ipcs_idr, next_id);\n\t\tif (ipc == NULL)\n\t\t\tcontinue;\n\t\tshp = container_of(ipc, struct shmid_kernel, shm_perm);", "\t\tshm_add_rss_swap(shp, rss, swp);", "\t\ttotal++;\n\t}\n}", "/*\n * This function handles some shmctl commands which require the rwsem\n * to be held in write mode.\n * NOTE: no locks must be held, the rwsem is taken inside this function.\n */\nstatic int shmctl_down(struct ipc_namespace *ns, int shmid, int cmd,\n\t\t struct shmid_ds __user *buf, int version)\n{\n\tstruct kern_ipc_perm *ipcp;\n\tstruct shmid64_ds shmid64;\n\tstruct shmid_kernel *shp;\n\tint err;", "\tif (cmd == IPC_SET) {\n\t\tif (copy_shmid_from_user(&shmid64, buf, version))\n\t\t\treturn -EFAULT;\n\t}", "\tdown_write(&shm_ids(ns).rwsem);\n\trcu_read_lock();", "\tipcp = ipcctl_pre_down_nolock(ns, &shm_ids(ns), shmid, cmd,\n\t\t\t\t &shmid64.shm_perm, 0);\n\tif (IS_ERR(ipcp)) {\n\t\terr = PTR_ERR(ipcp);\n\t\tgoto out_unlock1;\n\t}", "\tshp = container_of(ipcp, struct shmid_kernel, shm_perm);", "\terr = security_shm_shmctl(shp, cmd);\n\tif (err)\n\t\tgoto out_unlock1;", "\tswitch (cmd) {\n\tcase IPC_RMID:\n\t\tipc_lock_object(&shp->shm_perm);\n\t\t/* do_shm_rmid unlocks the ipc object and rcu */\n\t\tdo_shm_rmid(ns, ipcp);\n\t\tgoto out_up;\n\tcase IPC_SET:\n\t\tipc_lock_object(&shp->shm_perm);\n\t\terr = ipc_update_perm(&shmid64.shm_perm, ipcp);\n\t\tif (err)\n\t\t\tgoto out_unlock0;\n\t\tshp->shm_ctim = get_seconds();\n\t\tbreak;\n\tdefault:\n\t\terr = -EINVAL;\n\t\tgoto out_unlock1;\n\t}", "out_unlock0:\n\tipc_unlock_object(&shp->shm_perm);\nout_unlock1:\n\trcu_read_unlock();\nout_up:\n\tup_write(&shm_ids(ns).rwsem);\n\treturn err;\n}", "static int shmctl_nolock(struct ipc_namespace *ns, int shmid,\n\t\t\t int cmd, int version, void __user *buf)\n{\n\tint err;\n\tstruct shmid_kernel *shp;", "\t/* preliminary security checks for *_INFO */\n\tif (cmd == IPC_INFO || cmd == SHM_INFO) {\n\t\terr = security_shm_shmctl(NULL, cmd);\n\t\tif (err)\n\t\t\treturn err;\n\t}", "\tswitch (cmd) {\n\tcase IPC_INFO:\n\t{\n\t\tstruct shminfo64 shminfo;", "\t\tmemset(&shminfo, 0, sizeof(shminfo));\n\t\tshminfo.shmmni = shminfo.shmseg = ns->shm_ctlmni;\n\t\tshminfo.shmmax = ns->shm_ctlmax;\n\t\tshminfo.shmall = ns->shm_ctlall;", "\t\tshminfo.shmmin = SHMMIN;\n\t\tif (copy_shminfo_to_user(buf, &shminfo, version))\n\t\t\treturn -EFAULT;", "\t\tdown_read(&shm_ids(ns).rwsem);\n\t\terr = ipc_get_maxid(&shm_ids(ns));\n\t\tup_read(&shm_ids(ns).rwsem);", "\t\tif (err < 0)\n\t\t\terr = 0;\n\t\tgoto out;\n\t}\n\tcase SHM_INFO:\n\t{\n\t\tstruct shm_info shm_info;", "\t\tmemset(&shm_info, 0, sizeof(shm_info));\n\t\tdown_read(&shm_ids(ns).rwsem);\n\t\tshm_info.used_ids = shm_ids(ns).in_use;\n\t\tshm_get_stat(ns, &shm_info.shm_rss, &shm_info.shm_swp);\n\t\tshm_info.shm_tot = ns->shm_tot;\n\t\tshm_info.swap_attempts = 0;\n\t\tshm_info.swap_successes = 0;\n\t\terr = ipc_get_maxid(&shm_ids(ns));\n\t\tup_read(&shm_ids(ns).rwsem);\n\t\tif (copy_to_user(buf, &shm_info, sizeof(shm_info))) {\n\t\t\terr = -EFAULT;\n\t\t\tgoto out;\n\t\t}", "\t\terr = err < 0 ? 0 : err;\n\t\tgoto out;\n\t}\n\tcase SHM_STAT:\n\tcase IPC_STAT:\n\t{\n\t\tstruct shmid64_ds tbuf;\n\t\tint result;", "\t\trcu_read_lock();\n\t\tif (cmd == SHM_STAT) {\n\t\t\tshp = shm_obtain_object(ns, shmid);\n\t\t\tif (IS_ERR(shp)) {\n\t\t\t\terr = PTR_ERR(shp);\n\t\t\t\tgoto out_unlock;\n\t\t\t}\n\t\t\tresult = shp->shm_perm.id;\n\t\t} else {\n\t\t\tshp = shm_obtain_object_check(ns, shmid);\n\t\t\tif (IS_ERR(shp)) {\n\t\t\t\terr = PTR_ERR(shp);\n\t\t\t\tgoto out_unlock;\n\t\t\t}\n\t\t\tresult = 0;\n\t\t}", "\t\terr = -EACCES;\n\t\tif (ipcperms(ns, &shp->shm_perm, S_IRUGO))\n\t\t\tgoto out_unlock;", "\t\terr = security_shm_shmctl(shp, cmd);\n\t\tif (err)\n\t\t\tgoto out_unlock;", "\t\tmemset(&tbuf, 0, sizeof(tbuf));\n\t\tkernel_to_ipc64_perm(&shp->shm_perm, &tbuf.shm_perm);\n\t\ttbuf.shm_segsz\t= shp->shm_segsz;\n\t\ttbuf.shm_atime\t= shp->shm_atim;\n\t\ttbuf.shm_dtime\t= shp->shm_dtim;\n\t\ttbuf.shm_ctime\t= shp->shm_ctim;\n\t\ttbuf.shm_cpid\t= shp->shm_cprid;\n\t\ttbuf.shm_lpid\t= shp->shm_lprid;\n\t\ttbuf.shm_nattch\t= shp->shm_nattch;\n\t\trcu_read_unlock();", "\t\tif (copy_shmid_to_user(buf, &tbuf, version))\n\t\t\terr = -EFAULT;\n\t\telse\n\t\t\terr = result;\n\t\tgoto out;\n\t}\n\tdefault:\n\t\treturn -EINVAL;\n\t}", "out_unlock:\n\trcu_read_unlock();\nout:\n\treturn err;\n}", "SYSCALL_DEFINE3(shmctl, int, shmid, int, cmd, struct shmid_ds __user *, buf)\n{\n\tstruct shmid_kernel *shp;\n\tint err, version;\n\tstruct ipc_namespace *ns;", "\tif (cmd < 0 || shmid < 0)\n\t\treturn -EINVAL;", "\tversion = ipc_parse_version(&cmd);\n\tns = current->nsproxy->ipc_ns;", "\tswitch (cmd) {\n\tcase IPC_INFO:\n\tcase SHM_INFO:\n\tcase SHM_STAT:\n\tcase IPC_STAT:\n\t\treturn shmctl_nolock(ns, shmid, cmd, version, buf);\n\tcase IPC_RMID:\n\tcase IPC_SET:\n\t\treturn shmctl_down(ns, shmid, cmd, buf, version);\n\tcase SHM_LOCK:\n\tcase SHM_UNLOCK:\n\t{\n\t\tstruct file *shm_file;", "\t\trcu_read_lock();\n\t\tshp = shm_obtain_object_check(ns, shmid);\n\t\tif (IS_ERR(shp)) {\n\t\t\terr = PTR_ERR(shp);\n\t\t\tgoto out_unlock1;\n\t\t}", "\t\taudit_ipc_obj(&(shp->shm_perm));\n\t\terr = security_shm_shmctl(shp, cmd);\n\t\tif (err)\n\t\t\tgoto out_unlock1;", "\t\tipc_lock_object(&shp->shm_perm);", "\t\t/* check if shm_destroy() is tearing down shp */\n\t\tif (!ipc_valid_object(&shp->shm_perm)) {\n\t\t\terr = -EIDRM;\n\t\t\tgoto out_unlock0;\n\t\t}", "\t\tif (!ns_capable(ns->user_ns, CAP_IPC_LOCK)) {\n\t\t\tkuid_t euid = current_euid();", "\t\t\tif (!uid_eq(euid, shp->shm_perm.uid) &&\n\t\t\t !uid_eq(euid, shp->shm_perm.cuid)) {\n\t\t\t\terr = -EPERM;\n\t\t\t\tgoto out_unlock0;\n\t\t\t}\n\t\t\tif (cmd == SHM_LOCK && !rlimit(RLIMIT_MEMLOCK)) {\n\t\t\t\terr = -EPERM;\n\t\t\t\tgoto out_unlock0;\n\t\t\t}\n\t\t}", "\t\tshm_file = shp->shm_file;\n\t\tif (is_file_hugepages(shm_file))\n\t\t\tgoto out_unlock0;", "\t\tif (cmd == SHM_LOCK) {\n\t\t\tstruct user_struct *user = current_user();", "\t\t\terr = shmem_lock(shm_file, 1, user);\n\t\t\tif (!err && !(shp->shm_perm.mode & SHM_LOCKED)) {\n\t\t\t\tshp->shm_perm.mode |= SHM_LOCKED;\n\t\t\t\tshp->mlock_user = user;\n\t\t\t}\n\t\t\tgoto out_unlock0;\n\t\t}", "\t\t/* SHM_UNLOCK */\n\t\tif (!(shp->shm_perm.mode & SHM_LOCKED))\n\t\t\tgoto out_unlock0;\n\t\tshmem_lock(shm_file, 0, shp->mlock_user);\n\t\tshp->shm_perm.mode &= ~SHM_LOCKED;\n\t\tshp->mlock_user = NULL;\n\t\tget_file(shm_file);\n\t\tipc_unlock_object(&shp->shm_perm);\n\t\trcu_read_unlock();\n\t\tshmem_unlock_mapping(shm_file->f_mapping);", "\t\tfput(shm_file);\n\t\treturn err;\n\t}\n\tdefault:\n\t\treturn -EINVAL;\n\t}", "out_unlock0:\n\tipc_unlock_object(&shp->shm_perm);\nout_unlock1:\n\trcu_read_unlock();\n\treturn err;\n}", "/*\n * Fix shmaddr, allocate descriptor, map shm, add attach descriptor to lists.\n *\n * NOTE! Despite the name, this is NOT a direct system call entrypoint. The\n * \"raddr\" thing points to kernel space, and there has to be a wrapper around\n * this.\n */", "long do_shmat(int shmid, char __user *shmaddr, int shmflg, ulong *raddr,\n\t unsigned long shmlba)", "{\n\tstruct shmid_kernel *shp;\n\tunsigned long addr;\n\tunsigned long size;\n\tstruct file *file;\n\tint err;\n\tunsigned long flags;\n\tunsigned long prot;\n\tint acc_mode;\n\tstruct ipc_namespace *ns;\n\tstruct shm_file_data *sfd;\n\tstruct path path;\n\tfmode_t f_mode;\n\tunsigned long populate = 0;", "\terr = -EINVAL;\n\tif (shmid < 0)\n\t\tgoto out;\n\telse if ((addr = (ulong)shmaddr)) {\n\t\tif (addr & (shmlba - 1)) {", "\t\t\tif (shmflg & SHM_RND)\n\t\t\t\taddr &= ~(shmlba - 1);\t /* round down */", "\t\t\telse\n#ifndef __ARCH_FORCE_SHMLBA\n\t\t\t\tif (addr & ~PAGE_MASK)\n#endif\n\t\t\t\t\tgoto out;\n\t\t}\n\t\tflags = MAP_SHARED | MAP_FIXED;\n\t} else {\n\t\tif ((shmflg & SHM_REMAP))\n\t\t\tgoto out;", "\t\tflags = MAP_SHARED;\n\t}", "\tif (shmflg & SHM_RDONLY) {\n\t\tprot = PROT_READ;\n\t\tacc_mode = S_IRUGO;\n\t\tf_mode = FMODE_READ;\n\t} else {\n\t\tprot = PROT_READ | PROT_WRITE;\n\t\tacc_mode = S_IRUGO | S_IWUGO;\n\t\tf_mode = FMODE_READ | FMODE_WRITE;\n\t}\n\tif (shmflg & SHM_EXEC) {\n\t\tprot |= PROT_EXEC;\n\t\tacc_mode |= S_IXUGO;\n\t}", "\t/*\n\t * We cannot rely on the fs check since SYSV IPC does have an\n\t * additional creator id...\n\t */\n\tns = current->nsproxy->ipc_ns;\n\trcu_read_lock();\n\tshp = shm_obtain_object_check(ns, shmid);\n\tif (IS_ERR(shp)) {\n\t\terr = PTR_ERR(shp);\n\t\tgoto out_unlock;\n\t}", "\terr = -EACCES;\n\tif (ipcperms(ns, &shp->shm_perm, acc_mode))\n\t\tgoto out_unlock;", "\terr = security_shm_shmat(shp, shmaddr, shmflg);\n\tif (err)\n\t\tgoto out_unlock;", "\tipc_lock_object(&shp->shm_perm);", "\t/* check if shm_destroy() is tearing down shp */\n\tif (!ipc_valid_object(&shp->shm_perm)) {\n\t\tipc_unlock_object(&shp->shm_perm);\n\t\terr = -EIDRM;\n\t\tgoto out_unlock;\n\t}", "\tpath = shp->shm_file->f_path;\n\tpath_get(&path);\n\tshp->shm_nattch++;\n\tsize = i_size_read(d_inode(path.dentry));\n\tipc_unlock_object(&shp->shm_perm);\n\trcu_read_unlock();", "\terr = -ENOMEM;\n\tsfd = kzalloc(sizeof(*sfd), GFP_KERNEL);\n\tif (!sfd) {\n\t\tpath_put(&path);\n\t\tgoto out_nattch;\n\t}", "\tfile = alloc_file(&path, f_mode,\n\t\t\t is_file_hugepages(shp->shm_file) ?\n\t\t\t\t&shm_file_operations_huge :\n\t\t\t\t&shm_file_operations);\n\terr = PTR_ERR(file);\n\tif (IS_ERR(file)) {\n\t\tkfree(sfd);\n\t\tpath_put(&path);\n\t\tgoto out_nattch;\n\t}", "\tfile->private_data = sfd;\n\tfile->f_mapping = shp->shm_file->f_mapping;\n\tsfd->id = shp->shm_perm.id;\n\tsfd->ns = get_ipc_ns(ns);\n\tsfd->file = shp->shm_file;\n\tsfd->vm_ops = NULL;", "\terr = security_mmap_file(file, prot, flags);\n\tif (err)\n\t\tgoto out_fput;", "\tif (down_write_killable(&current->mm->mmap_sem)) {\n\t\terr = -EINTR;\n\t\tgoto out_fput;\n\t}", "\tif (addr && !(shmflg & SHM_REMAP)) {\n\t\terr = -EINVAL;\n\t\tif (addr + size < addr)\n\t\t\tgoto invalid;", "\t\tif (find_vma_intersection(current->mm, addr, addr + size))\n\t\t\tgoto invalid;\n\t}", "\taddr = do_mmap_pgoff(file, addr, size, prot, flags, 0, &populate, NULL);\n\t*raddr = addr;\n\terr = 0;\n\tif (IS_ERR_VALUE(addr))\n\t\terr = (long)addr;\ninvalid:\n\tup_write(&current->mm->mmap_sem);\n\tif (populate)\n\t\tmm_populate(addr, populate);", "out_fput:\n\tfput(file);", "out_nattch:\n\tdown_write(&shm_ids(ns).rwsem);\n\tshp = shm_lock(ns, shmid);\n\tshp->shm_nattch--;\n\tif (shm_may_destroy(ns, shp))\n\t\tshm_destroy(ns, shp);\n\telse\n\t\tshm_unlock(shp);\n\tup_write(&shm_ids(ns).rwsem);\n\treturn err;", "out_unlock:\n\trcu_read_unlock();\nout:\n\treturn err;\n}", "SYSCALL_DEFINE3(shmat, int, shmid, char __user *, shmaddr, int, shmflg)\n{\n\tunsigned long ret;\n\tlong err;", "\terr = do_shmat(shmid, shmaddr, shmflg, &ret, SHMLBA);\n\tif (err)\n\t\treturn err;\n\tforce_successful_syscall_return();\n\treturn (long)ret;\n}", "/*\n * detach and kill segment if marked destroyed.\n * The work is done in shm_close.\n */\nSYSCALL_DEFINE1(shmdt, char __user *, shmaddr)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma;\n\tunsigned long addr = (unsigned long)shmaddr;\n\tint retval = -EINVAL;\n#ifdef CONFIG_MMU\n\tloff_t size = 0;\n\tstruct file *file;\n\tstruct vm_area_struct *next;\n#endif", "\tif (addr & ~PAGE_MASK)\n\t\treturn retval;", "\tif (down_write_killable(&mm->mmap_sem))\n\t\treturn -EINTR;", "\t/*\n\t * This function tries to be smart and unmap shm segments that\n\t * were modified by partial mlock or munmap calls:\n\t * - It first determines the size of the shm segment that should be\n\t * unmapped: It searches for a vma that is backed by shm and that\n\t * started at address shmaddr. It records it's size and then unmaps\n\t * it.\n\t * - Then it unmaps all shm vmas that started at shmaddr and that\n\t * are within the initially determined size and that are from the\n\t * same shm segment from which we determined the size.\n\t * Errors from do_munmap are ignored: the function only fails if\n\t * it's called with invalid parameters or if it's called to unmap\n\t * a part of a vma. Both calls in this function are for full vmas,\n\t * the parameters are directly copied from the vma itself and always\n\t * valid - therefore do_munmap cannot fail. (famous last words?)\n\t */\n\t/*\n\t * If it had been mremap()'d, the starting address would not\n\t * match the usual checks anyway. So assume all vma's are\n\t * above the starting address given.\n\t */\n\tvma = find_vma(mm, addr);", "#ifdef CONFIG_MMU\n\twhile (vma) {\n\t\tnext = vma->vm_next;", "\t\t/*\n\t\t * Check if the starting address would match, i.e. it's\n\t\t * a fragment created by mprotect() and/or munmap(), or it\n\t\t * otherwise it starts at this address with no hassles.\n\t\t */\n\t\tif ((vma->vm_ops == &shm_vm_ops) &&\n\t\t\t(vma->vm_start - addr)/PAGE_SIZE == vma->vm_pgoff) {", "\t\t\t/*\n\t\t\t * Record the file of the shm segment being\n\t\t\t * unmapped. With mremap(), someone could place\n\t\t\t * page from another segment but with equal offsets\n\t\t\t * in the range we are unmapping.\n\t\t\t */\n\t\t\tfile = vma->vm_file;\n\t\t\tsize = i_size_read(file_inode(vma->vm_file));\n\t\t\tdo_munmap(mm, vma->vm_start, vma->vm_end - vma->vm_start, NULL);\n\t\t\t/*\n\t\t\t * We discovered the size of the shm segment, so\n\t\t\t * break out of here and fall through to the next\n\t\t\t * loop that uses the size information to stop\n\t\t\t * searching for matching vma's.\n\t\t\t */\n\t\t\tretval = 0;\n\t\t\tvma = next;\n\t\t\tbreak;\n\t\t}\n\t\tvma = next;\n\t}", "\t/*\n\t * We need look no further than the maximum address a fragment\n\t * could possibly have landed at. Also cast things to loff_t to\n\t * prevent overflows and make comparisons vs. equal-width types.\n\t */\n\tsize = PAGE_ALIGN(size);\n\twhile (vma && (loff_t)(vma->vm_end - addr) <= size) {\n\t\tnext = vma->vm_next;", "\t\t/* finding a matching vma now does not alter retval */\n\t\tif ((vma->vm_ops == &shm_vm_ops) &&\n\t\t ((vma->vm_start - addr)/PAGE_SIZE == vma->vm_pgoff) &&\n\t\t (vma->vm_file == file))\n\t\t\tdo_munmap(mm, vma->vm_start, vma->vm_end - vma->vm_start, NULL);\n\t\tvma = next;\n\t}", "#else\t/* CONFIG_MMU */\n\t/* under NOMMU conditions, the exact address to be destroyed must be\n\t * given\n\t */\n\tif (vma && vma->vm_start == addr && vma->vm_ops == &shm_vm_ops) {\n\t\tdo_munmap(mm, vma->vm_start, vma->vm_end - vma->vm_start, NULL);\n\t\tretval = 0;\n\t}", "#endif", "\tup_write(&mm->mmap_sem);\n\treturn retval;\n}", "#ifdef CONFIG_PROC_FS\nstatic int sysvipc_shm_proc_show(struct seq_file *s, void *it)\n{\n\tstruct user_namespace *user_ns = seq_user_ns(s);\n\tstruct shmid_kernel *shp = it;\n\tunsigned long rss = 0, swp = 0;", "\tshm_add_rss_swap(shp, &rss, &swp);", "#if BITS_PER_LONG <= 32\n#define SIZE_SPEC \"%10lu\"\n#else\n#define SIZE_SPEC \"%21lu\"\n#endif", "\tseq_printf(s,\n\t\t \"%10d %10d %4o \" SIZE_SPEC \" %5u %5u \"\n\t\t \"%5lu %5u %5u %5u %5u %10lu %10lu %10lu \"\n\t\t SIZE_SPEC \" \" SIZE_SPEC \"\\n\",\n\t\t shp->shm_perm.key,\n\t\t shp->shm_perm.id,\n\t\t shp->shm_perm.mode,\n\t\t shp->shm_segsz,\n\t\t shp->shm_cprid,\n\t\t shp->shm_lprid,\n\t\t shp->shm_nattch,\n\t\t from_kuid_munged(user_ns, shp->shm_perm.uid),\n\t\t from_kgid_munged(user_ns, shp->shm_perm.gid),\n\t\t from_kuid_munged(user_ns, shp->shm_perm.cuid),\n\t\t from_kgid_munged(user_ns, shp->shm_perm.cgid),\n\t\t shp->shm_atim,\n\t\t shp->shm_dtim,\n\t\t shp->shm_ctim,\n\t\t rss * PAGE_SIZE,\n\t\t swp * PAGE_SIZE);", "\treturn 0;\n}\n#endif" ]
[ 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, 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 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 ]
PreciseBugs
{"buggy_code_end_loc": [1118], "buggy_code_start_loc": [1094], "filenames": ["ipc/shm.c"], "fixing_code_end_loc": [1123], "fixing_code_start_loc": [1094], "message": "The do_shmat function in ipc/shm.c in the Linux kernel through 4.9.12 does not restrict the address calculated by a certain rounding operation, which allows local users to map page zero, and consequently bypass a protection mechanism that exists for the mmap system call, by making crafted shmget and shmat system calls in a privileged context.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "68E74529-58C5-4D73-8176-DDDF25C71F22", "versionEndExcluding": "4.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:esm:*:*:*", "matchCriteriaId": "8D305F7A-D159-4716-AB26-5E38BB5CD991", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:esm:*:*:*", "matchCriteriaId": "815D70A8-47D3-459C-A32C-9FEACA0659D1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The do_shmat function in ipc/shm.c in the Linux kernel through 4.9.12 does not restrict the address calculated by a certain rounding operation, which allows local users to map page zero, and consequently bypass a protection mechanism that exists for the mmap system call, by making crafted shmget and shmat system calls in a privileged context."}, {"lang": "es", "value": "La funci\u00f3n do_shmat en ipc/shm.c en el kernel de Linux hasta la versi\u00f3n 4.9.12 no restringe la direcci\u00f3n calculada por cierta operaci\u00f3n de redondeo, lo que permite a usuarios locales asignar la p\u00e1gina cero, y como consecuencia, eludir un mecanismo de protecci\u00f3n que existe por la llamada de sistema mmap, haciendo llamadas a sistema shmget y shmat manipuladas en un contexto privilegiado."}], "evaluatorComment": null, "id": "CVE-2017-5669", "lastModified": "2020-10-09T14:49:28.933", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.6, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:L/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2017-02-24T15:59:00.150", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2017/dsa-3804"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/96754"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securitytracker.com/id/1037918"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Vendor Advisory"], "url": "https://bugzilla.kernel.org/show_bug.cgi?id=192931"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/95e91b831f87ac8e1f8ed50c14d709089b4e01b8"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/e1d35d4dc7f089e6c9c080d556feedf9c706f0c7"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3583-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3583-2/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/95e91b831f87ac8e1f8ed50c14d709089b4e01b8"}, "type": "NVD-CWE-noinfo"}
196
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * linux/ipc/shm.c\n * Copyright (C) 1992, 1993 Krishna Balasubramanian\n *\t Many improvements/fixes by Bruno Haible.\n * Replaced `struct shm_desc' by `struct vm_area_struct', July 1994.\n * Fixed the shm swap deallocation (shm_unuse()), August 1998 Andrea Arcangeli.\n *\n * /proc/sysvipc/shm support (c) 1999 Dragos Acostachioaie <dragos@iname.com>\n * BIGMEM support, Andrea Arcangeli <andrea@suse.de>\n * SMP thread shm, Jean-Luc Boyard <jean-luc.boyard@siemens.fr>\n * HIGHMEM support, Ingo Molnar <mingo@redhat.com>\n * Make shmmax, shmall, shmmni sysctl'able, Christoph Rohland <cr@sap.com>\n * Shared /dev/zero support, Kanoj Sarcar <kanoj@sgi.com>\n * Move the mm functionality over to mm/shmem.c, Christoph Rohland <cr@sap.com>\n *\n * support for audit of ipc object properties and permission changes\n * Dustin Kirkland <dustin.kirkland@us.ibm.com>\n *\n * namespaces support\n * OpenVZ, SWsoft Inc.\n * Pavel Emelianov <xemul@openvz.org>\n *\n * Better ipc lock (kern_ipc_perm.lock) handling\n * Davidlohr Bueso <davidlohr.bueso@hp.com>, June 2013.\n */", "#include <linux/slab.h>\n#include <linux/mm.h>\n#include <linux/hugetlb.h>\n#include <linux/shm.h>\n#include <linux/init.h>\n#include <linux/file.h>\n#include <linux/mman.h>\n#include <linux/shmem_fs.h>\n#include <linux/security.h>\n#include <linux/syscalls.h>\n#include <linux/audit.h>\n#include <linux/capability.h>\n#include <linux/ptrace.h>\n#include <linux/seq_file.h>\n#include <linux/rwsem.h>\n#include <linux/nsproxy.h>\n#include <linux/mount.h>\n#include <linux/ipc_namespace.h>", "#include <linux/uaccess.h>", "#include \"util.h\"", "struct shm_file_data {\n\tint id;\n\tstruct ipc_namespace *ns;\n\tstruct file *file;\n\tconst struct vm_operations_struct *vm_ops;\n};", "#define shm_file_data(file) (*((struct shm_file_data **)&(file)->private_data))", "static const struct file_operations shm_file_operations;\nstatic const struct vm_operations_struct shm_vm_ops;", "#define shm_ids(ns)\t((ns)->ids[IPC_SHM_IDS])", "#define shm_unlock(shp)\t\t\t\\\n\tipc_unlock(&(shp)->shm_perm)", "static int newseg(struct ipc_namespace *, struct ipc_params *);\nstatic void shm_open(struct vm_area_struct *vma);\nstatic void shm_close(struct vm_area_struct *vma);\nstatic void shm_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp);\n#ifdef CONFIG_PROC_FS\nstatic int sysvipc_shm_proc_show(struct seq_file *s, void *it);\n#endif", "void shm_init_ns(struct ipc_namespace *ns)\n{\n\tns->shm_ctlmax = SHMMAX;\n\tns->shm_ctlall = SHMALL;\n\tns->shm_ctlmni = SHMMNI;\n\tns->shm_rmid_forced = 0;\n\tns->shm_tot = 0;\n\tipc_init_ids(&shm_ids(ns));\n}", "/*\n * Called with shm_ids.rwsem (writer) and the shp structure locked.\n * Only shm_ids.rwsem remains locked on exit.\n */\nstatic void do_shm_rmid(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp)\n{\n\tstruct shmid_kernel *shp;", "\tshp = container_of(ipcp, struct shmid_kernel, shm_perm);", "\tif (shp->shm_nattch) {\n\t\tshp->shm_perm.mode |= SHM_DEST;\n\t\t/* Do not find it any more */\n\t\tshp->shm_perm.key = IPC_PRIVATE;\n\t\tshm_unlock(shp);\n\t} else\n\t\tshm_destroy(ns, shp);\n}", "#ifdef CONFIG_IPC_NS\nvoid shm_exit_ns(struct ipc_namespace *ns)\n{\n\tfree_ipcs(ns, &shm_ids(ns), do_shm_rmid);\n\tidr_destroy(&ns->ids[IPC_SHM_IDS].ipcs_idr);\n}\n#endif", "static int __init ipc_ns_init(void)\n{\n\tshm_init_ns(&init_ipc_ns);\n\treturn 0;\n}", "pure_initcall(ipc_ns_init);", "void __init shm_init(void)\n{\n\tipc_init_proc_interface(\"sysvipc/shm\",\n#if BITS_PER_LONG <= 32\n\t\t\t\t\" key shmid perms size cpid lpid nattch uid gid cuid cgid atime dtime ctime rss swap\\n\",\n#else\n\t\t\t\t\" key shmid perms size cpid lpid nattch uid gid cuid cgid atime dtime ctime rss swap\\n\",\n#endif\n\t\t\t\tIPC_SHM_IDS, sysvipc_shm_proc_show);\n}", "static inline struct shmid_kernel *shm_obtain_object(struct ipc_namespace *ns, int id)\n{\n\tstruct kern_ipc_perm *ipcp = ipc_obtain_object_idr(&shm_ids(ns), id);", "\tif (IS_ERR(ipcp))\n\t\treturn ERR_CAST(ipcp);", "\treturn container_of(ipcp, struct shmid_kernel, shm_perm);\n}", "static inline struct shmid_kernel *shm_obtain_object_check(struct ipc_namespace *ns, int id)\n{\n\tstruct kern_ipc_perm *ipcp = ipc_obtain_object_check(&shm_ids(ns), id);", "\tif (IS_ERR(ipcp))\n\t\treturn ERR_CAST(ipcp);", "\treturn container_of(ipcp, struct shmid_kernel, shm_perm);\n}", "/*\n * shm_lock_(check_) routines are called in the paths where the rwsem\n * is not necessarily held.\n */\nstatic inline struct shmid_kernel *shm_lock(struct ipc_namespace *ns, int id)\n{\n\tstruct kern_ipc_perm *ipcp = ipc_lock(&shm_ids(ns), id);", "\t/*\n\t * Callers of shm_lock() must validate the status of the returned ipc\n\t * object pointer (as returned by ipc_lock()), and error out as\n\t * appropriate.\n\t */\n\tif (IS_ERR(ipcp))\n\t\treturn (void *)ipcp;\n\treturn container_of(ipcp, struct shmid_kernel, shm_perm);\n}", "static inline void shm_lock_by_ptr(struct shmid_kernel *ipcp)\n{\n\trcu_read_lock();\n\tipc_lock_object(&ipcp->shm_perm);\n}", "static void shm_rcu_free(struct rcu_head *head)\n{\n\tstruct ipc_rcu *p = container_of(head, struct ipc_rcu, rcu);\n\tstruct shmid_kernel *shp = ipc_rcu_to_struct(p);", "\tsecurity_shm_free(shp);\n\tipc_rcu_free(head);\n}", "static inline void shm_rmid(struct ipc_namespace *ns, struct shmid_kernel *s)\n{\n\tlist_del(&s->shm_clist);\n\tipc_rmid(&shm_ids(ns), &s->shm_perm);\n}", "\nstatic int __shm_open(struct vm_area_struct *vma)\n{\n\tstruct file *file = vma->vm_file;\n\tstruct shm_file_data *sfd = shm_file_data(file);\n\tstruct shmid_kernel *shp;", "\tshp = shm_lock(sfd->ns, sfd->id);", "\tif (IS_ERR(shp))\n\t\treturn PTR_ERR(shp);", "\tshp->shm_atim = get_seconds();\n\tshp->shm_lprid = task_tgid_vnr(current);\n\tshp->shm_nattch++;\n\tshm_unlock(shp);\n\treturn 0;\n}", "/* This is called by fork, once for every shm attach. */\nstatic void shm_open(struct vm_area_struct *vma)\n{\n\tint err = __shm_open(vma);\n\t/*\n\t * We raced in the idr lookup or with shm_destroy().\n\t * Either way, the ID is busted.\n\t */\n\tWARN_ON_ONCE(err);\n}", "/*\n * shm_destroy - free the struct shmid_kernel\n *\n * @ns: namespace\n * @shp: struct to free\n *\n * It has to be called with shp and shm_ids.rwsem (writer) locked,\n * but returns with shp unlocked and freed.\n */\nstatic void shm_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp)\n{\n\tstruct file *shm_file;", "\tshm_file = shp->shm_file;\n\tshp->shm_file = NULL;\n\tns->shm_tot -= (shp->shm_segsz + PAGE_SIZE - 1) >> PAGE_SHIFT;\n\tshm_rmid(ns, shp);\n\tshm_unlock(shp);\n\tif (!is_file_hugepages(shm_file))\n\t\tshmem_lock(shm_file, 0, shp->mlock_user);\n\telse if (shp->mlock_user)\n\t\tuser_shm_unlock(i_size_read(file_inode(shm_file)),\n\t\t\t\tshp->mlock_user);\n\tfput(shm_file);\n\tipc_rcu_putref(shp, shm_rcu_free);\n}", "/*\n * shm_may_destroy - identifies whether shm segment should be destroyed now\n *\n * Returns true if and only if there are no active users of the segment and\n * one of the following is true:\n *\n * 1) shmctl(id, IPC_RMID, NULL) was called for this shp\n *\n * 2) sysctl kernel.shm_rmid_forced is set to 1.\n */\nstatic bool shm_may_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp)\n{\n\treturn (shp->shm_nattch == 0) &&\n\t (ns->shm_rmid_forced ||\n\t\t(shp->shm_perm.mode & SHM_DEST));\n}", "/*\n * remove the attach descriptor vma.\n * free memory for segment if it is marked destroyed.\n * The descriptor has already been removed from the current->mm->mmap list\n * and will later be kfree()d.\n */\nstatic void shm_close(struct vm_area_struct *vma)\n{\n\tstruct file *file = vma->vm_file;\n\tstruct shm_file_data *sfd = shm_file_data(file);\n\tstruct shmid_kernel *shp;\n\tstruct ipc_namespace *ns = sfd->ns;", "\tdown_write(&shm_ids(ns).rwsem);\n\t/* remove from the list of attaches of the shm segment */\n\tshp = shm_lock(ns, sfd->id);", "\t/*\n\t * We raced in the idr lookup or with shm_destroy().\n\t * Either way, the ID is busted.\n\t */\n\tif (WARN_ON_ONCE(IS_ERR(shp)))\n\t\tgoto done; /* no-op */", "\tshp->shm_lprid = task_tgid_vnr(current);\n\tshp->shm_dtim = get_seconds();\n\tshp->shm_nattch--;\n\tif (shm_may_destroy(ns, shp))\n\t\tshm_destroy(ns, shp);\n\telse\n\t\tshm_unlock(shp);\ndone:\n\tup_write(&shm_ids(ns).rwsem);\n}", "/* Called with ns->shm_ids(ns).rwsem locked */\nstatic int shm_try_destroy_orphaned(int id, void *p, void *data)\n{\n\tstruct ipc_namespace *ns = data;\n\tstruct kern_ipc_perm *ipcp = p;\n\tstruct shmid_kernel *shp = container_of(ipcp, struct shmid_kernel, shm_perm);", "\t/*\n\t * We want to destroy segments without users and with already\n\t * exit'ed originating process.\n\t *\n\t * As shp->* are changed under rwsem, it's safe to skip shp locking.\n\t */\n\tif (shp->shm_creator != NULL)\n\t\treturn 0;", "\tif (shm_may_destroy(ns, shp)) {\n\t\tshm_lock_by_ptr(shp);\n\t\tshm_destroy(ns, shp);\n\t}\n\treturn 0;\n}", "void shm_destroy_orphaned(struct ipc_namespace *ns)\n{\n\tdown_write(&shm_ids(ns).rwsem);\n\tif (shm_ids(ns).in_use)\n\t\tidr_for_each(&shm_ids(ns).ipcs_idr, &shm_try_destroy_orphaned, ns);\n\tup_write(&shm_ids(ns).rwsem);\n}", "/* Locking assumes this will only be called with task == current */\nvoid exit_shm(struct task_struct *task)\n{\n\tstruct ipc_namespace *ns = task->nsproxy->ipc_ns;\n\tstruct shmid_kernel *shp, *n;", "\tif (list_empty(&task->sysvshm.shm_clist))\n\t\treturn;", "\t/*\n\t * If kernel.shm_rmid_forced is not set then only keep track of\n\t * which shmids are orphaned, so that a later set of the sysctl\n\t * can clean them up.\n\t */\n\tif (!ns->shm_rmid_forced) {\n\t\tdown_read(&shm_ids(ns).rwsem);\n\t\tlist_for_each_entry(shp, &task->sysvshm.shm_clist, shm_clist)\n\t\t\tshp->shm_creator = NULL;\n\t\t/*\n\t\t * Only under read lock but we are only called on current\n\t\t * so no entry on the list will be shared.\n\t\t */\n\t\tlist_del(&task->sysvshm.shm_clist);\n\t\tup_read(&shm_ids(ns).rwsem);\n\t\treturn;\n\t}", "\t/*\n\t * Destroy all already created segments, that were not yet mapped,\n\t * and mark any mapped as orphan to cover the sysctl toggling.\n\t * Destroy is skipped if shm_may_destroy() returns false.\n\t */\n\tdown_write(&shm_ids(ns).rwsem);\n\tlist_for_each_entry_safe(shp, n, &task->sysvshm.shm_clist, shm_clist) {\n\t\tshp->shm_creator = NULL;", "\t\tif (shm_may_destroy(ns, shp)) {\n\t\t\tshm_lock_by_ptr(shp);\n\t\t\tshm_destroy(ns, shp);\n\t\t}\n\t}", "\t/* Remove the list head from any segments still attached. */\n\tlist_del(&task->sysvshm.shm_clist);\n\tup_write(&shm_ids(ns).rwsem);\n}", "static int shm_fault(struct vm_fault *vmf)\n{\n\tstruct file *file = vmf->vma->vm_file;\n\tstruct shm_file_data *sfd = shm_file_data(file);", "\treturn sfd->vm_ops->fault(vmf);\n}", "#ifdef CONFIG_NUMA\nstatic int shm_set_policy(struct vm_area_struct *vma, struct mempolicy *new)\n{\n\tstruct file *file = vma->vm_file;\n\tstruct shm_file_data *sfd = shm_file_data(file);\n\tint err = 0;", "\tif (sfd->vm_ops->set_policy)\n\t\terr = sfd->vm_ops->set_policy(vma, new);\n\treturn err;\n}", "static struct mempolicy *shm_get_policy(struct vm_area_struct *vma,\n\t\t\t\t\tunsigned long addr)\n{\n\tstruct file *file = vma->vm_file;\n\tstruct shm_file_data *sfd = shm_file_data(file);\n\tstruct mempolicy *pol = NULL;", "\tif (sfd->vm_ops->get_policy)\n\t\tpol = sfd->vm_ops->get_policy(vma, addr);\n\telse if (vma->vm_policy)\n\t\tpol = vma->vm_policy;", "\treturn pol;\n}\n#endif", "static int shm_mmap(struct file *file, struct vm_area_struct *vma)\n{\n\tstruct shm_file_data *sfd = shm_file_data(file);\n\tint ret;", "\t/*\n\t * In case of remap_file_pages() emulation, the file can represent\n\t * removed IPC ID: propogate shm_lock() error to caller.\n\t */\n\tret = __shm_open(vma);\n\tif (ret)\n\t\treturn ret;", "\tret = sfd->file->f_op->mmap(sfd->file, vma);\n\tif (ret) {\n\t\tshm_close(vma);\n\t\treturn ret;\n\t}\n\tsfd->vm_ops = vma->vm_ops;\n#ifdef CONFIG_MMU\n\tWARN_ON(!sfd->vm_ops->fault);\n#endif\n\tvma->vm_ops = &shm_vm_ops;\n\treturn 0;\n}", "static int shm_release(struct inode *ino, struct file *file)\n{\n\tstruct shm_file_data *sfd = shm_file_data(file);", "\tput_ipc_ns(sfd->ns);\n\tshm_file_data(file) = NULL;\n\tkfree(sfd);\n\treturn 0;\n}", "static int shm_fsync(struct file *file, loff_t start, loff_t end, int datasync)\n{\n\tstruct shm_file_data *sfd = shm_file_data(file);", "\tif (!sfd->file->f_op->fsync)\n\t\treturn -EINVAL;\n\treturn sfd->file->f_op->fsync(sfd->file, start, end, datasync);\n}", "static long shm_fallocate(struct file *file, int mode, loff_t offset,\n\t\t\t loff_t len)\n{\n\tstruct shm_file_data *sfd = shm_file_data(file);", "\tif (!sfd->file->f_op->fallocate)\n\t\treturn -EOPNOTSUPP;\n\treturn sfd->file->f_op->fallocate(file, mode, offset, len);\n}", "static unsigned long shm_get_unmapped_area(struct file *file,\n\tunsigned long addr, unsigned long len, unsigned long pgoff,\n\tunsigned long flags)\n{\n\tstruct shm_file_data *sfd = shm_file_data(file);", "\treturn sfd->file->f_op->get_unmapped_area(sfd->file, addr, len,\n\t\t\t\t\t\tpgoff, flags);\n}", "static const struct file_operations shm_file_operations = {\n\t.mmap\t\t= shm_mmap,\n\t.fsync\t\t= shm_fsync,\n\t.release\t= shm_release,\n\t.get_unmapped_area\t= shm_get_unmapped_area,\n\t.llseek\t\t= noop_llseek,\n\t.fallocate\t= shm_fallocate,\n};", "/*\n * shm_file_operations_huge is now identical to shm_file_operations,\n * but we keep it distinct for the sake of is_file_shm_hugepages().\n */\nstatic const struct file_operations shm_file_operations_huge = {\n\t.mmap\t\t= shm_mmap,\n\t.fsync\t\t= shm_fsync,\n\t.release\t= shm_release,\n\t.get_unmapped_area\t= shm_get_unmapped_area,\n\t.llseek\t\t= noop_llseek,\n\t.fallocate\t= shm_fallocate,\n};", "bool is_file_shm_hugepages(struct file *file)\n{\n\treturn file->f_op == &shm_file_operations_huge;\n}", "static const struct vm_operations_struct shm_vm_ops = {\n\t.open\t= shm_open,\t/* callback for a new vm-area open */\n\t.close\t= shm_close,\t/* callback for when the vm-area is released */\n\t.fault\t= shm_fault,\n#if defined(CONFIG_NUMA)\n\t.set_policy = shm_set_policy,\n\t.get_policy = shm_get_policy,\n#endif\n};", "/**\n * newseg - Create a new shared memory segment\n * @ns: namespace\n * @params: ptr to the structure that contains key, size and shmflg\n *\n * Called with shm_ids.rwsem held as a writer.\n */\nstatic int newseg(struct ipc_namespace *ns, struct ipc_params *params)\n{\n\tkey_t key = params->key;\n\tint shmflg = params->flg;\n\tsize_t size = params->u.size;\n\tint error;\n\tstruct shmid_kernel *shp;\n\tsize_t numpages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;\n\tstruct file *file;\n\tchar name[13];\n\tint id;\n\tvm_flags_t acctflag = 0;", "\tif (size < SHMMIN || size > ns->shm_ctlmax)\n\t\treturn -EINVAL;", "\tif (numpages << PAGE_SHIFT < size)\n\t\treturn -ENOSPC;", "\tif (ns->shm_tot + numpages < ns->shm_tot ||\n\t\t\tns->shm_tot + numpages > ns->shm_ctlall)\n\t\treturn -ENOSPC;", "\tshp = ipc_rcu_alloc(sizeof(*shp));\n\tif (!shp)\n\t\treturn -ENOMEM;", "\tshp->shm_perm.key = key;\n\tshp->shm_perm.mode = (shmflg & S_IRWXUGO);\n\tshp->mlock_user = NULL;", "\tshp->shm_perm.security = NULL;\n\terror = security_shm_alloc(shp);\n\tif (error) {\n\t\tipc_rcu_putref(shp, ipc_rcu_free);\n\t\treturn error;\n\t}", "\tsprintf(name, \"SYSV%08x\", key);\n\tif (shmflg & SHM_HUGETLB) {\n\t\tstruct hstate *hs;\n\t\tsize_t hugesize;", "\t\ths = hstate_sizelog((shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK);\n\t\tif (!hs) {\n\t\t\terror = -EINVAL;\n\t\t\tgoto no_file;\n\t\t}\n\t\thugesize = ALIGN(size, huge_page_size(hs));", "\t\t/* hugetlb_file_setup applies strict accounting */\n\t\tif (shmflg & SHM_NORESERVE)\n\t\t\tacctflag = VM_NORESERVE;\n\t\tfile = hugetlb_file_setup(name, hugesize, acctflag,\n\t\t\t\t &shp->mlock_user, HUGETLB_SHMFS_INODE,\n\t\t\t\t(shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK);\n\t} else {\n\t\t/*\n\t\t * Do not allow no accounting for OVERCOMMIT_NEVER, even\n\t\t * if it's asked for.\n\t\t */\n\t\tif ((shmflg & SHM_NORESERVE) &&\n\t\t\t\tsysctl_overcommit_memory != OVERCOMMIT_NEVER)\n\t\t\tacctflag = VM_NORESERVE;\n\t\tfile = shmem_kernel_file_setup(name, size, acctflag);\n\t}\n\terror = PTR_ERR(file);\n\tif (IS_ERR(file))\n\t\tgoto no_file;", "\tshp->shm_cprid = task_tgid_vnr(current);\n\tshp->shm_lprid = 0;\n\tshp->shm_atim = shp->shm_dtim = 0;\n\tshp->shm_ctim = get_seconds();\n\tshp->shm_segsz = size;\n\tshp->shm_nattch = 0;\n\tshp->shm_file = file;\n\tshp->shm_creator = current;", "\tid = ipc_addid(&shm_ids(ns), &shp->shm_perm, ns->shm_ctlmni);\n\tif (id < 0) {\n\t\terror = id;\n\t\tgoto no_id;\n\t}", "\tlist_add(&shp->shm_clist, &current->sysvshm.shm_clist);", "\t/*\n\t * shmid gets reported as \"inode#\" in /proc/pid/maps.\n\t * proc-ps tools use this. Changing this will break them.\n\t */\n\tfile_inode(file)->i_ino = shp->shm_perm.id;", "\tns->shm_tot += numpages;\n\terror = shp->shm_perm.id;", "\tipc_unlock_object(&shp->shm_perm);\n\trcu_read_unlock();\n\treturn error;", "no_id:\n\tif (is_file_hugepages(file) && shp->mlock_user)\n\t\tuser_shm_unlock(size, shp->mlock_user);\n\tfput(file);\nno_file:\n\tipc_rcu_putref(shp, shm_rcu_free);\n\treturn error;\n}", "/*\n * Called with shm_ids.rwsem and ipcp locked.\n */\nstatic inline int shm_security(struct kern_ipc_perm *ipcp, int shmflg)\n{\n\tstruct shmid_kernel *shp;", "\tshp = container_of(ipcp, struct shmid_kernel, shm_perm);\n\treturn security_shm_associate(shp, shmflg);\n}", "/*\n * Called with shm_ids.rwsem and ipcp locked.\n */\nstatic inline int shm_more_checks(struct kern_ipc_perm *ipcp,\n\t\t\t\tstruct ipc_params *params)\n{\n\tstruct shmid_kernel *shp;", "\tshp = container_of(ipcp, struct shmid_kernel, shm_perm);\n\tif (shp->shm_segsz < params->u.size)\n\t\treturn -EINVAL;", "\treturn 0;\n}", "SYSCALL_DEFINE3(shmget, key_t, key, size_t, size, int, shmflg)\n{\n\tstruct ipc_namespace *ns;\n\tstatic const struct ipc_ops shm_ops = {\n\t\t.getnew = newseg,\n\t\t.associate = shm_security,\n\t\t.more_checks = shm_more_checks,\n\t};\n\tstruct ipc_params shm_params;", "\tns = current->nsproxy->ipc_ns;", "\tshm_params.key = key;\n\tshm_params.flg = shmflg;\n\tshm_params.u.size = size;", "\treturn ipcget(ns, &shm_ids(ns), &shm_ops, &shm_params);\n}", "static inline unsigned long copy_shmid_to_user(void __user *buf, struct shmid64_ds *in, int version)\n{\n\tswitch (version) {\n\tcase IPC_64:\n\t\treturn copy_to_user(buf, in, sizeof(*in));\n\tcase IPC_OLD:\n\t {\n\t\tstruct shmid_ds out;", "\t\tmemset(&out, 0, sizeof(out));\n\t\tipc64_perm_to_ipc_perm(&in->shm_perm, &out.shm_perm);\n\t\tout.shm_segsz\t= in->shm_segsz;\n\t\tout.shm_atime\t= in->shm_atime;\n\t\tout.shm_dtime\t= in->shm_dtime;\n\t\tout.shm_ctime\t= in->shm_ctime;\n\t\tout.shm_cpid\t= in->shm_cpid;\n\t\tout.shm_lpid\t= in->shm_lpid;\n\t\tout.shm_nattch\t= in->shm_nattch;", "\t\treturn copy_to_user(buf, &out, sizeof(out));\n\t }\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n}", "static inline unsigned long\ncopy_shmid_from_user(struct shmid64_ds *out, void __user *buf, int version)\n{\n\tswitch (version) {\n\tcase IPC_64:\n\t\tif (copy_from_user(out, buf, sizeof(*out)))\n\t\t\treturn -EFAULT;\n\t\treturn 0;\n\tcase IPC_OLD:\n\t {\n\t\tstruct shmid_ds tbuf_old;", "\t\tif (copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))\n\t\t\treturn -EFAULT;", "\t\tout->shm_perm.uid\t= tbuf_old.shm_perm.uid;\n\t\tout->shm_perm.gid\t= tbuf_old.shm_perm.gid;\n\t\tout->shm_perm.mode\t= tbuf_old.shm_perm.mode;", "\t\treturn 0;\n\t }\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n}", "static inline unsigned long copy_shminfo_to_user(void __user *buf, struct shminfo64 *in, int version)\n{\n\tswitch (version) {\n\tcase IPC_64:\n\t\treturn copy_to_user(buf, in, sizeof(*in));\n\tcase IPC_OLD:\n\t {\n\t\tstruct shminfo out;", "\t\tif (in->shmmax > INT_MAX)\n\t\t\tout.shmmax = INT_MAX;\n\t\telse\n\t\t\tout.shmmax = (int)in->shmmax;", "\t\tout.shmmin\t= in->shmmin;\n\t\tout.shmmni\t= in->shmmni;\n\t\tout.shmseg\t= in->shmseg;\n\t\tout.shmall\t= in->shmall;", "\t\treturn copy_to_user(buf, &out, sizeof(out));\n\t }\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n}", "/*\n * Calculate and add used RSS and swap pages of a shm.\n * Called with shm_ids.rwsem held as a reader\n */\nstatic void shm_add_rss_swap(struct shmid_kernel *shp,\n\tunsigned long *rss_add, unsigned long *swp_add)\n{\n\tstruct inode *inode;", "\tinode = file_inode(shp->shm_file);", "\tif (is_file_hugepages(shp->shm_file)) {\n\t\tstruct address_space *mapping = inode->i_mapping;\n\t\tstruct hstate *h = hstate_file(shp->shm_file);\n\t\t*rss_add += pages_per_huge_page(h) * mapping->nrpages;\n\t} else {\n#ifdef CONFIG_SHMEM\n\t\tstruct shmem_inode_info *info = SHMEM_I(inode);", "\t\tspin_lock_irq(&info->lock);\n\t\t*rss_add += inode->i_mapping->nrpages;\n\t\t*swp_add += info->swapped;\n\t\tspin_unlock_irq(&info->lock);\n#else\n\t\t*rss_add += inode->i_mapping->nrpages;\n#endif\n\t}\n}", "/*\n * Called with shm_ids.rwsem held as a reader\n */\nstatic void shm_get_stat(struct ipc_namespace *ns, unsigned long *rss,\n\t\tunsigned long *swp)\n{\n\tint next_id;\n\tint total, in_use;", "\t*rss = 0;\n\t*swp = 0;", "\tin_use = shm_ids(ns).in_use;", "\tfor (total = 0, next_id = 0; total < in_use; next_id++) {\n\t\tstruct kern_ipc_perm *ipc;\n\t\tstruct shmid_kernel *shp;", "\t\tipc = idr_find(&shm_ids(ns).ipcs_idr, next_id);\n\t\tif (ipc == NULL)\n\t\t\tcontinue;\n\t\tshp = container_of(ipc, struct shmid_kernel, shm_perm);", "\t\tshm_add_rss_swap(shp, rss, swp);", "\t\ttotal++;\n\t}\n}", "/*\n * This function handles some shmctl commands which require the rwsem\n * to be held in write mode.\n * NOTE: no locks must be held, the rwsem is taken inside this function.\n */\nstatic int shmctl_down(struct ipc_namespace *ns, int shmid, int cmd,\n\t\t struct shmid_ds __user *buf, int version)\n{\n\tstruct kern_ipc_perm *ipcp;\n\tstruct shmid64_ds shmid64;\n\tstruct shmid_kernel *shp;\n\tint err;", "\tif (cmd == IPC_SET) {\n\t\tif (copy_shmid_from_user(&shmid64, buf, version))\n\t\t\treturn -EFAULT;\n\t}", "\tdown_write(&shm_ids(ns).rwsem);\n\trcu_read_lock();", "\tipcp = ipcctl_pre_down_nolock(ns, &shm_ids(ns), shmid, cmd,\n\t\t\t\t &shmid64.shm_perm, 0);\n\tif (IS_ERR(ipcp)) {\n\t\terr = PTR_ERR(ipcp);\n\t\tgoto out_unlock1;\n\t}", "\tshp = container_of(ipcp, struct shmid_kernel, shm_perm);", "\terr = security_shm_shmctl(shp, cmd);\n\tif (err)\n\t\tgoto out_unlock1;", "\tswitch (cmd) {\n\tcase IPC_RMID:\n\t\tipc_lock_object(&shp->shm_perm);\n\t\t/* do_shm_rmid unlocks the ipc object and rcu */\n\t\tdo_shm_rmid(ns, ipcp);\n\t\tgoto out_up;\n\tcase IPC_SET:\n\t\tipc_lock_object(&shp->shm_perm);\n\t\terr = ipc_update_perm(&shmid64.shm_perm, ipcp);\n\t\tif (err)\n\t\t\tgoto out_unlock0;\n\t\tshp->shm_ctim = get_seconds();\n\t\tbreak;\n\tdefault:\n\t\terr = -EINVAL;\n\t\tgoto out_unlock1;\n\t}", "out_unlock0:\n\tipc_unlock_object(&shp->shm_perm);\nout_unlock1:\n\trcu_read_unlock();\nout_up:\n\tup_write(&shm_ids(ns).rwsem);\n\treturn err;\n}", "static int shmctl_nolock(struct ipc_namespace *ns, int shmid,\n\t\t\t int cmd, int version, void __user *buf)\n{\n\tint err;\n\tstruct shmid_kernel *shp;", "\t/* preliminary security checks for *_INFO */\n\tif (cmd == IPC_INFO || cmd == SHM_INFO) {\n\t\terr = security_shm_shmctl(NULL, cmd);\n\t\tif (err)\n\t\t\treturn err;\n\t}", "\tswitch (cmd) {\n\tcase IPC_INFO:\n\t{\n\t\tstruct shminfo64 shminfo;", "\t\tmemset(&shminfo, 0, sizeof(shminfo));\n\t\tshminfo.shmmni = shminfo.shmseg = ns->shm_ctlmni;\n\t\tshminfo.shmmax = ns->shm_ctlmax;\n\t\tshminfo.shmall = ns->shm_ctlall;", "\t\tshminfo.shmmin = SHMMIN;\n\t\tif (copy_shminfo_to_user(buf, &shminfo, version))\n\t\t\treturn -EFAULT;", "\t\tdown_read(&shm_ids(ns).rwsem);\n\t\terr = ipc_get_maxid(&shm_ids(ns));\n\t\tup_read(&shm_ids(ns).rwsem);", "\t\tif (err < 0)\n\t\t\terr = 0;\n\t\tgoto out;\n\t}\n\tcase SHM_INFO:\n\t{\n\t\tstruct shm_info shm_info;", "\t\tmemset(&shm_info, 0, sizeof(shm_info));\n\t\tdown_read(&shm_ids(ns).rwsem);\n\t\tshm_info.used_ids = shm_ids(ns).in_use;\n\t\tshm_get_stat(ns, &shm_info.shm_rss, &shm_info.shm_swp);\n\t\tshm_info.shm_tot = ns->shm_tot;\n\t\tshm_info.swap_attempts = 0;\n\t\tshm_info.swap_successes = 0;\n\t\terr = ipc_get_maxid(&shm_ids(ns));\n\t\tup_read(&shm_ids(ns).rwsem);\n\t\tif (copy_to_user(buf, &shm_info, sizeof(shm_info))) {\n\t\t\terr = -EFAULT;\n\t\t\tgoto out;\n\t\t}", "\t\terr = err < 0 ? 0 : err;\n\t\tgoto out;\n\t}\n\tcase SHM_STAT:\n\tcase IPC_STAT:\n\t{\n\t\tstruct shmid64_ds tbuf;\n\t\tint result;", "\t\trcu_read_lock();\n\t\tif (cmd == SHM_STAT) {\n\t\t\tshp = shm_obtain_object(ns, shmid);\n\t\t\tif (IS_ERR(shp)) {\n\t\t\t\terr = PTR_ERR(shp);\n\t\t\t\tgoto out_unlock;\n\t\t\t}\n\t\t\tresult = shp->shm_perm.id;\n\t\t} else {\n\t\t\tshp = shm_obtain_object_check(ns, shmid);\n\t\t\tif (IS_ERR(shp)) {\n\t\t\t\terr = PTR_ERR(shp);\n\t\t\t\tgoto out_unlock;\n\t\t\t}\n\t\t\tresult = 0;\n\t\t}", "\t\terr = -EACCES;\n\t\tif (ipcperms(ns, &shp->shm_perm, S_IRUGO))\n\t\t\tgoto out_unlock;", "\t\terr = security_shm_shmctl(shp, cmd);\n\t\tif (err)\n\t\t\tgoto out_unlock;", "\t\tmemset(&tbuf, 0, sizeof(tbuf));\n\t\tkernel_to_ipc64_perm(&shp->shm_perm, &tbuf.shm_perm);\n\t\ttbuf.shm_segsz\t= shp->shm_segsz;\n\t\ttbuf.shm_atime\t= shp->shm_atim;\n\t\ttbuf.shm_dtime\t= shp->shm_dtim;\n\t\ttbuf.shm_ctime\t= shp->shm_ctim;\n\t\ttbuf.shm_cpid\t= shp->shm_cprid;\n\t\ttbuf.shm_lpid\t= shp->shm_lprid;\n\t\ttbuf.shm_nattch\t= shp->shm_nattch;\n\t\trcu_read_unlock();", "\t\tif (copy_shmid_to_user(buf, &tbuf, version))\n\t\t\terr = -EFAULT;\n\t\telse\n\t\t\terr = result;\n\t\tgoto out;\n\t}\n\tdefault:\n\t\treturn -EINVAL;\n\t}", "out_unlock:\n\trcu_read_unlock();\nout:\n\treturn err;\n}", "SYSCALL_DEFINE3(shmctl, int, shmid, int, cmd, struct shmid_ds __user *, buf)\n{\n\tstruct shmid_kernel *shp;\n\tint err, version;\n\tstruct ipc_namespace *ns;", "\tif (cmd < 0 || shmid < 0)\n\t\treturn -EINVAL;", "\tversion = ipc_parse_version(&cmd);\n\tns = current->nsproxy->ipc_ns;", "\tswitch (cmd) {\n\tcase IPC_INFO:\n\tcase SHM_INFO:\n\tcase SHM_STAT:\n\tcase IPC_STAT:\n\t\treturn shmctl_nolock(ns, shmid, cmd, version, buf);\n\tcase IPC_RMID:\n\tcase IPC_SET:\n\t\treturn shmctl_down(ns, shmid, cmd, buf, version);\n\tcase SHM_LOCK:\n\tcase SHM_UNLOCK:\n\t{\n\t\tstruct file *shm_file;", "\t\trcu_read_lock();\n\t\tshp = shm_obtain_object_check(ns, shmid);\n\t\tif (IS_ERR(shp)) {\n\t\t\terr = PTR_ERR(shp);\n\t\t\tgoto out_unlock1;\n\t\t}", "\t\taudit_ipc_obj(&(shp->shm_perm));\n\t\terr = security_shm_shmctl(shp, cmd);\n\t\tif (err)\n\t\t\tgoto out_unlock1;", "\t\tipc_lock_object(&shp->shm_perm);", "\t\t/* check if shm_destroy() is tearing down shp */\n\t\tif (!ipc_valid_object(&shp->shm_perm)) {\n\t\t\terr = -EIDRM;\n\t\t\tgoto out_unlock0;\n\t\t}", "\t\tif (!ns_capable(ns->user_ns, CAP_IPC_LOCK)) {\n\t\t\tkuid_t euid = current_euid();", "\t\t\tif (!uid_eq(euid, shp->shm_perm.uid) &&\n\t\t\t !uid_eq(euid, shp->shm_perm.cuid)) {\n\t\t\t\terr = -EPERM;\n\t\t\t\tgoto out_unlock0;\n\t\t\t}\n\t\t\tif (cmd == SHM_LOCK && !rlimit(RLIMIT_MEMLOCK)) {\n\t\t\t\terr = -EPERM;\n\t\t\t\tgoto out_unlock0;\n\t\t\t}\n\t\t}", "\t\tshm_file = shp->shm_file;\n\t\tif (is_file_hugepages(shm_file))\n\t\t\tgoto out_unlock0;", "\t\tif (cmd == SHM_LOCK) {\n\t\t\tstruct user_struct *user = current_user();", "\t\t\terr = shmem_lock(shm_file, 1, user);\n\t\t\tif (!err && !(shp->shm_perm.mode & SHM_LOCKED)) {\n\t\t\t\tshp->shm_perm.mode |= SHM_LOCKED;\n\t\t\t\tshp->mlock_user = user;\n\t\t\t}\n\t\t\tgoto out_unlock0;\n\t\t}", "\t\t/* SHM_UNLOCK */\n\t\tif (!(shp->shm_perm.mode & SHM_LOCKED))\n\t\t\tgoto out_unlock0;\n\t\tshmem_lock(shm_file, 0, shp->mlock_user);\n\t\tshp->shm_perm.mode &= ~SHM_LOCKED;\n\t\tshp->mlock_user = NULL;\n\t\tget_file(shm_file);\n\t\tipc_unlock_object(&shp->shm_perm);\n\t\trcu_read_unlock();\n\t\tshmem_unlock_mapping(shm_file->f_mapping);", "\t\tfput(shm_file);\n\t\treturn err;\n\t}\n\tdefault:\n\t\treturn -EINVAL;\n\t}", "out_unlock0:\n\tipc_unlock_object(&shp->shm_perm);\nout_unlock1:\n\trcu_read_unlock();\n\treturn err;\n}", "/*\n * Fix shmaddr, allocate descriptor, map shm, add attach descriptor to lists.\n *\n * NOTE! Despite the name, this is NOT a direct system call entrypoint. The\n * \"raddr\" thing points to kernel space, and there has to be a wrapper around\n * this.\n */", "long do_shmat(int shmid, char __user *shmaddr, int shmflg,\n\t ulong *raddr, unsigned long shmlba)", "{\n\tstruct shmid_kernel *shp;\n\tunsigned long addr;\n\tunsigned long size;\n\tstruct file *file;\n\tint err;\n\tunsigned long flags;\n\tunsigned long prot;\n\tint acc_mode;\n\tstruct ipc_namespace *ns;\n\tstruct shm_file_data *sfd;\n\tstruct path path;\n\tfmode_t f_mode;\n\tunsigned long populate = 0;", "\terr = -EINVAL;\n\tif (shmid < 0)\n\t\tgoto out;\n\telse if ((addr = (ulong)shmaddr)) {\n\t\tif (addr & (shmlba - 1)) {", "\t\t\t/*\n\t\t\t * Round down to the nearest multiple of shmlba.\n\t\t\t * For sane do_mmap_pgoff() parameters, avoid\n\t\t\t * round downs that trigger nil-page and MAP_FIXED.\n\t\t\t */\n\t\t\tif ((shmflg & SHM_RND) && addr >= shmlba)\n\t\t\t\taddr &= ~(shmlba - 1);", "\t\t\telse\n#ifndef __ARCH_FORCE_SHMLBA\n\t\t\t\tif (addr & ~PAGE_MASK)\n#endif\n\t\t\t\t\tgoto out;\n\t\t}\n\t\tflags = MAP_SHARED | MAP_FIXED;\n\t} else {\n\t\tif ((shmflg & SHM_REMAP))\n\t\t\tgoto out;", "\t\tflags = MAP_SHARED;\n\t}", "\tif (shmflg & SHM_RDONLY) {\n\t\tprot = PROT_READ;\n\t\tacc_mode = S_IRUGO;\n\t\tf_mode = FMODE_READ;\n\t} else {\n\t\tprot = PROT_READ | PROT_WRITE;\n\t\tacc_mode = S_IRUGO | S_IWUGO;\n\t\tf_mode = FMODE_READ | FMODE_WRITE;\n\t}\n\tif (shmflg & SHM_EXEC) {\n\t\tprot |= PROT_EXEC;\n\t\tacc_mode |= S_IXUGO;\n\t}", "\t/*\n\t * We cannot rely on the fs check since SYSV IPC does have an\n\t * additional creator id...\n\t */\n\tns = current->nsproxy->ipc_ns;\n\trcu_read_lock();\n\tshp = shm_obtain_object_check(ns, shmid);\n\tif (IS_ERR(shp)) {\n\t\terr = PTR_ERR(shp);\n\t\tgoto out_unlock;\n\t}", "\terr = -EACCES;\n\tif (ipcperms(ns, &shp->shm_perm, acc_mode))\n\t\tgoto out_unlock;", "\terr = security_shm_shmat(shp, shmaddr, shmflg);\n\tif (err)\n\t\tgoto out_unlock;", "\tipc_lock_object(&shp->shm_perm);", "\t/* check if shm_destroy() is tearing down shp */\n\tif (!ipc_valid_object(&shp->shm_perm)) {\n\t\tipc_unlock_object(&shp->shm_perm);\n\t\terr = -EIDRM;\n\t\tgoto out_unlock;\n\t}", "\tpath = shp->shm_file->f_path;\n\tpath_get(&path);\n\tshp->shm_nattch++;\n\tsize = i_size_read(d_inode(path.dentry));\n\tipc_unlock_object(&shp->shm_perm);\n\trcu_read_unlock();", "\terr = -ENOMEM;\n\tsfd = kzalloc(sizeof(*sfd), GFP_KERNEL);\n\tif (!sfd) {\n\t\tpath_put(&path);\n\t\tgoto out_nattch;\n\t}", "\tfile = alloc_file(&path, f_mode,\n\t\t\t is_file_hugepages(shp->shm_file) ?\n\t\t\t\t&shm_file_operations_huge :\n\t\t\t\t&shm_file_operations);\n\terr = PTR_ERR(file);\n\tif (IS_ERR(file)) {\n\t\tkfree(sfd);\n\t\tpath_put(&path);\n\t\tgoto out_nattch;\n\t}", "\tfile->private_data = sfd;\n\tfile->f_mapping = shp->shm_file->f_mapping;\n\tsfd->id = shp->shm_perm.id;\n\tsfd->ns = get_ipc_ns(ns);\n\tsfd->file = shp->shm_file;\n\tsfd->vm_ops = NULL;", "\terr = security_mmap_file(file, prot, flags);\n\tif (err)\n\t\tgoto out_fput;", "\tif (down_write_killable(&current->mm->mmap_sem)) {\n\t\terr = -EINTR;\n\t\tgoto out_fput;\n\t}", "\tif (addr && !(shmflg & SHM_REMAP)) {\n\t\terr = -EINVAL;\n\t\tif (addr + size < addr)\n\t\t\tgoto invalid;", "\t\tif (find_vma_intersection(current->mm, addr, addr + size))\n\t\t\tgoto invalid;\n\t}", "\taddr = do_mmap_pgoff(file, addr, size, prot, flags, 0, &populate, NULL);\n\t*raddr = addr;\n\terr = 0;\n\tif (IS_ERR_VALUE(addr))\n\t\terr = (long)addr;\ninvalid:\n\tup_write(&current->mm->mmap_sem);\n\tif (populate)\n\t\tmm_populate(addr, populate);", "out_fput:\n\tfput(file);", "out_nattch:\n\tdown_write(&shm_ids(ns).rwsem);\n\tshp = shm_lock(ns, shmid);\n\tshp->shm_nattch--;\n\tif (shm_may_destroy(ns, shp))\n\t\tshm_destroy(ns, shp);\n\telse\n\t\tshm_unlock(shp);\n\tup_write(&shm_ids(ns).rwsem);\n\treturn err;", "out_unlock:\n\trcu_read_unlock();\nout:\n\treturn err;\n}", "SYSCALL_DEFINE3(shmat, int, shmid, char __user *, shmaddr, int, shmflg)\n{\n\tunsigned long ret;\n\tlong err;", "\terr = do_shmat(shmid, shmaddr, shmflg, &ret, SHMLBA);\n\tif (err)\n\t\treturn err;\n\tforce_successful_syscall_return();\n\treturn (long)ret;\n}", "/*\n * detach and kill segment if marked destroyed.\n * The work is done in shm_close.\n */\nSYSCALL_DEFINE1(shmdt, char __user *, shmaddr)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma;\n\tunsigned long addr = (unsigned long)shmaddr;\n\tint retval = -EINVAL;\n#ifdef CONFIG_MMU\n\tloff_t size = 0;\n\tstruct file *file;\n\tstruct vm_area_struct *next;\n#endif", "\tif (addr & ~PAGE_MASK)\n\t\treturn retval;", "\tif (down_write_killable(&mm->mmap_sem))\n\t\treturn -EINTR;", "\t/*\n\t * This function tries to be smart and unmap shm segments that\n\t * were modified by partial mlock or munmap calls:\n\t * - It first determines the size of the shm segment that should be\n\t * unmapped: It searches for a vma that is backed by shm and that\n\t * started at address shmaddr. It records it's size and then unmaps\n\t * it.\n\t * - Then it unmaps all shm vmas that started at shmaddr and that\n\t * are within the initially determined size and that are from the\n\t * same shm segment from which we determined the size.\n\t * Errors from do_munmap are ignored: the function only fails if\n\t * it's called with invalid parameters or if it's called to unmap\n\t * a part of a vma. Both calls in this function are for full vmas,\n\t * the parameters are directly copied from the vma itself and always\n\t * valid - therefore do_munmap cannot fail. (famous last words?)\n\t */\n\t/*\n\t * If it had been mremap()'d, the starting address would not\n\t * match the usual checks anyway. So assume all vma's are\n\t * above the starting address given.\n\t */\n\tvma = find_vma(mm, addr);", "#ifdef CONFIG_MMU\n\twhile (vma) {\n\t\tnext = vma->vm_next;", "\t\t/*\n\t\t * Check if the starting address would match, i.e. it's\n\t\t * a fragment created by mprotect() and/or munmap(), or it\n\t\t * otherwise it starts at this address with no hassles.\n\t\t */\n\t\tif ((vma->vm_ops == &shm_vm_ops) &&\n\t\t\t(vma->vm_start - addr)/PAGE_SIZE == vma->vm_pgoff) {", "\t\t\t/*\n\t\t\t * Record the file of the shm segment being\n\t\t\t * unmapped. With mremap(), someone could place\n\t\t\t * page from another segment but with equal offsets\n\t\t\t * in the range we are unmapping.\n\t\t\t */\n\t\t\tfile = vma->vm_file;\n\t\t\tsize = i_size_read(file_inode(vma->vm_file));\n\t\t\tdo_munmap(mm, vma->vm_start, vma->vm_end - vma->vm_start, NULL);\n\t\t\t/*\n\t\t\t * We discovered the size of the shm segment, so\n\t\t\t * break out of here and fall through to the next\n\t\t\t * loop that uses the size information to stop\n\t\t\t * searching for matching vma's.\n\t\t\t */\n\t\t\tretval = 0;\n\t\t\tvma = next;\n\t\t\tbreak;\n\t\t}\n\t\tvma = next;\n\t}", "\t/*\n\t * We need look no further than the maximum address a fragment\n\t * could possibly have landed at. Also cast things to loff_t to\n\t * prevent overflows and make comparisons vs. equal-width types.\n\t */\n\tsize = PAGE_ALIGN(size);\n\twhile (vma && (loff_t)(vma->vm_end - addr) <= size) {\n\t\tnext = vma->vm_next;", "\t\t/* finding a matching vma now does not alter retval */\n\t\tif ((vma->vm_ops == &shm_vm_ops) &&\n\t\t ((vma->vm_start - addr)/PAGE_SIZE == vma->vm_pgoff) &&\n\t\t (vma->vm_file == file))\n\t\t\tdo_munmap(mm, vma->vm_start, vma->vm_end - vma->vm_start, NULL);\n\t\tvma = next;\n\t}", "#else\t/* CONFIG_MMU */\n\t/* under NOMMU conditions, the exact address to be destroyed must be\n\t * given\n\t */\n\tif (vma && vma->vm_start == addr && vma->vm_ops == &shm_vm_ops) {\n\t\tdo_munmap(mm, vma->vm_start, vma->vm_end - vma->vm_start, NULL);\n\t\tretval = 0;\n\t}", "#endif", "\tup_write(&mm->mmap_sem);\n\treturn retval;\n}", "#ifdef CONFIG_PROC_FS\nstatic int sysvipc_shm_proc_show(struct seq_file *s, void *it)\n{\n\tstruct user_namespace *user_ns = seq_user_ns(s);\n\tstruct shmid_kernel *shp = it;\n\tunsigned long rss = 0, swp = 0;", "\tshm_add_rss_swap(shp, &rss, &swp);", "#if BITS_PER_LONG <= 32\n#define SIZE_SPEC \"%10lu\"\n#else\n#define SIZE_SPEC \"%21lu\"\n#endif", "\tseq_printf(s,\n\t\t \"%10d %10d %4o \" SIZE_SPEC \" %5u %5u \"\n\t\t \"%5lu %5u %5u %5u %5u %10lu %10lu %10lu \"\n\t\t SIZE_SPEC \" \" SIZE_SPEC \"\\n\",\n\t\t shp->shm_perm.key,\n\t\t shp->shm_perm.id,\n\t\t shp->shm_perm.mode,\n\t\t shp->shm_segsz,\n\t\t shp->shm_cprid,\n\t\t shp->shm_lprid,\n\t\t shp->shm_nattch,\n\t\t from_kuid_munged(user_ns, shp->shm_perm.uid),\n\t\t from_kgid_munged(user_ns, shp->shm_perm.gid),\n\t\t from_kuid_munged(user_ns, shp->shm_perm.cuid),\n\t\t from_kgid_munged(user_ns, shp->shm_perm.cgid),\n\t\t shp->shm_atim,\n\t\t shp->shm_dtim,\n\t\t shp->shm_ctim,\n\t\t rss * PAGE_SIZE,\n\t\t swp * PAGE_SIZE);", "\treturn 0;\n}\n#endif" ]
[ 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, 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, 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1118], "buggy_code_start_loc": [1094], "filenames": ["ipc/shm.c"], "fixing_code_end_loc": [1123], "fixing_code_start_loc": [1094], "message": "The do_shmat function in ipc/shm.c in the Linux kernel through 4.9.12 does not restrict the address calculated by a certain rounding operation, which allows local users to map page zero, and consequently bypass a protection mechanism that exists for the mmap system call, by making crafted shmget and shmat system calls in a privileged context.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "68E74529-58C5-4D73-8176-DDDF25C71F22", "versionEndExcluding": "4.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:esm:*:*:*", "matchCriteriaId": "8D305F7A-D159-4716-AB26-5E38BB5CD991", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:esm:*:*:*", "matchCriteriaId": "815D70A8-47D3-459C-A32C-9FEACA0659D1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The do_shmat function in ipc/shm.c in the Linux kernel through 4.9.12 does not restrict the address calculated by a certain rounding operation, which allows local users to map page zero, and consequently bypass a protection mechanism that exists for the mmap system call, by making crafted shmget and shmat system calls in a privileged context."}, {"lang": "es", "value": "La funci\u00f3n do_shmat en ipc/shm.c en el kernel de Linux hasta la versi\u00f3n 4.9.12 no restringe la direcci\u00f3n calculada por cierta operaci\u00f3n de redondeo, lo que permite a usuarios locales asignar la p\u00e1gina cero, y como consecuencia, eludir un mecanismo de protecci\u00f3n que existe por la llamada de sistema mmap, haciendo llamadas a sistema shmget y shmat manipuladas en un contexto privilegiado."}], "evaluatorComment": null, "id": "CVE-2017-5669", "lastModified": "2020-10-09T14:49:28.933", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.6, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:L/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2017-02-24T15:59:00.150", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2017/dsa-3804"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/96754"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securitytracker.com/id/1037918"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Vendor Advisory"], "url": "https://bugzilla.kernel.org/show_bug.cgi?id=192931"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/95e91b831f87ac8e1f8ed50c14d709089b4e01b8"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/e1d35d4dc7f089e6c9c080d556feedf9c706f0c7"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3583-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3583-2/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/95e91b831f87ac8e1f8ed50c14d709089b4e01b8"}, "type": "NVD-CWE-noinfo"}
196
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n##################################################\n#\n# Copyright (c) 2004-2016 OIC Group, Inc.\n#\n# This file is part of Exponent\n#\n# Exponent is free software; you can redistribute\n# it and/or modify it under the terms of the GNU\n# General Public License as published by the Free\n# Software Foundation; either version 2 of the\n# License, or (at your option) any later version.\n#\n# GPL: http://www.gnu.org/licenses/gpl.txt\n#\n##################################################", "/**\n * This is the class expController\n *\n * @package Core\n * @subpackage Controllers\n */", "abstract class expController {\n protected $classname = ''; // full controller name w/ 'Controller' suffix\n public $baseclassname = ''; // root controller name w/o 'Controller' suffix\n public $classinfo = null; // holds reflection class of class\n// public $module_name = ''; //FIXME not used and not actually set right index needed of -3 instead of -2 below\n// protected $basemodel = null; //FIXME never used, $basemodel_name replaced?\n public $basemodel_name = ''; // holds classname of base model associated w/ this controller\n public $model_table = ''; // holds table name for base model", " public $useractions = array(); // available (displayed) user actions/methods for this module\n public $remove_configs = array(); // all options: ('aggregation','categories','comments','ealerts','facebook','files','module_title','pagination','rss','tags','twitter',)", " // $permissions used to restrict access to module's actions/methods\n protected $permissions = array( // standard set of permissions for all modules unless add'ed or remove'd\n 'manage' => 'Manage',\n 'configure' => 'Configure',\n 'create' => 'Create',\n 'edit' => 'Edit',\n 'delete' => 'Delete',", " 'approve' => 'Approval',", " );\n protected $remove_permissions = array(); // $permissions not applicable for this module from above list", " protected $add_permissions = array(); // additional $permissions processed for this module\n public $requires_login = array(); // actions/methods which ONLY require user be logged in to access...$permissions take priority", "\n public $filepath = ''; // location of this controller's files\n public $viewpath = ''; // location of this controllers views; defaults to controller file location\n public $relative_viewpath = ''; // relative location of controller's views\n public $asset_path = ''; // location of this controller's assets; defaults to controller file location", " public $config = array(); // holds module configuration settings\n public $params = array(); // holds sanitized parameters passed to module\n public $loc = null; // module location object", " public $codequality = 'stable'; // code's level of stability", " public $rss_is_podcast = false;", " /**\n * @param null $src\n * @param array $params\n *\n * @return expController\n *\n */\n public function __construct($src = null, $params = array()) {\n // setup some basic information about this class\n $this->classinfo = new ReflectionClass($this);\n $this->classname = $this->classinfo->getName();\n $this->baseclassname = substr($this->classinfo->getName(), 0, -10);\n $this->filepath = __realpath($this->classinfo->getFileName());", " // figure out which \"module\" we belong to and setup view path information\n $controllerpath = explode('/', $this->filepath);\n// $this->module_name = $controllerpath[(count($controllerpath)-3)];", " // set up the path to this module view files\n array_pop($controllerpath); // remove 'controllers' from array\n $controllerpath[count($controllerpath) - 1] = 'views';\n array_push($controllerpath, $this->baseclassname);\n $this->relative_viewpath = implode('/', array_slice($controllerpath, -3, 3));\n// $this->viewpath = BASE.'framework/modules/'.$this->relative_viewpath;\n //FIXME this requires we move the 'core' controllers into the modules folder or use this hack\n $depth = array_search('core', $controllerpath);\n if ($depth) {\n $this->viewpath = BASE . 'framework/modules/' . $this->relative_viewpath;\n } else {\n $this->viewpath = implode('/', $controllerpath);\n }", " //grab the path to the module's assets\n array_pop($controllerpath);\n $controllerpath[count($controllerpath) - 1] = 'assets';\n// $this->asset_path = PATH_RELATIVE.'framework/'.implode('/', array_slice($controllerpath, -3, 3)).\"/\";\n $depth = array_search('framework', $controllerpath); // is this a system file (or theme)?\n if (!$depth) $depth = array_search('themes', $controllerpath);\n $this->asset_path = PATH_RELATIVE . implode('/', array_slice($controllerpath, $depth)) . \"/\";", " // figure out which model we're using and setup some info about it\n if (empty($this->basemodel_name)) $this->basemodel_name = get_model_for_controller($this->classname);\n $modelname = $this->basemodel_name;\n if (class_exists($modelname)) {\n $this->$modelname = new $modelname(null, false, false);\n $this->model_table = $this->$modelname->tablename;\n } else {\n $this->basemodel_name = 'expRecord';\n $this->$modelname = new expRecord(null, false, false);\n $this->model_table = null;\n }", " // set the location data\n $this->loc = expCore::makeLocation($this->baseclassname, $src, null);", " // flag for needing approval check\n if (ENABLE_WORKFLOW && $this->$modelname->supports_revisions) {\n $uilevel = 99;\n if (expSession::exists(\"uilevel\")) $uilevel = expSession::get(\"uilevel\");\n if (!expPermissions::check('approve', $this->loc)) {\n $this->$modelname->needs_approval = true;\n } elseif ($uilevel == UILEVEL_PREVIEW && isset($uilevel)) {\n $this->$modelname->needs_approval = true; // 'preview' should provide a true preview\n }\n }", " // get this controllers config data if there is any\n $config = new expConfig($this->loc);\n $this->config = $config->config;", " $this->params = $params;", "", " }", " /**\n * name of module for backwards compat with old modules\n *\n * @return string\n */\n public function name() {\n return static::displayname();\n }", " /**\n * name of module\n *\n * @return string\n */\n public static function displayname() {\n return gt(\"Exponent Base Controller\");\n }", " /**\n * description of module\n *\n * @return string\n */\n public static function description() {\n return gt(\"This is the base controller which most Exponent modules inherit their methods from.\");\n }", " /**\n * author of module\n *\n * @return string\n */\n public static function author() {\n return \"OIC Group, Inc\";\n }", " /**\n * does module have sources available? or does it treat content globally\n *\n * @return bool\n */\n public static function hasSources() {\n return true;\n }", " /**\n * does module have views available?\n *\n * @return bool\n */ //NOTE: Never used - equivalent to !empty ($this->useractions) via expModules::listUserRunnableControllers()?\n public static function hasViews() {\n return true;\n }", " /**\n * does module have content (stored items) available?\n *\n * @return bool\n */ //NOTE: Never used, better utilized/implemented as isSearchable()\n public static function hasContent() {\n return true;\n }", " /**\n * does module support workflow?\n *\n * @return bool\n */\n public static function supportsWorkflow() {\n return false;\n }", " /**\n * is module content searchable? should it be added to search index?\n *\n * @return bool\n */\n public static function isSearchable() {\n return false;\n }", " /**\n * can this module import data?\n *\n * @return bool\n */\n public static function canImportData() {\n return false;\n }", " /**\n * can this module export data?\n *\n * @return bool\n */\n public static function canExportData() {\n return false;\n }", " /**\n * does this module require configuration?\n *\n * @return bool\n */ //NOTE: Never Used\n public static function requiresConfiguration() {\n return false;\n }", " /**\n * glue to make the view template aware of the module\n * @deprecated\n */\n public function moduleSelfAwareness() {\n assign_to_template(array(\n 'asset_path' => $this->asset_path,\n 'model_name' => $this->basemodel_name,\n 'table' => $this->model_table,\n 'controller' => $this->baseclassname,\n 'config' => $this->config\n ));\n }", " /**\n * default module view method for all items\n */\n public function showall() {\n expHistory::set('viewable', $this->params);", " $page = new expPaginator(array(\n 'model' => $this->basemodel_name,\n 'where' => static::hasSources() ? $this->aggregateWhereClause() : null,\n 'limit' => (isset($this->params['limit']) && $this->params['limit'] != '') ? $this->params['limit'] : 10,\n 'order' => isset($this->params['order']) ? $this->params['order'] : null,\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->baseclassname,\n 'action' => $this->params['action'],\n 'src' => static::hasSources() == true ? $this->loc->src : null,\n 'columns' => array(\n gt('ID#') => 'id',\n gt('Title') => 'title',\n gt('Body') => 'body'\n ),\n ));", " assign_to_template(array(\n 'page' => $page,\n 'items' => $page->records\n ));\n }", " /**\n * default module view method for all items with a specific tag\n */\n public function showall_by_tags() {\n global $db;", " // set history\n expHistory::set('viewable', $this->params);\n $modelname = $this->basemodel_name;", " // get the tag being passed", " $tag = new expTag($this->params['tag']);", "\n // find all the id's of the portfolios for this module\n $item_ids = $db->selectColumn($modelname, 'id', $this->aggregateWhereClause());", " // find all the items that this tag is attached to\n $items = $tag->findWhereAttachedTo($modelname);", " // loop the items for this tag and find out which ones belong to this module\n $items_by_tags = array();\n foreach ($items as $item) {\n if (in_array($item->id, $item_ids)) $items_by_tags[] = $item;\n }", " // create a pagination object for the model and render the action\n $order = 'created_at DESC';\n $page = new expPaginator(array(\n 'records' => $items_by_tags,\n 'limit' => (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10,\n 'order' => $order,\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->baseclassname,\n 'action' => $this->params['action'],\n 'src'=>$this->loc->src,\n 'columns' => array(\n gt('Title') => 'title'\n ),\n ));\n// $page->records = expSorter::sort(array('array'=>$page->records, 'sortby'=>'rank', 'order'=>'ASC', 'ignore_case'=>true));\n $page->records = expSorter::sort(array('array' => $page->records, 'sortby' => 'created_at', 'order' => 'DESC', 'ignore_case' => true));", " assign_to_template(array(\n 'page' => $page,\n 'items' => $page->records,", " 'moduletitle' => ucfirst($modelname) . ' ' . gt('items tagged with') . ' \"' . expString::sanitize($this->params['tag']) . '\"',", " 'rank' => ($order === 'rank') ? 1 : 0\n ));\n }", " /**\n * return all tags used by module's items\n */\n public function tags() {\n expHistory::set('viewable', $this->params);\n $modelname = $this->basemodel_name;", " $items = $this->$modelname->find('all', $this->aggregateWhereClause());\n $used_tags = array();\n foreach ($items as $item) {\n foreach ($item->expTag as $tag) {\n if (isset($used_tags[$tag->id])) {\n $used_tags[$tag->id]->count++;\n } else {\n $exptag = new expTag($tag->id);\n $used_tags[$tag->id] = $exptag;\n $used_tags[$tag->id]->count = 1;\n }\n }\n }", "// $order = isset($this->config['order']) ? $this->config['order'] : 'rank';\n// $used_tags = expSorter::sort(array('array'=>$used_tags,'sortby'=>'title', 'order'=>'ASC', 'ignore_case'=>true, 'rank'=>($order==='rank')?1:0));\n// $order = isset($this->config['order']) ? $this->config['order'] : 'title ASC';\n// $used_tags = expSorter::sort(array('array'=>$used_tags, 'order'=>$order, 'ignore_case'=>true, 'rank'=>($order==='rank')?1:0));\n $used_tags = expSorter::sort(array('array' => $used_tags, 'order' => 'count DESC', 'type' => 'a'));\n if (!empty($this->config['limit'])) $used_tags = array_slice($used_tags, 0, $this->config['limit']);\n $order = isset($this->config['order']) ? $this->config['order'] : 'title ASC';\n if ($order != 'hits') {\n $used_tags = expSorter::sort(array('array' => $used_tags, 'order' => $order, 'ignore_case' => true, 'rank' => ($order === 'rank') ? 1 : 0));\n }", " assign_to_template(array(\n 'tags' => $used_tags\n ));\n }", " /**\n * return all categories used by module's items\n */\n public function categories() {\n expHistory::set('viewable', $this->params);\n $modelname = $this->basemodel_name;", " $items = $this->$modelname->find('all', $this->aggregateWhereClause());\n $used_cats = array();\n $used_cats[0] = new stdClass();\n $used_cats[0]->id = 0;\n $used_cats[0]->title = !empty($this->config['uncat']) ? $this->config['uncat'] : gt('Not Categorized');\n $used_cats[0]->count = 0;\n foreach ($items as $item) {\n if (!empty($item->expCat)) {\n if (isset($used_cats[$item->expCat[0]->id])) {\n $used_cats[$item->expCat[0]->id]->count++;\n } else {\n $expcat = new expCat($item->expCat[0]->id);\n $used_cats[$item->expCat[0]->id] = $expcat;\n $used_cats[$item->expCat[0]->id]->count = 1;\n }\n } else {\n $used_cats[0]->count++;\n }\n }", "// $order = isset($this->config['order']) ? $this->config['order'] : 'rank';\n// $used_cats = expSorter::sort(array('array'=>$used_cats,'sortby'=>'title', 'order'=>'ASC', 'ignore_case'=>true, 'rank'=>($order==='rank')?1:0));\n// $order = isset($this->config['order']) ? $this->config['order'] : 'title ASC';\n// $used_cats = expSorter::sort(array('array'=>$used_cats, 'order'=>$order, 'ignore_case'=>true, 'rank'=>($order==='rank')?1:0));\n $used_cats = expSorter::sort(array('array' => $used_cats, 'order' => 'count DESC', 'type' => 'a'));\n if (!empty($this->config['limit'])) $used_cats = array_slice($used_cats, 0, $this->config['limit']);\n $order = isset($this->config['order']) ? $this->config['order'] : 'title ASC';\n if ($order != 'count') {\n $used_cats = expSorter::sort(array('array' => $used_cats, 'order' => $order, 'ignore_case' => true, 'rank' => ($order === 'rank') ? 1 : 0));\n }", " assign_to_template(array(\n 'cats' => $used_cats\n ));\n }", " /**\n * return all comments used by module's items\n */\n public function comments() {\n\t expHistory::set('viewable', $this->params);\n $modelname = $this->basemodel_name;", " $items = $this->$modelname->find('all');\n $all_comments = array();\n // get all the blog comments\n foreach ($items as $item) {\n $more_comments = expCommentController::getComments(array('content_type'=>$modelname,'content_id'=>$item->id));\n if (!empty($more_comments)) {\n foreach ($more_comments as $next_comment) {\n $next_comment->ref = $item->title;\n $next_comment->sef_url = $item->sef_url;\n }\n $all_comments = array_merge($all_comments,$more_comments);\n }\n }\n // sort then limit all the blog comments\n $all_comments = expSorter::sort(array('array' => $all_comments, 'sortby' => 'created_at', 'order' => 'DESC', 'ignore_case' => true));\n $limit = (isset($this->config['headcount']) && $this->config['headcount'] != '') ? $this->config['headcount'] : 10;\n $comments = array_slice($all_comments,0,$limit);\n\t assign_to_template(array(\n 'comments'=>$comments,\n ));\n\t}", " /**\n * default view for individual item\n */\n public function show() {\n expHistory::set('viewable', $this->params);\n $modelname = $this->basemodel_name;", " // figure out if we're looking this up by id or title\n $id = null;\n if (isset($this->params['id'])) {\n $id = $this->params['id'];\n } elseif (isset($this->params['title'])) {", " $id = $this->params['title'];", " }", " $record = new $modelname($id);\n if (empty($record->id))\n redirect_to(array('controller'=>'notfound','action'=>'page_not_found','title'=>$this->params['title']));", " $config = expConfig::getConfig($record->location_data);\n if (empty($this->config))\n $this->config = $config;\n if (empty($this->loc->src)) {\n $r_loc = expUnserialize($record->location_data);\n $this->loc = new stdClass();\n $this->loc->src = $r_loc->src;\n }", " assign_to_template(array(\n 'record' => $record,\n 'config' => $config\n ));\n }", " /**\n * view the item by referring to its title\n * @deprecated\n */\n public function showByTitle() {\n expHistory::set('viewable', $this->params);\n $modelname = $this->basemodel_name;\n // first we'll check to see if this matches the sef_url field...if not then we'll look for the\n // title field", "", " $record = $this->$modelname->find('first', \"sef_url='\" . $this->params['title'] . \"'\");\n if (!is_object($record)) {\n $record = $this->$modelname->find('first', \"title='\" . $this->params['title'] . \"'\");\n }\n $this->loc = unserialize($record->location_data);", " assign_to_template(array(\n 'record' => $record,\n ));\n }", " /**\n * view a random item\n */\n public function showRandom() {\n expHistory::set('viewable', $this->params);\n $where = static::hasSources() ? $this->aggregateWhereClause() : null;\n $limit = isset($this->params['limit']) ? $this->params['limit'] : 1;\n $order = 'RAND()';\n assign_to_template(array(\n 'items' => $this->text->find('all', $where, $order, $limit)\n ));\n }", " /**\n * view items referenced by tags\n * @deprecated\n */\n public function showByTags() {\n global $db;", " // set the history point for this action\n expHistory::set('viewable', $this->params);", " // setup some objects\n $tagobj = new expTag();\n $modelname = empty($this->params['model']) ? $this->basemodel_name : $this->params['model'];\n $model = new $modelname();", " // start building the sql query\n $sql = 'SELECT DISTINCT m.id FROM ' . $db->prefix . $model->tablename . ' m ';\n $sql .= 'JOIN ' . $db->prefix . $tagobj->attachable_table . ' ct ';\n $sql .= 'ON m.id = ct.content_id WHERE (';\n $first = true;", " if (isset($this->params['tags'])) {\n $tags = is_array($this->params['tags']) ? $this->params['tags'] : array($this->params['tags']);\n } elseif (isset($this->config['expTags'])) {\n $tags = $this->config['expTags'];\n } else {\n $tags = array();\n }", " foreach ($tags as $tagid) {\n $sql .= ($first) ? 'exptags_id=' . intval($tagid) : ' OR exptags_id=' . intval($tagid);\n $first = false;\n }\n $sql .= \") AND content_type='\" . $model->classname . \"'\";", " // get the objects and render the template\n $tag_assocs = $db->selectObjectsBySql($sql);\n $records = array();\n foreach ($tag_assocs as $assoc) {\n $records[] = new $modelname($assoc->id);\n }", " assign_to_template(array(\n 'items' => $records\n ));\n }", " /**\n * create an item in this module\n * @deprecated in favor of edit w/o id param\n */\n public function create() {\n $args = array('controller' => $this->params['controller'], 'action' => 'edit');\n //if (!empty($this->params['instance'])) $args['instance'] = $this->params['instance'];\n if (!empty($this->params['src'])) $args['src'] = $this->params['src'];\n redirect_to($args);\n }", " /**\n * edit item in module, also used to copy items\n */\n public function edit() {\n expHistory::set('editable', $this->params);\n $taglist = expTag::getAllTags();\n $modelname = $this->basemodel_name;\n// $record = isset($this->params['id']) ? $this->$modelname->find($this->params['id']) : new $modelname($this->params);\n if (isset($this->params['id'])) {\n if (!isset($this->params['revision_id'])) {\n $record = $this->$modelname->find($this->params['id']);\n } else {\n $currentrecord = $this->$modelname->find($this->params['id']);\n $records = $this->$modelname->find('revisions', $this->$modelname->identifier . '=' . intval($this->params['id']) . ' AND revision_id=' . intval($this->params['revision_id']));\n $record = $records[0];\n $record->current_revision_id = $currentrecord->revision_id;\n }\n } else {\n $record = new $modelname($this->params);\n }\n if (!empty($this->params['copy'])) {\n $record->id = null;\n if (isset($record->sef_url)) $record->sef_url = null;\n }\n assign_to_template(array(\n 'record' => $record,\n// 'table' => $this->$modelname->tablename,\n// 'controller' => $this->params['controller'],\n 'taglist' => $taglist\n ));\n }", " /**\n * merge/move aggregated item into this module\n */\n public function merge() {\n expHistory::set('editable', $this->params);\n $modelname = $this->basemodel_name;\n $record = $this->$modelname->find($this->params['id']);", " $loc = expUnserialize($record->location_data);\n $loc->src = $this->loc->src;\n $record->location_data = serialize($loc);\n// $this->$modelname->update($record);\n $record->update();", " expHistory::back();\n }", " /**\n * update (save) item in module\n */\n public function update() {\n global $db;", " //check for and handle tags\n if (array_key_exists('expTag', $this->params)) {\n if (isset($this->params['id'])) {\n $db->delete('content_expTags', 'content_type=\"' . (!empty($this->params['content_type']) ? $this->params['content_type'] : $this->basemodel_name) . '\" AND content_id=' . $this->params['id']);\n }\n $tags = explode(\",\", trim($this->params['expTag']));\n unset($this->params['expTag']);", " foreach ($tags as $tag) {\n if (!empty($tag)) {\n $tag = strtolower(trim($tag));\n $tag = str_replace(array('\"', \"'\"), \"\", $tag); // strip double and single quotes\n if (!empty($tag)) {\n $expTag = new expTag($tag);\n if (empty($expTag->id))\n $expTag->update(array('title' => $tag));\n $this->params['expTag'][] = $expTag->id;\n }\n }\n }\n }", " //check for and handle cats\n if (array_key_exists('expCat', $this->params) && !empty($this->params['expCat'])) {\n $catid = $this->params['expCat'];\n unset($this->params['expCat']);\n $this->params['expCat'][] = $catid;\n }", " $modelname = $this->basemodel_name;\n $this->$modelname->update($this->params);", " if ($this->isSearchable()) {\n $this->addContentToSearch($this->params);\n }", " // check for auto send facebook status\n if (!empty($this->params['send_status'])) {\n if ($this->classname == 'eventController') {\n facebookController::postEvent(\n array('model' => $modelname, 'id' => $this->params['date_id'], 'src' => $this->loc->src, 'config' => $this->config, 'orig_controller' => expModules::getControllerName($this->classname))\n );\n } else {\n facebookController::postStatus(\n array('model' => $modelname, 'id' => $this->$modelname->id, 'src' => $this->loc->src, 'config' => $this->config, 'orig_controller' => expModules::getControllerName($this->classname))\n );\n }\n }", " // check for auto send tweet\n if (!empty($this->params['send_tweet'])) {\n if ($this->classname == 'eventController') {\n twitterController::postEventTweet(\n array('model' => $modelname, 'id' => $this->params['date_id'], 'src' => $this->loc->src, 'config' => $this->config, 'orig_controller' => expModules::getControllerName($this->classname))\n );\n } else {\n twitterController::postTweet(\n array('model' => $modelname, 'id' => $this->$modelname->id, 'src' => $this->loc->src, 'config' => $this->config, 'orig_controller' => expModules::getControllerName($this->classname))\n );\n }\n }", " // check for eAlerts\n if (!empty($this->params['send_ealerts'])) {\n redirect_to(array('controller' => 'ealert', 'action' => 'send_confirm', 'model' => $modelname, 'id' => $this->$modelname->id, 'src' => $this->loc->src, 'orig_controller' => expModules::getControllerName($this->classname)));\n } else {\n expHistory::back();\n }\n }", " /**\n * delete item in module\n */\n public function delete() {\n $modelname = $this->basemodel_name;\n if (empty($this->params['id'])) {\n flash('error', gt('Missing id for the') . ' ' . $modelname . ' ' . gt('you would like to delete'));\n expHistory::back();\n }", " $obj = new $modelname($this->params['id']);\n $rows = $obj->delete();", " // if this module is searchable lets delete spidered content\n if ($this->isSearchable()) {\n $search = new search();\n// $content = $search->find('first', 'original_id=' . $this->params['id'] . \" AND ref_module='\" . $this->classname . \"'\");\n $content = $search->find('first', 'original_id=' . $this->params['id'] . \" AND ref_module='\" . $this->baseclassname . \"'\");\n if (!empty($content->id)) $content->delete();\n }", " expHistory::back();\n }", " /**\n * rerank items in model\n */\n public function rerank() {\n $modelname = $this->basemodel_name;\n $obj = new $modelname($this->params['id']);\n $obj->rerank($this->params['push']);\n expHistory::back();\n }", " /**\n * display module management view\n */\n public function manage() {\n expHistory::set('manageable', $this->params);", " $page = new expPaginator(array(\n 'model' => $this->basemodel_name,\n 'where' => static::hasSources() ? $this->aggregateWhereClause() : null,\n 'limit' => isset($this->params['limit']) ? $this->params['limit'] : 10,\n 'order' => isset($this->params['order']) ? $this->params['order'] : null,\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->baseclassname,\n 'action' => $this->params['action'],\n 'src' => static::hasSources() == true ? $this->loc->src : null,\n 'columns' => array(\n gt('ID#') => 'id',\n gt('Title') => 'title',\n gt('Body') => 'body'\n ),\n ));", " assign_to_template(array(\n 'page' => $page,\n 'items' => $page->records\n ));\n }", " /**\n * rerank module items, called from ddrerank\n */\n public function manage_ranks() {\n $rank = 1;\n foreach ($this->params['rerank'] as $id) {\n $modelname = $this->params['model'];\n $obj = new $modelname($id);\n $obj->rank = $rank;\n $obj->save(false, true);\n $rank++;\n }", " if (!expJavascript::inAjaxAction())\n redirect_to($this->params['lastpage']);\n }", " /**\n * Configure the module\n */\n public function configure() {\n global $db;", " expHistory::set('editable', $this->params);\n $views = expTemplate::get_config_templates($this, $this->loc);", " // needed for aggregation list\n $pullable_modules = expModules::listInstalledControllers($this->baseclassname, $this->loc);\n $page = new expPaginator(array(\n 'records' => $pullable_modules,\n 'controller' => $this->loc->mod,\n 'action' => $this->params['action'],\n 'order' => isset($this->params['order']) ? $this->params['order'] : 'section',\n 'dir' => isset($this->params['dir']) ? $this->params['dir'] : '',\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'columns' => array(\n gt('Title') => 'title',\n gt('Page') => 'section'\n ),\n ));", "// if (empty($this->params['hcview'])) {\n $containerloc = expCore::makeLocation(expModules::getModuleName($this->loc->mod),$this->loc->src);\n $container = $db->selectObject('container', \"internal='\" . serialize($containerloc) . \"'\");\n if (empty($container)) {\n $container = new stdClass();\n $container->action = 'showall';\n } else {\n $container->internal = unserialize($container->internal);\n }\n if (empty($container->action)) {\n $container->action = 'showall';\n }\n// expSession::clearAllUsersSessionCache('containermodule');", "// $modules_list = expModules::getActiveModulesAndControllersList();\n// foreach ($modules_list as $moduleclass) {\n// $module = new $moduleclass();\n//\n// // Get basic module meta info\n// $mod = new stdClass();\n// $mod->name = $module->name();\n// $mod->author = $module->author();\n// $mod->description = $module->description();\n// if (isset($container->view) && $container->internal->mod == $moduleclass) {\n// $mod->defaultView = $container->view;\n// } else $mod->defaultView = DEFAULT_VIEW;\n//\n// // Get support flags\n// $mod->supportsSources = ($module->hasSources() ? 1 : 0);\n// $mod->supportsViews = ($module->hasViews() ? 1 : 0);\n//\n// // Get a list of views\n// $mod->views = expTemplate::listModuleViews($moduleclass);\n// natsort($mod->views);\n//\n// $modules[$moduleclass] = $mod;\n//// \t\t$mods[$moduleclass] = $module->name();\n// // $mods[$moduleclass] = $moduleclass::name();\n// }", "// array_multisort(array_map('strtolower', $mods), $mods);", " $actions = $this->useractions;\n $mod_views = array();\n if (!empty($actions)) {\n // Language-ize the action names\n foreach ($actions as $key => $value) {\n $actions[$key] = gt($value);\n }\n $mod_views = expTemplate::get_action_views($this->classname, $container->action, $actions[$container->action]);\n if (count($mod_views) < 1) $mod_views[$container->action] = $actions[$container->action] . ' - Default View';\n }", " assign_to_template(array(\n 'container' => $container,\n 'actions' => $actions,\n 'mod_views' => $mod_views,\n ));\n// } else {\n if (!empty($this->params['hcview'])) {\n // this must be a hard-coded module?\n assign_to_template(array(\n 'hcview' => $this->params['hcview'],\n ));\n }", " $expcat = new expCat();\n $cats = $expcat->find('all','module=\"file\"');\n $folders = array();\n $folders[] = 'Root Folder';\n foreach ($cats as $cat) {\n $folders[$cat->id] = $cat->title;\n }", " assign_to_template(array(\n// 'config' => $this->config, //FIXME already assigned in controllertemplate?\n 'page' => $page, // needed for aggregation list\n 'views' => $views,\n 'title' =>static::displayname(),\n 'current_section' => expSession::get('last_section'),\n// 'classname' => $this->classname, //FIXME $controller already assigned baseclassname (short vs long) in controllertemplate?\n 'viewpath' => $this->viewpath,\n 'relative_viewpath' => $this->relative_viewpath,\n 'folders' => $folders,\n ));", " }", " /**\n * save module configuration\n */\n public function saveconfig() {\n global $db;", " // update module title/action/view\n if (!empty($this->params['container_id'])) {\n $container = $db->selectObject('container', \"id=\" . $this->params['container_id']);\n if (!empty($container)) {\n $container->title = $this->params['moduletitle'];\n $container->action = $this->params['actions'];\n $container->view = $this->params['views'];\n $container->is_private = $this->params['is_private'];\n $db->updateObject($container, 'container');\n expSession::clearAllUsersSessionCache('containermodule');\n }\n unset(\n $this->params['container_id'],\n $this->params['moduletitle'],\n $this->params['modcntrol'],\n $this->params['actions'],\n $this->params['views'],\n $this->params['actions'],\n $this->params['is_private']\n );\n }", " // create a new RSS object if enable is checked.\n $params = $this->params;\n if (!empty($this->params['enable_rss'])) {\n $params['title'] = $params['feed_title'];\n unset($params['feed_title']);\n $params['sef_url'] = $params['feed_sef_url'];\n unset($params['feed_sef_url']);\n $rssfeed = new expRss($params);\n $rssfeed->update($params);\n $this->params['feed_sef_url'] = $rssfeed->sef_url;\n } else {\n $rssfeed = new expRss($this->params);\n $params['enable_rss'] = false;\n if (empty($params['advertise']))\n $params['advertise'] = false;\n $params['title'] = $params['feed_title'];\n unset($params['feed_title']);\n $params['sef_url'] = $params['feed_sef_url'];\n unset($params['feed_sef_url']);\n if (!empty($rssfeed->id)) { // do NOT create a new record, only update existing ones\n $rssfeed->update($params);\n $this->params['feed_sef_url'] = $rssfeed->sef_url;\n }\n }", " // create a new eAlerts object if enable is checked.\n if (!empty($this->params['enable_ealerts'])) {\n $ealert = new expeAlerts($this->params);\n $ealert->update($this->params);\n }", " // unset some unneeded params\n unset(\n $this->params['module'],\n $this->params['controller'],\n $this->params['src'],\n $this->params['int'],\n $this->params['id'],\n $this->params['cid'],\n $this->params['action'],\n $this->params['PHPSESSID'],\n $this->params['__utma'],\n $this->params['__utmb'],\n $this->params['__utmc'],\n $this->params['__utmz'],\n $this->params['__utmt'],\n $this->params['__utmli'],\n $this->params['__cfduid']\n );", " // setup and save the config\n $config = new expConfig($this->loc);\n $config->update(array('config' => $this->params));", " flash('message', gt('Configuration updated'));\n expHistory::back();\n }", " /**\n * get the module's items in an rss feed format\n *\n * this function is very general and will most of the time need to be overwritten and customized\n *\n * @return array\n */\n public function getRSSContent($limit = 0) {\n $class = new $this->basemodel_name;\n $items = $class->find('all', $this->aggregateWhereClause(), isset($this->config['order']) ? $this->config['order'] : 'created_at DESC', $limit);", " //Convert the items to rss items\n $rssitems = array();\n foreach ($items as $key => $item) {\n $rss_item = new FeedItem();\n $rss_item->title = expString::convertSmartQuotes($item->title);\n $rss_item->link = $rss_item->guid = makeLink(array('controller' => $this->baseclassname, 'action' => 'show', 'title' => $item->sef_url));\n $rss_item->description = expString::convertSmartQuotes($item->body);\n $rss_item->author = user::getUserById($item->poster)->firstname . ' ' . user::getUserById($item->poster)->lastname;\n $rss_item->authorEmail = user::getEmailById($item->poster);\n// $rss_item->date = isset($item->publish_date) ? date(DATE_RSS, $item->publish_date) : date(DATE_RSS, $item->created_at);\n $rss_item->date = isset($item->publish_date) ? $item->publish_date : $item->created_at;\n if (!empty($item->expCat[0]->title)) $rss_item->category = array($item->expCat[0]->title);\n $comment_count = expCommentController::countComments(array('content_id' => $item->id, 'content_type' => $this->basemodel_name));\n if ($comment_count) {\n $rss_item->comments = makeLink(array('controller' => $this->baseclassname, 'action' => 'show', 'title' => $item->sef_url)) . '#exp-comments';\n// $rss_item->commentsRSS = makeLink(array('controller'=>$this->baseclassname, 'action'=>'show', 'title'=>$item->sef_url)).'#exp-comments';\n $rss_item->commentsCount = $comment_count;\n }\n $rssitems[$key] = $rss_item;", " if ($limit && count($rssitems) >= $limit)\n break;\n }\n return $rssitems;\n }", " /**\n * method to display an rss feed from this module\n */\n public function rss() {\n require_once(BASE . 'external/feedcreator.class.php');\n", " $id = isset($this->params['title']) ? $this->params['title'] : (isset($this->params['id']) ? $this->params['id'] : null);", " if (empty($id)) {\n $module = !empty($this->params['module']) ? $this->params['module'] : $this->params['controller'];\n $id = array('module' => $module, 'src' => $this->params['src']);\n }\n $site_rss = new expRss($id);\n if ($site_rss->enable_rss == true && !empty($site_rss->id)) {\n $site_rss->title = empty($site_rss->title) ? gt('RSS for') . ' ' . URL_FULL : $site_rss->title;\n $site_rss->feed_desc = empty($site_rss->feed_desc) ? gt('This is an RSS syndication from') . ' ' . HOSTNAME : $site_rss->feed_desc;\n// if (isset($site_rss->rss_cachetime)) {\n// $ttl = $site_rss->rss_cachetime;\n// }\n if ($site_rss->rss_cachetime == 0) {\n $site_rss->rss_cachetime = 1440;\n }", " if (!empty($site_rss->itunes_cats)) {\n $ic = explode(\";\", $site_rss->itunes_cats);\n $x = 0;\n $itunes_cats = array();\n foreach ($ic as $cat) {\n $cat_sub = explode(\":\", $cat);\n $itunes_cats[$x]->category = $cat_sub[0];\n if (isset($cat_sub[1])) {\n $itunes_cats[$x]->subcategory = $cat_sub[1];\n }\n $x++;\n }\n }", " // NO buffering from here on out or things break unexpectedly. - RAM\n ob_end_clean();", " header('Content-Type: ' . 'application/rss+xml');\n// header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');\n// header('Content-Transfer-Encoding: binary');\n header('Content-Encoding:');\n // IE need specific headers\n if (EXPONENT_USER_BROWSER == 'IE') {\n header('Cache-Control: must-revalidate, post-check=0, pre-check=0');\n header('Pragma: public');\n header('Vary: User-Agent');\n } else {\n header('Pragma: no-cache');\n }", " if ($site_rss->rss_is_podcast) {\n $feed_type = \"PODCAST\";\n } else {\n $feed_type = \"RSS2.0\";\n }\n $feed_cache = BASE . 'tmp/rsscache/' . $site_rss->sef_url . '.xml';", " $rss = new UniversalFeedCreator();\n// if (file_exists(THEME_ABSOLUTE . \"rss/feed.css\")) // custom css style\n// $rss->cssStyleSheet = THEME_RELATIVE . \"rss/feed.css\";\n if (file_exists(THEME_ABSOLUTE . \"rss/feed.xsl\")) // custom xml style\n $rss->xslStyleSheet = THEME_RELATIVE . \"rss/feed.xsl\";\n $rss->useCached($feed_type, $feed_cache, $site_rss->rss_cachetime); // if cache exists output then redirect", " $rss->title = $site_rss->title;\n if (!empty($this->params['type']))\n $rss->title .= ' ' . ucfirst($this->params['type']);\n $rss->description = $site_rss->feed_desc;\n $rss->image = new FeedImage();\n $rss->image->url = !empty($site_rss->expFile['album'][0]) ? $site_rss->expFile['album'][0]->url : URL_FULL . 'themes/' . DISPLAY_THEME . '/images/logo.png';\n $rss->image->title = $site_rss->title;\n $rss->image->link = URL_FULL;\n // $rss->image->width = 64;\n // $rss->image->height = 64;\n $rss->ttl = $site_rss->rss_cachetime;\n $rss->link = URL_FULL;\n $rss->language = LOCALE;\n $rss->syndicationURL = makeLink(array('module'=>$site_rss->module, 'src'=>$site_rss->src));\n if ($site_rss->rss_is_podcast) {\n $rss->itunes = new iTunes();\n $rss->itunes->author = !empty($site_rss->feed_artist) ? $site_rss->feed_artist : ORGANIZATION_NAME;\n $rss->itunes->image = !empty($site_rss->expFile['album'][0]) ? $site_rss->expFile['album'][0]->url :URL_FULL . 'themes/' . DISPLAY_THEME . '/images/logo.png';\n $rss->itunes->summary = $site_rss->feed_desc;\n if (!empty($itunes_cats)) {\n $rss->itunes->category = $itunes_cats[0]->category;\n $rss->itunes->subcategory = $itunes_cats[0]->subcategory;\n }\n //\t\t$rss->itunes->explicit = 0;\n// $rss->itunes->subtitle = $site_rss->title;\n $rss->itunes->subtitle = $site_rss->feed_desc;\n //\t\t$rss->itunes->keywords = 0;\n $rss->itunes->owner_email = SMTP_FROMADDRESS;\n $rss->itunes->owner_name = ORGANIZATION_NAME;\n }", " $pubDate = '';\n $site_rss->params = $this->params;\n foreach ($site_rss->getFeedItems($site_rss->rss_limit) as $item) {\n if ($item->date > $pubDate) {\n $pubDate = $item->date;\n }\n $rss->addItem($item);\n }\n if (!empty($site_rss->rss_limit)) {\n $rss->items = array_slice($rss->items, 0, $site_rss->rss_limit);\n }\n $rss->pubDate = $pubDate;", "// echo $rss->createFeed($feed_type);\n echo $rss->saveFeed($feed_type, $feed_cache, $site_rss->rss_cachetime); // does redirect after updating cache\n } else {\n flash('notice', gt(\"This RSS feed is not available.\"));\n expHistory::back();\n }", " //Read the file out directly\n exit();\n }", " /**\n * download a file attached to item\n */\n public function downloadfile() {\n if (!isset($this->config['allowdownloads']) || $this->config['allowdownloads'] == true) {\n //if ($db->selectObject('content_expFiles', 'content_type=\"'.$this->baseclassname.'\" AND expfiles_id='.$this->params['id']) != null) {\n expFile::download($this->params['id']);\n //}\n } else {\n flash('error', gt('Downloads have not been enabled for this file'));\n expHistory::back();\n }", " }", " /**", " * permission functions to aggregate a module's permissions based on add/remove permissions", " *\n * @return array\n */\n public function permissions() {\n //set the permissions array\n $perms = array();\n foreach ($this->permissions as $perm => $name) {\n if (!in_array($perm, $this->remove_permissions)) $perms[$perm] = $name;\n }\n $perms = array_merge($perms, $this->add_permissions);", "", " return $perms;\n }", " // create a psuedo global permission specific to the module; return true grants permission, false continues with other permission checks\n public static function checkPermissions($permission, $location) {\n return false;\n }", " /**\n * get the model(s) associated with this module\n *\n * @return array\n */\n public function getModels() {\n return isset($this->models) ? $this->models : array($this->basemodel_name);\n }", " /**\n * type of items searched in the module\n *\n * @return string\n */\n public function searchName() {\n return static::displayname();\n }", " /**\n * category of items searched in the module\n *\n * @return string\n */\n public function searchCategory() {\n return $this->basemodel_name;\n }", " /**\n * add module items to search index\n *\n * @return int\n */\n public function addContentToSearch() {\n// global $db, $router;\n global $db;", " $count = 0;\n $model = new $this->basemodel_name(null, false, false);\n $where = (!empty($this->params['id'])) ? 'id=' . $this->params['id'] : null;\n $content = $db->selectArrays($model->tablename, $where);\n foreach ($content as $cnt) {\n $origid = $cnt['id'];\n unset($cnt['id']);\n //build the search record and save it.\n// $sql = \"original_id=\" . $origid . \" AND ref_module='\" . $this->classname . \"'\";\n $sql = \"original_id=\" . $origid . \" AND ref_module='\" . $this->baseclassname . \"'\";\n $oldindex = $db->selectObject('search', $sql);\n if (!empty($oldindex)) {\n $search_record = new search($oldindex->id, false, false);\n $search_record->update($cnt);\n } else {\n $search_record = new search($cnt, false, false);\n }", " //build the search record and save it.\n $search_record->original_id = $origid;\n $search_record->posted = empty($cnt['created_at']) ? null : $cnt['created_at'];\n // get the location data for this content\n if (isset($cnt['location_data']))\n $loc = expUnserialize($cnt['location_data']);\n $src = isset($loc->src) ? $loc->src : null;\n if (!empty($cnt['sef_url'])) {\n $link = str_replace(URL_FULL, '', makeLink(array('controller' => $this->baseclassname, 'action' => 'show', 'title' => $cnt['sef_url'])));\n } else {\n $link = str_replace(URL_FULL, '', makeLink(array('controller' => $this->baseclassname, 'action' => 'show', 'id' => $origid, 'src' => $src)));\n }\n//\t if (empty($search_record->title)) $search_record->title = 'Untitled';\n $search_record->view_link = $link;\n// $search_record->ref_module = $this->classname;\n $search_record->ref_module = $this->baseclassname;\n $search_record->category = $this->searchName();\n $search_record->ref_type = $this->searchCategory();\n $search_record->save();\n $count++;\n }", " return $count;\n }", " /**\n * additional check for display of search hit\n *\n * @param $record\n *\n * @return bool\n */\n public static function searchHit($record) {\n return true; // default is to display search hit\n }", " /**\n * remove all module items from search index\n */\n public function delete_search() {\n global $db;\n // remove this modules entries from the search table.\n if ($this->isSearchable()) {\n// $where = \"ref_module='\" . $this->classname . \"' AND location_data='\" . serialize($this->loc) . \"'\";\n $where = \"ref_module='\" . $this->baseclassname . \"' AND location_data='\" . serialize($this->loc) . \"'\";\n// $test = $db->selectObjects('search', $where);\n $db->delete('search', $where);\n }\n }", " /**\n * delete module and all its items for backwards compat with old modules\n *\n * @param $loc\n */\n public function delete_In($loc) {\n $this->delete_instance($loc);\n }", " /**\n * delete module, config, and all its items\n * @param bool $loc\n */\n public function delete_instance($loc = false) {\n $model = new $this->basemodel_name();\n $where = 1;\n if ($loc || static::hasSources())\n $where = \"location_data='\" . serialize($this->loc) . \"'\";\n $items = $model->find('all',$where);\n foreach ($items as $item) {\n $item->delete(); // model should delete attachments and other associated objects\n }\n $cfg = new expConfig($this->loc);\n $cfg->delete();\n }", " /**\n * get the metainfo for this module\n *\n * @return array\n */\n public function metainfo() {\n global $router;", " if (empty($router->params['action'])) return false;", " // figure out what metadata to pass back based on the action we are in.\n $action = $router->params['action'];\n $metainfo = array('title' => '', 'keywords' => '', 'description' => '', 'canonical' => '', 'noindex' => false, 'nofollow' => false);\n $modelname = $this->basemodel_name;", " switch ($action) {\n case 'showall':\n $metainfo['title'] = gt(\"Showing\") . \" \" . static::displayname() . ' - ' . SITE_TITLE;\n $metainfo['keywords'] = SITE_KEYWORDS;\n $metainfo['description'] = SITE_DESCRIPTION;\n break;\n case 'show':\n case 'showByTitle':\n // look up the record.\n if (isset($router->params['id']) || isset($router->params['title'])) {\n $lookup = isset($router->params['id']) ? $router->params['id'] : $router->params['title'];\n $object = new $modelname($lookup);\n // set the meta info\n if (!empty($object)) {\n if (!empty($object->body)) {\n $desc = str_replace('\"',\"'\",expString::summarize($object->body,'html','para'));\n } else {\n $desc = SITE_DESCRIPTION;\n }\n if (!empty($object->expTag)) {\n $keyw = '';\n foreach ($object->expTag as $tag) {\n if (!empty($keyw)) $keyw .= ', ';\n $keyw .= $tag->title;\n }\n } else {\n $keyw = SITE_KEYWORDS;\n }\n $metainfo['title'] = empty($object->meta_title) ? $object->title : $object->meta_title;\n $metainfo['keywords'] = empty($object->meta_keywords) ? $keyw : $object->meta_keywords;\n $metainfo['description'] = empty($object->meta_description) ? $desc : $object->meta_description;\n// $metainfo['canonical'] = empty($object->canonical) ? URL_FULL.substr($router->sefPath, 1) : $object->canonical;\n $metainfo['canonical'] = empty($object->canonical) ? $router->plainPath() : $object->canonical;\n $metainfo['noindex'] = empty($object->meta_noindex) ? false : $object->meta_noindex;\n $metainfo['nofollow'] = empty($object->meta_nofollow) ? false : $object->meta_nofollow;\n $metainfo['rich'] = $this->meta_rich($router->params, $object);\n $metainfo['fb'] = $this->meta_fb($router->params, $object, $metainfo['canonical']);\n $metainfo['tw'] = $this->meta_tw($router->params, $object, $metainfo['canonical']);\n }\n break;\n }\n default:\n //check for a function in the controller called 'action'_meta and use it if so\n $functionName = $action . \"_meta\";\n $mod = new $this->classname;\n if (method_exists($mod, $functionName)) {\n $metainfo = $mod->$functionName($router->params);\n } else {\n $metainfo['title'] = static::displayname() . \" - \" . SITE_TITLE;\n $metainfo['keywords'] = SITE_KEYWORDS;\n $metainfo['description'] = SITE_DESCRIPTION;\n// $metainfo['canonical'] = URL_FULL.substr($router->sefPath, 1);\n $metainfo['canonical'] = $router->plainPath();\n }\n }", " return $metainfo;\n }", " /**\n * Returns rich snippet PageMap meta data\n *\n * @param $request\n * @param $object\n *\n * @return null\n */\n public function meta_rich($request, $object) {\n return null;\n }", " /**\n * Returns Facebook og: meta data\n *\n * @param $request\n * @param $object\n *\n * @return array\n */\n public function meta_fb($request, $object, $canonical) {\n return array();\n }", " /**\n * Returns Twitter twitter: meta data\n *\n * @param $request\n * @param $object\n *\n * @return array\n */\n public function meta_tw($request, $object, $canonical) {\n return array();\n }", " /**\n * action specific metainfo\n *\n * @param $request\n * @return array\n */\n public function showall_by_tags_meta($request) {\n global $router;", " // look up the record.\n if (isset($request['tag'])) {\n $metainfo = array('title' => '', 'keywords' => '', 'description' => '', 'canonical' => '', 'noindex' => false, 'nofollow' => false);\n $tag = $request['tag'];\n // set the meta info\n $metainfo['title'] = gt('Showing all') . ' ' . ucwords($this->basemodel_name) . ' ' . gt('tagged as') . ' ' . $tag;\n// $metainfo['keywords'] = empty($object->meta_keywords) ? SITE_KEYWORDS : $object->meta_keywords; //FIXME $object not set\n $metainfo['keywords'] = $request['tag'];\n// $metainfo['description'] = empty($object->meta_description) ? SITE_DESCRIPTION : $object->meta_description; //FIXME $object not set\n $metainfo['description'] = SITE_DESCRIPTION;\n// $metainfo['canonical'] = empty($object->canonical) ? URL_FULL . substr($router->sefPath, 1) : $object->canonical; //FIXME $object not set\n// $metainfo['canonical'] = URL_FULL . substr($router->sefPath, 1);\n $metainfo['canonical'] = $router->plainPath();\n return $metainfo;\n }\n return null;\n }", " /**\n * action specific metainfo\n *\n * @param $request\n * @return array\n */\n public function showall_by_date_meta($request) {\n global $router;", " // look up the record.\n if (isset($request['month'])) {\n $metainfo = array('title' => '', 'keywords' => '', 'description' => '', 'canonical' => '', 'noindex' => false, 'nofollow' => false);\n $mk = mktime(0, 0, 0, $request['month'], 01, $request['year']);\n $ts = strftime('%B, %Y', $mk);\n // set the meta info\n $metainfo['title'] = gt('Showing all') . ' ' . ucwords($this->basemodel_name) . ' ' . gt('written in') . ' ' . $ts;\n// $metainfo['keywords'] = empty($object->meta_keywords) ? SITE_KEYWORDS : $object->meta_keywords; //FIXME $object not set\n $metainfo['keywords'] = SITE_KEYWORDS;\n// $metainfo['description'] = empty($object->meta_description) ? SITE_DESCRIPTION : $object->meta_description; //FIXME $object not set\n $metainfo['description'] = SITE_DESCRIPTION;\n// $metainfo['canonical'] = empty($object->canonical) ? URL_FULL . substr($router->sefPath, 1) : $object->canonical; //FIXME $object not set\n// $metainfo['canonical'] = URL_FULL . substr($router->sefPath, 1);\n $metainfo['canonical'] = $router->plainPath();\n return $metainfo;\n }\n return null;\n }", " /**\n * approve module item\n */\n public function approve() {\n $modelname = $this->basemodel_name;\n $lookup = isset($this->params['id']) ? $this->params['id'] : $this->params['title'];\n $object = new $modelname($lookup);\n $object->approved = true;\n $object->save(false, true); // we don't want to add this approval as a new revision\n expHistory::back();\n }", " /**\n * The aggregateWhereClause function creates a sql where clause which also includes aggregated module content\n *\n * @param string $type\n *\n * @return string\n */\n public function aggregateWhereClause($type='') {\n global $user;", " $sql = '';", " if (empty($this->config['add_source']) && !static::hasSources()) {\n return $sql;\n }", " if (!empty($this->config['aggregate'])) $sql .= '(';", " $sql .= \"location_data ='\" . serialize($this->loc) . \"'\";", " if (!empty($this->config['aggregate'])) {\n foreach ($this->config['aggregate'] as $src) {\n $loc = expCore::makeLocation($this->baseclassname, $src);\n $sql .= \" OR location_data ='\" . serialize($loc) . \"'\";\n }", " $sql .= ')';\n }\n $model = $this->basemodel_name;\n if (ENABLE_WORKFLOW && $this->$model->needs_approval) {\n if ($user->id) {\n $sql .= ' AND (approved=1 OR poster=' . $user->id . ' OR editor=' . $user->id . ')';\n } else {\n $sql .= ' AND approved=1';\n }\n }", " return $sql;\n }", "}", "?>" ]
[ 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 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 ]
PreciseBugs
{"buggy_code_end_loc": [1156, 821, 538, 1298, 1110, 656, 639, 481, 1974, 221, 1264, 168, 235, 25, 598, 133, 55, 383, 63, 58, 352, 125, 394, 59, 2152, 117, 137, 259, 537, 2235, 33, 72, 1773, 250, 679, 739, 285, 1941, 540, 62, 528, 25, 1290, 256, 199, 122, 41, 99, 2020, 355, 147, 129, 1499], "buggy_code_start_loc": [44, 288, 107, 354, 1102, 26, 194, 37, 244, 25, 27, 24, 31, 25, 27, 50, 27, 27, 25, 44, 26, 25, 29, 34, 25, 24, 24, 25, 25, 27, 26, 68, 1, 54, 26, 428, 41, 29, 44, 55, 24, 24, 1, 28, 30, 25, 29, 25, 25, 29, 146, 128, 27], "filenames": ["framework/core/controllers/expController.php", "framework/core/expFramework.php", "framework/core/models/expRecord.php", "framework/core/subsystems/database/mysqli.php", "framework/core/subsystems/expDatabase.php", "framework/core/subsystems/expPaginator.php", "framework/core/subsystems/expSettings.php", "framework/core/subsystems/expString.php", "framework/core/subsystems/expTheme.php", "framework/modules/addressbook/controllers/addressController.php", "framework/modules/administration/controllers/administrationController.php", "framework/modules/banners/controllers/bannerController.php", "framework/modules/blog/controllers/blogController.php", "framework/modules/core/controllers/expCatController.php", "framework/modules/core/controllers/expCommentController.php", "framework/modules/core/controllers/expDefinableFieldController.php", "framework/modules/core/controllers/expHTMLEditorController.php", "framework/modules/core/controllers/expSimpleNoteController.php", "framework/modules/core/controllers/expTagController.php", "framework/modules/eaas/controllers/eaasController.php", "framework/modules/ealerts/controllers/ealertController.php", "framework/modules/ecommerce/controllers/billingController.php", "framework/modules/ecommerce/controllers/ecomconfigController.php", "framework/modules/ecommerce/controllers/eventregistrationController.php", "framework/modules/ecommerce/controllers/orderController.php", "framework/modules/ecommerce/controllers/order_statusController.php", "framework/modules/ecommerce/controllers/purchaseOrderController.php", "framework/modules/ecommerce/controllers/shippingController.php", "framework/modules/ecommerce/controllers/storeCategoryController.php", "framework/modules/ecommerce/controllers/storeController.php", "framework/modules/ecommerce/controllers/taxController.php", "framework/modules/ecommerce/products/models/donation.php", "framework/modules/events/controllers/eventController.php", "framework/modules/events/models/event.php", "framework/modules/file/controllers/fileController.php", "framework/modules/file/models/expFile.php", "framework/modules/filedownloads/controllers/filedownloadController.php", "framework/modules/forms/controllers/formsController.php", "framework/modules/help/controllers/helpController.php", "framework/modules/help/models/help_version.php", "framework/modules/importexport/controllers/importexportController.php", "framework/modules/migration/controllers/migrationController.php", "framework/modules/navigation/controllers/navigationController.php", "framework/modules/news/controllers/newsController.php", "framework/modules/photoalbum/controllers/photosController.php", "framework/modules/pixidou/controllers/pixidouController.php", "framework/modules/portfolio/controllers/portfolioController.php", "framework/modules/recyclebin/controllers/recyclebinController.php", "framework/modules/report/controllers/reportController.php", "framework/modules/search/controllers/searchController.php", "framework/modules/simplepoll/controllers/simplePollController.php", "framework/modules/users/controllers/loginController.php", "framework/modules/users/controllers/usersController.php"], "fixing_code_end_loc": [1183, 823, 543, 1298, 1110, 664, 643, 481, 1977, 221, 1263, 171, 234, 29, 599, 133, 59, 383, 69, 52, 358, 126, 397, 57, 2154, 120, 130, 262, 538, 2232, 25, 72, 1774, 255, 685, 741, 285, 1949, 541, 62, 535, 25, 1306, 259, 202, 121, 40, 102, 2025, 356, 147, 129, 1513], "fixing_code_start_loc": [44, 288, 107, 354, 1102, 26, 194, 37, 244, 25, 27, 25, 32, 26, 27, 50, 27, 27, 26, 43, 26, 25, 29, 33, 25, 25, 25, 25, 25, 26, 25, 68, 1, 55, 25, 428, 41, 30, 44, 55, 25, 24, 1, 29, 31, 24, 30, 25, 25, 29, 146, 128, 27], "message": "Exponent CMS version 2.3.9 suffers from a Object Injection vulnerability in framework/modules/core/controllers/expTagController.php related to change_tags.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:exponentcms:exponent_cms:2.3.9:*:*:*:*:*:*:*", "matchCriteriaId": "12FDDF33-2B21-4F8A-AB9A-01857197E810", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Exponent CMS version 2.3.9 suffers from a Object Injection vulnerability in framework/modules/core/controllers/expTagController.php related to change_tags."}, {"lang": "es", "value": "Existe una vulnerabilidad en Exponent CMS versi\u00f3n 2.3.9, sufre de una vulnerabilidad de Inyecci\u00f3n de Objeto en el archivo framework/modules/core/controllers/expTagController.php asociado con el par\u00e1metro change_tags."}], "evaluatorComment": null, "id": "CVE-2016-8900", "lastModified": "2019-05-28T16:01:48.990", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-05-24T17:29:00.913", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Exploit", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2016/09/30/5"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/exponentcms/exponent-cms/commit/fdafb5ec97838e4edbd685f587f28d3174ebb3db"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/exponentcms/exponent-cms/commit/fdafb5ec97838e4edbd685f587f28d3174ebb3db"}, "type": "CWE-74"}
197
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n##################################################\n#\n# Copyright (c) 2004-2016 OIC Group, Inc.\n#\n# This file is part of Exponent\n#\n# Exponent is free software; you can redistribute\n# it and/or modify it under the terms of the GNU\n# General Public License as published by the Free\n# Software Foundation; either version 2 of the\n# License, or (at your option) any later version.\n#\n# GPL: http://www.gnu.org/licenses/gpl.txt\n#\n##################################################", "/**\n * This is the class expController\n *\n * @package Core\n * @subpackage Controllers\n */", "abstract class expController {\n protected $classname = ''; // full controller name w/ 'Controller' suffix\n public $baseclassname = ''; // root controller name w/o 'Controller' suffix\n public $classinfo = null; // holds reflection class of class\n// public $module_name = ''; //FIXME not used and not actually set right index needed of -3 instead of -2 below\n// protected $basemodel = null; //FIXME never used, $basemodel_name replaced?\n public $basemodel_name = ''; // holds classname of base model associated w/ this controller\n public $model_table = ''; // holds table name for base model", " public $useractions = array(); // available (displayed) user actions/methods for this module\n public $remove_configs = array(); // all options: ('aggregation','categories','comments','ealerts','facebook','files','module_title','pagination','rss','tags','twitter',)", " // $permissions used to restrict access to module's actions/methods\n protected $permissions = array( // standard set of permissions for all modules unless add'ed or remove'd\n 'manage' => 'Manage',\n 'configure' => 'Configure',\n 'create' => 'Create',\n 'edit' => 'Edit',\n 'delete' => 'Delete',", " );\n protected $m_permissions = array( // standard set of actions requiring manage permission for all modules\n 'activate' => 'Activate',\n 'approve' => 'Approve',\n 'merge' => 'Merge',\n 'rerank' => 'ReRank',\n 'import' => 'Import Items',\n 'export' => 'Export Items'", " );\n protected $remove_permissions = array(); // $permissions not applicable for this module from above list", " protected $add_permissions = array(); // additional $permissions processed and visible for this module\n protected $manage_permissions = array(); // additional actions requiring manage permission in addition to $m_permissions\n public $requires_login = array(); // actions/methods which ONLY require user be logged in to access...$permissions take priority", "\n public $filepath = ''; // location of this controller's files\n public $viewpath = ''; // location of this controllers views; defaults to controller file location\n public $relative_viewpath = ''; // relative location of controller's views\n public $asset_path = ''; // location of this controller's assets; defaults to controller file location", " public $config = array(); // holds module configuration settings\n public $params = array(); // holds sanitized parameters passed to module\n public $loc = null; // module location object", " public $codequality = 'stable'; // code's level of stability", " public $rss_is_podcast = false;", " /**\n * @param null $src\n * @param array $params\n *\n * @return expController\n *\n */\n public function __construct($src = null, $params = array()) {\n // setup some basic information about this class\n $this->classinfo = new ReflectionClass($this);\n $this->classname = $this->classinfo->getName();\n $this->baseclassname = substr($this->classinfo->getName(), 0, -10);\n $this->filepath = __realpath($this->classinfo->getFileName());", " // figure out which \"module\" we belong to and setup view path information\n $controllerpath = explode('/', $this->filepath);\n// $this->module_name = $controllerpath[(count($controllerpath)-3)];", " // set up the path to this module view files\n array_pop($controllerpath); // remove 'controllers' from array\n $controllerpath[count($controllerpath) - 1] = 'views';\n array_push($controllerpath, $this->baseclassname);\n $this->relative_viewpath = implode('/', array_slice($controllerpath, -3, 3));\n// $this->viewpath = BASE.'framework/modules/'.$this->relative_viewpath;\n //FIXME this requires we move the 'core' controllers into the modules folder or use this hack\n $depth = array_search('core', $controllerpath);\n if ($depth) {\n $this->viewpath = BASE . 'framework/modules/' . $this->relative_viewpath;\n } else {\n $this->viewpath = implode('/', $controllerpath);\n }", " //grab the path to the module's assets\n array_pop($controllerpath);\n $controllerpath[count($controllerpath) - 1] = 'assets';\n// $this->asset_path = PATH_RELATIVE.'framework/'.implode('/', array_slice($controllerpath, -3, 3)).\"/\";\n $depth = array_search('framework', $controllerpath); // is this a system file (or theme)?\n if (!$depth) $depth = array_search('themes', $controllerpath);\n $this->asset_path = PATH_RELATIVE . implode('/', array_slice($controllerpath, $depth)) . \"/\";", " // figure out which model we're using and setup some info about it\n if (empty($this->basemodel_name)) $this->basemodel_name = get_model_for_controller($this->classname);\n $modelname = $this->basemodel_name;\n if (class_exists($modelname)) {\n $this->$modelname = new $modelname(null, false, false);\n $this->model_table = $this->$modelname->tablename;\n } else {\n $this->basemodel_name = 'expRecord';\n $this->$modelname = new expRecord(null, false, false);\n $this->model_table = null;\n }", " // set the location data\n $this->loc = expCore::makeLocation($this->baseclassname, $src, null);", " // flag for needing approval check\n if (ENABLE_WORKFLOW && $this->$modelname->supports_revisions) {\n $uilevel = 99;\n if (expSession::exists(\"uilevel\")) $uilevel = expSession::get(\"uilevel\");\n if (!expPermissions::check('approve', $this->loc)) {\n $this->$modelname->needs_approval = true;\n } elseif ($uilevel == UILEVEL_PREVIEW && isset($uilevel)) {\n $this->$modelname->needs_approval = true; // 'preview' should provide a true preview\n }\n }", " // get this controllers config data if there is any\n $config = new expConfig($this->loc);\n $this->config = $config->config;", " $this->params = $params;", " if (ENABLE_WORKFLOW)\n $this->permissions = array_merge($this->permissions, array('approve'=>'Approval'));", " }", " /**\n * name of module for backwards compat with old modules\n *\n * @return string\n */\n public function name() {\n return static::displayname();\n }", " /**\n * name of module\n *\n * @return string\n */\n public static function displayname() {\n return gt(\"Exponent Base Controller\");\n }", " /**\n * description of module\n *\n * @return string\n */\n public static function description() {\n return gt(\"This is the base controller which most Exponent modules inherit their methods from.\");\n }", " /**\n * author of module\n *\n * @return string\n */\n public static function author() {\n return \"OIC Group, Inc\";\n }", " /**\n * does module have sources available? or does it treat content globally\n *\n * @return bool\n */\n public static function hasSources() {\n return true;\n }", " /**\n * does module have views available?\n *\n * @return bool\n */ //NOTE: Never used - equivalent to !empty ($this->useractions) via expModules::listUserRunnableControllers()?\n public static function hasViews() {\n return true;\n }", " /**\n * does module have content (stored items) available?\n *\n * @return bool\n */ //NOTE: Never used, better utilized/implemented as isSearchable()\n public static function hasContent() {\n return true;\n }", " /**\n * does module support workflow?\n *\n * @return bool\n */\n public static function supportsWorkflow() {\n return false;\n }", " /**\n * is module content searchable? should it be added to search index?\n *\n * @return bool\n */\n public static function isSearchable() {\n return false;\n }", " /**\n * can this module import data?\n *\n * @return bool\n */\n public static function canImportData() {\n return false;\n }", " /**\n * can this module export data?\n *\n * @return bool\n */\n public static function canExportData() {\n return false;\n }", " /**\n * does this module require configuration?\n *\n * @return bool\n */ //NOTE: Never Used\n public static function requiresConfiguration() {\n return false;\n }", " /**\n * glue to make the view template aware of the module\n * @deprecated\n */\n public function moduleSelfAwareness() {\n assign_to_template(array(\n 'asset_path' => $this->asset_path,\n 'model_name' => $this->basemodel_name,\n 'table' => $this->model_table,\n 'controller' => $this->baseclassname,\n 'config' => $this->config\n ));\n }", " /**\n * default module view method for all items\n */\n public function showall() {\n expHistory::set('viewable', $this->params);", " $page = new expPaginator(array(\n 'model' => $this->basemodel_name,\n 'where' => static::hasSources() ? $this->aggregateWhereClause() : null,\n 'limit' => (isset($this->params['limit']) && $this->params['limit'] != '') ? $this->params['limit'] : 10,\n 'order' => isset($this->params['order']) ? $this->params['order'] : null,\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->baseclassname,\n 'action' => $this->params['action'],\n 'src' => static::hasSources() == true ? $this->loc->src : null,\n 'columns' => array(\n gt('ID#') => 'id',\n gt('Title') => 'title',\n gt('Body') => 'body'\n ),\n ));", " assign_to_template(array(\n 'page' => $page,\n 'items' => $page->records\n ));\n }", " /**\n * default module view method for all items with a specific tag\n */\n public function showall_by_tags() {\n global $db;", " // set history\n expHistory::set('viewable', $this->params);\n $modelname = $this->basemodel_name;", " // get the tag being passed", " $tag = new expTag(expString::escape($this->params['tag']));", "\n // find all the id's of the portfolios for this module\n $item_ids = $db->selectColumn($modelname, 'id', $this->aggregateWhereClause());", " // find all the items that this tag is attached to\n $items = $tag->findWhereAttachedTo($modelname);", " // loop the items for this tag and find out which ones belong to this module\n $items_by_tags = array();\n foreach ($items as $item) {\n if (in_array($item->id, $item_ids)) $items_by_tags[] = $item;\n }", " // create a pagination object for the model and render the action\n $order = 'created_at DESC';\n $page = new expPaginator(array(\n 'records' => $items_by_tags,\n 'limit' => (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10,\n 'order' => $order,\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->baseclassname,\n 'action' => $this->params['action'],\n 'src'=>$this->loc->src,\n 'columns' => array(\n gt('Title') => 'title'\n ),\n ));\n// $page->records = expSorter::sort(array('array'=>$page->records, 'sortby'=>'rank', 'order'=>'ASC', 'ignore_case'=>true));\n $page->records = expSorter::sort(array('array' => $page->records, 'sortby' => 'created_at', 'order' => 'DESC', 'ignore_case' => true));", " assign_to_template(array(\n 'page' => $page,\n 'items' => $page->records,", " 'moduletitle' => ucfirst($modelname) . ' ' . gt('items tagged with') . ' \"' . expString::escape($this->params['tag']) . '\"',", " 'rank' => ($order === 'rank') ? 1 : 0\n ));\n }", " /**\n * return all tags used by module's items\n */\n public function tags() {\n expHistory::set('viewable', $this->params);\n $modelname = $this->basemodel_name;", " $items = $this->$modelname->find('all', $this->aggregateWhereClause());\n $used_tags = array();\n foreach ($items as $item) {\n foreach ($item->expTag as $tag) {\n if (isset($used_tags[$tag->id])) {\n $used_tags[$tag->id]->count++;\n } else {\n $exptag = new expTag($tag->id);\n $used_tags[$tag->id] = $exptag;\n $used_tags[$tag->id]->count = 1;\n }\n }\n }", "// $order = isset($this->config['order']) ? $this->config['order'] : 'rank';\n// $used_tags = expSorter::sort(array('array'=>$used_tags,'sortby'=>'title', 'order'=>'ASC', 'ignore_case'=>true, 'rank'=>($order==='rank')?1:0));\n// $order = isset($this->config['order']) ? $this->config['order'] : 'title ASC';\n// $used_tags = expSorter::sort(array('array'=>$used_tags, 'order'=>$order, 'ignore_case'=>true, 'rank'=>($order==='rank')?1:0));\n $used_tags = expSorter::sort(array('array' => $used_tags, 'order' => 'count DESC', 'type' => 'a'));\n if (!empty($this->config['limit'])) $used_tags = array_slice($used_tags, 0, $this->config['limit']);\n $order = isset($this->config['order']) ? $this->config['order'] : 'title ASC';\n if ($order != 'hits') {\n $used_tags = expSorter::sort(array('array' => $used_tags, 'order' => $order, 'ignore_case' => true, 'rank' => ($order === 'rank') ? 1 : 0));\n }", " assign_to_template(array(\n 'tags' => $used_tags\n ));\n }", " /**\n * return all categories used by module's items\n */\n public function categories() {\n expHistory::set('viewable', $this->params);\n $modelname = $this->basemodel_name;", " $items = $this->$modelname->find('all', $this->aggregateWhereClause());\n $used_cats = array();\n $used_cats[0] = new stdClass();\n $used_cats[0]->id = 0;\n $used_cats[0]->title = !empty($this->config['uncat']) ? $this->config['uncat'] : gt('Not Categorized');\n $used_cats[0]->count = 0;\n foreach ($items as $item) {\n if (!empty($item->expCat)) {\n if (isset($used_cats[$item->expCat[0]->id])) {\n $used_cats[$item->expCat[0]->id]->count++;\n } else {\n $expcat = new expCat($item->expCat[0]->id);\n $used_cats[$item->expCat[0]->id] = $expcat;\n $used_cats[$item->expCat[0]->id]->count = 1;\n }\n } else {\n $used_cats[0]->count++;\n }\n }", "// $order = isset($this->config['order']) ? $this->config['order'] : 'rank';\n// $used_cats = expSorter::sort(array('array'=>$used_cats,'sortby'=>'title', 'order'=>'ASC', 'ignore_case'=>true, 'rank'=>($order==='rank')?1:0));\n// $order = isset($this->config['order']) ? $this->config['order'] : 'title ASC';\n// $used_cats = expSorter::sort(array('array'=>$used_cats, 'order'=>$order, 'ignore_case'=>true, 'rank'=>($order==='rank')?1:0));\n $used_cats = expSorter::sort(array('array' => $used_cats, 'order' => 'count DESC', 'type' => 'a'));\n if (!empty($this->config['limit'])) $used_cats = array_slice($used_cats, 0, $this->config['limit']);\n $order = isset($this->config['order']) ? $this->config['order'] : 'title ASC';\n if ($order != 'count') {\n $used_cats = expSorter::sort(array('array' => $used_cats, 'order' => $order, 'ignore_case' => true, 'rank' => ($order === 'rank') ? 1 : 0));\n }", " assign_to_template(array(\n 'cats' => $used_cats\n ));\n }", " /**\n * return all comments used by module's items\n */\n public function comments() {\n\t expHistory::set('viewable', $this->params);\n $modelname = $this->basemodel_name;", " $items = $this->$modelname->find('all');\n $all_comments = array();\n // get all the blog comments\n foreach ($items as $item) {\n $more_comments = expCommentController::getComments(array('content_type'=>$modelname,'content_id'=>$item->id));\n if (!empty($more_comments)) {\n foreach ($more_comments as $next_comment) {\n $next_comment->ref = $item->title;\n $next_comment->sef_url = $item->sef_url;\n }\n $all_comments = array_merge($all_comments,$more_comments);\n }\n }\n // sort then limit all the blog comments\n $all_comments = expSorter::sort(array('array' => $all_comments, 'sortby' => 'created_at', 'order' => 'DESC', 'ignore_case' => true));\n $limit = (isset($this->config['headcount']) && $this->config['headcount'] != '') ? $this->config['headcount'] : 10;\n $comments = array_slice($all_comments,0,$limit);\n\t assign_to_template(array(\n 'comments'=>$comments,\n ));\n\t}", " /**\n * default view for individual item\n */\n public function show() {\n expHistory::set('viewable', $this->params);\n $modelname = $this->basemodel_name;", " // figure out if we're looking this up by id or title\n $id = null;\n if (isset($this->params['id'])) {\n $id = $this->params['id'];\n } elseif (isset($this->params['title'])) {", " $id = expString::escape($this->params['title']);", " }", " $record = new $modelname($id);\n if (empty($record->id))\n redirect_to(array('controller'=>'notfound','action'=>'page_not_found','title'=>$this->params['title']));", " $config = expConfig::getConfig($record->location_data);\n if (empty($this->config))\n $this->config = $config;\n if (empty($this->loc->src)) {\n $r_loc = expUnserialize($record->location_data);\n $this->loc = new stdClass();\n $this->loc->src = $r_loc->src;\n }", " assign_to_template(array(\n 'record' => $record,\n 'config' => $config\n ));\n }", " /**\n * view the item by referring to its title\n * @deprecated\n */\n public function showByTitle() {\n expHistory::set('viewable', $this->params);\n $modelname = $this->basemodel_name;\n // first we'll check to see if this matches the sef_url field...if not then we'll look for the\n // title field", " $this->params['title'] = expString::escape($this->params['title']); // escape title to prevent sql injection", " $record = $this->$modelname->find('first', \"sef_url='\" . $this->params['title'] . \"'\");\n if (!is_object($record)) {\n $record = $this->$modelname->find('first', \"title='\" . $this->params['title'] . \"'\");\n }\n $this->loc = unserialize($record->location_data);", " assign_to_template(array(\n 'record' => $record,\n ));\n }", " /**\n * view a random item\n */\n public function showRandom() {\n expHistory::set('viewable', $this->params);\n $where = static::hasSources() ? $this->aggregateWhereClause() : null;\n $limit = isset($this->params['limit']) ? $this->params['limit'] : 1;\n $order = 'RAND()';\n assign_to_template(array(\n 'items' => $this->text->find('all', $where, $order, $limit)\n ));\n }", " /**\n * view items referenced by tags\n * @deprecated\n */\n public function showByTags() {\n global $db;", " // set the history point for this action\n expHistory::set('viewable', $this->params);", " // setup some objects\n $tagobj = new expTag();\n $modelname = empty($this->params['model']) ? $this->basemodel_name : $this->params['model'];\n $model = new $modelname();", " // start building the sql query\n $sql = 'SELECT DISTINCT m.id FROM ' . $db->prefix . $model->tablename . ' m ';\n $sql .= 'JOIN ' . $db->prefix . $tagobj->attachable_table . ' ct ';\n $sql .= 'ON m.id = ct.content_id WHERE (';\n $first = true;", " if (isset($this->params['tags'])) {\n $tags = is_array($this->params['tags']) ? $this->params['tags'] : array($this->params['tags']);\n } elseif (isset($this->config['expTags'])) {\n $tags = $this->config['expTags'];\n } else {\n $tags = array();\n }", " foreach ($tags as $tagid) {\n $sql .= ($first) ? 'exptags_id=' . intval($tagid) : ' OR exptags_id=' . intval($tagid);\n $first = false;\n }\n $sql .= \") AND content_type='\" . $model->classname . \"'\";", " // get the objects and render the template\n $tag_assocs = $db->selectObjectsBySql($sql);\n $records = array();\n foreach ($tag_assocs as $assoc) {\n $records[] = new $modelname($assoc->id);\n }", " assign_to_template(array(\n 'items' => $records\n ));\n }", " /**\n * create an item in this module\n * @deprecated in favor of edit w/o id param\n */\n public function create() {\n $args = array('controller' => $this->params['controller'], 'action' => 'edit');\n //if (!empty($this->params['instance'])) $args['instance'] = $this->params['instance'];\n if (!empty($this->params['src'])) $args['src'] = $this->params['src'];\n redirect_to($args);\n }", " /**\n * edit item in module, also used to copy items\n */\n public function edit() {\n expHistory::set('editable', $this->params);\n $taglist = expTag::getAllTags();\n $modelname = $this->basemodel_name;\n// $record = isset($this->params['id']) ? $this->$modelname->find($this->params['id']) : new $modelname($this->params);\n if (isset($this->params['id'])) {\n if (!isset($this->params['revision_id'])) {\n $record = $this->$modelname->find($this->params['id']);\n } else {\n $currentrecord = $this->$modelname->find($this->params['id']);\n $records = $this->$modelname->find('revisions', $this->$modelname->identifier . '=' . intval($this->params['id']) . ' AND revision_id=' . intval($this->params['revision_id']));\n $record = $records[0];\n $record->current_revision_id = $currentrecord->revision_id;\n }\n } else {\n $record = new $modelname($this->params);\n }\n if (!empty($this->params['copy'])) {\n $record->id = null;\n if (isset($record->sef_url)) $record->sef_url = null;\n }\n assign_to_template(array(\n 'record' => $record,\n// 'table' => $this->$modelname->tablename,\n// 'controller' => $this->params['controller'],\n 'taglist' => $taglist\n ));\n }", " /**\n * merge/move aggregated item into this module\n */\n public function merge() {\n expHistory::set('editable', $this->params);\n $modelname = $this->basemodel_name;\n $record = $this->$modelname->find($this->params['id']);", " $loc = expUnserialize($record->location_data);\n $loc->src = $this->loc->src;\n $record->location_data = serialize($loc);\n// $this->$modelname->update($record);\n $record->update();", " expHistory::back();\n }", " /**\n * update (save) item in module\n */\n public function update() {\n global $db;", " //check for and handle tags\n if (array_key_exists('expTag', $this->params)) {\n if (isset($this->params['id'])) {\n $db->delete('content_expTags', 'content_type=\"' . (!empty($this->params['content_type']) ? $this->params['content_type'] : $this->basemodel_name) . '\" AND content_id=' . $this->params['id']);\n }\n $tags = explode(\",\", trim($this->params['expTag']));\n unset($this->params['expTag']);", " foreach ($tags as $tag) {\n if (!empty($tag)) {\n $tag = strtolower(trim($tag));\n $tag = str_replace(array('\"', \"'\"), \"\", $tag); // strip double and single quotes\n if (!empty($tag)) {\n $expTag = new expTag($tag);\n if (empty($expTag->id))\n $expTag->update(array('title' => $tag));\n $this->params['expTag'][] = $expTag->id;\n }\n }\n }\n }", " //check for and handle cats\n if (array_key_exists('expCat', $this->params) && !empty($this->params['expCat'])) {\n $catid = $this->params['expCat'];\n unset($this->params['expCat']);\n $this->params['expCat'][] = $catid;\n }", " $modelname = $this->basemodel_name;\n $this->$modelname->update($this->params);", " if ($this->isSearchable()) {\n $this->addContentToSearch($this->params);\n }", " // check for auto send facebook status\n if (!empty($this->params['send_status'])) {\n if ($this->classname == 'eventController') {\n facebookController::postEvent(\n array('model' => $modelname, 'id' => $this->params['date_id'], 'src' => $this->loc->src, 'config' => $this->config, 'orig_controller' => expModules::getControllerName($this->classname))\n );\n } else {\n facebookController::postStatus(\n array('model' => $modelname, 'id' => $this->$modelname->id, 'src' => $this->loc->src, 'config' => $this->config, 'orig_controller' => expModules::getControllerName($this->classname))\n );\n }\n }", " // check for auto send tweet\n if (!empty($this->params['send_tweet'])) {\n if ($this->classname == 'eventController') {\n twitterController::postEventTweet(\n array('model' => $modelname, 'id' => $this->params['date_id'], 'src' => $this->loc->src, 'config' => $this->config, 'orig_controller' => expModules::getControllerName($this->classname))\n );\n } else {\n twitterController::postTweet(\n array('model' => $modelname, 'id' => $this->$modelname->id, 'src' => $this->loc->src, 'config' => $this->config, 'orig_controller' => expModules::getControllerName($this->classname))\n );\n }\n }", " // check for eAlerts\n if (!empty($this->params['send_ealerts'])) {\n redirect_to(array('controller' => 'ealert', 'action' => 'send_confirm', 'model' => $modelname, 'id' => $this->$modelname->id, 'src' => $this->loc->src, 'orig_controller' => expModules::getControllerName($this->classname)));\n } else {\n expHistory::back();\n }\n }", " /**\n * delete item in module\n */\n public function delete() {\n $modelname = $this->basemodel_name;\n if (empty($this->params['id'])) {\n flash('error', gt('Missing id for the') . ' ' . $modelname . ' ' . gt('you would like to delete'));\n expHistory::back();\n }", " $obj = new $modelname($this->params['id']);\n $rows = $obj->delete();", " // if this module is searchable lets delete spidered content\n if ($this->isSearchable()) {\n $search = new search();\n// $content = $search->find('first', 'original_id=' . $this->params['id'] . \" AND ref_module='\" . $this->classname . \"'\");\n $content = $search->find('first', 'original_id=' . $this->params['id'] . \" AND ref_module='\" . $this->baseclassname . \"'\");\n if (!empty($content->id)) $content->delete();\n }", " expHistory::back();\n }", " /**\n * rerank items in model\n */\n public function rerank() {\n $modelname = $this->basemodel_name;\n $obj = new $modelname($this->params['id']);\n $obj->rerank($this->params['push']);\n expHistory::back();\n }", " /**\n * display module management view\n */\n public function manage() {\n expHistory::set('manageable', $this->params);", " $page = new expPaginator(array(\n 'model' => $this->basemodel_name,\n 'where' => static::hasSources() ? $this->aggregateWhereClause() : null,\n 'limit' => isset($this->params['limit']) ? $this->params['limit'] : 10,\n 'order' => isset($this->params['order']) ? $this->params['order'] : null,\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->baseclassname,\n 'action' => $this->params['action'],\n 'src' => static::hasSources() == true ? $this->loc->src : null,\n 'columns' => array(\n gt('ID#') => 'id',\n gt('Title') => 'title',\n gt('Body') => 'body'\n ),\n ));", " assign_to_template(array(\n 'page' => $page,\n 'items' => $page->records\n ));\n }", " /**\n * rerank module items, called from ddrerank\n */\n public function manage_ranks() {\n $rank = 1;\n foreach ($this->params['rerank'] as $id) {\n $modelname = $this->params['model'];\n $obj = new $modelname($id);\n $obj->rank = $rank;\n $obj->save(false, true);\n $rank++;\n }", " if (!expJavascript::inAjaxAction())\n redirect_to($this->params['lastpage']);\n }", " /**\n * Configure the module\n */\n public function configure() {\n global $db;", " expHistory::set('editable', $this->params);\n $views = expTemplate::get_config_templates($this, $this->loc);", " // needed for aggregation list\n $pullable_modules = expModules::listInstalledControllers($this->baseclassname, $this->loc);\n $page = new expPaginator(array(\n 'records' => $pullable_modules,\n 'controller' => $this->loc->mod,\n 'action' => $this->params['action'],\n 'order' => isset($this->params['order']) ? $this->params['order'] : 'section',\n 'dir' => isset($this->params['dir']) ? $this->params['dir'] : '',\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'columns' => array(\n gt('Title') => 'title',\n gt('Page') => 'section'\n ),\n ));", "// if (empty($this->params['hcview'])) {\n $containerloc = expCore::makeLocation(expModules::getModuleName($this->loc->mod),$this->loc->src);\n $container = $db->selectObject('container', \"internal='\" . serialize($containerloc) . \"'\");\n if (empty($container)) {\n $container = new stdClass();\n $container->action = 'showall';\n } else {\n $container->internal = unserialize($container->internal);\n }\n if (empty($container->action)) {\n $container->action = 'showall';\n }\n// expSession::clearAllUsersSessionCache('containermodule');", "// $modules_list = expModules::getActiveModulesAndControllersList();\n// foreach ($modules_list as $moduleclass) {\n// $module = new $moduleclass();\n//\n// // Get basic module meta info\n// $mod = new stdClass();\n// $mod->name = $module->name();\n// $mod->author = $module->author();\n// $mod->description = $module->description();\n// if (isset($container->view) && $container->internal->mod == $moduleclass) {\n// $mod->defaultView = $container->view;\n// } else $mod->defaultView = DEFAULT_VIEW;\n//\n// // Get support flags\n// $mod->supportsSources = ($module->hasSources() ? 1 : 0);\n// $mod->supportsViews = ($module->hasViews() ? 1 : 0);\n//\n// // Get a list of views\n// $mod->views = expTemplate::listModuleViews($moduleclass);\n// natsort($mod->views);\n//\n// $modules[$moduleclass] = $mod;\n//// \t\t$mods[$moduleclass] = $module->name();\n// // $mods[$moduleclass] = $moduleclass::name();\n// }", "// array_multisort(array_map('strtolower', $mods), $mods);", " $actions = $this->useractions;\n $mod_views = array();\n if (!empty($actions)) {\n // Language-ize the action names\n foreach ($actions as $key => $value) {\n $actions[$key] = gt($value);\n }\n $mod_views = expTemplate::get_action_views($this->classname, $container->action, $actions[$container->action]);\n if (count($mod_views) < 1) $mod_views[$container->action] = $actions[$container->action] . ' - Default View';\n }", " assign_to_template(array(\n 'container' => $container,\n 'actions' => $actions,\n 'mod_views' => $mod_views,\n ));\n// } else {\n if (!empty($this->params['hcview'])) {\n // this must be a hard-coded module?\n assign_to_template(array(\n 'hcview' => $this->params['hcview'],\n ));\n }", " $expcat = new expCat();\n $cats = $expcat->find('all','module=\"file\"');\n $folders = array();\n $folders[] = 'Root Folder';\n foreach ($cats as $cat) {\n $folders[$cat->id] = $cat->title;\n }", " assign_to_template(array(\n// 'config' => $this->config, //FIXME already assigned in controllertemplate?\n 'page' => $page, // needed for aggregation list\n 'views' => $views,\n 'title' =>static::displayname(),\n 'current_section' => expSession::get('last_section'),\n// 'classname' => $this->classname, //FIXME $controller already assigned baseclassname (short vs long) in controllertemplate?\n 'viewpath' => $this->viewpath,\n 'relative_viewpath' => $this->relative_viewpath,\n 'folders' => $folders,\n ));", " }", " /**\n * save module configuration\n */\n public function saveconfig() {\n global $db;", " // update module title/action/view\n if (!empty($this->params['container_id'])) {\n $container = $db->selectObject('container', \"id=\" . $this->params['container_id']);\n if (!empty($container)) {\n $container->title = $this->params['moduletitle'];\n $container->action = $this->params['actions'];\n $container->view = $this->params['views'];\n $container->is_private = $this->params['is_private'];\n $db->updateObject($container, 'container');\n expSession::clearAllUsersSessionCache('containermodule');\n }\n unset(\n $this->params['container_id'],\n $this->params['moduletitle'],\n $this->params['modcntrol'],\n $this->params['actions'],\n $this->params['views'],\n $this->params['actions'],\n $this->params['is_private']\n );\n }", " // create a new RSS object if enable is checked.\n $params = $this->params;\n if (!empty($this->params['enable_rss'])) {\n $params['title'] = $params['feed_title'];\n unset($params['feed_title']);\n $params['sef_url'] = $params['feed_sef_url'];\n unset($params['feed_sef_url']);\n $rssfeed = new expRss($params);\n $rssfeed->update($params);\n $this->params['feed_sef_url'] = $rssfeed->sef_url;\n } else {\n $rssfeed = new expRss($this->params);\n $params['enable_rss'] = false;\n if (empty($params['advertise']))\n $params['advertise'] = false;\n $params['title'] = $params['feed_title'];\n unset($params['feed_title']);\n $params['sef_url'] = $params['feed_sef_url'];\n unset($params['feed_sef_url']);\n if (!empty($rssfeed->id)) { // do NOT create a new record, only update existing ones\n $rssfeed->update($params);\n $this->params['feed_sef_url'] = $rssfeed->sef_url;\n }\n }", " // create a new eAlerts object if enable is checked.\n if (!empty($this->params['enable_ealerts'])) {\n $ealert = new expeAlerts($this->params);\n $ealert->update($this->params);\n }", " // unset some unneeded params\n unset(\n $this->params['module'],\n $this->params['controller'],\n $this->params['src'],\n $this->params['int'],\n $this->params['id'],\n $this->params['cid'],\n $this->params['action'],\n $this->params['PHPSESSID'],\n $this->params['__utma'],\n $this->params['__utmb'],\n $this->params['__utmc'],\n $this->params['__utmz'],\n $this->params['__utmt'],\n $this->params['__utmli'],\n $this->params['__cfduid']\n );", " // setup and save the config\n $config = new expConfig($this->loc);\n $config->update(array('config' => $this->params));", " flash('message', gt('Configuration updated'));\n expHistory::back();\n }", " /**\n * get the module's items in an rss feed format\n *\n * this function is very general and will most of the time need to be overwritten and customized\n *\n * @return array\n */\n public function getRSSContent($limit = 0) {\n $class = new $this->basemodel_name;\n $items = $class->find('all', $this->aggregateWhereClause(), isset($this->config['order']) ? $this->config['order'] : 'created_at DESC', $limit);", " //Convert the items to rss items\n $rssitems = array();\n foreach ($items as $key => $item) {\n $rss_item = new FeedItem();\n $rss_item->title = expString::convertSmartQuotes($item->title);\n $rss_item->link = $rss_item->guid = makeLink(array('controller' => $this->baseclassname, 'action' => 'show', 'title' => $item->sef_url));\n $rss_item->description = expString::convertSmartQuotes($item->body);\n $rss_item->author = user::getUserById($item->poster)->firstname . ' ' . user::getUserById($item->poster)->lastname;\n $rss_item->authorEmail = user::getEmailById($item->poster);\n// $rss_item->date = isset($item->publish_date) ? date(DATE_RSS, $item->publish_date) : date(DATE_RSS, $item->created_at);\n $rss_item->date = isset($item->publish_date) ? $item->publish_date : $item->created_at;\n if (!empty($item->expCat[0]->title)) $rss_item->category = array($item->expCat[0]->title);\n $comment_count = expCommentController::countComments(array('content_id' => $item->id, 'content_type' => $this->basemodel_name));\n if ($comment_count) {\n $rss_item->comments = makeLink(array('controller' => $this->baseclassname, 'action' => 'show', 'title' => $item->sef_url)) . '#exp-comments';\n// $rss_item->commentsRSS = makeLink(array('controller'=>$this->baseclassname, 'action'=>'show', 'title'=>$item->sef_url)).'#exp-comments';\n $rss_item->commentsCount = $comment_count;\n }\n $rssitems[$key] = $rss_item;", " if ($limit && count($rssitems) >= $limit)\n break;\n }\n return $rssitems;\n }", " /**\n * method to display an rss feed from this module\n */\n public function rss() {\n require_once(BASE . 'external/feedcreator.class.php');\n", " $id = isset($this->params['title']) ? expString::escape($this->params['title']) : (isset($this->params['id']) ? $this->params['id'] : null);", " if (empty($id)) {\n $module = !empty($this->params['module']) ? $this->params['module'] : $this->params['controller'];\n $id = array('module' => $module, 'src' => $this->params['src']);\n }\n $site_rss = new expRss($id);\n if ($site_rss->enable_rss == true && !empty($site_rss->id)) {\n $site_rss->title = empty($site_rss->title) ? gt('RSS for') . ' ' . URL_FULL : $site_rss->title;\n $site_rss->feed_desc = empty($site_rss->feed_desc) ? gt('This is an RSS syndication from') . ' ' . HOSTNAME : $site_rss->feed_desc;\n// if (isset($site_rss->rss_cachetime)) {\n// $ttl = $site_rss->rss_cachetime;\n// }\n if ($site_rss->rss_cachetime == 0) {\n $site_rss->rss_cachetime = 1440;\n }", " if (!empty($site_rss->itunes_cats)) {\n $ic = explode(\";\", $site_rss->itunes_cats);\n $x = 0;\n $itunes_cats = array();\n foreach ($ic as $cat) {\n $cat_sub = explode(\":\", $cat);\n $itunes_cats[$x]->category = $cat_sub[0];\n if (isset($cat_sub[1])) {\n $itunes_cats[$x]->subcategory = $cat_sub[1];\n }\n $x++;\n }\n }", " // NO buffering from here on out or things break unexpectedly. - RAM\n ob_end_clean();", " header('Content-Type: ' . 'application/rss+xml');\n// header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');\n// header('Content-Transfer-Encoding: binary');\n header('Content-Encoding:');\n // IE need specific headers\n if (EXPONENT_USER_BROWSER == 'IE') {\n header('Cache-Control: must-revalidate, post-check=0, pre-check=0');\n header('Pragma: public');\n header('Vary: User-Agent');\n } else {\n header('Pragma: no-cache');\n }", " if ($site_rss->rss_is_podcast) {\n $feed_type = \"PODCAST\";\n } else {\n $feed_type = \"RSS2.0\";\n }\n $feed_cache = BASE . 'tmp/rsscache/' . $site_rss->sef_url . '.xml';", " $rss = new UniversalFeedCreator();\n// if (file_exists(THEME_ABSOLUTE . \"rss/feed.css\")) // custom css style\n// $rss->cssStyleSheet = THEME_RELATIVE . \"rss/feed.css\";\n if (file_exists(THEME_ABSOLUTE . \"rss/feed.xsl\")) // custom xml style\n $rss->xslStyleSheet = THEME_RELATIVE . \"rss/feed.xsl\";\n $rss->useCached($feed_type, $feed_cache, $site_rss->rss_cachetime); // if cache exists output then redirect", " $rss->title = $site_rss->title;\n if (!empty($this->params['type']))\n $rss->title .= ' ' . ucfirst($this->params['type']);\n $rss->description = $site_rss->feed_desc;\n $rss->image = new FeedImage();\n $rss->image->url = !empty($site_rss->expFile['album'][0]) ? $site_rss->expFile['album'][0]->url : URL_FULL . 'themes/' . DISPLAY_THEME . '/images/logo.png';\n $rss->image->title = $site_rss->title;\n $rss->image->link = URL_FULL;\n // $rss->image->width = 64;\n // $rss->image->height = 64;\n $rss->ttl = $site_rss->rss_cachetime;\n $rss->link = URL_FULL;\n $rss->language = LOCALE;\n $rss->syndicationURL = makeLink(array('module'=>$site_rss->module, 'src'=>$site_rss->src));\n if ($site_rss->rss_is_podcast) {\n $rss->itunes = new iTunes();\n $rss->itunes->author = !empty($site_rss->feed_artist) ? $site_rss->feed_artist : ORGANIZATION_NAME;\n $rss->itunes->image = !empty($site_rss->expFile['album'][0]) ? $site_rss->expFile['album'][0]->url :URL_FULL . 'themes/' . DISPLAY_THEME . '/images/logo.png';\n $rss->itunes->summary = $site_rss->feed_desc;\n if (!empty($itunes_cats)) {\n $rss->itunes->category = $itunes_cats[0]->category;\n $rss->itunes->subcategory = $itunes_cats[0]->subcategory;\n }\n //\t\t$rss->itunes->explicit = 0;\n// $rss->itunes->subtitle = $site_rss->title;\n $rss->itunes->subtitle = $site_rss->feed_desc;\n //\t\t$rss->itunes->keywords = 0;\n $rss->itunes->owner_email = SMTP_FROMADDRESS;\n $rss->itunes->owner_name = ORGANIZATION_NAME;\n }", " $pubDate = '';\n $site_rss->params = $this->params;\n foreach ($site_rss->getFeedItems($site_rss->rss_limit) as $item) {\n if ($item->date > $pubDate) {\n $pubDate = $item->date;\n }\n $rss->addItem($item);\n }\n if (!empty($site_rss->rss_limit)) {\n $rss->items = array_slice($rss->items, 0, $site_rss->rss_limit);\n }\n $rss->pubDate = $pubDate;", "// echo $rss->createFeed($feed_type);\n echo $rss->saveFeed($feed_type, $feed_cache, $site_rss->rss_cachetime); // does redirect after updating cache\n } else {\n flash('notice', gt(\"This RSS feed is not available.\"));\n expHistory::back();\n }", " //Read the file out directly\n exit();\n }", " /**\n * download a file attached to item\n */\n public function downloadfile() {\n if (!isset($this->config['allowdownloads']) || $this->config['allowdownloads'] == true) {\n //if ($db->selectObject('content_expFiles', 'content_type=\"'.$this->baseclassname.'\" AND expfiles_id='.$this->params['id']) != null) {\n expFile::download($this->params['id']);\n //}\n } else {\n flash('error', gt('Downloads have not been enabled for this file'));\n expHistory::back();\n }", " }", " /**", " * permission functions to aggregate a module's visible permissions based on add/remove permissions", " *\n * @return array\n */\n public function permissions() {\n //set the permissions array\n $perms = array();\n foreach ($this->permissions as $perm => $name) {\n if (!in_array($perm, $this->remove_permissions)) $perms[$perm] = $name;\n }\n $perms = array_merge($perms, $this->add_permissions);", " return $perms;\n }", " /**\n * permission functions to aggregate a module's permissions based on add/remove and manage permissions\n *\n * @return array\n */\n public function permissions_all() {\n //set the permissions array\n $perms = array();\n foreach ($this->permissions as $perm => $name) {\n if (!in_array($perm, $this->remove_permissions)) $perms[$perm] = $name;\n }\n $perms = array_merge($perms, $this->m_permissions, $this->add_permissions, $this->manage_permissions);", " return $perms;\n }", " // create a psuedo global permission specific to the module; return true grants permission, false continues with other permission checks\n public static function checkPermissions($permission, $location) {\n return false;\n }", " /**\n * get the model(s) associated with this module\n *\n * @return array\n */\n public function getModels() {\n return isset($this->models) ? $this->models : array($this->basemodel_name);\n }", " /**\n * type of items searched in the module\n *\n * @return string\n */\n public function searchName() {\n return static::displayname();\n }", " /**\n * category of items searched in the module\n *\n * @return string\n */\n public function searchCategory() {\n return $this->basemodel_name;\n }", " /**\n * add module items to search index\n *\n * @return int\n */\n public function addContentToSearch() {\n// global $db, $router;\n global $db;", " $count = 0;\n $model = new $this->basemodel_name(null, false, false);\n $where = (!empty($this->params['id'])) ? 'id=' . $this->params['id'] : null;\n $content = $db->selectArrays($model->tablename, $where);\n foreach ($content as $cnt) {\n $origid = $cnt['id'];\n unset($cnt['id']);\n //build the search record and save it.\n// $sql = \"original_id=\" . $origid . \" AND ref_module='\" . $this->classname . \"'\";\n $sql = \"original_id=\" . $origid . \" AND ref_module='\" . $this->baseclassname . \"'\";\n $oldindex = $db->selectObject('search', $sql);\n if (!empty($oldindex)) {\n $search_record = new search($oldindex->id, false, false);\n $search_record->update($cnt);\n } else {\n $search_record = new search($cnt, false, false);\n }", " //build the search record and save it.\n $search_record->original_id = $origid;\n $search_record->posted = empty($cnt['created_at']) ? null : $cnt['created_at'];\n // get the location data for this content\n if (isset($cnt['location_data']))\n $loc = expUnserialize($cnt['location_data']);\n $src = isset($loc->src) ? $loc->src : null;\n if (!empty($cnt['sef_url'])) {\n $link = str_replace(URL_FULL, '', makeLink(array('controller' => $this->baseclassname, 'action' => 'show', 'title' => $cnt['sef_url'])));\n } else {\n $link = str_replace(URL_FULL, '', makeLink(array('controller' => $this->baseclassname, 'action' => 'show', 'id' => $origid, 'src' => $src)));\n }\n//\t if (empty($search_record->title)) $search_record->title = 'Untitled';\n $search_record->view_link = $link;\n// $search_record->ref_module = $this->classname;\n $search_record->ref_module = $this->baseclassname;\n $search_record->category = $this->searchName();\n $search_record->ref_type = $this->searchCategory();\n $search_record->save();\n $count++;\n }", " return $count;\n }", " /**\n * additional check for display of search hit\n *\n * @param $record\n *\n * @return bool\n */\n public static function searchHit($record) {\n return true; // default is to display search hit\n }", " /**\n * remove all module items from search index\n */\n public function delete_search() {\n global $db;\n // remove this modules entries from the search table.\n if ($this->isSearchable()) {\n// $where = \"ref_module='\" . $this->classname . \"' AND location_data='\" . serialize($this->loc) . \"'\";\n $where = \"ref_module='\" . $this->baseclassname . \"' AND location_data='\" . serialize($this->loc) . \"'\";\n// $test = $db->selectObjects('search', $where);\n $db->delete('search', $where);\n }\n }", " /**\n * delete module and all its items for backwards compat with old modules\n *\n * @param $loc\n */\n public function delete_In($loc) {\n $this->delete_instance($loc);\n }", " /**\n * delete module, config, and all its items\n * @param bool $loc\n */\n public function delete_instance($loc = false) {\n $model = new $this->basemodel_name();\n $where = 1;\n if ($loc || static::hasSources())\n $where = \"location_data='\" . serialize($this->loc) . \"'\";\n $items = $model->find('all',$where);\n foreach ($items as $item) {\n $item->delete(); // model should delete attachments and other associated objects\n }\n $cfg = new expConfig($this->loc);\n $cfg->delete();\n }", " /**\n * get the metainfo for this module\n *\n * @return array\n */\n public function metainfo() {\n global $router;", " if (empty($router->params['action'])) return false;", " // figure out what metadata to pass back based on the action we are in.\n $action = $router->params['action'];\n $metainfo = array('title' => '', 'keywords' => '', 'description' => '', 'canonical' => '', 'noindex' => false, 'nofollow' => false);\n $modelname = $this->basemodel_name;", " switch ($action) {\n case 'showall':\n $metainfo['title'] = gt(\"Showing\") . \" \" . static::displayname() . ' - ' . SITE_TITLE;\n $metainfo['keywords'] = SITE_KEYWORDS;\n $metainfo['description'] = SITE_DESCRIPTION;\n break;\n case 'show':\n case 'showByTitle':\n // look up the record.\n if (isset($router->params['id']) || isset($router->params['title'])) {\n $lookup = isset($router->params['id']) ? $router->params['id'] : $router->params['title'];\n $object = new $modelname($lookup);\n // set the meta info\n if (!empty($object)) {\n if (!empty($object->body)) {\n $desc = str_replace('\"',\"'\",expString::summarize($object->body,'html','para'));\n } else {\n $desc = SITE_DESCRIPTION;\n }\n if (!empty($object->expTag)) {\n $keyw = '';\n foreach ($object->expTag as $tag) {\n if (!empty($keyw)) $keyw .= ', ';\n $keyw .= $tag->title;\n }\n } else {\n $keyw = SITE_KEYWORDS;\n }\n $metainfo['title'] = empty($object->meta_title) ? $object->title : $object->meta_title;\n $metainfo['keywords'] = empty($object->meta_keywords) ? $keyw : $object->meta_keywords;\n $metainfo['description'] = empty($object->meta_description) ? $desc : $object->meta_description;\n// $metainfo['canonical'] = empty($object->canonical) ? URL_FULL.substr($router->sefPath, 1) : $object->canonical;\n $metainfo['canonical'] = empty($object->canonical) ? $router->plainPath() : $object->canonical;\n $metainfo['noindex'] = empty($object->meta_noindex) ? false : $object->meta_noindex;\n $metainfo['nofollow'] = empty($object->meta_nofollow) ? false : $object->meta_nofollow;\n $metainfo['rich'] = $this->meta_rich($router->params, $object);\n $metainfo['fb'] = $this->meta_fb($router->params, $object, $metainfo['canonical']);\n $metainfo['tw'] = $this->meta_tw($router->params, $object, $metainfo['canonical']);\n }\n break;\n }\n default:\n //check for a function in the controller called 'action'_meta and use it if so\n $functionName = $action . \"_meta\";\n $mod = new $this->classname;\n if (method_exists($mod, $functionName)) {\n $metainfo = $mod->$functionName($router->params);\n } else {\n $metainfo['title'] = static::displayname() . \" - \" . SITE_TITLE;\n $metainfo['keywords'] = SITE_KEYWORDS;\n $metainfo['description'] = SITE_DESCRIPTION;\n// $metainfo['canonical'] = URL_FULL.substr($router->sefPath, 1);\n $metainfo['canonical'] = $router->plainPath();\n }\n }", " return $metainfo;\n }", " /**\n * Returns rich snippet PageMap meta data\n *\n * @param $request\n * @param $object\n *\n * @return null\n */\n public function meta_rich($request, $object) {\n return null;\n }", " /**\n * Returns Facebook og: meta data\n *\n * @param $request\n * @param $object\n *\n * @return array\n */\n public function meta_fb($request, $object, $canonical) {\n return array();\n }", " /**\n * Returns Twitter twitter: meta data\n *\n * @param $request\n * @param $object\n *\n * @return array\n */\n public function meta_tw($request, $object, $canonical) {\n return array();\n }", " /**\n * action specific metainfo\n *\n * @param $request\n * @return array\n */\n public function showall_by_tags_meta($request) {\n global $router;", " // look up the record.\n if (isset($request['tag'])) {\n $metainfo = array('title' => '', 'keywords' => '', 'description' => '', 'canonical' => '', 'noindex' => false, 'nofollow' => false);\n $tag = $request['tag'];\n // set the meta info\n $metainfo['title'] = gt('Showing all') . ' ' . ucwords($this->basemodel_name) . ' ' . gt('tagged as') . ' ' . $tag;\n// $metainfo['keywords'] = empty($object->meta_keywords) ? SITE_KEYWORDS : $object->meta_keywords; //FIXME $object not set\n $metainfo['keywords'] = $request['tag'];\n// $metainfo['description'] = empty($object->meta_description) ? SITE_DESCRIPTION : $object->meta_description; //FIXME $object not set\n $metainfo['description'] = SITE_DESCRIPTION;\n// $metainfo['canonical'] = empty($object->canonical) ? URL_FULL . substr($router->sefPath, 1) : $object->canonical; //FIXME $object not set\n// $metainfo['canonical'] = URL_FULL . substr($router->sefPath, 1);\n $metainfo['canonical'] = $router->plainPath();\n return $metainfo;\n }\n return null;\n }", " /**\n * action specific metainfo\n *\n * @param $request\n * @return array\n */\n public function showall_by_date_meta($request) {\n global $router;", " // look up the record.\n if (isset($request['month'])) {\n $metainfo = array('title' => '', 'keywords' => '', 'description' => '', 'canonical' => '', 'noindex' => false, 'nofollow' => false);\n $mk = mktime(0, 0, 0, $request['month'], 01, $request['year']);\n $ts = strftime('%B, %Y', $mk);\n // set the meta info\n $metainfo['title'] = gt('Showing all') . ' ' . ucwords($this->basemodel_name) . ' ' . gt('written in') . ' ' . $ts;\n// $metainfo['keywords'] = empty($object->meta_keywords) ? SITE_KEYWORDS : $object->meta_keywords; //FIXME $object not set\n $metainfo['keywords'] = SITE_KEYWORDS;\n// $metainfo['description'] = empty($object->meta_description) ? SITE_DESCRIPTION : $object->meta_description; //FIXME $object not set\n $metainfo['description'] = SITE_DESCRIPTION;\n// $metainfo['canonical'] = empty($object->canonical) ? URL_FULL . substr($router->sefPath, 1) : $object->canonical; //FIXME $object not set\n// $metainfo['canonical'] = URL_FULL . substr($router->sefPath, 1);\n $metainfo['canonical'] = $router->plainPath();\n return $metainfo;\n }\n return null;\n }", " /**\n * approve module item\n */\n public function approve() {\n $modelname = $this->basemodel_name;\n $lookup = isset($this->params['id']) ? $this->params['id'] : $this->params['title'];\n $object = new $modelname($lookup);\n $object->approved = true;\n $object->save(false, true); // we don't want to add this approval as a new revision\n expHistory::back();\n }", " /**\n * The aggregateWhereClause function creates a sql where clause which also includes aggregated module content\n *\n * @param string $type\n *\n * @return string\n */\n public function aggregateWhereClause($type='') {\n global $user;", " $sql = '';", " if (empty($this->config['add_source']) && !static::hasSources()) {\n return $sql;\n }", " if (!empty($this->config['aggregate'])) $sql .= '(';", " $sql .= \"location_data ='\" . serialize($this->loc) . \"'\";", " if (!empty($this->config['aggregate'])) {\n foreach ($this->config['aggregate'] as $src) {\n $loc = expCore::makeLocation($this->baseclassname, $src);\n $sql .= \" OR location_data ='\" . serialize($loc) . \"'\";\n }", " $sql .= ')';\n }\n $model = $this->basemodel_name;\n if (ENABLE_WORKFLOW && $this->$model->needs_approval) {\n if ($user->id) {\n $sql .= ' AND (approved=1 OR poster=' . $user->id . ' OR editor=' . $user->id . ')';\n } else {\n $sql .= ' AND approved=1';\n }\n }", " return $sql;\n }", "}", "?>" ]
[ 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, 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, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [1156, 821, 538, 1298, 1110, 656, 639, 481, 1974, 221, 1264, 168, 235, 25, 598, 133, 55, 383, 63, 58, 352, 125, 394, 59, 2152, 117, 137, 259, 537, 2235, 33, 72, 1773, 250, 679, 739, 285, 1941, 540, 62, 528, 25, 1290, 256, 199, 122, 41, 99, 2020, 355, 147, 129, 1499], "buggy_code_start_loc": [44, 288, 107, 354, 1102, 26, 194, 37, 244, 25, 27, 24, 31, 25, 27, 50, 27, 27, 25, 44, 26, 25, 29, 34, 25, 24, 24, 25, 25, 27, 26, 68, 1, 54, 26, 428, 41, 29, 44, 55, 24, 24, 1, 28, 30, 25, 29, 25, 25, 29, 146, 128, 27], "filenames": ["framework/core/controllers/expController.php", "framework/core/expFramework.php", "framework/core/models/expRecord.php", "framework/core/subsystems/database/mysqli.php", "framework/core/subsystems/expDatabase.php", "framework/core/subsystems/expPaginator.php", "framework/core/subsystems/expSettings.php", "framework/core/subsystems/expString.php", "framework/core/subsystems/expTheme.php", "framework/modules/addressbook/controllers/addressController.php", "framework/modules/administration/controllers/administrationController.php", "framework/modules/banners/controllers/bannerController.php", "framework/modules/blog/controllers/blogController.php", "framework/modules/core/controllers/expCatController.php", "framework/modules/core/controllers/expCommentController.php", "framework/modules/core/controllers/expDefinableFieldController.php", "framework/modules/core/controllers/expHTMLEditorController.php", "framework/modules/core/controllers/expSimpleNoteController.php", "framework/modules/core/controllers/expTagController.php", "framework/modules/eaas/controllers/eaasController.php", "framework/modules/ealerts/controllers/ealertController.php", "framework/modules/ecommerce/controllers/billingController.php", "framework/modules/ecommerce/controllers/ecomconfigController.php", "framework/modules/ecommerce/controllers/eventregistrationController.php", "framework/modules/ecommerce/controllers/orderController.php", "framework/modules/ecommerce/controllers/order_statusController.php", "framework/modules/ecommerce/controllers/purchaseOrderController.php", "framework/modules/ecommerce/controllers/shippingController.php", "framework/modules/ecommerce/controllers/storeCategoryController.php", "framework/modules/ecommerce/controllers/storeController.php", "framework/modules/ecommerce/controllers/taxController.php", "framework/modules/ecommerce/products/models/donation.php", "framework/modules/events/controllers/eventController.php", "framework/modules/events/models/event.php", "framework/modules/file/controllers/fileController.php", "framework/modules/file/models/expFile.php", "framework/modules/filedownloads/controllers/filedownloadController.php", "framework/modules/forms/controllers/formsController.php", "framework/modules/help/controllers/helpController.php", "framework/modules/help/models/help_version.php", "framework/modules/importexport/controllers/importexportController.php", "framework/modules/migration/controllers/migrationController.php", "framework/modules/navigation/controllers/navigationController.php", "framework/modules/news/controllers/newsController.php", "framework/modules/photoalbum/controllers/photosController.php", "framework/modules/pixidou/controllers/pixidouController.php", "framework/modules/portfolio/controllers/portfolioController.php", "framework/modules/recyclebin/controllers/recyclebinController.php", "framework/modules/report/controllers/reportController.php", "framework/modules/search/controllers/searchController.php", "framework/modules/simplepoll/controllers/simplePollController.php", "framework/modules/users/controllers/loginController.php", "framework/modules/users/controllers/usersController.php"], "fixing_code_end_loc": [1183, 823, 543, 1298, 1110, 664, 643, 481, 1977, 221, 1263, 171, 234, 29, 599, 133, 59, 383, 69, 52, 358, 126, 397, 57, 2154, 120, 130, 262, 538, 2232, 25, 72, 1774, 255, 685, 741, 285, 1949, 541, 62, 535, 25, 1306, 259, 202, 121, 40, 102, 2025, 356, 147, 129, 1513], "fixing_code_start_loc": [44, 288, 107, 354, 1102, 26, 194, 37, 244, 25, 27, 25, 32, 26, 27, 50, 27, 27, 26, 43, 26, 25, 29, 33, 25, 25, 25, 25, 25, 26, 25, 68, 1, 55, 25, 428, 41, 30, 44, 55, 25, 24, 1, 29, 31, 24, 30, 25, 25, 29, 146, 128, 27], "message": "Exponent CMS version 2.3.9 suffers from a Object Injection vulnerability in framework/modules/core/controllers/expTagController.php related to change_tags.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:exponentcms:exponent_cms:2.3.9:*:*:*:*:*:*:*", "matchCriteriaId": "12FDDF33-2B21-4F8A-AB9A-01857197E810", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Exponent CMS version 2.3.9 suffers from a Object Injection vulnerability in framework/modules/core/controllers/expTagController.php related to change_tags."}, {"lang": "es", "value": "Existe una vulnerabilidad en Exponent CMS versi\u00f3n 2.3.9, sufre de una vulnerabilidad de Inyecci\u00f3n de Objeto en el archivo framework/modules/core/controllers/expTagController.php asociado con el par\u00e1metro change_tags."}], "evaluatorComment": null, "id": "CVE-2016-8900", "lastModified": "2019-05-28T16:01:48.990", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-05-24T17:29:00.913", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Exploit", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2016/09/30/5"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/exponentcms/exponent-cms/commit/fdafb5ec97838e4edbd685f587f28d3174ebb3db"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/exponentcms/exponent-cms/commit/fdafb5ec97838e4edbd685f587f28d3174ebb3db"}, "type": "CWE-74"}
197
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n##################################################\n#\n# Copyright (c) 2004-2016 OIC Group, Inc.\n#\n# This file is part of Exponent\n#\n# Exponent is free software; you can redistribute\n# it and/or modify it under the terms of the GNU\n# General Public License as published by the Free\n# Software Foundation; either version 2 of the\n# License, or (at your option) any later version.\n#\n# GPL: http://www.gnu.org/licenses/gpl.txt\n#\n##################################################", "//Global Variables", "// expModules\n/**\n * Stores the list of available/active controllers\n * @var array $available_controllers\n * @name $available_controllers\n */\n$available_controllers = array();", "// expTheme\n/**\n * Stores the theme validation flags\n * @var array $validateTheme does theme have header & footer\n * @name $validateTheme\n */\n$validateTheme = array(\"headerinfo\"=>false,\"footerinfo\"=>false);\n/**\n * Stores the list of module scopes\n * @var array $module_scope\n * @name $module_scope\n */\n$module_scope = array();\n/**\n * Stores the theme framework\n * @var integer $framework\n * @name $framework\n */\n$framework = null;", "// expLang\n/**\n * Stores the list of language strings for the current language\n * @var array $cur_lang\n * @name $cur_lang\n */\n$cur_lang = array();\n/**\n * Stores the list of language strings for the default language (English - US)\n * @var array $default_lang\n * @name $default_lang\n */\n$default_lang = array();\n/**\n * Stores the list of language specific strings specific to the theme\n * @var array $custom_lang\n * @name $custom_lang\n */\n$custom_lang = array();\n/**\n * Stores the name of the default language file\n * @var array $default_lang_file\n * @name $default_lang_file\n */\n$default_lang_file = '';\n/**\n * Stores the name of the language file to be created\n * @var array $target_lang_file\n * @name $target_lang_file\n */\n$target_lang_file = '';", "// expDatabase\n/**\n * Stores the exponent database object\n * @var \\database $db the exponent database object\n * @name $db\n */\n$db = new stdClass();", "// expHistory\n/**\n * Stores the browsing history object\n * @var expHistory $history\n * @name $history\n */\n$history = new stdClass();", "// user model\n/**\n * Stores the current user object\n * @var user $user\n * @name $user\n */\n$user = new stdClass();\n/**\n * This global array belongs exclusively to the user model, and is used to cache\n * users as they are retrieved, to help out with performance when doing a lot of\n * work with user accounts and profile information.\n * @var array $SYS_USERS_CACHE\n * @name $SYS_USERS_CACHE\n */\n$SYS_USERS_CACHE = array();", "// expRouter\n/**\n * Stores the routing/link/url object\n * @var expRouter $router\n * @name $router\n */\n$router = new stdClass();\n/**\n * Stores the routing/link/url object\n * @var section $sectionObj\n * @name $sectionObj\n */\n$sectionObj = new stdClass();", "// expCore\n/**\n * Stores the list of sections/pages for the site\n * @var array $sections\n * @name $sections\n */\n$sections = array();\n// expPermissions\n/**\n * Stores the permission data for the current user.\n * This should not be modified by anything outside of the permissions subsystem.\n * @var array $exponent_permissions_r\n * @name $exponent_permissions_r\n */\n$exponent_permissions_r = array();", "// expJavascript\n/**\n * Stores the page's inline javascript code\n * @var array $js2foot\n * @name $js2foot\n */\n$js2foot = array();\n/**\n * Stores the yui3 javascript files list\n * @var array $yui3js\n * @name $yui3js\n */\n$yui3js = false;\n/**\n * Stores the jquery javascript files list\n * @var array $jqueryjs\n * @name $jqueryjs\n */\n$jqueryjs = array();\n/**\n * Stores the twitter bootstrap javascript file list\n * @var array $bootstrapjs\n * @name $bootstrapjs\n */\n$bootstrapjs = array();\n/**\n * Stores the 'other' javascript files list\n * @var array $expJS\n * @name $expJS\n */\n$expJS = array();", "// expCSS\n/**\n * Stores the user's less global variables\n * @var array $less_vars\n * @name $less_vars\n */\n$less_vars = array();\n/**\n * Stores the user's css files to load first\n * @var array $css_primer\n * @name $css_primer\n */\n$css_primer = array();\n/**\n * Stores the user's css core/system files\n * @var array $css_core\n * @name $css_core\n */\n$css_core = array();\n/**\n * Stores the user's css files\n * @var array $css_links\n * @name $css_links\n */\n$css_links = array();\n/**\n * Stores the user's css files\n * @var array $css_theme\n * @name $css_theme\n */\n$css_theme = array();\n/**\n * Stores the user's css files\n * @var array $css_inline\n * @name $css_inline\n */\n$css_inline = array();\n/**\n * Stores the user's css files\n * @var array $head_config\n * @name $head_config\n */\n$head_config = array();\n/**\n * Stores the user's css files\n * @var string $jsForHead\n * @name $jsForHead\n */\n$jsForHead = \"\";\n/**\n * Stores the user's css files\n * @var string $cssForHead\n * @name $cssForHead\n */\n$cssForHead = \"\";", "// expTemplate\n/**\n * Stores the global template\n * @var \\basetemplate $template\n * @name $template\n */\n$template = null;", "// expTimer\n/**\n * Stores the timer\n * @var expTimer $timer\n * @name $timer\n */\n$timer = null;", "// e-commerce\n/**\n * Stores the order\n * @var \\order $order\n * @name $order\n */\n$order = null;", "/**\n * Main module action/display logic/routine; initializes/checks controller before calling action/method\n *\n * @param array $parms\n * @return bool|mixed|string\n */\nfunction renderAction(array $parms=array()) {\n global $user, $db;", " //Get some info about the controller\n// $baseControllerName = expModules::getControllerName($parms['controller']);\n $fullControllerName = expModules::getControllerClassName($parms['controller']);\n if (expModules::controllerExists($fullControllerName)) {\n $controllerClass = new ReflectionClass($fullControllerName);\n } else {\n return sprintf(gt('The module \"%s\" was not found in the system'), $parms['controller']);\n }", " if (isset($parms['view'])) $parms['view'] = urldecode($parms['view']);\n // Figure out the action to use...if the specified action doesn't exist then we look for the showall action.\n if ($controllerClass->hasMethod($parms['action'])) {\n $action = $parms['action'];\n /* TODO: Not sure if we need to check for private methods to be here. FJD\n\t\t$meth = $controllerClass->getMethod($action);\n if ($meth->isPrivate()) expQueue::flashAndFlow('error', gt('The requested action could not be performed: Action not found'));*/\n } elseif ($controllerClass->hasMethod('showall')) {\n $parms['action'] = 'showall';\n $action = 'showall';\n } else {\n expQueue::flashAndFlow('error', gt('The requested action could not be performed: Action not found'));\n }", " // initialize the controller.\n $src = isset($parms['src']) ? $parms['src'] : null;", " $controller = new $fullControllerName($src, $parms); \n ", " //Set up the correct template to use for this action\n global $template;\n $view = !empty($parms['view']) ? $parms['view'] : $action;\n $template = expTemplate::get_template_for_action($controller, $view, $controller->loc);", " ", " //setup default model(s) for this controller's actions to use\n foreach ($controller->getModels() as $model) {\n $controller->$model = new $model(null,false,false); //added null,false,false to reduce unnecessary queries. FJD\n // flag for needing approval check\n if ($controller->$model->supports_revisions && ENABLE_WORKFLOW) {\n $uilevel = 99;\n if (expSession::exists(\"uilevel\")) $uilevel = expSession::get(\"uilevel\");\n if (!expPermissions::check('approve', $controller->loc)) {\n $controller->$model->needs_approval = true;\n } elseif (isset($uilevel) && $uilevel == UILEVEL_PREVIEW) {\n $controller->$model->needs_approval = true;\n }\n }\n }", "// FIXME this is now handled by the template class during get_template_for_action since it only sets template variables\n // have the controller assign knowledge about itself to the template.\n // this has to be done after the controller gets the template for its actions\n// $controller->moduleSelfAwareness();", " //if this controller is being called by a container then we should have a module title.\n if (isset($parms['moduletitle'])) {\n $template->assign('moduletitle', $parms['moduletitle']);\n } else {\n $title = new stdClass();\n $title->mod = $controller->loc->mod;\n $title->src = $controller->loc->src;\n $title->int = '';\n $template->assign('moduletitle', $db->selectValue('container', 'title', \"internal='\".serialize($title).\"'\"));\n }", " // check the perms for this action", " $perms = $controller->permissions();\n ", " // we have to treat the update permission a little different..it's tied to the create/edit\n // permissions. Really the only way this will fail will be if someone bypasses the perm check\n // on the edit form somehow..like a hacker trying to bypass the form and just submit straight to\n // the action. To safeguard, we'll catch if the action is update and change it either to create or\n // edit depending on whether an id param is passed to. that should be sufficient.", " $common_action = null;\n //FIXME do we also need to account for actions with camelcase action/perm such as editItem ???\n if ($parms['action'] == 'update') {", " $perm_action = (!isset($parms['id']) || $parms['id'] == 0) ? 'create' : 'edit';", " } elseif ($parms['action'] == 'edit' && (!isset($parms['id']) || $parms['id'] == 0)) {", " $perm_action = 'create';\n } elseif ($parms['action'] == 'saveconfig') {\n $perm_action = 'configure';\n } else {", " // action convention for controllers that manage more than one model (datatype). \n // if you preface the name action name with a common crud action name we can check perms on \n // it with the developer needing to specify any...better safe than sorry.\n // i.e if the action is edit_mymodel it will be checked against the edit permission\n if (stristr($parms['action'], '_')) $parts = explode(\"_\", $parms['action']);\n $common_action = isset($parts[0]) ? $parts[0] : null;", " $perm_action = $parms['action'];\n }", " // Here is where we check for ownership of an item and 'create' perm\n if (($parms['action'] == 'edit' || $parms['action'] == 'update' || $parms['action'] == 'delete' ||\n $common_action == 'edit' || $common_action == 'update' || $common_action == 'delete') && !empty($parms['id'])) {\n $theaction = !empty($common_action) ? $common_action : $parms['action'];\n $owner = $db->selectValue($model, 'poster', 'id=' . $parms['id']);\n if ($owner == $user->id && !expPermissions::check($theaction, $controller->loc) && expPermissions::check('create', $controller->loc)) {\n $perm_action = 'create';\n }\n }", " if (!DISABLE_PRIVACY) {\n // check to see if it's on a private page and we shouldn't see it\n if ($perm_action == 'showall' || $perm_action == 'show' || $perm_action == 'downloadfile' || $common_action == 'showall' || $common_action == 'show' || $common_action == 'downloadfile') {\n $loc = null;\n if (!empty($parms['src'])) {\n $loc = expCore::makeLocation($parms['controller'], $parms['src']);\n } elseif (!empty($parms['id']) || !empty($parms['title']) || !empty($parms['sef_url'])) {\n if (!empty($parms['id'])) {\n $record = new $controller->basemodel_name($parms['id']);\n } elseif (!empty($parms['title'])) {\n $record = new $controller->basemodel_name($parms['title']);\n } elseif (!empty($parms['sef_url'])) {\n $record = new $controller->basemodel_name($parms['sef_url']);\n }\n if (!empty($record->location_data)) $loc = expUnserialize($record->location_data);\n }\n if (!empty($loc)) {\n $section = new section();\n $sectionref = new sectionref();\n $container = new container();\n $secref = $sectionref->find('first',\"module='\".$parms['controller'].\"' AND source='\" . $loc->src . \"'\");\n if (!empty($secref->section)) {\n $page = $section->find('first','id=' . $secref->section); // only one page can have the section id#\n $module = $container->find('first',\"internal='\" . serialize($loc) . \"'\"); // only one container can have the internal == location\n if ($page !== null && $module !== null && !empty($page->id) && (empty($page->public) || !empty($module->is_private))) {\n // we've found the page and module/container and it's either a private page or private module\n if (!expPermissions::check('view',expCore::makeLocation('navigation', $page->id))) {\n if (expTheme::inAction()) {\n flash('error', gt(\"You don't have permission to view that item\"));\n notfoundController::handle_not_authorized();\n expHistory::returnTo('viewable');\n } else {\n return false;\n }\n }\n }\n }\n }\n }\n }", " //FIXME? if the assoc $perm doesn't exist, the 'action' will ALWAYS be allowed, e.g., default is to allow action\n if (array_key_exists($perm_action, $perms)) {\n if (!expPermissions::check($perm_action, $controller->loc)) {\n if (expTheme::inAction()) {\n flash('error', gt(\"You don't have permission to\").\" \".$perms[$perm_action]);\n notfoundController::handle_not_authorized();\n expHistory::returnTo('viewable');\n } else {\n return false;\n }\n }\n } elseif (array_key_exists($common_action, $perms)) {\n if (!expPermissions::check($common_action, $controller->loc)) {\n if (expTheme::inAction()) {\n flash('error', gt(\"You don't have permission to\").\" \".$perms[$common_action]);\n notfoundController::handle_not_authorized();\n expHistory::returnTo('viewable');\n } else {\n return false;\n }\n }\n } elseif (array_key_exists($perm_action, $controller->requires_login)) {\n // check if the action requires the user to at least be logged in\n if (!$user->isLoggedIn()) {", " $msg = empty($controller->requires_login[$perm_action]) ? gt(\"You must be logged in to perform this action\") : $controller->requires_login[$perm_action];", " flash('error', $msg);\n notfoundController::handle_not_authorized();\n expHistory::redirecto_login();\n }\n } elseif (array_key_exists($common_action, $controller->requires_login)) {\n // check if the action requires the user to at least be logged in\n if (!$user->isLoggedIn()) {", " $msg = empty($controller->requires_login[$common_action]) ? gt(\"You must be logged in to perform this action\") : $controller->requires_login[$common_action];", " flash('error', $msg);\n notfoundController::handle_not_authorized();\n expHistory::redirecto_login();\n }", " } \n ", " // register this controllers permissions to the view for in view perm checks\n $template->register_permissions(array_keys($perms), $controller->loc);", " ", " // globalizing $user inside all templates\n $template->assign('user', $user);", " // lastly, run the action which can also override the above assignments\n $controller->$action();", " if (empty($parms['no_output'])) {\n $template->output();\n } else {\n $html = $template->render();\n return $html;\n }\n}", "function hotspot($source = null) {\n if (!empty($source)) {\n global $sectionObj;", "\t //FIXME there is NO 'page' object and section has no _construct method\n $page = new section($sectionObj->id);\n $modules = $page->getModulesBySource($source); //FIXME there is no getModulesBySource method anywhere\n //eDebug($modules);exit();", " foreach ($modules as $module) {\n renderAction(array('controller'=>$module->type, 'action'=>$module->action, 'instance'=>$module->id));\n }\n }\n}", "function makeLink($params=array(), $secure=false) {\n global $router;", " if(!is_array($params) || count($params) == 0) return false;\n $secure = empty($secure) ? false : true;\n return $router->makeLink($params, false, $secure);\n}", "function redirect_to($params=array(), $secure=false) {\n global $router;", " $secure = empty($secure) ? false : true;\n $link = (!is_array($params)) ? $params : $router->makeLink($params, false, $secure);\n header(\"Location: \" . $link);\n exit();", "} ", "\nfunction flash($name, $msg) {\n expQueue::flash($name, $msg);\n}", "function flashAndFlow($name, $msg) {\n expQueue::flashAndFlow($name, $msg);\n}", "/**\n * Display the message queue\n *\n * @param null $name\n * @return bool|mixed|string\n */\nfunction show_msg_queue($name=null) {\n return expQueue::show($name);\n}", "/**\n * Assign a variable to the current template\n *\n * @param array $vars\n * @return bool\n */\nfunction assign_to_template(array $vars=array()) {\n global $template;", " ", " if (empty($template) || count($vars) == 0) return false;\n foreach ($vars as $key=>$val) {\n $template->assign($key, $val);\n }\n}", "function get_model_for_controller($controller_name) {\n //FIXME this works by making assumptions\n $start_pos = stripos($controller_name, 'controller');\n if ($start_pos === false) {\n return false;\n } else {\n return substr($controller_name, 0, $start_pos);\n }\n}", "/**\n * @deprecated 2.3.3 moved to expTemplate subsystem\n */\nfunction get_common_template($view, $loc, $controllername='') {\n return expTemplate::get_common_template($view, $loc, $controllername);", " $controller = new stdClass();\n $controller->baseclassname = empty($controllername) ? 'common' : $controllername;\n $controller->loc = $loc;", " ", " $themepath = BASE . 'themes/' . DISPLAY_THEME . '/modules/common/views/' . $controllername . '/' . $view . '.tpl';\n $basenewuipath = BASE . 'framework/modules/common/views/' . $controllername . '/' . $view . '.newui.tpl';\n $basepath = BASE . 'framework/modules/common/views/' . $controllername . '/' . $view . '.tpl';", " if (bs(true)) {\n $basebstrap3path = BASE . 'framework/modules/common/views/' . $controllername . '/' . $view . '.bootstrap3.tpl';\n $basebstrappath = BASE . 'framework/modules/common/views/' . $controllername . '/' . $view . '.bootstrap.tpl';\n if (file_exists($themepath)) {\n return new controllertemplate($controller, $themepath);\n } elseif (bs3(true) && file_exists($basebstrap3path)) {\n return new controllertemplate($controller, $basebstrap3path);\n } elseif (file_exists($basebstrappath)) {\n return new controllertemplate($controller, $basebstrappath);\n } elseif(newui() && file_exists($basenewuipath)) { //FIXME is this the correct sequence spot?\n return new controllertemplate($controller,$basenewuipath);\n } elseif (file_exists($basepath)) {\n return new controllertemplate($controller, $basepath);\n } else {\n return new controllertemplate($controller, BASE.'framework/modules/common/views/scaffold/blank.tpl');\n }\n } else {\n if (file_exists($themepath)) {\n return new controllertemplate($controller,$themepath);\n } elseif (newui() && file_exists($basenewuipath)) {\n return new controllertemplate($controller,$basenewuipath);\n } elseif(file_exists($basepath)) {\n return new controllertemplate($controller,$basepath);\n } else {\n return new controllertemplate($controller, BASE.'framework/modules/common/views/scaffold/blank.tpl');\n }\n }\n}", "/**\n * @deprecated 2.3.3 moved to expTemplate subsystem\n */\nfunction get_config_templates($controller, $loc) {\n return expTemplate::get_config_templates($controller, $loc);", "// global $db;", " ", " // set paths we will search in for the view\n $commonpaths = array(\n BASE.'framework/modules/common/views/configure',\n BASE.'themes/'.DISPLAY_THEME.'/modules/common/views/configure',\n );", " ", " $modpaths = array(\n $controller->viewpath.'/configure',\n\t BASE.'themes/'.DISPLAY_THEME.'/modules/'.$controller->relative_viewpath.'/configure'\n );", " \n // get the common configuration files ", " $common_views = expTemplate::find_config_views($commonpaths, $controller->remove_configs);\n foreach ($common_views as $key=>$value) {\n $common_views[$key]['name'] = gt($value['name']);\n }\n $moduleconfig = array();\n if (!empty($common_views['module'])) $moduleconfig['module'] = $common_views['module'];\n unset($common_views['module']);", " // get the config views for the module\n $module_views = expTemplate::find_config_views($modpaths);\n foreach ($module_views as $key=>$value) {\n $module_views[$key]['name'] = gt($value['name']);\n }\n", " // look for a config form for this module's current view ", "// $controller->loc->mod = expModules::getControllerClassName($controller->loc->mod);\n //check to see if hcview was passed along, indicating a hard-coded module\n// if (!empty($controller->params['hcview'])) {\n// $viewname = $controller->params['hcview'];\n// } else {\n// $viewname = $db->selectValue('container', 'view', \"internal='\".serialize($controller->loc).\"'\");\n// }\n// $viewconfig = $viewname.'.config';\n// foreach ($modpaths as $path) {\n// if (file_exists($path.'/'.$viewconfig)) {\n// $fileparts = explode('_', $viewname);\n// if ($fileparts[0]=='show'||$fileparts[0]=='showall') array_shift($fileparts);\n// $module_views[$viewname]['name'] = ucwords(implode(' ', $fileparts)).' '.gt('View Configuration');\n// $module_views[$viewname]['file'] =$path.'/'.$viewconfig;\n// }\n// }", " ", " // sort the views highest to lowest by filename\n // we are reverse sorting now so our array merge\n // will overwrite property..we will run array_reverse\n // when we're finished to get them back in the right order\n krsort($common_views);\n krsort($module_views);", " if (!empty($moduleconfig)) $common_views = array_merge($common_views, $moduleconfig);\n $views = array_merge($common_views, $module_views);\n $views = array_reverse($views);", " return $views;\n}", "/**\n * @deprecated 2.3.3 moved to expTemplate subsystem\n */\nfunction find_config_views($paths=array(), $excludes=array()) {\n return expTemplate::find_config_views($paths, $excludes);", " $views = array();\n foreach ($paths as $path) {\n if (is_readable($path)) {\n $dh = opendir($path);\n while (($file = readdir($dh)) !== false) {\n if (is_readable($path.'/'.$file) && substr($file, -4) == '.tpl' && substr($file, -14) != '.bootstrap.tpl' && substr($file, -15) != '.bootstrap3.tpl' && substr($file, -10) != '.newui.tpl') {\n $filename = substr($file, 0, -4);\n if (!in_array($filename, $excludes)) {\n $fileparts = explode('_', $filename);\n $views[$filename]['name'] = ucwords(implode(' ', $fileparts));\n $views[$filename]['file'] = $path.'/'.$file;\n if ((bs(true)) && file_exists($path.'/'.$filename.'.bootstrap.tpl')) {\n $views[$filename]['file'] = $path . '/' . $filename . '.bootstrap.tpl';\n }\n if (bs3() && file_exists($path.'/'.$filename.'.bootstrap3.tpl')) {\n $views[$filename]['file'] = $path.'/'.$filename.'.bootstrap3.tpl';\n }\n if (newui() && file_exists($path.'/'.$filename.'.newui.tpl')) { //FIXME newui take priority\n $views[$filename]['file'] = $path.'/'.$filename.'.newui.tpl';\n }\n }\n }\n }\n }\n }", " ", " return $views;\n}", "/**\n * @deprecated 2.3.3 moved to expTemplate subsystem\n */\nfunction get_template_for_action($controller, $action, $loc=null) {\n expTemplate::get_template_for_action($controller, $action, $loc);", " // set paths we will search in for the view\n $themepath = BASE.'themes/'.DISPLAY_THEME.'/modules/'.$controller->relative_viewpath.'/'.$action.'.tpl';\n $basepath = $controller->viewpath.'/'.$action.'.tpl';\n $newuithemepath = BASE.'themes/'.DISPLAY_THEME.'/modules/'.$controller->relative_viewpath.'/'.$action.'.newui.tpl'; //FIXME shoudl there be a theme newui variation?\n $basenewuipath = $controller->viewpath.'/'.$action.'.newui.tpl';", " // the root action will be used if we don't find a view for this action and it is a derivative of\n // action. i.e. showall_by_tags would use the showall.tpl view if we do not have a view named\n // showall_by_tags.tpl\n $root_action = explode('_', $action);\n $rootthemepath = BASE . 'themes/' . DISPLAY_THEME . '/modules/' . $controller->relative_viewpath . '/' . $root_action[0] . '.tpl';\n $rootbasepath = $controller->viewpath . '/' . $root_action[0] . '.tpl';", " if (newui()) {\n if (file_exists($newuithemepath)) {\n return new controllertemplate($controller, $newuithemepath);\n } elseif (file_exists($basenewuipath)) {\n return new controllertemplate($controller, $basenewuipath);\n }\n }\n if (bs(true)) {\n $rootbstrap3path = $controller->viewpath . '/' . $root_action[0] . '.bootstrap3.tpl';\n $basebstrap3path = $controller->viewpath . '/' . $action . '.bootstrap3.tpl';\n $rootbstrappath = $controller->viewpath . '/' . $root_action[0] . '.bootstrap.tpl';\n $basebstrappath = $controller->viewpath . '/' . $action . '.bootstrap.tpl';\n if (file_exists($themepath)) {\n return new controllertemplate($controller, $themepath);\n } elseif (bs3(true) && file_exists($basebstrap3path)) {\n return new controllertemplate($controller, $basebstrap3path);\n } elseif (file_exists($basebstrappath)) {\n return new controllertemplate($controller, $basebstrappath);\n } elseif (file_exists($basepath)) {\n return new controllertemplate($controller, $basepath);\n } elseif ($root_action[0] != $action) {\n if (file_exists($rootthemepath)) {\n return new controllertemplate($controller, $rootthemepath);\n } elseif (bs3(true) && file_exists($rootbstrap3path)) {\n return new controllertemplate($controller, $rootbstrap3path);\n } elseif (file_exists($rootbstrappath)) {\n return new controllertemplate($controller, $rootbstrappath);\n } elseif (file_exists($rootbasepath)) {\n return new controllertemplate($controller, $rootbasepath);\n }\n }\n } else {\n if (file_exists($themepath)) {\n return new controllertemplate($controller, $themepath);\n } elseif (file_exists($basepath)) {\n return new controllertemplate($controller, $basepath);\n } elseif ($root_action[0] != $action) {\n if (file_exists($rootthemepath)) {\n return new controllertemplate($controller, $rootthemepath);\n } elseif (file_exists($rootbasepath)) {\n return new controllertemplate($controller, $rootbasepath);\n }\n }\n }", " // if we get here it means there were no views for the this action to be found.\n // we will check to see if we have a scaffolded version or else just grab a blank template.\n if (file_exists(BASE . 'framework/modules/common/views/scaffold/' . $action . (newui()?'.newui':'') . '.tpl')) {\n return new controllertemplate($controller, BASE . 'framework/modules/common/views/scaffold/' . $action . (newui()?'.newui':'') . '.tpl');\n } else {\n return new controllertemplate($controller, BASE . 'framework/modules/common/views/scaffold/blank.tpl');\n }\n}", "/**\n * @deprecated 2.3.3 moved to expTemplate subsystem\n */\nfunction get_action_views($ctl, $action, $human_readable) {\n expTemplate::get_action_views($ctl, $action, $human_readable);", " // setup the controller\n// $controllerName = expModules::getControllerClassName($ctl);\n// $controller = new $controllerName();\n $controller = expModules::getController($ctl);\n", " // set path information ", " $paths = array(\n $controller->viewpath,\n BASE.'themes/'.DISPLAY_THEME.'/modules/'.$controller->relative_viewpath,\n );", " ", " $views = array();\n foreach ($paths as $path) {\n if (is_readable($path)) {\n $dh = opendir($path);\n while (($file = readdir($dh)) !== false) {\n if (is_readable($path.'/'.$file) && substr($file, -4) == '.tpl' && substr($file, -14) != '.bootstrap.tpl' && substr($file, -15) != '.bootstrap3.tpl' && substr($file, -10) != '.newui.tpl') {\n $filename = substr($file, 0, -4);\n $fileparts = explode('_', $filename);\n if ($fileparts[0] == $action) {\n if (count($fileparts) == 1) {\n $views[$filename] = 'Default';\n } else {\n array_shift($fileparts); //shift the action name off the array of words\n $views[$filename] = ucwords(implode(' ', $fileparts));\n }\n }\n }\n }\n }\n }", " // Language-ize the views names\n foreach ($views as $key=>$value) {\n $views[$key] = gt($value);\n }", " return $views;\n}", "/**\n * @deprecated 2.3.3 moved to expTemplate subsystem\n */\nfunction get_filedisplay_views() {\n expTemplate::get_filedisplay_views();", " $paths = array(\n BASE.'framework/modules/common/views/file/',\n BASE.'themes/'.DISPLAY_THEME.'modules/common/views/file/',\n );", " ", " $views = array();\n foreach ($paths as $path) {\n if (is_readable($path)) {\n $dh = opendir($path);\n while (($file = readdir($dh)) !== false) {\n if (is_readable($path.'/'.$file) && substr($file, -4) == '.tpl' && substr($file, -14) != '.bootstrap.tpl' && substr($file, -15) != '.bootstrap3.tpl' && substr($file, -10) != '.newui.tpl') {\n $filename = substr($file, 0, -4);\n $views[$filename] = gt($filename);\n }\n }\n }\n }", " ", " return $views;\n}", "function object2Array($object=null) {\n $ret_array = array();\n if(empty($object)) return $ret_array;", " foreach($object as $key=>$value) {\n $ret_array[$key] = $value;\n }", " return $ret_array;\n}", "function expUnserialize($serial_str) {\n if ($serial_str === 'Array') return null; // empty array string??\n if (is_array($serial_str) || is_object($serial_str)) return $serial_str; // already unserialized\n// $out1 = @preg_replace('!s:(\\d+):\"(.*?)\";!se', \"'s:'.strlen('$2').':\\\"$2\\\";'\", $serial_str );\n $out = preg_replace_callback(\n '!s:(\\d+):\"(.*?)\";!s',\n create_function ('$m',\n '$m_new = str_replace(\\'\"\\',\\'\\\"\\',$m[2]);\n return \"s:\".strlen($m_new).\\':\"\\'.$m_new.\\'\";\\';'\n ),\n $serial_str );\n// if ($out1 !== $out) {\n// eDebug('problem:<br>'.$out.'<br>'.$out1);\n// }\n $out2 = unserialize($out);\n if (is_array($out2)) {\n if (!empty($out2['moduledescription'])) { // work-around for links in module descriptions\n $out2['moduledescription'] = stripslashes($out2['moduledescription']);\n }\n if (!empty($out2['description'])) { // work-around for links in forms descriptions\n $out2['description'] = stripslashes($out2['description']);\n }\n if (!empty($out2['report_desc'])) { // work-around for links in forms report descriptions\n $out2['report_desc'] = stripslashes($out2['report_desc']);\n }\n if (!empty($out2['response'])) { // work-around for links in forms response\n $out2['response'] = stripslashes($out2['response']);\n }\n if (!empty($out2['auto_respond_body'])) { // work-around for links in forms auto respond\n $out2['auto_respond_body'] = stripslashes($out2['auto_respond_body']);\n }\n } elseif (is_object($out2) && get_class($out2) == 'htmlcontrol') {\n $out2->html = stripslashes($out2->html);\n }\n return $out2;\n}", "/**\n * callback when the buffer gets flushed. Any processing on the page output\n * just before it gets rendered to the screen should happen here.\n * @param $buffer\n * @param null $mode\n * @return mixed\n */\nfunction expProcessBuffer($buffer, $mode=null) {\n global $jsForHead, $cssForHead;", "// return (str_replace(\"<!-- MINIFY REPLACE -->\", $cssForHead.$jsForHead, $buffer));\n return (str_replace(\"<!-- MINIFY REPLACE -->\", $cssForHead, $buffer));\n}", "/**\n * Ensure we have a valid html 'id' attribute\n *\n * @param $id\n * @return mixed\n */\nfunction createValidId($id, $value='') {\n $badvals = array(\"[\", \"]\", \",\", \" \", \"'\", \"\\\"\", \"&\", \"#\", \"%\", \"@\", \"!\", \"$\", \"(\", \")\", \"{\", \"}\"); //FIXME do we need to update this to HTML5 and only include the space?\n if (strpos($id, '[]') !== false)\n $id .= $value;\n $new_id = str_replace($badvals, \"_\", trim($id));\n return $new_id;\n}", "function curPageURL() {\n if (expJavascript::inAjaxAction()) {\n $new_request = $_REQUEST;\n unset($new_request['ajax_action']);\n if ($new_request['controller'] == 'store' && $new_request['action'] == 'edit')\n unset($new_request['view']);\n $pageURL = makeLink($new_request);\n } else {\n $pageURL = 'http';\n if (!empty($_SERVER[\"HTTPS\"]) && $_SERVER[\"HTTPS\"] == \"on\") {\n $pageURL .= \"s\";\n }\n $pageURL .= \"://\";\n if ($_SERVER[\"SERVER_PORT\"] != \"80\") {\n $pageURL .= $_SERVER[\"SERVER_NAME\"] . \":\" . $_SERVER[\"SERVER_PORT\"] . $_SERVER[\"REQUEST_URI\"];\n } else {\n $pageURL .= $_SERVER[\"SERVER_NAME\"] . $_SERVER[\"REQUEST_URI\"];\n }\n }\n return $pageURL;\n}", "/**\n * Return status of e-commerce\n */\nfunction ecom_active() {\n global $db;", " return ($db->selectValue('modstate', 'active', 'module=\"store\"') ||\n $db->selectValue('modstate', 'active', 'module=\"eventregistration\"') ||\n $db->selectValue('modstate', 'active', 'module=\"donation\"') || FORCE_ECOM);\n}", "/**\n * Return the current framework\n *\n * @return bool\n */\nfunction framework() {\n global $framework;", " return $framework;\n}", "/**\n * Is the current framework Bootstrap v2 based?\n *\n * @return bool\n */\nfunction bs2() {\n global $framework;", " if ($framework == 'bootstrap') {\n return true;\n } else {\n return false;\n }\n}", "/**\n * Is the current framework Bootstrap v3 based?\n *\n * @param bool $strict must be bootstrap3 and NOT newui\n * @return bool\n */\nfunction bs3($strict = false) {\n global $framework;", " if ($framework == 'bootstrap3') {\n return true;\n } elseif ($framework == 'newui' && !$strict) {\n return true;\n } else {\n return false;\n }\n}", "/**\n * Is the current framework Bootstrap based?\n *\n * @param bool $strict must be bootstrap 2 or 3 and NOT newui\n * @return bool\n */\nfunction bs($strict = false) {\n global $framework;", " if ($framework == 'bootstrap3' || $framework == 'bootstrap') {\n return true;\n } elseif ($framework == 'newui' && !$strict) {\n return true;\n } else {\n return false;\n }\n}", "/**\n * Is the current framework NEWUI and NOT a Bootstrap framework\n *\n * @return bool\n */\nfunction newui() {\n global $framework;", " if ($framework == 'newui') {\n return true;\n } else {\n return false;\n }\n}", "function gt($s){\n return expLang::gettext($s);\n}", "function glist($s){\n if (is_array($s)) {\n $list = array();\n foreach ($s as $key=>$phrase) {\n $list[$key] = expLang::gettext(trim($phrase));\n }\n } else {\n $list = '';\n $phrases = explode(\",\",$s);\n foreach ($phrases as $key=>$phrase) {\n if ($key) $list .= ',';\n $list .= expLang::gettext(trim($phrase));\n }\n }\n return $list;\n}", "/**\n * called from exponent.php as the ajax error handler\n *\n * @param $errno\n * @param $errstr\n * @param $errfile\n * @param $errline\n */\nfunction handleErrors($errno, $errstr, $errfile, $errline) {\n if (DEVELOPMENT > 0 && AJAX_ERROR_REPORTING == 1) {\n switch ($errno) {\n case E_ERROR:\n case E_USER_ERROR:\n $msg = 'PHP Error('.$errno.'): ';\n break;\n case E_WARNING:\n case E_USER_WARNING:\n $msg = 'PHP Warning('.$errno.'): ';\n break;\n case E_NOTICE:\n case E_USER_NOTICE:\n $msg = 'PHP Notice('.$errno.'): ';\n break;\n default:\n return; // we really don't want other issues printed\n $msg = 'PHP Issue('.$errno.'): ';\n break;\n }\n $msg .= $errstr;\n $msg .= !empty($errfile) ? ' in file '.$errfile : \"\";\n $msg .= !empty($errline) ? ' on line '.$errline : \"\";\n // send to the debug output\n eDebug($msg);\n }\n}", "/**\n * dumps the passed variable to screen/log, but only if in development mode\n *\n * @param mixed $var the variable to dump\n * @param bool $halt if set to true will halt execution\n * @param bool $disable_log if set to true will disable logging and force to screen\n * @return void\n */\nfunction eDebug($var, $halt=false, $disable_log=false){\n\tif (DEVELOPMENT) {\n if (LOGGER && !$disable_log) {\n// if(is_array($var) || is_object($var)) {\n// $pvar = print_r($var, true);\n// } else {\n// $pvar = $var;\n// }\n// echo(\"<script>YUI(EXPONENT.YUI3_CONFIG).use('node', function(Y) {Y.log('\".json_encode($pvar).\"','info','exp')});;</script>\");\n eLog($var, gt('DEBUG'));\n } else {\n if (file_exists(BASE . 'external/kint/Kint.class.php')) {\n require_once BASE . 'external/kint/Kint.class.php';\n d($var); // kint\n } else {\n echo \"<pre>\";\n print_r($var);\n echo \"</pre>\";\n }\n }", "\t\tif ($halt) die();\n\t}\n}", "/**\n * dumps the passed variable to a log, but only if in development mode\n *\n * @param mixed $var the variable to log\n * @param string $type the type of entry to record\n * @param string $path the pathname for the log file\n * @param string $minlevel\n * @return void\n */\nfunction eLog($var, $type='', $path='', $minlevel='0') {\n\tif($type == '') { $type = \"INFO\"; }\n\tif($path == '') { $path = BASE . 'tmp/exponent.log'; }\n\tif (DEVELOPMENT >= $minlevel) {\n\t\tif (is_writable ($path) || !file_exists($path)) {\n\t\t\tif (!$log = fopen ($path, \"ab\")) {\n\t\t\t\teDebug(gt(\"Error opening log file for writing.\"), false, true);\n\t\t\t} else {\n if(is_array($var) || is_object($var)) {\n// $pvar = print_r($var, true);\n $pvar = json_encode($var, true); // json is easier to deal with as data\n } else {\n $pvar = $var;\n }\n\t\t\t\tif (fwrite ($log, $type . \": \" . $pvar . \"\\r\\n\") === FALSE) {\n\t\t\t\t\teDebug(gt(\"Error writing to log file\").\" (\".$path.\").\", false, true);\n\t\t\t\t}\n\t\t\t\tfclose ($log);\n\t\t\t}\n\t\t} else {\n\t\t\teDebug(gt(\"Log file\".\" (\".$path).\" \".gt(\"not writable.\"), false, true);\n\t\t}\n\t}\n}", "?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 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 ]
PreciseBugs
{"buggy_code_end_loc": [1156, 821, 538, 1298, 1110, 656, 639, 481, 1974, 221, 1264, 168, 235, 25, 598, 133, 55, 383, 63, 58, 352, 125, 394, 59, 2152, 117, 137, 259, 537, 2235, 33, 72, 1773, 250, 679, 739, 285, 1941, 540, 62, 528, 25, 1290, 256, 199, 122, 41, 99, 2020, 355, 147, 129, 1499], "buggy_code_start_loc": [44, 288, 107, 354, 1102, 26, 194, 37, 244, 25, 27, 24, 31, 25, 27, 50, 27, 27, 25, 44, 26, 25, 29, 34, 25, 24, 24, 25, 25, 27, 26, 68, 1, 54, 26, 428, 41, 29, 44, 55, 24, 24, 1, 28, 30, 25, 29, 25, 25, 29, 146, 128, 27], "filenames": ["framework/core/controllers/expController.php", "framework/core/expFramework.php", "framework/core/models/expRecord.php", "framework/core/subsystems/database/mysqli.php", "framework/core/subsystems/expDatabase.php", "framework/core/subsystems/expPaginator.php", "framework/core/subsystems/expSettings.php", "framework/core/subsystems/expString.php", "framework/core/subsystems/expTheme.php", "framework/modules/addressbook/controllers/addressController.php", "framework/modules/administration/controllers/administrationController.php", "framework/modules/banners/controllers/bannerController.php", "framework/modules/blog/controllers/blogController.php", "framework/modules/core/controllers/expCatController.php", "framework/modules/core/controllers/expCommentController.php", "framework/modules/core/controllers/expDefinableFieldController.php", "framework/modules/core/controllers/expHTMLEditorController.php", "framework/modules/core/controllers/expSimpleNoteController.php", "framework/modules/core/controllers/expTagController.php", "framework/modules/eaas/controllers/eaasController.php", "framework/modules/ealerts/controllers/ealertController.php", "framework/modules/ecommerce/controllers/billingController.php", "framework/modules/ecommerce/controllers/ecomconfigController.php", "framework/modules/ecommerce/controllers/eventregistrationController.php", "framework/modules/ecommerce/controllers/orderController.php", "framework/modules/ecommerce/controllers/order_statusController.php", "framework/modules/ecommerce/controllers/purchaseOrderController.php", "framework/modules/ecommerce/controllers/shippingController.php", "framework/modules/ecommerce/controllers/storeCategoryController.php", "framework/modules/ecommerce/controllers/storeController.php", "framework/modules/ecommerce/controllers/taxController.php", "framework/modules/ecommerce/products/models/donation.php", "framework/modules/events/controllers/eventController.php", "framework/modules/events/models/event.php", "framework/modules/file/controllers/fileController.php", "framework/modules/file/models/expFile.php", "framework/modules/filedownloads/controllers/filedownloadController.php", "framework/modules/forms/controllers/formsController.php", "framework/modules/help/controllers/helpController.php", "framework/modules/help/models/help_version.php", "framework/modules/importexport/controllers/importexportController.php", "framework/modules/migration/controllers/migrationController.php", "framework/modules/navigation/controllers/navigationController.php", "framework/modules/news/controllers/newsController.php", "framework/modules/photoalbum/controllers/photosController.php", "framework/modules/pixidou/controllers/pixidouController.php", "framework/modules/portfolio/controllers/portfolioController.php", "framework/modules/recyclebin/controllers/recyclebinController.php", "framework/modules/report/controllers/reportController.php", "framework/modules/search/controllers/searchController.php", "framework/modules/simplepoll/controllers/simplePollController.php", "framework/modules/users/controllers/loginController.php", "framework/modules/users/controllers/usersController.php"], "fixing_code_end_loc": [1183, 823, 543, 1298, 1110, 664, 643, 481, 1977, 221, 1263, 171, 234, 29, 599, 133, 59, 383, 69, 52, 358, 126, 397, 57, 2154, 120, 130, 262, 538, 2232, 25, 72, 1774, 255, 685, 741, 285, 1949, 541, 62, 535, 25, 1306, 259, 202, 121, 40, 102, 2025, 356, 147, 129, 1513], "fixing_code_start_loc": [44, 288, 107, 354, 1102, 26, 194, 37, 244, 25, 27, 25, 32, 26, 27, 50, 27, 27, 26, 43, 26, 25, 29, 33, 25, 25, 25, 25, 25, 26, 25, 68, 1, 55, 25, 428, 41, 30, 44, 55, 25, 24, 1, 29, 31, 24, 30, 25, 25, 29, 146, 128, 27], "message": "Exponent CMS version 2.3.9 suffers from a Object Injection vulnerability in framework/modules/core/controllers/expTagController.php related to change_tags.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:exponentcms:exponent_cms:2.3.9:*:*:*:*:*:*:*", "matchCriteriaId": "12FDDF33-2B21-4F8A-AB9A-01857197E810", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Exponent CMS version 2.3.9 suffers from a Object Injection vulnerability in framework/modules/core/controllers/expTagController.php related to change_tags."}, {"lang": "es", "value": "Existe una vulnerabilidad en Exponent CMS versi\u00f3n 2.3.9, sufre de una vulnerabilidad de Inyecci\u00f3n de Objeto en el archivo framework/modules/core/controllers/expTagController.php asociado con el par\u00e1metro change_tags."}], "evaluatorComment": null, "id": "CVE-2016-8900", "lastModified": "2019-05-28T16:01:48.990", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-05-24T17:29:00.913", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Exploit", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2016/09/30/5"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/exponentcms/exponent-cms/commit/fdafb5ec97838e4edbd685f587f28d3174ebb3db"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/exponentcms/exponent-cms/commit/fdafb5ec97838e4edbd685f587f28d3174ebb3db"}, "type": "CWE-74"}
197
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n##################################################\n#\n# Copyright (c) 2004-2016 OIC Group, Inc.\n#\n# This file is part of Exponent\n#\n# Exponent is free software; you can redistribute\n# it and/or modify it under the terms of the GNU\n# General Public License as published by the Free\n# Software Foundation; either version 2 of the\n# License, or (at your option) any later version.\n#\n# GPL: http://www.gnu.org/licenses/gpl.txt\n#\n##################################################", "//Global Variables", "// expModules\n/**\n * Stores the list of available/active controllers\n * @var array $available_controllers\n * @name $available_controllers\n */\n$available_controllers = array();", "// expTheme\n/**\n * Stores the theme validation flags\n * @var array $validateTheme does theme have header & footer\n * @name $validateTheme\n */\n$validateTheme = array(\"headerinfo\"=>false,\"footerinfo\"=>false);\n/**\n * Stores the list of module scopes\n * @var array $module_scope\n * @name $module_scope\n */\n$module_scope = array();\n/**\n * Stores the theme framework\n * @var integer $framework\n * @name $framework\n */\n$framework = null;", "// expLang\n/**\n * Stores the list of language strings for the current language\n * @var array $cur_lang\n * @name $cur_lang\n */\n$cur_lang = array();\n/**\n * Stores the list of language strings for the default language (English - US)\n * @var array $default_lang\n * @name $default_lang\n */\n$default_lang = array();\n/**\n * Stores the list of language specific strings specific to the theme\n * @var array $custom_lang\n * @name $custom_lang\n */\n$custom_lang = array();\n/**\n * Stores the name of the default language file\n * @var array $default_lang_file\n * @name $default_lang_file\n */\n$default_lang_file = '';\n/**\n * Stores the name of the language file to be created\n * @var array $target_lang_file\n * @name $target_lang_file\n */\n$target_lang_file = '';", "// expDatabase\n/**\n * Stores the exponent database object\n * @var \\database $db the exponent database object\n * @name $db\n */\n$db = new stdClass();", "// expHistory\n/**\n * Stores the browsing history object\n * @var expHistory $history\n * @name $history\n */\n$history = new stdClass();", "// user model\n/**\n * Stores the current user object\n * @var user $user\n * @name $user\n */\n$user = new stdClass();\n/**\n * This global array belongs exclusively to the user model, and is used to cache\n * users as they are retrieved, to help out with performance when doing a lot of\n * work with user accounts and profile information.\n * @var array $SYS_USERS_CACHE\n * @name $SYS_USERS_CACHE\n */\n$SYS_USERS_CACHE = array();", "// expRouter\n/**\n * Stores the routing/link/url object\n * @var expRouter $router\n * @name $router\n */\n$router = new stdClass();\n/**\n * Stores the routing/link/url object\n * @var section $sectionObj\n * @name $sectionObj\n */\n$sectionObj = new stdClass();", "// expCore\n/**\n * Stores the list of sections/pages for the site\n * @var array $sections\n * @name $sections\n */\n$sections = array();\n// expPermissions\n/**\n * Stores the permission data for the current user.\n * This should not be modified by anything outside of the permissions subsystem.\n * @var array $exponent_permissions_r\n * @name $exponent_permissions_r\n */\n$exponent_permissions_r = array();", "// expJavascript\n/**\n * Stores the page's inline javascript code\n * @var array $js2foot\n * @name $js2foot\n */\n$js2foot = array();\n/**\n * Stores the yui3 javascript files list\n * @var array $yui3js\n * @name $yui3js\n */\n$yui3js = false;\n/**\n * Stores the jquery javascript files list\n * @var array $jqueryjs\n * @name $jqueryjs\n */\n$jqueryjs = array();\n/**\n * Stores the twitter bootstrap javascript file list\n * @var array $bootstrapjs\n * @name $bootstrapjs\n */\n$bootstrapjs = array();\n/**\n * Stores the 'other' javascript files list\n * @var array $expJS\n * @name $expJS\n */\n$expJS = array();", "// expCSS\n/**\n * Stores the user's less global variables\n * @var array $less_vars\n * @name $less_vars\n */\n$less_vars = array();\n/**\n * Stores the user's css files to load first\n * @var array $css_primer\n * @name $css_primer\n */\n$css_primer = array();\n/**\n * Stores the user's css core/system files\n * @var array $css_core\n * @name $css_core\n */\n$css_core = array();\n/**\n * Stores the user's css files\n * @var array $css_links\n * @name $css_links\n */\n$css_links = array();\n/**\n * Stores the user's css files\n * @var array $css_theme\n * @name $css_theme\n */\n$css_theme = array();\n/**\n * Stores the user's css files\n * @var array $css_inline\n * @name $css_inline\n */\n$css_inline = array();\n/**\n * Stores the user's css files\n * @var array $head_config\n * @name $head_config\n */\n$head_config = array();\n/**\n * Stores the user's css files\n * @var string $jsForHead\n * @name $jsForHead\n */\n$jsForHead = \"\";\n/**\n * Stores the user's css files\n * @var string $cssForHead\n * @name $cssForHead\n */\n$cssForHead = \"\";", "// expTemplate\n/**\n * Stores the global template\n * @var \\basetemplate $template\n * @name $template\n */\n$template = null;", "// expTimer\n/**\n * Stores the timer\n * @var expTimer $timer\n * @name $timer\n */\n$timer = null;", "// e-commerce\n/**\n * Stores the order\n * @var \\order $order\n * @name $order\n */\n$order = null;", "/**\n * Main module action/display logic/routine; initializes/checks controller before calling action/method\n *\n * @param array $parms\n * @return bool|mixed|string\n */\nfunction renderAction(array $parms=array()) {\n global $user, $db;", " //Get some info about the controller\n// $baseControllerName = expModules::getControllerName($parms['controller']);\n $fullControllerName = expModules::getControllerClassName($parms['controller']);\n if (expModules::controllerExists($fullControllerName)) {\n $controllerClass = new ReflectionClass($fullControllerName);\n } else {\n return sprintf(gt('The module \"%s\" was not found in the system'), $parms['controller']);\n }", " if (isset($parms['view'])) $parms['view'] = urldecode($parms['view']);\n // Figure out the action to use...if the specified action doesn't exist then we look for the showall action.\n if ($controllerClass->hasMethod($parms['action'])) {\n $action = $parms['action'];\n /* TODO: Not sure if we need to check for private methods to be here. FJD\n\t\t$meth = $controllerClass->getMethod($action);\n if ($meth->isPrivate()) expQueue::flashAndFlow('error', gt('The requested action could not be performed: Action not found'));*/\n } elseif ($controllerClass->hasMethod('showall')) {\n $parms['action'] = 'showall';\n $action = 'showall';\n } else {\n expQueue::flashAndFlow('error', gt('The requested action could not be performed: Action not found'));\n }", " // initialize the controller.\n $src = isset($parms['src']) ? $parms['src'] : null;", " $controller = new $fullControllerName($src, $parms);\n", " //Set up the correct template to use for this action\n global $template;\n $view = !empty($parms['view']) ? $parms['view'] : $action;\n $template = expTemplate::get_template_for_action($controller, $view, $controller->loc);", "", " //setup default model(s) for this controller's actions to use\n foreach ($controller->getModels() as $model) {\n $controller->$model = new $model(null,false,false); //added null,false,false to reduce unnecessary queries. FJD\n // flag for needing approval check\n if ($controller->$model->supports_revisions && ENABLE_WORKFLOW) {\n $uilevel = 99;\n if (expSession::exists(\"uilevel\")) $uilevel = expSession::get(\"uilevel\");\n if (!expPermissions::check('approve', $controller->loc)) {\n $controller->$model->needs_approval = true;\n } elseif (isset($uilevel) && $uilevel == UILEVEL_PREVIEW) {\n $controller->$model->needs_approval = true;\n }\n }\n }", "// FIXME this is now handled by the template class during get_template_for_action since it only sets template variables\n // have the controller assign knowledge about itself to the template.\n // this has to be done after the controller gets the template for its actions\n// $controller->moduleSelfAwareness();", " //if this controller is being called by a container then we should have a module title.\n if (isset($parms['moduletitle'])) {\n $template->assign('moduletitle', $parms['moduletitle']);\n } else {\n $title = new stdClass();\n $title->mod = $controller->loc->mod;\n $title->src = $controller->loc->src;\n $title->int = '';\n $template->assign('moduletitle', $db->selectValue('container', 'title', \"internal='\".serialize($title).\"'\"));\n }", " // check the perms for this action", " $perms = $controller->permissions_all();", " $common_action = null;\n // action convention for controllers that manage more than one model (datatype).\n // if you preface the name action name with a common crud action name we can check perms on\n // it with the developer needing to specify any...better safe than sorry.\n // i.e if the action is edit_mymodel it will be checked against the edit permission\n if (stristr($parms['action'], '_'))\n $parts = explode(\"_\", $parms['action']);\n else\n $parts = preg_split('/(?=[A-Z])/', $parms['action']); // account for actions with camelCase action/perm such as editItem\n $common_action = isset($parts[0]) ? $parts[0] : null;", " // we have to treat the update permission a little different..it's tied to the create/edit\n // permissions. Really the only way this will fail will be if someone bypasses the perm check\n // on the edit form somehow..like a hacker trying to bypass the form and just submit straight to\n // the action. To safeguard, we'll catch if the action is update and change it either to create or\n // edit depending on whether an id param is passed to. that should be sufficient.", " if ($parms['action'] == 'update' || $common_action == 'update') {", " $perm_action = (!isset($parms['id']) || $parms['id'] == 0) ? 'create' : 'edit';", " } elseif (($parms['action'] == 'edit' || $common_action == 'edit') && (!isset($parms['id']) || $parms['id'] == 0)) {", " $perm_action = 'create';\n } elseif ($parms['action'] == 'saveconfig') {\n $perm_action = 'configure';\n } else {", "", " $perm_action = $parms['action'];\n }", " // Here is where we check for ownership of an item and 'create' perm\n if (($parms['action'] == 'edit' || $parms['action'] == 'update' || $parms['action'] == 'delete' ||\n $common_action == 'edit' || $common_action == 'update' || $common_action == 'delete') && !empty($parms['id'])) {\n $theaction = !empty($common_action) ? $common_action : $parms['action'];\n $owner = $db->selectValue($model, 'poster', 'id=' . $parms['id']);\n if ($owner == $user->id && !expPermissions::check($theaction, $controller->loc) && expPermissions::check('create', $controller->loc)) {\n $perm_action = 'create';\n }\n }", " if (!DISABLE_PRIVACY) {\n // check to see if it's on a private page and we shouldn't see it\n if ($perm_action == 'showall' || $perm_action == 'show' || $perm_action == 'downloadfile' || $common_action == 'showall' || $common_action == 'show' || $common_action == 'downloadfile') {\n $loc = null;\n if (!empty($parms['src'])) {\n $loc = expCore::makeLocation($parms['controller'], $parms['src']);\n } elseif (!empty($parms['id']) || !empty($parms['title']) || !empty($parms['sef_url'])) {\n if (!empty($parms['id'])) {\n $record = new $controller->basemodel_name($parms['id']);\n } elseif (!empty($parms['title'])) {\n $record = new $controller->basemodel_name($parms['title']);\n } elseif (!empty($parms['sef_url'])) {\n $record = new $controller->basemodel_name($parms['sef_url']);\n }\n if (!empty($record->location_data)) $loc = expUnserialize($record->location_data);\n }\n if (!empty($loc)) {\n $section = new section();\n $sectionref = new sectionref();\n $container = new container();\n $secref = $sectionref->find('first',\"module='\".$parms['controller'].\"' AND source='\" . $loc->src . \"'\");\n if (!empty($secref->section)) {\n $page = $section->find('first','id=' . $secref->section); // only one page can have the section id#\n $module = $container->find('first',\"internal='\" . serialize($loc) . \"'\"); // only one container can have the internal == location\n if ($page !== null && $module !== null && !empty($page->id) && (empty($page->public) || !empty($module->is_private))) {\n // we've found the page and module/container and it's either a private page or private module\n if (!expPermissions::check('view',expCore::makeLocation('navigation', $page->id))) {\n if (expTheme::inAction()) {\n flash('error', gt(\"You don't have permission to view that item\"));\n notfoundController::handle_not_authorized();\n expHistory::returnTo('viewable');\n } else {\n return false;\n }\n }\n }\n }\n }\n }\n }", " //FIXME? if the assoc $perm doesn't exist, the 'action' will ALWAYS be allowed, e.g., default is to allow action\n if (array_key_exists($perm_action, $perms)) {\n if (!expPermissions::check($perm_action, $controller->loc)) {\n if (expTheme::inAction()) {\n flash('error', gt(\"You don't have permission to\").\" \".$perms[$perm_action]);\n notfoundController::handle_not_authorized();\n expHistory::returnTo('viewable');\n } else {\n return false;\n }\n }\n } elseif (array_key_exists($common_action, $perms)) {\n if (!expPermissions::check($common_action, $controller->loc)) {\n if (expTheme::inAction()) {\n flash('error', gt(\"You don't have permission to\").\" \".$perms[$common_action]);\n notfoundController::handle_not_authorized();\n expHistory::returnTo('viewable');\n } else {\n return false;\n }\n }\n } elseif (array_key_exists($perm_action, $controller->requires_login)) {\n // check if the action requires the user to at least be logged in\n if (!$user->isLoggedIn()) {", " $msg = empty($controller->requires_login[$perm_action]) ? gt(\"You must be logged in to perform this action\") : gt($controller->requires_login[$perm_action]);", " flash('error', $msg);\n notfoundController::handle_not_authorized();\n expHistory::redirecto_login();\n }\n } elseif (array_key_exists($common_action, $controller->requires_login)) {\n // check if the action requires the user to at least be logged in\n if (!$user->isLoggedIn()) {", " $msg = empty($controller->requires_login[$common_action]) ? gt(\"You must be logged in to perform this action\") : gt($controller->requires_login[$common_action]);", " flash('error', $msg);\n notfoundController::handle_not_authorized();\n expHistory::redirecto_login();\n }", " }\n", " // register this controllers permissions to the view for in view perm checks\n $template->register_permissions(array_keys($perms), $controller->loc);", "", " // globalizing $user inside all templates\n $template->assign('user', $user);", " // lastly, run the action which can also override the above assignments\n $controller->$action();", " if (empty($parms['no_output'])) {\n $template->output();\n } else {\n $html = $template->render();\n return $html;\n }\n}", "function hotspot($source = null) {\n if (!empty($source)) {\n global $sectionObj;", "\t //FIXME there is NO 'page' object and section has no _construct method\n $page = new section($sectionObj->id);\n $modules = $page->getModulesBySource($source); //FIXME there is no getModulesBySource method anywhere\n //eDebug($modules);exit();", " foreach ($modules as $module) {\n renderAction(array('controller'=>$module->type, 'action'=>$module->action, 'instance'=>$module->id));\n }\n }\n}", "function makeLink($params=array(), $secure=false) {\n global $router;", " if(!is_array($params) || count($params) == 0) return false;\n $secure = empty($secure) ? false : true;\n return $router->makeLink($params, false, $secure);\n}", "function redirect_to($params=array(), $secure=false) {\n global $router;", " $secure = empty($secure) ? false : true;\n $link = (!is_array($params)) ? $params : $router->makeLink($params, false, $secure);\n header(\"Location: \" . $link);\n exit();", "}", "\nfunction flash($name, $msg) {\n expQueue::flash($name, $msg);\n}", "function flashAndFlow($name, $msg) {\n expQueue::flashAndFlow($name, $msg);\n}", "/**\n * Display the message queue\n *\n * @param null $name\n * @return bool|mixed|string\n */\nfunction show_msg_queue($name=null) {\n return expQueue::show($name);\n}", "/**\n * Assign a variable to the current template\n *\n * @param array $vars\n * @return bool\n */\nfunction assign_to_template(array $vars=array()) {\n global $template;", "", " if (empty($template) || count($vars) == 0) return false;\n foreach ($vars as $key=>$val) {\n $template->assign($key, $val);\n }\n}", "function get_model_for_controller($controller_name) {\n //FIXME this works by making assumptions\n $start_pos = stripos($controller_name, 'controller');\n if ($start_pos === false) {\n return false;\n } else {\n return substr($controller_name, 0, $start_pos);\n }\n}", "/**\n * @deprecated 2.3.3 moved to expTemplate subsystem\n */\nfunction get_common_template($view, $loc, $controllername='') {\n return expTemplate::get_common_template($view, $loc, $controllername);", " $controller = new stdClass();\n $controller->baseclassname = empty($controllername) ? 'common' : $controllername;\n $controller->loc = $loc;", "", " $themepath = BASE . 'themes/' . DISPLAY_THEME . '/modules/common/views/' . $controllername . '/' . $view . '.tpl';\n $basenewuipath = BASE . 'framework/modules/common/views/' . $controllername . '/' . $view . '.newui.tpl';\n $basepath = BASE . 'framework/modules/common/views/' . $controllername . '/' . $view . '.tpl';", " if (bs(true)) {\n $basebstrap3path = BASE . 'framework/modules/common/views/' . $controllername . '/' . $view . '.bootstrap3.tpl';\n $basebstrappath = BASE . 'framework/modules/common/views/' . $controllername . '/' . $view . '.bootstrap.tpl';\n if (file_exists($themepath)) {\n return new controllertemplate($controller, $themepath);\n } elseif (bs3(true) && file_exists($basebstrap3path)) {\n return new controllertemplate($controller, $basebstrap3path);\n } elseif (file_exists($basebstrappath)) {\n return new controllertemplate($controller, $basebstrappath);\n } elseif(newui() && file_exists($basenewuipath)) { //FIXME is this the correct sequence spot?\n return new controllertemplate($controller,$basenewuipath);\n } elseif (file_exists($basepath)) {\n return new controllertemplate($controller, $basepath);\n } else {\n return new controllertemplate($controller, BASE.'framework/modules/common/views/scaffold/blank.tpl');\n }\n } else {\n if (file_exists($themepath)) {\n return new controllertemplate($controller,$themepath);\n } elseif (newui() && file_exists($basenewuipath)) {\n return new controllertemplate($controller,$basenewuipath);\n } elseif(file_exists($basepath)) {\n return new controllertemplate($controller,$basepath);\n } else {\n return new controllertemplate($controller, BASE.'framework/modules/common/views/scaffold/blank.tpl');\n }\n }\n}", "/**\n * @deprecated 2.3.3 moved to expTemplate subsystem\n */\nfunction get_config_templates($controller, $loc) {\n return expTemplate::get_config_templates($controller, $loc);", "// global $db;", "", " // set paths we will search in for the view\n $commonpaths = array(\n BASE.'framework/modules/common/views/configure',\n BASE.'themes/'.DISPLAY_THEME.'/modules/common/views/configure',\n );", "", " $modpaths = array(\n $controller->viewpath.'/configure',\n\t BASE.'themes/'.DISPLAY_THEME.'/modules/'.$controller->relative_viewpath.'/configure'\n );", "\n // get the common configuration files", " $common_views = expTemplate::find_config_views($commonpaths, $controller->remove_configs);\n foreach ($common_views as $key=>$value) {\n $common_views[$key]['name'] = gt($value['name']);\n }\n $moduleconfig = array();\n if (!empty($common_views['module'])) $moduleconfig['module'] = $common_views['module'];\n unset($common_views['module']);", " // get the config views for the module\n $module_views = expTemplate::find_config_views($modpaths);\n foreach ($module_views as $key=>$value) {\n $module_views[$key]['name'] = gt($value['name']);\n }\n", " // look for a config form for this module's current view", "// $controller->loc->mod = expModules::getControllerClassName($controller->loc->mod);\n //check to see if hcview was passed along, indicating a hard-coded module\n// if (!empty($controller->params['hcview'])) {\n// $viewname = $controller->params['hcview'];\n// } else {\n// $viewname = $db->selectValue('container', 'view', \"internal='\".serialize($controller->loc).\"'\");\n// }\n// $viewconfig = $viewname.'.config';\n// foreach ($modpaths as $path) {\n// if (file_exists($path.'/'.$viewconfig)) {\n// $fileparts = explode('_', $viewname);\n// if ($fileparts[0]=='show'||$fileparts[0]=='showall') array_shift($fileparts);\n// $module_views[$viewname]['name'] = ucwords(implode(' ', $fileparts)).' '.gt('View Configuration');\n// $module_views[$viewname]['file'] =$path.'/'.$viewconfig;\n// }\n// }", "", " // sort the views highest to lowest by filename\n // we are reverse sorting now so our array merge\n // will overwrite property..we will run array_reverse\n // when we're finished to get them back in the right order\n krsort($common_views);\n krsort($module_views);", " if (!empty($moduleconfig)) $common_views = array_merge($common_views, $moduleconfig);\n $views = array_merge($common_views, $module_views);\n $views = array_reverse($views);", " return $views;\n}", "/**\n * @deprecated 2.3.3 moved to expTemplate subsystem\n */\nfunction find_config_views($paths=array(), $excludes=array()) {\n return expTemplate::find_config_views($paths, $excludes);", " $views = array();\n foreach ($paths as $path) {\n if (is_readable($path)) {\n $dh = opendir($path);\n while (($file = readdir($dh)) !== false) {\n if (is_readable($path.'/'.$file) && substr($file, -4) == '.tpl' && substr($file, -14) != '.bootstrap.tpl' && substr($file, -15) != '.bootstrap3.tpl' && substr($file, -10) != '.newui.tpl') {\n $filename = substr($file, 0, -4);\n if (!in_array($filename, $excludes)) {\n $fileparts = explode('_', $filename);\n $views[$filename]['name'] = ucwords(implode(' ', $fileparts));\n $views[$filename]['file'] = $path.'/'.$file;\n if ((bs(true)) && file_exists($path.'/'.$filename.'.bootstrap.tpl')) {\n $views[$filename]['file'] = $path . '/' . $filename . '.bootstrap.tpl';\n }\n if (bs3() && file_exists($path.'/'.$filename.'.bootstrap3.tpl')) {\n $views[$filename]['file'] = $path.'/'.$filename.'.bootstrap3.tpl';\n }\n if (newui() && file_exists($path.'/'.$filename.'.newui.tpl')) { //FIXME newui take priority\n $views[$filename]['file'] = $path.'/'.$filename.'.newui.tpl';\n }\n }\n }\n }\n }\n }", "", " return $views;\n}", "/**\n * @deprecated 2.3.3 moved to expTemplate subsystem\n */\nfunction get_template_for_action($controller, $action, $loc=null) {\n expTemplate::get_template_for_action($controller, $action, $loc);", " // set paths we will search in for the view\n $themepath = BASE.'themes/'.DISPLAY_THEME.'/modules/'.$controller->relative_viewpath.'/'.$action.'.tpl';\n $basepath = $controller->viewpath.'/'.$action.'.tpl';\n $newuithemepath = BASE.'themes/'.DISPLAY_THEME.'/modules/'.$controller->relative_viewpath.'/'.$action.'.newui.tpl'; //FIXME shoudl there be a theme newui variation?\n $basenewuipath = $controller->viewpath.'/'.$action.'.newui.tpl';", " // the root action will be used if we don't find a view for this action and it is a derivative of\n // action. i.e. showall_by_tags would use the showall.tpl view if we do not have a view named\n // showall_by_tags.tpl\n $root_action = explode('_', $action);\n $rootthemepath = BASE . 'themes/' . DISPLAY_THEME . '/modules/' . $controller->relative_viewpath . '/' . $root_action[0] . '.tpl';\n $rootbasepath = $controller->viewpath . '/' . $root_action[0] . '.tpl';", " if (newui()) {\n if (file_exists($newuithemepath)) {\n return new controllertemplate($controller, $newuithemepath);\n } elseif (file_exists($basenewuipath)) {\n return new controllertemplate($controller, $basenewuipath);\n }\n }\n if (bs(true)) {\n $rootbstrap3path = $controller->viewpath . '/' . $root_action[0] . '.bootstrap3.tpl';\n $basebstrap3path = $controller->viewpath . '/' . $action . '.bootstrap3.tpl';\n $rootbstrappath = $controller->viewpath . '/' . $root_action[0] . '.bootstrap.tpl';\n $basebstrappath = $controller->viewpath . '/' . $action . '.bootstrap.tpl';\n if (file_exists($themepath)) {\n return new controllertemplate($controller, $themepath);\n } elseif (bs3(true) && file_exists($basebstrap3path)) {\n return new controllertemplate($controller, $basebstrap3path);\n } elseif (file_exists($basebstrappath)) {\n return new controllertemplate($controller, $basebstrappath);\n } elseif (file_exists($basepath)) {\n return new controllertemplate($controller, $basepath);\n } elseif ($root_action[0] != $action) {\n if (file_exists($rootthemepath)) {\n return new controllertemplate($controller, $rootthemepath);\n } elseif (bs3(true) && file_exists($rootbstrap3path)) {\n return new controllertemplate($controller, $rootbstrap3path);\n } elseif (file_exists($rootbstrappath)) {\n return new controllertemplate($controller, $rootbstrappath);\n } elseif (file_exists($rootbasepath)) {\n return new controllertemplate($controller, $rootbasepath);\n }\n }\n } else {\n if (file_exists($themepath)) {\n return new controllertemplate($controller, $themepath);\n } elseif (file_exists($basepath)) {\n return new controllertemplate($controller, $basepath);\n } elseif ($root_action[0] != $action) {\n if (file_exists($rootthemepath)) {\n return new controllertemplate($controller, $rootthemepath);\n } elseif (file_exists($rootbasepath)) {\n return new controllertemplate($controller, $rootbasepath);\n }\n }\n }", " // if we get here it means there were no views for the this action to be found.\n // we will check to see if we have a scaffolded version or else just grab a blank template.\n if (file_exists(BASE . 'framework/modules/common/views/scaffold/' . $action . (newui()?'.newui':'') . '.tpl')) {\n return new controllertemplate($controller, BASE . 'framework/modules/common/views/scaffold/' . $action . (newui()?'.newui':'') . '.tpl');\n } else {\n return new controllertemplate($controller, BASE . 'framework/modules/common/views/scaffold/blank.tpl');\n }\n}", "/**\n * @deprecated 2.3.3 moved to expTemplate subsystem\n */\nfunction get_action_views($ctl, $action, $human_readable) {\n expTemplate::get_action_views($ctl, $action, $human_readable);", " // setup the controller\n// $controllerName = expModules::getControllerClassName($ctl);\n// $controller = new $controllerName();\n $controller = expModules::getController($ctl);\n", " // set path information", " $paths = array(\n $controller->viewpath,\n BASE.'themes/'.DISPLAY_THEME.'/modules/'.$controller->relative_viewpath,\n );", "", " $views = array();\n foreach ($paths as $path) {\n if (is_readable($path)) {\n $dh = opendir($path);\n while (($file = readdir($dh)) !== false) {\n if (is_readable($path.'/'.$file) && substr($file, -4) == '.tpl' && substr($file, -14) != '.bootstrap.tpl' && substr($file, -15) != '.bootstrap3.tpl' && substr($file, -10) != '.newui.tpl') {\n $filename = substr($file, 0, -4);\n $fileparts = explode('_', $filename);\n if ($fileparts[0] == $action) {\n if (count($fileparts) == 1) {\n $views[$filename] = 'Default';\n } else {\n array_shift($fileparts); //shift the action name off the array of words\n $views[$filename] = ucwords(implode(' ', $fileparts));\n }\n }\n }\n }\n }\n }", " // Language-ize the views names\n foreach ($views as $key=>$value) {\n $views[$key] = gt($value);\n }", " return $views;\n}", "/**\n * @deprecated 2.3.3 moved to expTemplate subsystem\n */\nfunction get_filedisplay_views() {\n expTemplate::get_filedisplay_views();", " $paths = array(\n BASE.'framework/modules/common/views/file/',\n BASE.'themes/'.DISPLAY_THEME.'modules/common/views/file/',\n );", "", " $views = array();\n foreach ($paths as $path) {\n if (is_readable($path)) {\n $dh = opendir($path);\n while (($file = readdir($dh)) !== false) {\n if (is_readable($path.'/'.$file) && substr($file, -4) == '.tpl' && substr($file, -14) != '.bootstrap.tpl' && substr($file, -15) != '.bootstrap3.tpl' && substr($file, -10) != '.newui.tpl') {\n $filename = substr($file, 0, -4);\n $views[$filename] = gt($filename);\n }\n }\n }\n }", "", " return $views;\n}", "function object2Array($object=null) {\n $ret_array = array();\n if(empty($object)) return $ret_array;", " foreach($object as $key=>$value) {\n $ret_array[$key] = $value;\n }", " return $ret_array;\n}", "function expUnserialize($serial_str) {\n if ($serial_str === 'Array') return null; // empty array string??\n if (is_array($serial_str) || is_object($serial_str)) return $serial_str; // already unserialized\n// $out1 = @preg_replace('!s:(\\d+):\"(.*?)\";!se', \"'s:'.strlen('$2').':\\\"$2\\\";'\", $serial_str );\n $out = preg_replace_callback(\n '!s:(\\d+):\"(.*?)\";!s',\n create_function ('$m',\n '$m_new = str_replace(\\'\"\\',\\'\\\"\\',$m[2]);\n return \"s:\".strlen($m_new).\\':\"\\'.$m_new.\\'\";\\';'\n ),\n $serial_str );\n// if ($out1 !== $out) {\n// eDebug('problem:<br>'.$out.'<br>'.$out1);\n// }\n $out2 = unserialize($out);\n if (is_array($out2)) {\n if (!empty($out2['moduledescription'])) { // work-around for links in module descriptions\n $out2['moduledescription'] = stripslashes($out2['moduledescription']);\n }\n if (!empty($out2['description'])) { // work-around for links in forms descriptions\n $out2['description'] = stripslashes($out2['description']);\n }\n if (!empty($out2['report_desc'])) { // work-around for links in forms report descriptions\n $out2['report_desc'] = stripslashes($out2['report_desc']);\n }\n if (!empty($out2['response'])) { // work-around for links in forms response\n $out2['response'] = stripslashes($out2['response']);\n }\n if (!empty($out2['auto_respond_body'])) { // work-around for links in forms auto respond\n $out2['auto_respond_body'] = stripslashes($out2['auto_respond_body']);\n }\n } elseif (is_object($out2) && get_class($out2) == 'htmlcontrol') {\n $out2->html = stripslashes($out2->html);\n }\n return $out2;\n}", "/**\n * callback when the buffer gets flushed. Any processing on the page output\n * just before it gets rendered to the screen should happen here.\n * @param $buffer\n * @param null $mode\n * @return mixed\n */\nfunction expProcessBuffer($buffer, $mode=null) {\n global $jsForHead, $cssForHead;", "// return (str_replace(\"<!-- MINIFY REPLACE -->\", $cssForHead.$jsForHead, $buffer));\n return (str_replace(\"<!-- MINIFY REPLACE -->\", $cssForHead, $buffer));\n}", "/**\n * Ensure we have a valid html 'id' attribute\n *\n * @param $id\n * @return mixed\n */\nfunction createValidId($id, $value='') {\n $badvals = array(\"[\", \"]\", \",\", \" \", \"'\", \"\\\"\", \"&\", \"#\", \"%\", \"@\", \"!\", \"$\", \"(\", \")\", \"{\", \"}\"); //FIXME do we need to update this to HTML5 and only include the space?\n if (strpos($id, '[]') !== false)\n $id .= $value;\n $new_id = str_replace($badvals, \"_\", trim($id));\n return $new_id;\n}", "function curPageURL() {\n if (expJavascript::inAjaxAction()) {\n $new_request = $_REQUEST;\n unset($new_request['ajax_action']);\n if ($new_request['controller'] == 'store' && $new_request['action'] == 'edit')\n unset($new_request['view']);\n $pageURL = makeLink($new_request);\n } else {\n $pageURL = 'http';\n if (!empty($_SERVER[\"HTTPS\"]) && $_SERVER[\"HTTPS\"] == \"on\") {\n $pageURL .= \"s\";\n }\n $pageURL .= \"://\";\n if ($_SERVER[\"SERVER_PORT\"] != \"80\") {\n $pageURL .= $_SERVER[\"SERVER_NAME\"] . \":\" . $_SERVER[\"SERVER_PORT\"] . $_SERVER[\"REQUEST_URI\"];\n } else {\n $pageURL .= $_SERVER[\"SERVER_NAME\"] . $_SERVER[\"REQUEST_URI\"];\n }\n }\n return $pageURL;\n}", "/**\n * Return status of e-commerce\n */\nfunction ecom_active() {\n global $db;", " return ($db->selectValue('modstate', 'active', 'module=\"store\"') ||\n $db->selectValue('modstate', 'active', 'module=\"eventregistration\"') ||\n $db->selectValue('modstate', 'active', 'module=\"donation\"') || FORCE_ECOM);\n}", "/**\n * Return the current framework\n *\n * @return bool\n */\nfunction framework() {\n global $framework;", " return $framework;\n}", "/**\n * Is the current framework Bootstrap v2 based?\n *\n * @return bool\n */\nfunction bs2() {\n global $framework;", " if ($framework == 'bootstrap') {\n return true;\n } else {\n return false;\n }\n}", "/**\n * Is the current framework Bootstrap v3 based?\n *\n * @param bool $strict must be bootstrap3 and NOT newui\n * @return bool\n */\nfunction bs3($strict = false) {\n global $framework;", " if ($framework == 'bootstrap3') {\n return true;\n } elseif ($framework == 'newui' && !$strict) {\n return true;\n } else {\n return false;\n }\n}", "/**\n * Is the current framework Bootstrap based?\n *\n * @param bool $strict must be bootstrap 2 or 3 and NOT newui\n * @return bool\n */\nfunction bs($strict = false) {\n global $framework;", " if ($framework == 'bootstrap3' || $framework == 'bootstrap') {\n return true;\n } elseif ($framework == 'newui' && !$strict) {\n return true;\n } else {\n return false;\n }\n}", "/**\n * Is the current framework NEWUI and NOT a Bootstrap framework\n *\n * @return bool\n */\nfunction newui() {\n global $framework;", " if ($framework == 'newui') {\n return true;\n } else {\n return false;\n }\n}", "function gt($s){\n return expLang::gettext($s);\n}", "function glist($s){\n if (is_array($s)) {\n $list = array();\n foreach ($s as $key=>$phrase) {\n $list[$key] = expLang::gettext(trim($phrase));\n }\n } else {\n $list = '';\n $phrases = explode(\",\",$s);\n foreach ($phrases as $key=>$phrase) {\n if ($key) $list .= ',';\n $list .= expLang::gettext(trim($phrase));\n }\n }\n return $list;\n}", "/**\n * called from exponent.php as the ajax error handler\n *\n * @param $errno\n * @param $errstr\n * @param $errfile\n * @param $errline\n */\nfunction handleErrors($errno, $errstr, $errfile, $errline) {\n if (DEVELOPMENT > 0 && AJAX_ERROR_REPORTING == 1) {\n switch ($errno) {\n case E_ERROR:\n case E_USER_ERROR:\n $msg = 'PHP Error('.$errno.'): ';\n break;\n case E_WARNING:\n case E_USER_WARNING:\n $msg = 'PHP Warning('.$errno.'): ';\n break;\n case E_NOTICE:\n case E_USER_NOTICE:\n $msg = 'PHP Notice('.$errno.'): ';\n break;\n default:\n return; // we really don't want other issues printed\n $msg = 'PHP Issue('.$errno.'): ';\n break;\n }\n $msg .= $errstr;\n $msg .= !empty($errfile) ? ' in file '.$errfile : \"\";\n $msg .= !empty($errline) ? ' on line '.$errline : \"\";\n // send to the debug output\n eDebug($msg);\n }\n}", "/**\n * dumps the passed variable to screen/log, but only if in development mode\n *\n * @param mixed $var the variable to dump\n * @param bool $halt if set to true will halt execution\n * @param bool $disable_log if set to true will disable logging and force to screen\n * @return void\n */\nfunction eDebug($var, $halt=false, $disable_log=false){\n\tif (DEVELOPMENT) {\n if (LOGGER && !$disable_log) {\n// if(is_array($var) || is_object($var)) {\n// $pvar = print_r($var, true);\n// } else {\n// $pvar = $var;\n// }\n// echo(\"<script>YUI(EXPONENT.YUI3_CONFIG).use('node', function(Y) {Y.log('\".json_encode($pvar).\"','info','exp')});;</script>\");\n eLog($var, gt('DEBUG'));\n } else {\n if (file_exists(BASE . 'external/kint/Kint.class.php')) {\n require_once BASE . 'external/kint/Kint.class.php';\n d($var); // kint\n } else {\n echo \"<pre>\";\n print_r($var);\n echo \"</pre>\";\n }\n }", "\t\tif ($halt) die();\n\t}\n}", "/**\n * dumps the passed variable to a log, but only if in development mode\n *\n * @param mixed $var the variable to log\n * @param string $type the type of entry to record\n * @param string $path the pathname for the log file\n * @param string $minlevel\n * @return void\n */\nfunction eLog($var, $type='', $path='', $minlevel='0') {\n\tif($type == '') { $type = \"INFO\"; }\n\tif($path == '') { $path = BASE . 'tmp/exponent.log'; }\n\tif (DEVELOPMENT >= $minlevel) {\n\t\tif (is_writable ($path) || !file_exists($path)) {\n\t\t\tif (!$log = fopen ($path, \"ab\")) {\n\t\t\t\teDebug(gt(\"Error opening log file for writing.\"), false, true);\n\t\t\t} else {\n if(is_array($var) || is_object($var)) {\n// $pvar = print_r($var, true);\n $pvar = json_encode($var, true); // json is easier to deal with as data\n } else {\n $pvar = $var;\n }\n\t\t\t\tif (fwrite ($log, $type . \": \" . $pvar . \"\\r\\n\") === FALSE) {\n\t\t\t\t\teDebug(gt(\"Error writing to log file\").\" (\".$path.\").\", false, true);\n\t\t\t\t}\n\t\t\t\tfclose ($log);\n\t\t\t}\n\t\t} else {\n\t\t\teDebug(gt(\"Log file\".\" (\".$path).\" \".gt(\"not writable.\"), false, true);\n\t\t}\n\t}\n}", "?>" ]
[ 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, 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, 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 ]
PreciseBugs
{"buggy_code_end_loc": [1156, 821, 538, 1298, 1110, 656, 639, 481, 1974, 221, 1264, 168, 235, 25, 598, 133, 55, 383, 63, 58, 352, 125, 394, 59, 2152, 117, 137, 259, 537, 2235, 33, 72, 1773, 250, 679, 739, 285, 1941, 540, 62, 528, 25, 1290, 256, 199, 122, 41, 99, 2020, 355, 147, 129, 1499], "buggy_code_start_loc": [44, 288, 107, 354, 1102, 26, 194, 37, 244, 25, 27, 24, 31, 25, 27, 50, 27, 27, 25, 44, 26, 25, 29, 34, 25, 24, 24, 25, 25, 27, 26, 68, 1, 54, 26, 428, 41, 29, 44, 55, 24, 24, 1, 28, 30, 25, 29, 25, 25, 29, 146, 128, 27], "filenames": ["framework/core/controllers/expController.php", "framework/core/expFramework.php", "framework/core/models/expRecord.php", "framework/core/subsystems/database/mysqli.php", "framework/core/subsystems/expDatabase.php", "framework/core/subsystems/expPaginator.php", "framework/core/subsystems/expSettings.php", "framework/core/subsystems/expString.php", "framework/core/subsystems/expTheme.php", "framework/modules/addressbook/controllers/addressController.php", "framework/modules/administration/controllers/administrationController.php", "framework/modules/banners/controllers/bannerController.php", "framework/modules/blog/controllers/blogController.php", "framework/modules/core/controllers/expCatController.php", "framework/modules/core/controllers/expCommentController.php", "framework/modules/core/controllers/expDefinableFieldController.php", "framework/modules/core/controllers/expHTMLEditorController.php", "framework/modules/core/controllers/expSimpleNoteController.php", "framework/modules/core/controllers/expTagController.php", "framework/modules/eaas/controllers/eaasController.php", "framework/modules/ealerts/controllers/ealertController.php", "framework/modules/ecommerce/controllers/billingController.php", "framework/modules/ecommerce/controllers/ecomconfigController.php", "framework/modules/ecommerce/controllers/eventregistrationController.php", "framework/modules/ecommerce/controllers/orderController.php", "framework/modules/ecommerce/controllers/order_statusController.php", "framework/modules/ecommerce/controllers/purchaseOrderController.php", "framework/modules/ecommerce/controllers/shippingController.php", "framework/modules/ecommerce/controllers/storeCategoryController.php", "framework/modules/ecommerce/controllers/storeController.php", "framework/modules/ecommerce/controllers/taxController.php", "framework/modules/ecommerce/products/models/donation.php", "framework/modules/events/controllers/eventController.php", "framework/modules/events/models/event.php", "framework/modules/file/controllers/fileController.php", "framework/modules/file/models/expFile.php", "framework/modules/filedownloads/controllers/filedownloadController.php", "framework/modules/forms/controllers/formsController.php", "framework/modules/help/controllers/helpController.php", "framework/modules/help/models/help_version.php", "framework/modules/importexport/controllers/importexportController.php", "framework/modules/migration/controllers/migrationController.php", "framework/modules/navigation/controllers/navigationController.php", "framework/modules/news/controllers/newsController.php", "framework/modules/photoalbum/controllers/photosController.php", "framework/modules/pixidou/controllers/pixidouController.php", "framework/modules/portfolio/controllers/portfolioController.php", "framework/modules/recyclebin/controllers/recyclebinController.php", "framework/modules/report/controllers/reportController.php", "framework/modules/search/controllers/searchController.php", "framework/modules/simplepoll/controllers/simplePollController.php", "framework/modules/users/controllers/loginController.php", "framework/modules/users/controllers/usersController.php"], "fixing_code_end_loc": [1183, 823, 543, 1298, 1110, 664, 643, 481, 1977, 221, 1263, 171, 234, 29, 599, 133, 59, 383, 69, 52, 358, 126, 397, 57, 2154, 120, 130, 262, 538, 2232, 25, 72, 1774, 255, 685, 741, 285, 1949, 541, 62, 535, 25, 1306, 259, 202, 121, 40, 102, 2025, 356, 147, 129, 1513], "fixing_code_start_loc": [44, 288, 107, 354, 1102, 26, 194, 37, 244, 25, 27, 25, 32, 26, 27, 50, 27, 27, 26, 43, 26, 25, 29, 33, 25, 25, 25, 25, 25, 26, 25, 68, 1, 55, 25, 428, 41, 30, 44, 55, 25, 24, 1, 29, 31, 24, 30, 25, 25, 29, 146, 128, 27], "message": "Exponent CMS version 2.3.9 suffers from a Object Injection vulnerability in framework/modules/core/controllers/expTagController.php related to change_tags.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:exponentcms:exponent_cms:2.3.9:*:*:*:*:*:*:*", "matchCriteriaId": "12FDDF33-2B21-4F8A-AB9A-01857197E810", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Exponent CMS version 2.3.9 suffers from a Object Injection vulnerability in framework/modules/core/controllers/expTagController.php related to change_tags."}, {"lang": "es", "value": "Existe una vulnerabilidad en Exponent CMS versi\u00f3n 2.3.9, sufre de una vulnerabilidad de Inyecci\u00f3n de Objeto en el archivo framework/modules/core/controllers/expTagController.php asociado con el par\u00e1metro change_tags."}], "evaluatorComment": null, "id": "CVE-2016-8900", "lastModified": "2019-05-28T16:01:48.990", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-05-24T17:29:00.913", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Exploit", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2016/09/30/5"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/exponentcms/exponent-cms/commit/fdafb5ec97838e4edbd685f587f28d3174ebb3db"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/exponentcms/exponent-cms/commit/fdafb5ec97838e4edbd685f587f28d3174ebb3db"}, "type": "CWE-74"}
197